symbolic.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. """Fortran/C symbolic expressions
  2. References:
  3. - J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf
  4. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  5. Copyright 2011 -- present NumPy Developers.
  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. """
  10. # To analyze Fortran expressions to solve dimensions specifications,
  11. # for instances, we implement a minimal symbolic engine for parsing
  12. # expressions into a tree of expression instances. As a first
  13. # instance, we care only about arithmetic expressions involving
  14. # integers and operations like addition (+), subtraction (-),
  15. # multiplication (*), division (Fortran / is Python //, Fortran // is
  16. # concatenate), and exponentiation (**). In addition, .pyf files may
  17. # contain C expressions that support here is implemented as well.
  18. #
  19. # TODO: support logical constants (Op.BOOLEAN)
  20. # TODO: support logical operators (.AND., ...)
  21. # TODO: support defined operators (.MYOP., ...)
  22. #
  23. __all__ = ['Expr']
  24. import re
  25. import warnings
  26. from enum import Enum
  27. from math import gcd
  28. class Language(Enum):
  29. """
  30. Used as Expr.tostring language argument.
  31. """
  32. Python = 0
  33. Fortran = 1
  34. C = 2
  35. class Op(Enum):
  36. """
  37. Used as Expr op attribute.
  38. """
  39. INTEGER = 10
  40. REAL = 12
  41. COMPLEX = 15
  42. STRING = 20
  43. ARRAY = 30
  44. SYMBOL = 40
  45. TERNARY = 100
  46. APPLY = 200
  47. INDEXING = 210
  48. CONCAT = 220
  49. RELATIONAL = 300
  50. TERMS = 1000
  51. FACTORS = 2000
  52. REF = 3000
  53. DEREF = 3001
  54. class RelOp(Enum):
  55. """
  56. Used in Op.RELATIONAL expression to specify the function part.
  57. """
  58. EQ = 1
  59. NE = 2
  60. LT = 3
  61. LE = 4
  62. GT = 5
  63. GE = 6
  64. @classmethod
  65. def fromstring(cls, s, language=Language.C):
  66. if language is Language.Fortran:
  67. return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE,
  68. '.lt.': RelOp.LT, '.le.': RelOp.LE,
  69. '.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()]
  70. return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT,
  71. '<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s]
  72. def tostring(self, language=Language.C):
  73. if language is Language.Fortran:
  74. return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.',
  75. RelOp.LT: '.lt.', RelOp.LE: '.le.',
  76. RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self]
  77. return {RelOp.EQ: '==', RelOp.NE: '!=',
  78. RelOp.LT: '<', RelOp.LE: '<=',
  79. RelOp.GT: '>', RelOp.GE: '>='}[self]
  80. class ArithOp(Enum):
  81. """
  82. Used in Op.APPLY expression to specify the function part.
  83. """
  84. POS = 1
  85. NEG = 2
  86. ADD = 3
  87. SUB = 4
  88. MUL = 5
  89. DIV = 6
  90. POW = 7
  91. class OpError(Exception):
  92. pass
  93. class Precedence(Enum):
  94. """
  95. Used as Expr.tostring precedence argument.
  96. """
  97. ATOM = 0
  98. POWER = 1
  99. UNARY = 2
  100. PRODUCT = 3
  101. SUM = 4
  102. LT = 6
  103. EQ = 7
  104. LAND = 11
  105. LOR = 12
  106. TERNARY = 13
  107. ASSIGN = 14
  108. TUPLE = 15
  109. NONE = 100
  110. integer_types = (int,)
  111. number_types = (int, float)
  112. def _pairs_add(d, k, v):
  113. # Internal utility method for updating terms and factors data.
  114. c = d.get(k)
  115. if c is None:
  116. d[k] = v
  117. else:
  118. c = c + v
  119. if c:
  120. d[k] = c
  121. else:
  122. del d[k]
  123. class ExprWarning(UserWarning):
  124. pass
  125. def ewarn(message):
  126. warnings.warn(message, ExprWarning, stacklevel=2)
  127. class Expr:
  128. """Represents a Fortran expression as a op-data pair.
  129. Expr instances are hashable and sortable.
  130. """
  131. @staticmethod
  132. def parse(s, language=Language.C):
  133. """Parse a Fortran expression to a Expr.
  134. """
  135. return fromstring(s, language=language)
  136. def __init__(self, op, data):
  137. assert isinstance(op, Op)
  138. # sanity checks
  139. if op is Op.INTEGER:
  140. # data is a 2-tuple of numeric object and a kind value
  141. # (default is 4)
  142. assert isinstance(data, tuple) and len(data) == 2
  143. assert isinstance(data[0], int)
  144. assert isinstance(data[1], (int, str)), data
  145. elif op is Op.REAL:
  146. # data is a 2-tuple of numeric object and a kind value
  147. # (default is 4)
  148. assert isinstance(data, tuple) and len(data) == 2
  149. assert isinstance(data[0], float)
  150. assert isinstance(data[1], (int, str)), data
  151. elif op is Op.COMPLEX:
  152. # data is a 2-tuple of constant expressions
  153. assert isinstance(data, tuple) and len(data) == 2
  154. elif op is Op.STRING:
  155. # data is a 2-tuple of quoted string and a kind value
  156. # (default is 1)
  157. assert isinstance(data, tuple) and len(data) == 2
  158. assert (isinstance(data[0], str)
  159. and data[0][::len(data[0])-1] in ('""', "''", '@@'))
  160. assert isinstance(data[1], (int, str)), data
  161. elif op is Op.SYMBOL:
  162. # data is any hashable object
  163. assert hash(data) is not None
  164. elif op in (Op.ARRAY, Op.CONCAT):
  165. # data is a tuple of expressions
  166. assert isinstance(data, tuple)
  167. assert all(isinstance(item, Expr) for item in data), data
  168. elif op in (Op.TERMS, Op.FACTORS):
  169. # data is {<term|base>:<coeff|exponent>} where dict values
  170. # are nonzero Python integers
  171. assert isinstance(data, dict)
  172. elif op is Op.APPLY:
  173. # data is (<function>, <operands>, <kwoperands>) where
  174. # operands are Expr instances
  175. assert isinstance(data, tuple) and len(data) == 3
  176. # function is any hashable object
  177. assert hash(data[0]) is not None
  178. assert isinstance(data[1], tuple)
  179. assert isinstance(data[2], dict)
  180. elif op is Op.INDEXING:
  181. # data is (<object>, <indices>)
  182. assert isinstance(data, tuple) and len(data) == 2
  183. # function is any hashable object
  184. assert hash(data[0]) is not None
  185. elif op is Op.TERNARY:
  186. # data is (<cond>, <expr1>, <expr2>)
  187. assert isinstance(data, tuple) and len(data) == 3
  188. elif op in (Op.REF, Op.DEREF):
  189. # data is Expr instance
  190. assert isinstance(data, Expr)
  191. elif op is Op.RELATIONAL:
  192. # data is (<relop>, <left>, <right>)
  193. assert isinstance(data, tuple) and len(data) == 3
  194. else:
  195. raise NotImplementedError(
  196. f'unknown op or missing sanity check: {op}')
  197. self.op = op
  198. self.data = data
  199. def __eq__(self, other):
  200. return (isinstance(other, Expr)
  201. and self.op is other.op
  202. and self.data == other.data)
  203. def __hash__(self):
  204. if self.op in (Op.TERMS, Op.FACTORS):
  205. data = tuple(sorted(self.data.items()))
  206. elif self.op is Op.APPLY:
  207. data = self.data[:2] + tuple(sorted(self.data[2].items()))
  208. else:
  209. data = self.data
  210. return hash((self.op, data))
  211. def __lt__(self, other):
  212. if isinstance(other, Expr):
  213. if self.op is not other.op:
  214. return self.op.value < other.op.value
  215. if self.op in (Op.TERMS, Op.FACTORS):
  216. return (tuple(sorted(self.data.items()))
  217. < tuple(sorted(other.data.items())))
  218. if self.op is Op.APPLY:
  219. if self.data[:2] != other.data[:2]:
  220. return self.data[:2] < other.data[:2]
  221. return tuple(sorted(self.data[2].items())) < tuple(
  222. sorted(other.data[2].items()))
  223. return self.data < other.data
  224. return NotImplemented
  225. def __le__(self, other): return self == other or self < other
  226. def __gt__(self, other): return not (self <= other)
  227. def __ge__(self, other): return not (self < other)
  228. def __repr__(self):
  229. return f'{type(self).__name__}({self.op}, {self.data!r})'
  230. def __str__(self):
  231. return self.tostring()
  232. def tostring(self, parent_precedence=Precedence.NONE,
  233. language=Language.Fortran):
  234. """Return a string representation of Expr.
  235. """
  236. if self.op in (Op.INTEGER, Op.REAL):
  237. precedence = (Precedence.SUM if self.data[0] < 0
  238. else Precedence.ATOM)
  239. r = str(self.data[0]) + (f'_{self.data[1]}'
  240. if self.data[1] != 4 else '')
  241. elif self.op is Op.COMPLEX:
  242. r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
  243. for item in self.data)
  244. r = '(' + r + ')'
  245. precedence = Precedence.ATOM
  246. elif self.op is Op.SYMBOL:
  247. precedence = Precedence.ATOM
  248. r = str(self.data)
  249. elif self.op is Op.STRING:
  250. r = self.data[0]
  251. if self.data[1] != 1:
  252. r = self.data[1] + '_' + r
  253. precedence = Precedence.ATOM
  254. elif self.op is Op.ARRAY:
  255. r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
  256. for item in self.data)
  257. r = '[' + r + ']'
  258. precedence = Precedence.ATOM
  259. elif self.op is Op.TERMS:
  260. terms = []
  261. for term, coeff in sorted(self.data.items()):
  262. if coeff < 0:
  263. op = ' - '
  264. coeff = -coeff
  265. else:
  266. op = ' + '
  267. if coeff == 1:
  268. term = term.tostring(Precedence.SUM, language=language)
  269. else:
  270. if term == as_number(1):
  271. term = str(coeff)
  272. else:
  273. term = f'{coeff} * ' + term.tostring(
  274. Precedence.PRODUCT, language=language)
  275. if terms:
  276. terms.append(op)
  277. elif op == ' - ':
  278. terms.append('-')
  279. terms.append(term)
  280. r = ''.join(terms) or '0'
  281. precedence = Precedence.SUM if terms else Precedence.ATOM
  282. elif self.op is Op.FACTORS:
  283. factors = []
  284. tail = []
  285. for base, exp in sorted(self.data.items()):
  286. op = ' * '
  287. if exp == 1:
  288. factor = base.tostring(Precedence.PRODUCT,
  289. language=language)
  290. elif language is Language.C:
  291. if exp in range(2, 10):
  292. factor = base.tostring(Precedence.PRODUCT,
  293. language=language)
  294. factor = ' * '.join([factor] * exp)
  295. elif exp in range(-10, 0):
  296. factor = base.tostring(Precedence.PRODUCT,
  297. language=language)
  298. tail += [factor] * -exp
  299. continue
  300. else:
  301. factor = base.tostring(Precedence.TUPLE,
  302. language=language)
  303. factor = f'pow({factor}, {exp})'
  304. else:
  305. factor = base.tostring(Precedence.POWER,
  306. language=language) + f' ** {exp}'
  307. if factors:
  308. factors.append(op)
  309. factors.append(factor)
  310. if tail:
  311. if not factors:
  312. factors += ['1']
  313. factors += ['/', '(', ' * '.join(tail), ')']
  314. r = ''.join(factors) or '1'
  315. precedence = Precedence.PRODUCT if factors else Precedence.ATOM
  316. elif self.op is Op.APPLY:
  317. name, args, kwargs = self.data
  318. if name is ArithOp.DIV and language is Language.C:
  319. numer, denom = [arg.tostring(Precedence.PRODUCT,
  320. language=language)
  321. for arg in args]
  322. r = f'{numer} / {denom}'
  323. precedence = Precedence.PRODUCT
  324. else:
  325. args = [arg.tostring(Precedence.TUPLE, language=language)
  326. for arg in args]
  327. args += [k + '=' + v.tostring(Precedence.NONE)
  328. for k, v in kwargs.items()]
  329. r = f'{name}({", ".join(args)})'
  330. precedence = Precedence.ATOM
  331. elif self.op is Op.INDEXING:
  332. name = self.data[0]
  333. args = [arg.tostring(Precedence.TUPLE, language=language)
  334. for arg in self.data[1:]]
  335. r = f'{name}[{", ".join(args)}]'
  336. precedence = Precedence.ATOM
  337. elif self.op is Op.CONCAT:
  338. args = [arg.tostring(Precedence.PRODUCT, language=language)
  339. for arg in self.data]
  340. r = " // ".join(args)
  341. precedence = Precedence.PRODUCT
  342. elif self.op is Op.TERNARY:
  343. cond, expr1, expr2 = [a.tostring(Precedence.TUPLE,
  344. language=language)
  345. for a in self.data]
  346. if language is Language.C:
  347. r = f'({cond}?{expr1}:{expr2})'
  348. elif language is Language.Python:
  349. r = f'({expr1} if {cond} else {expr2})'
  350. elif language is Language.Fortran:
  351. r = f'merge({expr1}, {expr2}, {cond})'
  352. else:
  353. raise NotImplementedError(
  354. f'tostring for {self.op} and {language}')
  355. precedence = Precedence.ATOM
  356. elif self.op is Op.REF:
  357. r = '&' + self.data.tostring(Precedence.UNARY, language=language)
  358. precedence = Precedence.UNARY
  359. elif self.op is Op.DEREF:
  360. r = '*' + self.data.tostring(Precedence.UNARY, language=language)
  361. precedence = Precedence.UNARY
  362. elif self.op is Op.RELATIONAL:
  363. rop, left, right = self.data
  364. precedence = (Precedence.EQ if rop in (RelOp.EQ, RelOp.NE)
  365. else Precedence.LT)
  366. left = left.tostring(precedence, language=language)
  367. right = right.tostring(precedence, language=language)
  368. rop = rop.tostring(language=language)
  369. r = f'{left} {rop} {right}'
  370. else:
  371. raise NotImplementedError(f'tostring for op {self.op}')
  372. if parent_precedence.value < precedence.value:
  373. # If parent precedence is higher than operand precedence,
  374. # operand will be enclosed in parenthesis.
  375. return '(' + r + ')'
  376. return r
  377. def __pos__(self):
  378. return self
  379. def __neg__(self):
  380. return self * -1
  381. def __add__(self, other):
  382. other = as_expr(other)
  383. if isinstance(other, Expr):
  384. if self.op is other.op:
  385. if self.op in (Op.INTEGER, Op.REAL):
  386. return as_number(
  387. self.data[0] + other.data[0],
  388. max(self.data[1], other.data[1]))
  389. if self.op is Op.COMPLEX:
  390. r1, i1 = self.data
  391. r2, i2 = other.data
  392. return as_complex(r1 + r2, i1 + i2)
  393. if self.op is Op.TERMS:
  394. r = Expr(self.op, dict(self.data))
  395. for k, v in other.data.items():
  396. _pairs_add(r.data, k, v)
  397. return normalize(r)
  398. if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
  399. return self + as_complex(other)
  400. elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX:
  401. return as_complex(self) + other
  402. elif self.op is Op.REAL and other.op is Op.INTEGER:
  403. return self + as_real(other, kind=self.data[1])
  404. elif self.op is Op.INTEGER and other.op is Op.REAL:
  405. return as_real(self, kind=other.data[1]) + other
  406. return as_terms(self) + as_terms(other)
  407. return NotImplemented
  408. def __radd__(self, other):
  409. if isinstance(other, number_types):
  410. return as_number(other) + self
  411. return NotImplemented
  412. def __sub__(self, other):
  413. return self + (-other)
  414. def __rsub__(self, other):
  415. if isinstance(other, number_types):
  416. return as_number(other) - self
  417. return NotImplemented
  418. def __mul__(self, other):
  419. other = as_expr(other)
  420. if isinstance(other, Expr):
  421. if self.op is other.op:
  422. if self.op in (Op.INTEGER, Op.REAL):
  423. return as_number(self.data[0] * other.data[0],
  424. max(self.data[1], other.data[1]))
  425. elif self.op is Op.COMPLEX:
  426. r1, i1 = self.data
  427. r2, i2 = other.data
  428. return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1)
  429. if self.op is Op.FACTORS:
  430. r = Expr(self.op, dict(self.data))
  431. for k, v in other.data.items():
  432. _pairs_add(r.data, k, v)
  433. return normalize(r)
  434. elif self.op is Op.TERMS:
  435. r = Expr(self.op, {})
  436. for t1, c1 in self.data.items():
  437. for t2, c2 in other.data.items():
  438. _pairs_add(r.data, t1 * t2, c1 * c2)
  439. return normalize(r)
  440. if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
  441. return self * as_complex(other)
  442. elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL):
  443. return as_complex(self) * other
  444. elif self.op is Op.REAL and other.op is Op.INTEGER:
  445. return self * as_real(other, kind=self.data[1])
  446. elif self.op is Op.INTEGER and other.op is Op.REAL:
  447. return as_real(self, kind=other.data[1]) * other
  448. if self.op is Op.TERMS:
  449. return self * as_terms(other)
  450. elif other.op is Op.TERMS:
  451. return as_terms(self) * other
  452. return as_factors(self) * as_factors(other)
  453. return NotImplemented
  454. def __rmul__(self, other):
  455. if isinstance(other, number_types):
  456. return as_number(other) * self
  457. return NotImplemented
  458. def __pow__(self, other):
  459. other = as_expr(other)
  460. if isinstance(other, Expr):
  461. if other.op is Op.INTEGER:
  462. exponent = other.data[0]
  463. # TODO: other kind not used
  464. if exponent == 0:
  465. return as_number(1)
  466. if exponent == 1:
  467. return self
  468. if exponent > 0:
  469. if self.op is Op.FACTORS:
  470. r = Expr(self.op, {})
  471. for k, v in self.data.items():
  472. r.data[k] = v * exponent
  473. return normalize(r)
  474. return self * (self ** (exponent - 1))
  475. elif exponent != -1:
  476. return (self ** (-exponent)) ** -1
  477. return Expr(Op.FACTORS, {self: exponent})
  478. return as_apply(ArithOp.POW, self, other)
  479. return NotImplemented
  480. def __truediv__(self, other):
  481. other = as_expr(other)
  482. if isinstance(other, Expr):
  483. # Fortran / is different from Python /:
  484. # - `/` is a truncate operation for integer operands
  485. return normalize(as_apply(ArithOp.DIV, self, other))
  486. return NotImplemented
  487. def __rtruediv__(self, other):
  488. other = as_expr(other)
  489. if isinstance(other, Expr):
  490. return other / self
  491. return NotImplemented
  492. def __floordiv__(self, other):
  493. other = as_expr(other)
  494. if isinstance(other, Expr):
  495. # Fortran // is different from Python //:
  496. # - `//` is a concatenate operation for string operands
  497. return normalize(Expr(Op.CONCAT, (self, other)))
  498. return NotImplemented
  499. def __rfloordiv__(self, other):
  500. other = as_expr(other)
  501. if isinstance(other, Expr):
  502. return other // self
  503. return NotImplemented
  504. def __call__(self, *args, **kwargs):
  505. # In Fortran, parenthesis () are use for both function call as
  506. # well as indexing operations.
  507. #
  508. # TODO: implement a method for deciding when __call__ should
  509. # return an INDEXING expression.
  510. return as_apply(self, *map(as_expr, args),
  511. **dict((k, as_expr(v)) for k, v in kwargs.items()))
  512. def __getitem__(self, index):
  513. # Provided to support C indexing operations that .pyf files
  514. # may contain.
  515. index = as_expr(index)
  516. if not isinstance(index, tuple):
  517. index = index,
  518. if len(index) > 1:
  519. ewarn(f'C-index should be a single expression but got `{index}`')
  520. return Expr(Op.INDEXING, (self,) + index)
  521. def substitute(self, symbols_map):
  522. """Recursively substitute symbols with values in symbols map.
  523. Symbols map is a dictionary of symbol-expression pairs.
  524. """
  525. if self.op is Op.SYMBOL:
  526. value = symbols_map.get(self)
  527. if value is None:
  528. return self
  529. m = re.match(r'\A(@__f2py_PARENTHESIS_(\w+)_\d+@)\Z', self.data)
  530. if m:
  531. # complement to fromstring method
  532. items, paren = m.groups()
  533. if paren in ['ROUNDDIV', 'SQUARE']:
  534. return as_array(value)
  535. assert paren == 'ROUND', (paren, value)
  536. return value
  537. if self.op in (Op.INTEGER, Op.REAL, Op.STRING):
  538. return self
  539. if self.op in (Op.ARRAY, Op.COMPLEX):
  540. return Expr(self.op, tuple(item.substitute(symbols_map)
  541. for item in self.data))
  542. if self.op is Op.CONCAT:
  543. return normalize(Expr(self.op, tuple(item.substitute(symbols_map)
  544. for item in self.data)))
  545. if self.op is Op.TERMS:
  546. r = None
  547. for term, coeff in self.data.items():
  548. if r is None:
  549. r = term.substitute(symbols_map) * coeff
  550. else:
  551. r += term.substitute(symbols_map) * coeff
  552. if r is None:
  553. ewarn('substitute: empty TERMS expression interpreted as'
  554. ' int-literal 0')
  555. return as_number(0)
  556. return r
  557. if self.op is Op.FACTORS:
  558. r = None
  559. for base, exponent in self.data.items():
  560. if r is None:
  561. r = base.substitute(symbols_map) ** exponent
  562. else:
  563. r *= base.substitute(symbols_map) ** exponent
  564. if r is None:
  565. ewarn('substitute: empty FACTORS expression interpreted'
  566. ' as int-literal 1')
  567. return as_number(1)
  568. return r
  569. if self.op is Op.APPLY:
  570. target, args, kwargs = self.data
  571. if isinstance(target, Expr):
  572. target = target.substitute(symbols_map)
  573. args = tuple(a.substitute(symbols_map) for a in args)
  574. kwargs = dict((k, v.substitute(symbols_map))
  575. for k, v in kwargs.items())
  576. return normalize(Expr(self.op, (target, args, kwargs)))
  577. if self.op is Op.INDEXING:
  578. func = self.data[0]
  579. if isinstance(func, Expr):
  580. func = func.substitute(symbols_map)
  581. args = tuple(a.substitute(symbols_map) for a in self.data[1:])
  582. return normalize(Expr(self.op, (func,) + args))
  583. if self.op is Op.TERNARY:
  584. operands = tuple(a.substitute(symbols_map) for a in self.data)
  585. return normalize(Expr(self.op, operands))
  586. if self.op in (Op.REF, Op.DEREF):
  587. return normalize(Expr(self.op, self.data.substitute(symbols_map)))
  588. if self.op is Op.RELATIONAL:
  589. rop, left, right = self.data
  590. left = left.substitute(symbols_map)
  591. right = right.substitute(symbols_map)
  592. return normalize(Expr(self.op, (rop, left, right)))
  593. raise NotImplementedError(f'substitute method for {self.op}: {self!r}')
  594. def traverse(self, visit, *args, **kwargs):
  595. """Traverse expression tree with visit function.
  596. The visit function is applied to an expression with given args
  597. and kwargs.
  598. Traverse call returns an expression returned by visit when not
  599. None, otherwise return a new normalized expression with
  600. traverse-visit sub-expressions.
  601. """
  602. result = visit(self, *args, **kwargs)
  603. if result is not None:
  604. return result
  605. if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL):
  606. return self
  607. elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY):
  608. return normalize(Expr(self.op, tuple(
  609. item.traverse(visit, *args, **kwargs)
  610. for item in self.data)))
  611. elif self.op in (Op.TERMS, Op.FACTORS):
  612. data = {}
  613. for k, v in self.data.items():
  614. k = k.traverse(visit, *args, **kwargs)
  615. v = (v.traverse(visit, *args, **kwargs)
  616. if isinstance(v, Expr) else v)
  617. if k in data:
  618. v = data[k] + v
  619. data[k] = v
  620. return normalize(Expr(self.op, data))
  621. elif self.op is Op.APPLY:
  622. obj = self.data[0]
  623. func = (obj.traverse(visit, *args, **kwargs)
  624. if isinstance(obj, Expr) else obj)
  625. operands = tuple(operand.traverse(visit, *args, **kwargs)
  626. for operand in self.data[1])
  627. kwoperands = dict((k, v.traverse(visit, *args, **kwargs))
  628. for k, v in self.data[2].items())
  629. return normalize(Expr(self.op, (func, operands, kwoperands)))
  630. elif self.op is Op.INDEXING:
  631. obj = self.data[0]
  632. obj = (obj.traverse(visit, *args, **kwargs)
  633. if isinstance(obj, Expr) else obj)
  634. indices = tuple(index.traverse(visit, *args, **kwargs)
  635. for index in self.data[1:])
  636. return normalize(Expr(self.op, (obj,) + indices))
  637. elif self.op in (Op.REF, Op.DEREF):
  638. return normalize(Expr(self.op,
  639. self.data.traverse(visit, *args, **kwargs)))
  640. elif self.op is Op.RELATIONAL:
  641. rop, left, right = self.data
  642. left = left.traverse(visit, *args, **kwargs)
  643. right = right.traverse(visit, *args, **kwargs)
  644. return normalize(Expr(self.op, (rop, left, right)))
  645. raise NotImplementedError(f'traverse method for {self.op}')
  646. def contains(self, other):
  647. """Check if self contains other.
  648. """
  649. found = []
  650. def visit(expr, found=found):
  651. if found:
  652. return expr
  653. elif expr == other:
  654. found.append(1)
  655. return expr
  656. self.traverse(visit)
  657. return len(found) != 0
  658. def symbols(self):
  659. """Return a set of symbols contained in self.
  660. """
  661. found = set()
  662. def visit(expr, found=found):
  663. if expr.op is Op.SYMBOL:
  664. found.add(expr)
  665. self.traverse(visit)
  666. return found
  667. def polynomial_atoms(self):
  668. """Return a set of expressions used as atoms in polynomial self.
  669. """
  670. found = set()
  671. def visit(expr, found=found):
  672. if expr.op is Op.FACTORS:
  673. for b in expr.data:
  674. b.traverse(visit)
  675. return expr
  676. if expr.op in (Op.TERMS, Op.COMPLEX):
  677. return
  678. if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp):
  679. if expr.data[0] is ArithOp.POW:
  680. expr.data[1][0].traverse(visit)
  681. return expr
  682. return
  683. if expr.op in (Op.INTEGER, Op.REAL):
  684. return expr
  685. found.add(expr)
  686. if expr.op in (Op.INDEXING, Op.APPLY):
  687. return expr
  688. self.traverse(visit)
  689. return found
  690. def linear_solve(self, symbol):
  691. """Return a, b such that a * symbol + b == self.
  692. If self is not linear with respect to symbol, raise RuntimeError.
  693. """
  694. b = self.substitute({symbol: as_number(0)})
  695. ax = self - b
  696. a = ax.substitute({symbol: as_number(1)})
  697. zero, _ = as_numer_denom(a * symbol - ax)
  698. if zero != as_number(0):
  699. raise RuntimeError(f'not a {symbol}-linear equation:'
  700. f' {a} * {symbol} + {b} == {self}')
  701. return a, b
  702. def normalize(obj):
  703. """Normalize Expr and apply basic evaluation methods.
  704. """
  705. if not isinstance(obj, Expr):
  706. return obj
  707. if obj.op is Op.TERMS:
  708. d = {}
  709. for t, c in obj.data.items():
  710. if c == 0:
  711. continue
  712. if t.op is Op.COMPLEX and c != 1:
  713. t = t * c
  714. c = 1
  715. if t.op is Op.TERMS:
  716. for t1, c1 in t.data.items():
  717. _pairs_add(d, t1, c1 * c)
  718. else:
  719. _pairs_add(d, t, c)
  720. if len(d) == 0:
  721. # TODO: determine correct kind
  722. return as_number(0)
  723. elif len(d) == 1:
  724. (t, c), = d.items()
  725. if c == 1:
  726. return t
  727. return Expr(Op.TERMS, d)
  728. if obj.op is Op.FACTORS:
  729. coeff = 1
  730. d = {}
  731. for b, e in obj.data.items():
  732. if e == 0:
  733. continue
  734. if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1:
  735. # expand integer powers of sums
  736. b = b * (b ** (e - 1))
  737. e = 1
  738. if b.op in (Op.INTEGER, Op.REAL):
  739. if e == 1:
  740. coeff *= b.data[0]
  741. elif e > 0:
  742. coeff *= b.data[0] ** e
  743. else:
  744. _pairs_add(d, b, e)
  745. elif b.op is Op.FACTORS:
  746. if e > 0 and isinstance(e, integer_types):
  747. for b1, e1 in b.data.items():
  748. _pairs_add(d, b1, e1 * e)
  749. else:
  750. _pairs_add(d, b, e)
  751. else:
  752. _pairs_add(d, b, e)
  753. if len(d) == 0 or coeff == 0:
  754. # TODO: determine correct kind
  755. assert isinstance(coeff, number_types)
  756. return as_number(coeff)
  757. elif len(d) == 1:
  758. (b, e), = d.items()
  759. if e == 1:
  760. t = b
  761. else:
  762. t = Expr(Op.FACTORS, d)
  763. if coeff == 1:
  764. return t
  765. return Expr(Op.TERMS, {t: coeff})
  766. elif coeff == 1:
  767. return Expr(Op.FACTORS, d)
  768. else:
  769. return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff})
  770. if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
  771. dividend, divisor = obj.data[1]
  772. t1, c1 = as_term_coeff(dividend)
  773. t2, c2 = as_term_coeff(divisor)
  774. if isinstance(c1, integer_types) and isinstance(c2, integer_types):
  775. g = gcd(c1, c2)
  776. c1, c2 = c1//g, c2//g
  777. else:
  778. c1, c2 = c1/c2, 1
  779. if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV:
  780. numer = t1.data[1][0] * c1
  781. denom = t1.data[1][1] * t2 * c2
  782. return as_apply(ArithOp.DIV, numer, denom)
  783. if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV:
  784. numer = t2.data[1][1] * t1 * c1
  785. denom = t2.data[1][0] * c2
  786. return as_apply(ArithOp.DIV, numer, denom)
  787. d = dict(as_factors(t1).data)
  788. for b, e in as_factors(t2).data.items():
  789. _pairs_add(d, b, -e)
  790. numer, denom = {}, {}
  791. for b, e in d.items():
  792. if e > 0:
  793. numer[b] = e
  794. else:
  795. denom[b] = -e
  796. numer = normalize(Expr(Op.FACTORS, numer)) * c1
  797. denom = normalize(Expr(Op.FACTORS, denom)) * c2
  798. if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1:
  799. # TODO: denom kind not used
  800. return numer
  801. return as_apply(ArithOp.DIV, numer, denom)
  802. if obj.op is Op.CONCAT:
  803. lst = [obj.data[0]]
  804. for s in obj.data[1:]:
  805. last = lst[-1]
  806. if (
  807. last.op is Op.STRING
  808. and s.op is Op.STRING
  809. and last.data[0][0] in '"\''
  810. and s.data[0][0] == last.data[0][-1]
  811. ):
  812. new_last = as_string(last.data[0][:-1] + s.data[0][1:],
  813. max(last.data[1], s.data[1]))
  814. lst[-1] = new_last
  815. else:
  816. lst.append(s)
  817. if len(lst) == 1:
  818. return lst[0]
  819. return Expr(Op.CONCAT, tuple(lst))
  820. if obj.op is Op.TERNARY:
  821. cond, expr1, expr2 = map(normalize, obj.data)
  822. if cond.op is Op.INTEGER:
  823. return expr1 if cond.data[0] else expr2
  824. return Expr(Op.TERNARY, (cond, expr1, expr2))
  825. return obj
  826. def as_expr(obj):
  827. """Convert non-Expr objects to Expr objects.
  828. """
  829. if isinstance(obj, complex):
  830. return as_complex(obj.real, obj.imag)
  831. if isinstance(obj, number_types):
  832. return as_number(obj)
  833. if isinstance(obj, str):
  834. # STRING expression holds string with boundary quotes, hence
  835. # applying repr:
  836. return as_string(repr(obj))
  837. if isinstance(obj, tuple):
  838. return tuple(map(as_expr, obj))
  839. return obj
  840. def as_symbol(obj):
  841. """Return object as SYMBOL expression (variable or unparsed expression).
  842. """
  843. return Expr(Op.SYMBOL, obj)
  844. def as_number(obj, kind=4):
  845. """Return object as INTEGER or REAL constant.
  846. """
  847. if isinstance(obj, int):
  848. return Expr(Op.INTEGER, (obj, kind))
  849. if isinstance(obj, float):
  850. return Expr(Op.REAL, (obj, kind))
  851. if isinstance(obj, Expr):
  852. if obj.op in (Op.INTEGER, Op.REAL):
  853. return obj
  854. raise OpError(f'cannot convert {obj} to INTEGER or REAL constant')
  855. def as_integer(obj, kind=4):
  856. """Return object as INTEGER constant.
  857. """
  858. if isinstance(obj, int):
  859. return Expr(Op.INTEGER, (obj, kind))
  860. if isinstance(obj, Expr):
  861. if obj.op is Op.INTEGER:
  862. return obj
  863. raise OpError(f'cannot convert {obj} to INTEGER constant')
  864. def as_real(obj, kind=4):
  865. """Return object as REAL constant.
  866. """
  867. if isinstance(obj, int):
  868. return Expr(Op.REAL, (float(obj), kind))
  869. if isinstance(obj, float):
  870. return Expr(Op.REAL, (obj, kind))
  871. if isinstance(obj, Expr):
  872. if obj.op is Op.REAL:
  873. return obj
  874. elif obj.op is Op.INTEGER:
  875. return Expr(Op.REAL, (float(obj.data[0]), kind))
  876. raise OpError(f'cannot convert {obj} to REAL constant')
  877. def as_string(obj, kind=1):
  878. """Return object as STRING expression (string literal constant).
  879. """
  880. return Expr(Op.STRING, (obj, kind))
  881. def as_array(obj):
  882. """Return object as ARRAY expression (array constant).
  883. """
  884. if isinstance(obj, Expr):
  885. obj = obj,
  886. return Expr(Op.ARRAY, obj)
  887. def as_complex(real, imag=0):
  888. """Return object as COMPLEX expression (complex literal constant).
  889. """
  890. return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag)))
  891. def as_apply(func, *args, **kwargs):
  892. """Return object as APPLY expression (function call, constructor, etc.)
  893. """
  894. return Expr(Op.APPLY,
  895. (func, tuple(map(as_expr, args)),
  896. dict((k, as_expr(v)) for k, v in kwargs.items())))
  897. def as_ternary(cond, expr1, expr2):
  898. """Return object as TERNARY expression (cond?expr1:expr2).
  899. """
  900. return Expr(Op.TERNARY, (cond, expr1, expr2))
  901. def as_ref(expr):
  902. """Return object as referencing expression.
  903. """
  904. return Expr(Op.REF, expr)
  905. def as_deref(expr):
  906. """Return object as dereferencing expression.
  907. """
  908. return Expr(Op.DEREF, expr)
  909. def as_eq(left, right):
  910. return Expr(Op.RELATIONAL, (RelOp.EQ, left, right))
  911. def as_ne(left, right):
  912. return Expr(Op.RELATIONAL, (RelOp.NE, left, right))
  913. def as_lt(left, right):
  914. return Expr(Op.RELATIONAL, (RelOp.LT, left, right))
  915. def as_le(left, right):
  916. return Expr(Op.RELATIONAL, (RelOp.LE, left, right))
  917. def as_gt(left, right):
  918. return Expr(Op.RELATIONAL, (RelOp.GT, left, right))
  919. def as_ge(left, right):
  920. return Expr(Op.RELATIONAL, (RelOp.GE, left, right))
  921. def as_terms(obj):
  922. """Return expression as TERMS expression.
  923. """
  924. if isinstance(obj, Expr):
  925. obj = normalize(obj)
  926. if obj.op is Op.TERMS:
  927. return obj
  928. if obj.op is Op.INTEGER:
  929. return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]})
  930. if obj.op is Op.REAL:
  931. return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]})
  932. return Expr(Op.TERMS, {obj: 1})
  933. raise OpError(f'cannot convert {type(obj)} to terms Expr')
  934. def as_factors(obj):
  935. """Return expression as FACTORS expression.
  936. """
  937. if isinstance(obj, Expr):
  938. obj = normalize(obj)
  939. if obj.op is Op.FACTORS:
  940. return obj
  941. if obj.op is Op.TERMS:
  942. if len(obj.data) == 1:
  943. (term, coeff), = obj.data.items()
  944. if coeff == 1:
  945. return Expr(Op.FACTORS, {term: 1})
  946. return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1})
  947. if (obj.op is Op.APPLY
  948. and obj.data[0] is ArithOp.DIV
  949. and not obj.data[2]):
  950. return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1})
  951. return Expr(Op.FACTORS, {obj: 1})
  952. raise OpError(f'cannot convert {type(obj)} to terms Expr')
  953. def as_term_coeff(obj):
  954. """Return expression as term-coefficient pair.
  955. """
  956. if isinstance(obj, Expr):
  957. obj = normalize(obj)
  958. if obj.op is Op.INTEGER:
  959. return as_integer(1, obj.data[1]), obj.data[0]
  960. if obj.op is Op.REAL:
  961. return as_real(1, obj.data[1]), obj.data[0]
  962. if obj.op is Op.TERMS:
  963. if len(obj.data) == 1:
  964. (term, coeff), = obj.data.items()
  965. return term, coeff
  966. # TODO: find common divisor of coefficients
  967. if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
  968. t, c = as_term_coeff(obj.data[1][0])
  969. return as_apply(ArithOp.DIV, t, obj.data[1][1]), c
  970. return obj, 1
  971. raise OpError(f'cannot convert {type(obj)} to term and coeff')
  972. def as_numer_denom(obj):
  973. """Return expression as numer-denom pair.
  974. """
  975. if isinstance(obj, Expr):
  976. obj = normalize(obj)
  977. if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL,
  978. Op.INDEXING, Op.TERNARY):
  979. return obj, as_number(1)
  980. elif obj.op is Op.APPLY:
  981. if obj.data[0] is ArithOp.DIV and not obj.data[2]:
  982. numers, denoms = map(as_numer_denom, obj.data[1])
  983. return numers[0] * denoms[1], numers[1] * denoms[0]
  984. return obj, as_number(1)
  985. elif obj.op is Op.TERMS:
  986. numers, denoms = [], []
  987. for term, coeff in obj.data.items():
  988. n, d = as_numer_denom(term)
  989. n = n * coeff
  990. numers.append(n)
  991. denoms.append(d)
  992. numer, denom = as_number(0), as_number(1)
  993. for i in range(len(numers)):
  994. n = numers[i]
  995. for j in range(len(numers)):
  996. if i != j:
  997. n *= denoms[j]
  998. numer += n
  999. denom *= denoms[i]
  1000. if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0:
  1001. numer, denom = -numer, -denom
  1002. return numer, denom
  1003. elif obj.op is Op.FACTORS:
  1004. numer, denom = as_number(1), as_number(1)
  1005. for b, e in obj.data.items():
  1006. bnumer, bdenom = as_numer_denom(b)
  1007. if e > 0:
  1008. numer *= bnumer ** e
  1009. denom *= bdenom ** e
  1010. elif e < 0:
  1011. numer *= bdenom ** (-e)
  1012. denom *= bnumer ** (-e)
  1013. return numer, denom
  1014. raise OpError(f'cannot convert {type(obj)} to numer and denom')
  1015. def _counter():
  1016. # Used internally to generate unique dummy symbols
  1017. counter = 0
  1018. while True:
  1019. counter += 1
  1020. yield counter
  1021. COUNTER = _counter()
  1022. def eliminate_quotes(s):
  1023. """Replace quoted substrings of input string.
  1024. Return a new string and a mapping of replacements.
  1025. """
  1026. d = {}
  1027. def repl(m):
  1028. kind, value = m.groups()[:2]
  1029. if kind:
  1030. # remove trailing underscore
  1031. kind = kind[:-1]
  1032. p = {"'": "SINGLE", '"': "DOUBLE"}[value[0]]
  1033. k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@'
  1034. d[k] = value
  1035. return k
  1036. new_s = re.sub(r'({kind}_|)({single_quoted}|{double_quoted})'.format(
  1037. kind=r'\w[\w\d_]*',
  1038. single_quoted=r"('([^'\\]|(\\.))*')",
  1039. double_quoted=r'("([^"\\]|(\\.))*")'),
  1040. repl, s)
  1041. assert '"' not in new_s
  1042. assert "'" not in new_s
  1043. return new_s, d
  1044. def insert_quotes(s, d):
  1045. """Inverse of eliminate_quotes.
  1046. """
  1047. for k, v in d.items():
  1048. kind = k[:k.find('@')]
  1049. if kind:
  1050. kind += '_'
  1051. s = s.replace(k, kind + v)
  1052. return s
  1053. def replace_parenthesis(s):
  1054. """Replace substrings of input that are enclosed in parenthesis.
  1055. Return a new string and a mapping of replacements.
  1056. """
  1057. # Find a parenthesis pair that appears first.
  1058. # Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`.
  1059. # We don't handle `/` deliminator because it is not a part of an
  1060. # expression.
  1061. left, right = None, None
  1062. mn_i = len(s)
  1063. for left_, right_ in (('(/', '/)'),
  1064. '()',
  1065. '{}', # to support C literal structs
  1066. '[]'):
  1067. i = s.find(left_)
  1068. if i == -1:
  1069. continue
  1070. if i < mn_i:
  1071. mn_i = i
  1072. left, right = left_, right_
  1073. if left is None:
  1074. return s, {}
  1075. i = mn_i
  1076. j = s.find(right, i)
  1077. while s.count(left, i + 1, j) != s.count(right, i + 1, j):
  1078. j = s.find(right, j + 1)
  1079. if j == -1:
  1080. raise ValueError(f'Mismatch of {left+right} parenthesis in {s!r}')
  1081. p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left]
  1082. k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@'
  1083. v = s[i+len(left):j]
  1084. r, d = replace_parenthesis(s[j+len(right):])
  1085. d[k] = v
  1086. return s[:i] + k + r, d
  1087. def _get_parenthesis_kind(s):
  1088. assert s.startswith('@__f2py_PARENTHESIS_'), s
  1089. return s.split('_')[4]
  1090. def unreplace_parenthesis(s, d):
  1091. """Inverse of replace_parenthesis.
  1092. """
  1093. for k, v in d.items():
  1094. p = _get_parenthesis_kind(k)
  1095. left = dict(ROUND='(', SQUARE='[', CURLY='{', ROUNDDIV='(/')[p]
  1096. right = dict(ROUND=')', SQUARE=']', CURLY='}', ROUNDDIV='/)')[p]
  1097. s = s.replace(k, left + v + right)
  1098. return s
  1099. def fromstring(s, language=Language.C):
  1100. """Create an expression from a string.
  1101. This is a "lazy" parser, that is, only arithmetic operations are
  1102. resolved, non-arithmetic operations are treated as symbols.
  1103. """
  1104. r = _FromStringWorker(language=language).parse(s)
  1105. if isinstance(r, Expr):
  1106. return r
  1107. raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`')
  1108. class _Pair:
  1109. # Internal class to represent a pair of expressions
  1110. def __init__(self, left, right):
  1111. self.left = left
  1112. self.right = right
  1113. def substitute(self, symbols_map):
  1114. left, right = self.left, self.right
  1115. if isinstance(left, Expr):
  1116. left = left.substitute(symbols_map)
  1117. if isinstance(right, Expr):
  1118. right = right.substitute(symbols_map)
  1119. return _Pair(left, right)
  1120. def __repr__(self):
  1121. return f'{type(self).__name__}({self.left}, {self.right})'
  1122. class _FromStringWorker:
  1123. def __init__(self, language=Language.C):
  1124. self.original = None
  1125. self.quotes_map = None
  1126. self.language = language
  1127. def finalize_string(self, s):
  1128. return insert_quotes(s, self.quotes_map)
  1129. def parse(self, inp):
  1130. self.original = inp
  1131. unquoted, self.quotes_map = eliminate_quotes(inp)
  1132. return self.process(unquoted)
  1133. def process(self, s, context='expr'):
  1134. """Parse string within the given context.
  1135. The context may define the result in case of ambiguous
  1136. expressions. For instance, consider expressions `f(x, y)` and
  1137. `(x, y) + (a, b)` where `f` is a function and pair `(x, y)`
  1138. denotes complex number. Specifying context as "args" or
  1139. "expr", the subexpression `(x, y)` will be parse to an
  1140. argument list or to a complex number, respectively.
  1141. """
  1142. if isinstance(s, (list, tuple)):
  1143. return type(s)(self.process(s_, context) for s_ in s)
  1144. assert isinstance(s, str), (type(s), s)
  1145. # replace subexpressions in parenthesis with f2py @-names
  1146. r, raw_symbols_map = replace_parenthesis(s)
  1147. r = r.strip()
  1148. def restore(r):
  1149. # restores subexpressions marked with f2py @-names
  1150. if isinstance(r, (list, tuple)):
  1151. return type(r)(map(restore, r))
  1152. return unreplace_parenthesis(r, raw_symbols_map)
  1153. # comma-separated tuple
  1154. if ',' in r:
  1155. operands = restore(r.split(','))
  1156. if context == 'args':
  1157. return tuple(self.process(operands))
  1158. if context == 'expr':
  1159. if len(operands) == 2:
  1160. # complex number literal
  1161. return as_complex(*self.process(operands))
  1162. raise NotImplementedError(
  1163. f'parsing comma-separated list (context={context}): {r}')
  1164. # ternary operation
  1165. m = re.match(r'\A([^?]+)[?]([^:]+)[:](.+)\Z', r)
  1166. if m:
  1167. assert context == 'expr', context
  1168. oper, expr1, expr2 = restore(m.groups())
  1169. oper = self.process(oper)
  1170. expr1 = self.process(expr1)
  1171. expr2 = self.process(expr2)
  1172. return as_ternary(oper, expr1, expr2)
  1173. # relational expression
  1174. if self.language is Language.Fortran:
  1175. m = re.match(
  1176. r'\A(.+)\s*[.](eq|ne|lt|le|gt|ge)[.]\s*(.+)\Z', r, re.I)
  1177. else:
  1178. m = re.match(
  1179. r'\A(.+)\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\s*(.+)\Z', r)
  1180. if m:
  1181. left, rop, right = m.groups()
  1182. if self.language is Language.Fortran:
  1183. rop = '.' + rop + '.'
  1184. left, right = self.process(restore((left, right)))
  1185. rop = RelOp.fromstring(rop, language=self.language)
  1186. return Expr(Op.RELATIONAL, (rop, left, right))
  1187. # keyword argument
  1188. m = re.match(r'\A(\w[\w\d_]*)\s*[=](.*)\Z', r)
  1189. if m:
  1190. keyname, value = m.groups()
  1191. value = restore(value)
  1192. return _Pair(keyname, self.process(value))
  1193. # addition/subtraction operations
  1194. operands = re.split(r'((?<!\d[edED])[+-])', r)
  1195. if len(operands) > 1:
  1196. result = self.process(restore(operands[0] or '0'))
  1197. for op, operand in zip(operands[1::2], operands[2::2]):
  1198. operand = self.process(restore(operand))
  1199. op = op.strip()
  1200. if op == '+':
  1201. result += operand
  1202. else:
  1203. assert op == '-'
  1204. result -= operand
  1205. return result
  1206. # string concatenate operation
  1207. if self.language is Language.Fortran and '//' in r:
  1208. operands = restore(r.split('//'))
  1209. return Expr(Op.CONCAT,
  1210. tuple(self.process(operands)))
  1211. # multiplication/division operations
  1212. operands = re.split(r'(?<=[@\w\d_])\s*([*]|/)',
  1213. (r if self.language is Language.C
  1214. else r.replace('**', '@__f2py_DOUBLE_STAR@')))
  1215. if len(operands) > 1:
  1216. operands = restore(operands)
  1217. if self.language is not Language.C:
  1218. operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**')
  1219. for operand in operands]
  1220. # Expression is an arithmetic product
  1221. result = self.process(operands[0])
  1222. for op, operand in zip(operands[1::2], operands[2::2]):
  1223. operand = self.process(operand)
  1224. op = op.strip()
  1225. if op == '*':
  1226. result *= operand
  1227. else:
  1228. assert op == '/'
  1229. result /= operand
  1230. return result
  1231. # referencing/dereferencing
  1232. if r.startswith(('*', '&')):
  1233. op = {'*': Op.DEREF, '&': Op.REF}[r[0]]
  1234. operand = self.process(restore(r[1:]))
  1235. return Expr(op, operand)
  1236. # exponentiation operations
  1237. if self.language is not Language.C and '**' in r:
  1238. operands = list(reversed(restore(r.split('**'))))
  1239. result = self.process(operands[0])
  1240. for operand in operands[1:]:
  1241. operand = self.process(operand)
  1242. result = operand ** result
  1243. return result
  1244. # int-literal-constant
  1245. m = re.match(r'\A({digit_string})({kind}|)\Z'.format(
  1246. digit_string=r'\d+',
  1247. kind=r'_(\d+|\w[\w\d_]*)'), r)
  1248. if m:
  1249. value, _, kind = m.groups()
  1250. if kind and kind.isdigit():
  1251. kind = int(kind)
  1252. return as_integer(int(value), kind or 4)
  1253. # real-literal-constant
  1254. m = re.match(r'\A({significant}({exponent}|)|\d+{exponent})({kind}|)\Z'
  1255. .format(
  1256. significant=r'[.]\d+|\d+[.]\d*',
  1257. exponent=r'[edED][+-]?\d+',
  1258. kind=r'_(\d+|\w[\w\d_]*)'), r)
  1259. if m:
  1260. value, _, _, kind = m.groups()
  1261. if kind and kind.isdigit():
  1262. kind = int(kind)
  1263. value = value.lower()
  1264. if 'd' in value:
  1265. return as_real(float(value.replace('d', 'e')), kind or 8)
  1266. return as_real(float(value), kind or 4)
  1267. # string-literal-constant with kind parameter specification
  1268. if r in self.quotes_map:
  1269. kind = r[:r.find('@')]
  1270. return as_string(self.quotes_map[r], kind or 1)
  1271. # array constructor or literal complex constant or
  1272. # parenthesized expression
  1273. if r in raw_symbols_map:
  1274. paren = _get_parenthesis_kind(r)
  1275. items = self.process(restore(raw_symbols_map[r]),
  1276. 'expr' if paren == 'ROUND' else 'args')
  1277. if paren == 'ROUND':
  1278. if isinstance(items, Expr):
  1279. return items
  1280. if paren in ['ROUNDDIV', 'SQUARE']:
  1281. # Expression is a array constructor
  1282. if isinstance(items, Expr):
  1283. items = (items,)
  1284. return as_array(items)
  1285. # function call/indexing
  1286. m = re.match(r'\A(.+)\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\d+@)\Z',
  1287. r)
  1288. if m:
  1289. target, args, paren = m.groups()
  1290. target = self.process(restore(target))
  1291. args = self.process(restore(args)[1:-1], 'args')
  1292. if not isinstance(args, tuple):
  1293. args = args,
  1294. if paren == 'ROUND':
  1295. kwargs = dict((a.left, a.right) for a in args
  1296. if isinstance(a, _Pair))
  1297. args = tuple(a for a in args if not isinstance(a, _Pair))
  1298. # Warning: this could also be Fortran indexing operation..
  1299. return as_apply(target, *args, **kwargs)
  1300. else:
  1301. # Expression is a C/Python indexing operation
  1302. # (e.g. used in .pyf files)
  1303. assert paren == 'SQUARE'
  1304. return target[args]
  1305. # Fortran standard conforming identifier
  1306. m = re.match(r'\A\w[\w\d_]*\Z', r)
  1307. if m:
  1308. return as_symbol(r)
  1309. # fall-back to symbol
  1310. r = self.finalize_string(restore(r))
  1311. ewarn(
  1312. f'fromstring: treating {r!r} as symbol (original={self.original})')
  1313. return as_symbol(r)