Debian Codegraph @

brian2/parsing/statements.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 from pyparsing import (
2 CharsNotIn,
3 Combine,
4 Optional,
5 ParseException,
6 Regex,
7 Suppress,
8 Word,
9 alphas,
10 nums,
11 )
12
13 from brian2.utils.caching import cached
14
15 VARIABLE = Word(f"{alphas}_", f"{alphas + nums}_").set_results_name("variable")
16
17 OP = Regex(r"(\+|\-|\*|/|//|%|\*\*|>>|<<|&|\^|\|)?=").set_results_name("operation")
18 EXPR = Combine(
19 CharsNotIn("=", min=1, max=1) + Optional(CharsNotIn("#"))
20 ).set_results_name("expression")
21 COMMENT = Optional(CharsNotIn("#")).set_results_name("comment")
22 STATEMENT = VARIABLE + OP + EXPR + Optional(Suppress("#") + COMMENT)
23
24
25 @cached
26 def parse_statement(code):
27 """
28 parse_statement(code)
29
30 Parses a single line of code into "var op expr".
31
32 Parameters
33 ----------
34 code : str
35 A string containing a single statement of the form
36 ``var op expr # comment``, where the ``# comment`` part is optional.
37
38 Returns
39 -------
40 var, op, expr, comment : str, str, str, str
41 The four parts of the statement.
42
43 Examples
44 --------
45 >>> parse_statement('v = -65*mV # reset the membrane potential')
46 ('v', '=', '-65*mV', 'reset the membrane potential')
47 >>> parse_statement('v += dt*(-v/tau)')
48 ('v', '+=', 'dt*(-v/tau)', '')
49 """
50 try:
51 parsed = STATEMENT.parse_string(code, parseAll=True)
52 except ParseException as p_exc:
53 raise ValueError(
54 "Parsing the statement failed: \n"
55 + str(p_exc.line)
56 + "\n"
57 + " " * (p_exc.column - 1)
58 + "^\n"
59 + str(p_exc)
60 ) from p_exc
61 parsed_statement = (
62 parsed["variable"].strip(),
63 parsed["operation"],
64 parsed["expression"].strip(),
65 parsed.get("comment", "").strip(),
66 )
67
68 return parsed_statement