File: statements.py

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (68 lines) | stat: -rw-r--r-- 1,778 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from pyparsing import (
    CharsNotIn,
    Combine,
    Optional,
    ParseException,
    Regex,
    Suppress,
    Word,
    alphas,
    nums,
)

from brian2.utils.caching import cached

VARIABLE = Word(f"{alphas}_", f"{alphas + nums}_").setResultsName("variable")

OP = Regex(r"(\+|\-|\*|/|//|%|\*\*|>>|<<|&|\^|\|)?=").setResultsName("operation")
EXPR = Combine(
    CharsNotIn("=", min=1, max=1) + Optional(CharsNotIn("#"))
).setResultsName("expression")
COMMENT = Optional(CharsNotIn("#")).setResultsName("comment")
STATEMENT = VARIABLE + OP + EXPR + Optional(Suppress("#") + COMMENT)


@cached
def parse_statement(code):
    """
    parse_statement(code)

    Parses a single line of code into "var op expr".

    Parameters
    ----------
    code : str
        A string containing a single statement of the form
        ``var op expr # comment``, where the ``# comment`` part is optional.

    Returns
    -------
    var, op, expr, comment : str, str, str, str
        The four parts of the statement.

    Examples
    --------
    >>> parse_statement('v = -65*mV  # reset the membrane potential')
    ('v', '=', '-65*mV', 'reset the membrane potential')
    >>> parse_statement('v += dt*(-v/tau)')
    ('v', '+=', 'dt*(-v/tau)', '')
    """
    try:
        parsed = STATEMENT.parseString(code, parseAll=True)
    except ParseException as p_exc:
        raise ValueError(
            "Parsing the statement failed: \n"
            + str(p_exc.line)
            + "\n"
            + " " * (p_exc.column - 1)
            + "^\n"
            + str(p_exc)
        )
    parsed_statement = (
        parsed["variable"].strip(),
        parsed["operation"],
        parsed["expression"].strip(),
        parsed.get("comment", "").strip(),
    )

    return parsed_statement