symbolic.py 52 KB

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