stack.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #!/usr/bin/env python3
  2. #
  3. # Script to find stack usage at the function level. Will detect recursion and
  4. # report as infinite stack usage.
  5. #
  6. # Example:
  7. # ./scripts/stack.py lfs.ci lfs_util.ci -Slimit
  8. #
  9. # Copyright (c) 2022, The littlefs authors.
  10. # SPDX-License-Identifier: BSD-3-Clause
  11. #
  12. import collections as co
  13. import csv
  14. import itertools as it
  15. import math as m
  16. import os
  17. import re
  18. # integer fields
  19. class Int(co.namedtuple('Int', 'x')):
  20. __slots__ = ()
  21. def __new__(cls, x=0):
  22. if isinstance(x, Int):
  23. return x
  24. if isinstance(x, str):
  25. try:
  26. x = int(x, 0)
  27. except ValueError:
  28. # also accept +-∞ and +-inf
  29. if re.match('^\s*\+?\s*(?:∞|inf)\s*$', x):
  30. x = m.inf
  31. elif re.match('^\s*-\s*(?:∞|inf)\s*$', x):
  32. x = -m.inf
  33. else:
  34. raise
  35. assert isinstance(x, int) or m.isinf(x), x
  36. return super().__new__(cls, x)
  37. def __str__(self):
  38. if self.x == m.inf:
  39. return '∞'
  40. elif self.x == -m.inf:
  41. return '-∞'
  42. else:
  43. return str(self.x)
  44. def __int__(self):
  45. assert not m.isinf(self.x)
  46. return self.x
  47. def __float__(self):
  48. return float(self.x)
  49. none = '%7s' % '-'
  50. def table(self):
  51. return '%7s' % (self,)
  52. diff_none = '%7s' % '-'
  53. diff_table = table
  54. def diff_diff(self, other):
  55. new = self.x if self else 0
  56. old = other.x if other else 0
  57. diff = new - old
  58. if diff == +m.inf:
  59. return '%7s' % '+∞'
  60. elif diff == -m.inf:
  61. return '%7s' % '-∞'
  62. else:
  63. return '%+7d' % diff
  64. def ratio(self, other):
  65. new = self.x if self else 0
  66. old = other.x if other else 0
  67. if m.isinf(new) and m.isinf(old):
  68. return 0.0
  69. elif m.isinf(new):
  70. return +m.inf
  71. elif m.isinf(old):
  72. return -m.inf
  73. elif not old and not new:
  74. return 0.0
  75. elif not old:
  76. return 1.0
  77. else:
  78. return (new-old) / old
  79. def __add__(self, other):
  80. return self.__class__(self.x + other.x)
  81. def __sub__(self, other):
  82. return self.__class__(self.x - other.x)
  83. def __mul__(self, other):
  84. return self.__class__(self.x * other.x)
  85. # size results
  86. class StackResult(co.namedtuple('StackResult', [
  87. 'file', 'function', 'frame', 'limit', 'children'])):
  88. _by = ['file', 'function']
  89. _fields = ['frame', 'limit']
  90. _sort = ['limit', 'frame']
  91. _types = {'frame': Int, 'limit': Int}
  92. __slots__ = ()
  93. def __new__(cls, file='', function='',
  94. frame=0, limit=0, children=set()):
  95. return super().__new__(cls, file, function,
  96. Int(frame), Int(limit),
  97. children)
  98. def __add__(self, other):
  99. return StackResult(self.file, self.function,
  100. self.frame + other.frame,
  101. max(self.limit, other.limit),
  102. self.children | other.children)
  103. def openio(path, mode='r', buffering=-1):
  104. # allow '-' for stdin/stdout
  105. if path == '-':
  106. if mode == 'r':
  107. return os.fdopen(os.dup(sys.stdin.fileno()), mode, buffering)
  108. else:
  109. return os.fdopen(os.dup(sys.stdout.fileno()), mode, buffering)
  110. else:
  111. return open(path, mode, buffering)
  112. def collect(ci_paths, *,
  113. sources=None,
  114. everything=False,
  115. **args):
  116. # parse the vcg format
  117. k_pattern = re.compile('([a-z]+)\s*:', re.DOTALL)
  118. v_pattern = re.compile('(?:"(.*?)"|([a-z]+))', re.DOTALL)
  119. def parse_vcg(rest):
  120. def parse_vcg(rest):
  121. node = []
  122. while True:
  123. rest = rest.lstrip()
  124. m_ = k_pattern.match(rest)
  125. if not m_:
  126. return (node, rest)
  127. k, rest = m_.group(1), rest[m_.end(0):]
  128. rest = rest.lstrip()
  129. if rest.startswith('{'):
  130. v, rest = parse_vcg(rest[1:])
  131. assert rest[0] == '}', "unexpected %r" % rest[0:1]
  132. rest = rest[1:]
  133. node.append((k, v))
  134. else:
  135. m_ = v_pattern.match(rest)
  136. assert m_, "unexpected %r" % rest[0:1]
  137. v, rest = m_.group(1) or m_.group(2), rest[m_.end(0):]
  138. node.append((k, v))
  139. node, rest = parse_vcg(rest)
  140. assert rest == '', "unexpected %r" % rest[0:1]
  141. return node
  142. # collect into functions
  143. callgraph = co.defaultdict(lambda: (None, None, 0, set()))
  144. f_pattern = re.compile(
  145. r'([^\\]*)\\n([^:]*)[^\\]*\\n([0-9]+) bytes \((.*)\)')
  146. for path in ci_paths:
  147. with open(path) as f:
  148. vcg = parse_vcg(f.read())
  149. for k, graph in vcg:
  150. if k != 'graph':
  151. continue
  152. for k, info in graph:
  153. if k == 'node':
  154. info = dict(info)
  155. m_ = f_pattern.match(info['label'])
  156. if m_:
  157. function, file, size, type = m_.groups()
  158. if (not args.get('quiet')
  159. and 'static' not in type
  160. and 'bounded' not in type):
  161. print("warning: "
  162. "found non-static stack for %s (%s, %s)" % (
  163. function, type, size))
  164. _, _, _, targets = callgraph[info['title']]
  165. callgraph[info['title']] = (
  166. file, function, int(size), targets)
  167. elif k == 'edge':
  168. info = dict(info)
  169. _, _, _, targets = callgraph[info['sourcename']]
  170. targets.add(info['targetname'])
  171. else:
  172. continue
  173. callgraph_ = co.defaultdict(lambda: (None, None, 0, set()))
  174. for source, (s_file, s_function, frame, targets) in callgraph.items():
  175. # discard internal functions
  176. if not everything and s_function.startswith('__'):
  177. continue
  178. # ignore filtered sources
  179. if sources is not None:
  180. if not any(
  181. os.path.abspath(s_file) == os.path.abspath(s)
  182. for s in sources):
  183. continue
  184. else:
  185. # default to only cwd
  186. if not everything and not os.path.commonpath([
  187. os.getcwd(),
  188. os.path.abspath(s_file)]) == os.getcwd():
  189. continue
  190. # smiplify path
  191. if os.path.commonpath([
  192. os.getcwd(),
  193. os.path.abspath(s_file)]) == os.getcwd():
  194. s_file = os.path.relpath(s_file)
  195. else:
  196. s_file = os.path.abspath(s_file)
  197. callgraph_[source] = (s_file, s_function, frame, targets)
  198. callgraph = callgraph_
  199. if not everything:
  200. callgraph_ = co.defaultdict(lambda: (None, None, 0, set()))
  201. for source, (s_file, s_function, frame, targets) in callgraph.items():
  202. # discard filtered sources
  203. if sources is not None and not any(
  204. os.path.abspath(s_file) == os.path.abspath(s)
  205. for s in sources):
  206. continue
  207. # discard internal functions
  208. if s_function.startswith('__'):
  209. continue
  210. callgraph_[source] = (s_file, s_function, frame, targets)
  211. callgraph = callgraph_
  212. # find maximum stack size recursively, this requires also detecting cycles
  213. # (in case of recursion)
  214. def find_limit(source, seen=None):
  215. seen = seen or set()
  216. if source not in callgraph:
  217. return 0
  218. _, _, frame, targets = callgraph[source]
  219. limit = 0
  220. for target in targets:
  221. if target in seen:
  222. # found a cycle
  223. return m.inf
  224. limit_ = find_limit(target, seen | {target})
  225. limit = max(limit, limit_)
  226. return frame + limit
  227. def find_children(targets):
  228. children = set()
  229. for target in targets:
  230. if target in callgraph:
  231. t_file, t_function, _, _ = callgraph[target]
  232. children.add((t_file, t_function))
  233. return children
  234. # build results
  235. results = []
  236. for source, (s_file, s_function, frame, targets) in callgraph.items():
  237. limit = find_limit(source)
  238. children = find_children(targets)
  239. results.append(StackResult(s_file, s_function, frame, limit, children))
  240. return results
  241. def fold(Result, results, *,
  242. by=None,
  243. defines=None,
  244. **_):
  245. if by is None:
  246. by = Result._by
  247. for k in it.chain(by or [], (k for k, _ in defines or [])):
  248. if k not in Result._by and k not in Result._fields:
  249. print("error: could not find field %r?" % k)
  250. sys.exit(-1)
  251. # filter by matching defines
  252. if defines is not None:
  253. results_ = []
  254. for r in results:
  255. if all(getattr(r, k) in vs for k, vs in defines):
  256. results_.append(r)
  257. results = results_
  258. # organize results into conflicts
  259. folding = co.OrderedDict()
  260. for r in results:
  261. name = tuple(getattr(r, k) for k in by)
  262. if name not in folding:
  263. folding[name] = []
  264. folding[name].append(r)
  265. # merge conflicts
  266. folded = []
  267. for name, rs in folding.items():
  268. folded.append(sum(rs[1:], start=rs[0]))
  269. return folded
  270. def table(Result, results, diff_results=None, *,
  271. by=None,
  272. fields=None,
  273. sort=None,
  274. summary=False,
  275. all=False,
  276. percent=False,
  277. tree=False,
  278. depth=1,
  279. **_):
  280. all_, all = all, __builtins__.all
  281. if by is None:
  282. by = Result._by
  283. if fields is None:
  284. fields = Result._fields
  285. types = Result._types
  286. # fold again
  287. results = fold(Result, results, by=by)
  288. if diff_results is not None:
  289. diff_results = fold(Result, diff_results, by=by)
  290. # organize by name
  291. table = {
  292. ','.join(str(getattr(r, k) or '') for k in by): r
  293. for r in results}
  294. diff_table = {
  295. ','.join(str(getattr(r, k) or '') for k in by): r
  296. for r in diff_results or []}
  297. names = list(table.keys() | diff_table.keys())
  298. # sort again, now with diff info, note that python's sort is stable
  299. names.sort()
  300. if diff_results is not None:
  301. names.sort(key=lambda n: tuple(
  302. types[k].ratio(
  303. getattr(table.get(n), k, None),
  304. getattr(diff_table.get(n), k, None))
  305. for k in fields),
  306. reverse=True)
  307. if sort:
  308. for k, reverse in reversed(sort):
  309. names.sort(
  310. key=lambda n: tuple(
  311. (getattr(table[n], k),)
  312. if getattr(table.get(n), k, None) is not None else ()
  313. for k in ([k] if k else [
  314. k for k in Result._sort if k in fields])),
  315. reverse=reverse ^ (not k or k in Result._fields))
  316. # build up our lines
  317. lines = []
  318. # header
  319. header = []
  320. header.append('%s%s' % (
  321. ','.join(by),
  322. ' (%d added, %d removed)' % (
  323. sum(1 for n in table if n not in diff_table),
  324. sum(1 for n in diff_table if n not in table))
  325. if diff_results is not None and not percent else '')
  326. if not summary else '')
  327. if diff_results is None:
  328. for k in fields:
  329. header.append(k)
  330. elif percent:
  331. for k in fields:
  332. header.append(k)
  333. else:
  334. for k in fields:
  335. header.append('o'+k)
  336. for k in fields:
  337. header.append('n'+k)
  338. for k in fields:
  339. header.append('d'+k)
  340. header.append('')
  341. lines.append(header)
  342. def table_entry(name, r, diff_r=None, ratios=[]):
  343. entry = []
  344. entry.append(name)
  345. if diff_results is None:
  346. for k in fields:
  347. entry.append(getattr(r, k).table()
  348. if getattr(r, k, None) is not None
  349. else types[k].none)
  350. elif percent:
  351. for k in fields:
  352. entry.append(getattr(r, k).diff_table()
  353. if getattr(r, k, None) is not None
  354. else types[k].diff_none)
  355. else:
  356. for k in fields:
  357. entry.append(getattr(diff_r, k).diff_table()
  358. if getattr(diff_r, k, None) is not None
  359. else types[k].diff_none)
  360. for k in fields:
  361. entry.append(getattr(r, k).diff_table()
  362. if getattr(r, k, None) is not None
  363. else types[k].diff_none)
  364. for k in fields:
  365. entry.append(types[k].diff_diff(
  366. getattr(r, k, None),
  367. getattr(diff_r, k, None)))
  368. if diff_results is None:
  369. entry.append('')
  370. elif percent:
  371. entry.append(' (%s)' % ', '.join(
  372. '+∞%' if t == +m.inf
  373. else '-∞%' if t == -m.inf
  374. else '%+.1f%%' % (100*t)
  375. for t in ratios))
  376. else:
  377. entry.append(' (%s)' % ', '.join(
  378. '+∞%' if t == +m.inf
  379. else '-∞%' if t == -m.inf
  380. else '%+.1f%%' % (100*t)
  381. for t in ratios
  382. if t)
  383. if any(ratios) else '')
  384. return entry
  385. # entries
  386. if not summary:
  387. for name in names:
  388. r = table.get(name)
  389. if diff_results is None:
  390. diff_r = None
  391. ratios = None
  392. else:
  393. diff_r = diff_table.get(name)
  394. ratios = [
  395. types[k].ratio(
  396. getattr(r, k, None),
  397. getattr(diff_r, k, None))
  398. for k in fields]
  399. if not all_ and not any(ratios):
  400. continue
  401. lines.append(table_entry(name, r, diff_r, ratios))
  402. # total
  403. r = next(iter(fold(Result, results, by=[])), None)
  404. if diff_results is None:
  405. diff_r = None
  406. ratios = None
  407. else:
  408. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  409. ratios = [
  410. types[k].ratio(
  411. getattr(r, k, None),
  412. getattr(diff_r, k, None))
  413. for k in fields]
  414. lines.append(table_entry('TOTAL', r, diff_r, ratios))
  415. # find the best widths, note that column 0 contains the names and column -1
  416. # the ratios, so those are handled a bit differently
  417. widths = [
  418. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  419. for w, i in zip(
  420. it.chain([23], it.repeat(7)),
  421. range(len(lines[0])-1))]
  422. # adjust the name width based on the expected call depth, though
  423. # note this doesn't really work with unbounded recursion
  424. if not summary and not m.isinf(depth):
  425. widths[0] += 4*(depth-1)
  426. # print the tree recursively
  427. if not tree:
  428. print('%-*s %s%s' % (
  429. widths[0], lines[0][0],
  430. ' '.join('%*s' % (w, x)
  431. for w, x in zip(widths[1:], lines[0][1:-1])),
  432. lines[0][-1]))
  433. if not summary:
  434. line_table = {n: l for n, l in zip(names, lines[1:-1])}
  435. def recurse(names_, depth_, prefixes=('', '', '', '')):
  436. for i, name in enumerate(names_):
  437. if name not in line_table:
  438. continue
  439. line = line_table[name]
  440. is_last = (i == len(names_)-1)
  441. print('%s%-*s ' % (
  442. prefixes[0+is_last],
  443. widths[0] - (
  444. len(prefixes[0+is_last])
  445. if not m.isinf(depth) else 0),
  446. line[0]),
  447. end='')
  448. if not tree:
  449. print(' %s%s' % (
  450. ' '.join('%*s' % (w, x)
  451. for w, x in zip(widths[1:], line[1:-1])),
  452. line[-1]),
  453. end='')
  454. print()
  455. # recurse?
  456. if name in table and depth_ > 1:
  457. children = {
  458. ','.join(str(getattr(Result(*c), k) or '') for k in by)
  459. for c in table[name].children}
  460. recurse(
  461. # note we're maintaining sort order
  462. [n for n in names if n in children],
  463. depth_-1,
  464. (prefixes[2+is_last] + "|-> ",
  465. prefixes[2+is_last] + "'-> ",
  466. prefixes[2+is_last] + "| ",
  467. prefixes[2+is_last] + " "))
  468. recurse(names, depth)
  469. if not tree:
  470. print('%-*s %s%s' % (
  471. widths[0], lines[-1][0],
  472. ' '.join('%*s' % (w, x)
  473. for w, x in zip(widths[1:], lines[-1][1:-1])),
  474. lines[-1][-1]))
  475. def main(ci_paths,
  476. by=None,
  477. fields=None,
  478. defines=None,
  479. sort=None,
  480. **args):
  481. # it doesn't really make sense to not have a depth with tree,
  482. # so assume depth=inf if tree by default
  483. if args.get('depth') is None:
  484. args['depth'] = m.inf if args['tree'] else 1
  485. elif args.get('depth') == 0:
  486. args['depth'] = m.inf
  487. # find sizes
  488. if not args.get('use', None):
  489. results = collect(ci_paths, **args)
  490. else:
  491. results = []
  492. with openio(args['use']) as f:
  493. reader = csv.DictReader(f, restval='')
  494. for r in reader:
  495. if not any('stack_'+k in r and r['stack_'+k].strip()
  496. for k in StackResult._fields):
  497. continue
  498. try:
  499. results.append(StackResult(
  500. **{k: r[k] for k in StackResult._by
  501. if k in r and r[k].strip()},
  502. **{k: r['stack_'+k] for k in StackResult._fields
  503. if 'stack_'+k in r and r['stack_'+k].strip()}))
  504. except TypeError:
  505. pass
  506. # fold
  507. results = fold(StackResult, results, by=by, defines=defines)
  508. # sort, note that python's sort is stable
  509. results.sort()
  510. if sort:
  511. for k, reverse in reversed(sort):
  512. results.sort(
  513. key=lambda r: tuple(
  514. (getattr(r, k),) if getattr(r, k) is not None else ()
  515. for k in ([k] if k else StackResult._sort)),
  516. reverse=reverse ^ (not k or k in StackResult._fields))
  517. # write results to CSV
  518. if args.get('output'):
  519. with openio(args['output'], 'w') as f:
  520. writer = csv.DictWriter(f,
  521. (by if by is not None else StackResult._by)
  522. + ['stack_'+k for k in (
  523. fields if fields is not None else StackResult._fields)])
  524. writer.writeheader()
  525. for r in results:
  526. writer.writerow(
  527. {k: getattr(r, k) for k in (
  528. by if by is not None else StackResult._by)}
  529. | {'stack_'+k: getattr(r, k) for k in (
  530. fields if fields is not None else StackResult._fields)})
  531. # find previous results?
  532. if args.get('diff'):
  533. diff_results = []
  534. try:
  535. with openio(args['diff']) as f:
  536. reader = csv.DictReader(f, restval='')
  537. for r in reader:
  538. if not any('stack_'+k in r and r['stack_'+k].strip()
  539. for k in StackResult._fields):
  540. continue
  541. try:
  542. diff_results.append(StackResult(
  543. **{k: r[k] for k in StackResult._by
  544. if k in r and r[k].strip()},
  545. **{k: r['stack_'+k] for k in StackResult._fields
  546. if 'stack_'+k in r and r['stack_'+k].strip()}))
  547. except TypeError:
  548. raise
  549. except FileNotFoundError:
  550. pass
  551. # fold
  552. diff_results = fold(StackResult, diff_results, by=by, defines=defines)
  553. # print table
  554. if not args.get('quiet'):
  555. table(StackResult, results,
  556. diff_results if args.get('diff') else None,
  557. by=by if by is not None else ['function'],
  558. fields=fields,
  559. sort=sort,
  560. **args)
  561. # error on recursion
  562. if args.get('error_on_recursion') and any(
  563. m.isinf(float(r.limit)) for r in results):
  564. sys.exit(2)
  565. if __name__ == "__main__":
  566. import argparse
  567. import sys
  568. parser = argparse.ArgumentParser(
  569. description="Find stack usage at the function level.",
  570. allow_abbrev=False)
  571. parser.add_argument(
  572. 'ci_paths',
  573. nargs='*',
  574. help="Input *.ci files.")
  575. parser.add_argument(
  576. '-v', '--verbose',
  577. action='store_true',
  578. help="Output commands that run behind the scenes.")
  579. parser.add_argument(
  580. '-q', '--quiet',
  581. action='store_true',
  582. help="Don't show anything, useful with -o.")
  583. parser.add_argument(
  584. '-o', '--output',
  585. help="Specify CSV file to store results.")
  586. parser.add_argument(
  587. '-u', '--use',
  588. help="Don't parse anything, use this CSV file.")
  589. parser.add_argument(
  590. '-d', '--diff',
  591. help="Specify CSV file to diff against.")
  592. parser.add_argument(
  593. '-a', '--all',
  594. action='store_true',
  595. help="Show all, not just the ones that changed.")
  596. parser.add_argument(
  597. '-p', '--percent',
  598. action='store_true',
  599. help="Only show percentage change, not a full diff.")
  600. parser.add_argument(
  601. '-b', '--by',
  602. action='append',
  603. choices=StackResult._by,
  604. help="Group by this field.")
  605. parser.add_argument(
  606. '-f', '--field',
  607. dest='fields',
  608. action='append',
  609. choices=StackResult._fields,
  610. help="Show this field.")
  611. parser.add_argument(
  612. '-D', '--define',
  613. dest='defines',
  614. action='append',
  615. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  616. help="Only include results where this field is this value.")
  617. class AppendSort(argparse.Action):
  618. def __call__(self, parser, namespace, value, option):
  619. if namespace.sort is None:
  620. namespace.sort = []
  621. namespace.sort.append((value, True if option == '-S' else False))
  622. parser.add_argument(
  623. '-s', '--sort',
  624. nargs='?',
  625. action=AppendSort,
  626. help="Sort by this field.")
  627. parser.add_argument(
  628. '-S', '--reverse-sort',
  629. nargs='?',
  630. action=AppendSort,
  631. help="Sort by this field, but backwards.")
  632. parser.add_argument(
  633. '-Y', '--summary',
  634. action='store_true',
  635. help="Only show the total.")
  636. parser.add_argument(
  637. '-F', '--source',
  638. dest='sources',
  639. action='append',
  640. help="Only consider definitions in this file. Defaults to anything "
  641. "in the current directory.")
  642. parser.add_argument(
  643. '--everything',
  644. action='store_true',
  645. help="Include builtin and libc specific symbols.")
  646. parser.add_argument(
  647. '--tree',
  648. action='store_true',
  649. help="Only show the function call tree.")
  650. parser.add_argument(
  651. '-Z', '--depth',
  652. nargs='?',
  653. type=lambda x: int(x, 0),
  654. const=0,
  655. help="Depth of function calls to show. 0 shows all calls but may not "
  656. "terminate!")
  657. parser.add_argument(
  658. '-e', '--error-on-recursion',
  659. action='store_true',
  660. help="Error if any functions are recursive.")
  661. sys.exit(main(**{k: v
  662. for k, v in vars(parser.parse_intermixed_args()).items()
  663. if v is not None}))