Exemplo n.º 1
0
class identifier_def:
	nondigit = pp.Char(pp.alphas + "_")
	digit = pp.Char(pp.nums)
	universal_character_name_u = pp.Literal("\\u") + pp.Char(pp.hexnums * 4)
	universal_character_name_U = pp.Literal("\\U") + pp.Char(pp.hexnums * 8)
	universal_character_name = (universal_character_name_u | universal_character_name_U)
	identifier_nondigit = (nondigit | universal_character_name)
Exemplo n.º 2
0
def UnxParser():

    COMMENT_CHAR = '%%'
    WHITESPACE = ' \t\r'

    PRIMITIVES = '`ski'

    VARIABLES = pp.alphas

    VARIABLE_DECL = '^'
    VARIABLE_USE = '$'

    PURE_FUNCTION_START = '<'
    PURE_FUNCTION_END = '>'

    IMPURE_FUNCTION_START = '['
    IMPURE_FUNCTION_END = ']'

    FUNCTION_CHARS = pp.alphanums + '_'

    TYPE_CHARS = FUNCTION_CHARS
    TYPE_ARROW = '->'

    FUNCTION_DEFINITION_SEPARATOR = '::'

    INCLUDE_KEYWORD = 'include'
    INCLUDE_FILE_CHARS = pp.alphanums + '_./'

    pp.ParserElement.setDefaultWhitespaceChars(WHITESPACE)

    # Comments and blank lines
    comment = pp.Literal(COMMENT_CHAR) + pp.ZeroOrMore(pp.Word(pp.printables, excludeChars='\n'))
    newlines = pp.Group(pp.OneOrMore((comment + pp.LineEnd()) | pp.LineEnd())).setName('new line(s)').suppress()

    # Function definition
    pure_function = pp.Group(pp.Char(PURE_FUNCTION_START) + pp.Word(FUNCTION_CHARS).setResultsName('pure_function') + pp.Char(PURE_FUNCTION_END))
    impure_function = pp.Group(pp.Char(IMPURE_FUNCTION_START) + pp.Word(FUNCTION_CHARS).setResultsName('impure_function') + pp.Char(IMPURE_FUNCTION_END))

    function_sep = pp.Literal(FUNCTION_DEFINITION_SEPARATOR).suppress()
    variable_declaration = pp.Literal(VARIABLE_DECL).suppress() + pp.Char(VARIABLES)
    variable_use = pp.Literal(VARIABLE_USE).suppress() + pp.Group(pp.Char(VARIABLES).setResultsName('variable'))
    function_body = pp.ZeroOrMore(variable_declaration).setResultsName('variables') + pp.OneOrMore(pp.Group(pp.Char(PRIMITIVES).setResultsName('primitive')) | pure_function | impure_function | variable_use).setResultsName('body')
    
    type_ = pp.Word(TYPE_CHARS)
    type_arrow = pp.Literal(TYPE_ARROW).suppress()

    function_signature = (type_ + pp.ZeroOrMore(type_arrow + type_)).setResultsName('signature')

    function = pp.Group((pure_function.setResultsName('name') | impure_function.setResultsName('name')) + pp.Optional(function_sep + function_signature) + function_sep + function_body).setResultsName('function')

    # Includes
    include_file = pp.Word(INCLUDE_FILE_CHARS)
    include_statement = (pp.Keyword(INCLUDE_KEYWORD).suppress() + pp.OneOrMore(include_file)).setResultsName('includes')

    parser = pp.Optional(pp.Optional(include_statement) + newlines) + (pp.Group(function) + pp.ZeroOrMore(pp.Group(newlines + function))).setResultsName('definitions') + pp.Optional(newlines)

    return parser
Exemplo n.º 3
0
def parseExpression(input):
    xNum = pp.Word(pp.nums)
    xOp = pp.Char('+') | pp.Char('*')
    exp = xOp | xNum
    nest = pp.nestedExpr(
        '(',
        ')',
        content=exp,
    )

    return nest.parseString(input).asList()
Exemplo n.º 4
0
Arquivo: mml.py Projeto: ongyx/putao
def _mml_syntax():
    key = pp.Combine(pp.Char("cdefgab") + pp.Optional(pp.Char("+-#")))
    key.setParseAction(lambda tk: tk[0].replace("+", "#").replace("-", "b"))

    length = pp.Optional(pp.Word(pp.nums))

    note = pp.Group(key + length)
    note.setParseAction(_note)

    rest = pp.Combine((pp.Suppress("r") | pp.Suppress("p")) + length)
    rest.setParseAction(_rest)

    prop_num = pp.Word(pp.nums)

    prop = pp.Group(pp.Char("olt") + prop_num)
    prop.setParseAction(_prop)

    oct_shift = pp.Char("<>")
    oct_shift.setParseAction(_oct_shift)

    mml = (note | rest | prop | oct_shift)[1, ...]

    # eXtended syntax
    comment = pp.Literal("#") + pp.restOfLine

    track = pp.Suppress("@") + pp.Word(pp.alphanums)
    track.setParseAction(_track)

    lyrics = pp.Suppress("|") + pp.delimitedList(
        pp.Word(pp.alphas + pp_u.Japanese.printables), delim=" ", combine=True)
    lyrics.setParseAction(_lyrics)

    mml = (lyrics | track | comment | mml)[1, ...]
    mml.ignore(comment)

    return mml
Exemplo n.º 5
0
class preprocessing_directive:
	pp_group = pp.Char("#")
	# 
	pp_if = pp.Keyword("if")
	pp_ifdef = pp.Keyword("ifdef")
	pp_ifndef = pp.Keyword("ifndef")
	pp_elif = pp.Keyword("elif")
	pp_else = pp.Keyword("else")
	pp_endif = pp.Keyword("endif")
	# control
	pp_include = pp.Keyword("include")
	pp_define = pp.Keyword("define")
	pp_undef = pp.Keyword("undef")
	pp_line = pp.Keyword("line")
	pp_error = pp.Keyword("error")
	pp_pragma = pp.Keyword("pragma")
Exemplo n.º 6
0
def translateRule(rules, idx, done):
    if idx in done:
        return

    if rules[idx][0][0].startswith('"'):
        rules[idx] = pp.Char(rules[idx][1])
    else:
        rule = [x.split(' ') for x in rules[idx].split('|')]
        rule = [[x.strip() for x in r] for r in rule]
        rule = [[x for x in r if x] for r in rule]

        [translateRule(rules, x, done) for r in rule for x in r]

        rule = [reduce(lambda x,y: x + y, [rules[x] for x in r]) for r in rule]
        rules[idx] = reduce(lambda x,y: x ^ y, rule)

    done.append(idx)
Exemplo n.º 7
0
def timeentry_expr():
    # fmt:off
    start_time = (
        pp.Word(pp.nums) +
        pp.Optional(":" + pp.Word(pp.nums))).setResultsName("first_time")
    end_time = (
        pp.Word(pp.nums) +
        pp.Optional(":" + pp.Word(pp.nums))).setResultsName("last_time")

    interval_h = pp.Word(pp.nums).setResultsName("hours") + pp.Char("h")
    interval_m = pp.Word(pp.nums).setResultsName("minutes") + pp.Char("m")

    timepart = pp.Or([
        start_time + pp.Char("-") + end_time,
        pp.Or([interval_h, interval_m, interval_h + interval_m])
    ])
    timeseppart = pp.Optional(pp.Char('|:-'))
    tagpart = (pp.Char('[') +
               pp.CharsNotIn('[]').setResultsName("tag", listAllMatches=True) +
               pp.Char(']'))
    descpart = pp.SkipTo(pp.lineEnd).setResultsName("desc")

    return timepart + timeseppart + pp.OneOrMore(tagpart) + descpart
Exemplo n.º 8
0
import pyparsing as pp

ppc = pp.pyparsing_common

# fmt: off
word = pp.Word(pp.alphas).setName("word")
integer = pp.Word(pp.nums).setName("integer")
plus_minus = pp.Char("+-").set_name("add_sub")
mult_div = pp.Char("*/").set_name("mult_div")
street_address = pp.Group(
    integer("house_number") +
    word[1, ...]("street_name")).setName("street_address")
time = pp.Regex(r"\d\d:\d\d")

grammar = (
    pp.Group(integer[1, ...]) +
    (ppc.ipv4_address
     & word("header_word")
     & pp.Optional(time)).setName("header with various elements")("header") +
    street_address("address") + pp.Group(pp.counted_array(word)) +
    pp.Group(integer * 8)("data") +
    pp.Group(pp.Word("abc") + pp.Word("def") * 3) +
    pp.infix_notation(integer, [
        (plus_minus().setName("pos_neg"), 1, pp.opAssoc.RIGHT),
        (mult_div, 2, pp.opAssoc.LEFT),
        (plus_minus, 2, pp.opAssoc.LEFT),
    ]).setName("simple_arithmetic") + ... +
    pp.Group(ppc.ipv4_address)("ip_address")).setName("grammar")

grammar.create_diagram("railroad_diagram_demo.html",
                       vertical=6,
Exemplo n.º 9
0
def detectChemicalType(formula):
    """detectChemicalType: utility routine for detecting chemical type

    Arguments
    ----------
    formula : text version of formula

    Returns
    -------
    type: string "element"|"ionic"|"covalent"|"acid"|"water"

    """
    verbose = False
    #if verbose: print(f"detect formula:{formula}")
    if formula in ['H2O', 'HOH']:
        return "water"
    if formula == 'O2':
        return "oxygen"

    integer = pp.Word(pp.nums)
    element = pp.StringStart() + pp.oneOf(element_symbols) + pp.Optional(
        integer) + pp.StringEnd()
    try:
        parts = element.parseString(formula)
        return "element"
    except pp.ParseException:
        pass

    ammonium_formulas = [ammonium_formula, '(' + ammonium_formula + ')']
    cation = pp.StringStart() + pp.oneOf(ionic_metal_symbols)
    try:
        parts = cation.parseString(formula)
        return "ionic"
    except pp.ParseException:
        pass

    hydrocarbon_formula = [ammonium_formula, '(' + ammonium_formula + ')']
    integer_or_hco = pp.Word("HC", "CHO1234567890")
    hydrocarbon = pp.StringStart() + integer_or_hco + pp.StringEnd()
    if formula in ["CO2", "CO"]: return "covalent"
    if formula in ["H2CO3"]: return "ionic"
    try:
        parts = hydrocarbon.parseString(formula)
        return "hydrocarbon"
    except pp.ParseException:
        pass

    ammonium_formulas = [ammonium_formula, '(' + ammonium_formula + ')']
    polycation = pp.StringStart() + pp.oneOf(ammonium_formulas)
    try:
        parts = polycation.parseString(formula)
        return "ionic"
    except pp.ParseException:
        pass

    acid = pp.StringStart() + pp.Char('H') + pp.NotAny(pp.oneOf('e o f g s'))
    try:
        parts = acid.parseString(formula)
        return "acid"
    except pp.ParseException:
        pass

    return "covalent"
Exemplo n.º 10
0
def is_timeentry(line):
    return pp.Char(pp.nums).matches(line, parseAll=False)
Exemplo n.º 11
0
	# (6.4.4.3) enumeration-constant:
	enumeration_constant = identifier
	# (6.4.4.4) character-constant:
	simple_escape_sequence = pp.Char("\\") + pp.Char("\\'\"?abfnrtv")
	octal_escape_sequence = pp.Char("\\") + octal_digit.copy()[1, ...]
	hexadecimal_escape_sequence = pp.Word("\\x") + hexadecimal_digit.copy()[1, ...]
	escape_sequence = simple_escape_sequence | octal_escape_sequence | hexadecimal_escape_sequence | identifier_def.universal_character_name
	c_char = pp.CharsNotIn("'\\\r\n") | escape_sequence
	character_constant = pp.Optional(pp.Char("L")) + pp.Char("'") + c_char[1,...] + pp.Char("'")
# (6.4.4) constant:
constant = pp.Combine(constant_def.integer_constant | constant_def.enumeration_constant | constant_def.character_constant)

# A.1.6 String literals
class string_literal_def:
	s_char = pp.CharsNotIn('"\\\r\n') | constant_def.escape_sequence
string_literal = pp.Combine(pp.Optional(pp.Char("L")) + pp.Char('"') + string_literal_def.s_char[1, ...] + pp.Char('"'))

# A.1.7 Punctuators
class punctuator:
	left_bracket = pp.Literal("[")
	right_bracket = pp.Literal("]")
	left_paren = pp.Literal("(")
	right_paren = pp.Literal(")")
	left_brace = pp.Literal("{")
	right_brace = pp.Literal("}")
	dot = pp.Literal(".")
	arrow_op = pp.Literal("->")
	increment_op = pp.Literal("++")
	decrement_op = pp.Literal("--")
	ampersand = pp.Literal("&")
	asterisk = pp.Literal("*")
Exemplo n.º 12
0
import pyparsing as pp

scheme = pp.Literal("http") + pp.Optional('s') + "://"
url = pp.Optional("www.") + "youtube." + ... + (pp.Literal("/v/") ^ "&v="
                                                ^ "?v=" ^ "/embed/")
short = pp.Literal("youtu.be/")
vid = pp.SkipTo(pp.LineEnd() ^ pp.Char("#?&") ^ pp.White())("vid")

parser = pp.Suppress(pp.Optional(scheme) + (url ^ short)) + vid


def get_vid(s):
    return parser.parseString(s).asDict()["vid"]
Exemplo n.º 13
0
    A
        100
        101

        102
    B
        200
        201
    
    C
        300

"""

integer = ppc.integer
group = pp.Group(pp.Char(pp.alphas) + pp.Group(pp.IndentedBlock(integer)))

print(group[...].parseString(data).dump())

# example of a recursive IndentedBlock

data = """\

    A
        100
        101

        102
    B
        200
        b
Exemplo n.º 14
0
input_lines = open(sys.argv[1]).read().split('\n')

raw_rules = list(itertools.takewhile(lambda l: l != '', input_lines))
received_messages = list(
    itertools.takewhile(lambda l: l != '', input_lines[len(raw_rules) + 1:]))

rules = {}

for raw_rule in raw_rules:
    rule_name, raw_rule_def = raw_rule.split(': ')
    rule_def = raw_rule_def.split(' | ')
    if rule_name not in rules: rules[rule_name] = pp.Forward()
    if len(rule_def) == 1 and rule_def[0].startswith('"'):  # single character
        c = rule_def[0][1]  # extract character
        rules[rule_name] <<= pp.Char(c)
        continue
    rule_def_exp = None
    for sub in rule_def:
        all_needed = sub.split(' ')
        pattern_for_group = None
        for referenced in all_needed:
            if referenced not in rules:
                rules[referenced] = pp.Forward()
            if not pattern_for_group:
                pattern_for_group = rules[
                    referenced]  # get first referenced as pattern start
            else:
                pattern_for_group += rules[
                    referenced]  # and append future ones
        if not rule_def_exp:
Exemplo n.º 15
0
    def is_and(self):
        return str(self) == ','

    def is_or(self):
        return str(self) == ';'


def parse_rule_action(tokens):
    return Rule(tokens[0], tokens[1].asList())


def parse_functor_action(tokens):
    return Functor(tokens[0], tokens[2].asList())


pOP = pp.Char(',;')
pOP.setParseAction(lambda tokens: Operator(tokens[0]))

pSPECIAL_CHAR = pp.Char("@+-*/<>=:.&~ ")
pATOM = pp.Word(string.ascii_lowercase,
                pp.alphanums + "_") ^ pp.sglQuotedString()
#     | [0] ---------------------------------------------------------------------|
pATOM.setParseAction(lambda tokens: Atom(tokens[0]))

pVARIABLE = pp.Word(string.ascii_uppercase + "_", pp.alphanums + "_")
#         | [0] -----------------------------------------------------|
pVARIABLE.setParseAction(lambda tokens: Variable(tokens[0]))

# pNUMBER = pp.Word(pp.nums) + pp.Optional(pp.Char('.') + pp.Word(pp.nums))
# #       | [0] ---------------[1]--------------------------------------|
# pNUMBER.setParseAction(lambda tokens: float(tokens[0] + tokens[1] + tokens[2]) if len(tokens) > 1) else int(tokens[0]))
Exemplo n.º 16
0
 def build_bnfs(self):
     self.float = ppc.real
     self.int = ppc.integer
     self.number = ppc.number
     self.wildcard = pp.Empty().setParseAction(lambda _: ':')
     self.rawstr = pp.oneOf('"\'') + pp.Word(pp.alphanums) + pp.oneOf('"\'')
     self.ident = pp.Char('_') | (
         pp.Word(pp.alphas, pp.alphanums + '_') +
         pp.Optional(pp.Char('~') + pp.Word(pp.alphanums)) +
         pp.Optional(pp.Char('^') + pp.Word(pp.alphanums)))
     self.ident = self.ident.setParseAction(self._ident)
     self.expr = pp.Forward()
     self.atom = pp.Forward()
     self.slice = (self.expr | self.wildcard) + ':' + (
         self.expr | self.wildcard) + pp.Optional(
             ':' + (self.expr | self.wildcard))  # in-dev v0.0.2
     self.slice = self.slice.setParseAction(self._slice)
     self.varindex = self.ident + pp.Suppress('[') + pp.Group(
         pp.delimitedList(self.slice | self.expr | ':' | self.wildcard)
     ) + pp.Suppress(
         ']'
     )  # + pp.Optional(pp.Suppress('(') + pp.Group(pp.delimitedList(self.expr)) + pp.Suppress(')'))
     self.varindex = self.varindex.setParseAction(self._varindex)
     self.arbitraryfncall = (self.ident + pp.Optional(pp.Suppress('{') + pp.Word(pp.alphanums + '@', pp.alphanums + '_') + pp.Suppress('}')) + pp.Optional(pp.Suppress('[') + pp.Group(pp.delimitedList(self.expr | ':' | self.wildcard)) + pp.Suppress(']')) +\
         (pp.Suppress('(') + pp.Group(pp.delimitedList(self.expr)) + pp.Suppress(')'))).setParseAction(self._fncall)
     self.unaryfncall_ = pp.Forward()
     self.unaryfncall_tail_ = pp.Group(
         pp.Suppress('.') + self.ident + pp.Optional(
             pp.Suppress('{') + pp.Word(pp.alphanums + '@', pp.alphanums) +
             pp.Suppress('}')) +
         pp.Optional(
             pp.Suppress('[') +
             pp.Group(pp.delimitedList(self.expr | ':' | self.wildcard)) +
             pp.Suppress(']')))
     self.unaryfncall_head_ = (
         pp.Suppress('(') + self.expr +
         pp.Suppress(')')) | self.varindex | self.ident | self.wildcard
     # self.unaryfncall = (self.unaryfncall_head_ + self.unaryfncall_tail_) ^ (self.arbitraryfncall + self.unaryfncall_tail_) + self.unaryfncall_
     # self.unaryfncall = (self.unaryfncall_head_ + self.unaryfncall_tail_) | (self.arbitraryfncall + self.unaryfncall_tail_) + self.unaryfncall_
     self.unaryfncall = (self.arbitraryfncall + self.unaryfncall_tail_
                         ) | (self.unaryfncall_head_ +
                              self.unaryfncall_tail_) + self.unaryfncall_
     self.unaryfncall_ <<= (self.unaryfncall_tail_ +
                            self.unaryfncall_) | pp.empty
     self.unaryfncall = self.unaryfncall.setParseAction(self._unaryfncall)
     self.fncall = self.unaryfncall | self.arbitraryfncall
     self.atom <<= self.rawstr | self.number | (
         pp.oneOf('+ -') + self.atom).setParseAction(
             self._posneg) | self.fncall | (
                 pp.Suppress('(') + self.expr +
                 pp.Suppress(')')) | self.varindex | self.ident
     self.matmul_ = pp.Forward()
     self.matmul = self.atom + self.matmul_
     self.matmul_ <<= (pp.Suppress('#') + self.atom +
                       self.matmul_) | pp.empty
     self.matmul = self.matmul.setParseAction(self._matmul)
     self.muldiv_ = pp.Forward()
     self.muldiv = self.matmul + self.muldiv_
     self.muldiv_ <<= (pp.oneOf('* / //') + self.matmul +
                       self.muldiv_) | pp.empty
     self.muldiv = self.muldiv.setParseAction(self._muldiv)
     self.addsub_ = pp.Forward()
     self.addsub = self.muldiv + self.addsub_
     self.addsub_ <<= (pp.oneOf('+ -') + self.muldiv +
                       self.addsub_) | pp.empty
     self.addsub = self.addsub.setParseAction(self._addsub)
     self.comp = self.addsub + pp.oneOf('> < == >= <= !=') + self.addsub
     self.comp = self.comp.setParseAction(self._comp)
     self.boolexpr = pp.Forward()
     self.boolatom = pp.Forward()
     self.boolatom <<= (
         pp.oneOf('not binot ! ~') + self.boolatom).setParseAction(
             self._not) | self.comp | (
                 pp.Suppress('(') + self.boolexpr +
                 pp.Suppress(')')) | pp.Keyword('True').setParseAction(
                     self._ident) | pp.Keyword('False').setParseAction(
                         self._ident)
     self.booland_ = pp.Forward()
     self.booland = self.boolatom + self.booland_
     self.booland_ <<= (pp.oneOf('and biand && &') + self.boolatom +
                        self.booland_) | pp.empty
     self.booland = self.booland.setParseAction(self._and)
     self.boolor_ = pp.Forward()
     self.boolor = self.booland + self.boolor_
     self.boolor_ <<= (pp.oneOf('or bior || |') + self.booland +
                       self.boolor_) | pp.empty
     self.boolor = self.boolor.setParseAction(self._or)
     self.boolexpr <<= self.boolor
     self.expr <<= self.boolexpr ^ self.addsub
     self.body = pp.Keyword('body')
     self.end = pp.Keyword('end')
     self.for_ = pp.Keyword('for')
     self.in_ = pp.Keyword('in')
     self.if_ = pp.Keyword('if')
     self.elif_ = pp.Keyword('elif')
     self.else_ = pp.Keyword('else')
     self.return_ = pp.Keyword('return')
     self.static = pp.Keyword('static')
     self.forhead = self.for_ + self.ident + pp.Suppress(
         self.in_) + pp.oneOf('[ (') + pp.Group(pp.delimitedList(
             self.expr)) + pp.oneOf('] )')
     self.ifhead = self.if_ + self.expr
     self.elifhead = self.elif_ + self.expr
     self.elsehead = self.else_
     self.return_stat = self.return_ + pp.Group(pp.delimitedList(self.expr))
     self.statement = (pp.Optional(self.static) + pp.Group(pp.delimitedList(self.varindex | self.ident)) + pp.Suppress('=') + self.expr) |\
         self.return_stat | self.forhead | self.ifhead | self.elifhead | self.elsehead | self.end
Exemplo n.º 17
0
class constant_def:
	zero = pp.Char("0")
	nonzero_digit = pp.Char("123456789")
	digit = pp.Char(pp.nums)
	octal_digit = pp.Char("01234567")
	hexadecimal_digit = pp.Char(pp.hexnums)
	# (6.4.4.1) decimal-constant:
	decimal_constant = nonzero_digit + digit.copy()[...]
	# (6.4.4.1) octal-constant:
	octal_constant = zero + octal_digit.copy()[...]
	# (6.4.4.1) hexadecimal-constant:
	hexadecimal_prefix = pp.Word("0x") | pp.Word("0X")
	hexadecimal_constant = hexadecimal_prefix + hexadecimal_digit.copy()[1, ...]
	# (6.4.4.1) integer-suffix:
	unsigned_suffix = pp.Char("uU")
	long_suffix = pp.Char("lL")
	longlong_suffix = pp.Word("ll") | pp.Word("LL")
	integer_suffix = (unsigned_suffix + pp.Optional(long_suffix | longlong_suffix)) | ((long_suffix | longlong_suffix) + pp.Optional(unsigned_suffix))
	# (6.4.4.1) integer-constant:
	integer_constant = (decimal_constant | octal_constant | hexadecimal_constant) + pp.Optional(integer_suffix)
	# (6.4.4.2) floating-constant:
	# 略
	# (6.4.4.3) enumeration-constant:
	enumeration_constant = identifier
	# (6.4.4.4) character-constant:
	simple_escape_sequence = pp.Char("\\") + pp.Char("\\'\"?abfnrtv")
	octal_escape_sequence = pp.Char("\\") + octal_digit.copy()[1, ...]
	hexadecimal_escape_sequence = pp.Word("\\x") + hexadecimal_digit.copy()[1, ...]
	escape_sequence = simple_escape_sequence | octal_escape_sequence | hexadecimal_escape_sequence | identifier_def.universal_character_name
	c_char = pp.CharsNotIn("'\\\r\n") | escape_sequence
	character_constant = pp.Optional(pp.Char("L")) + pp.Char("'") + c_char[1,...] + pp.Char("'")
Exemplo n.º 18
0
    def __init__(self,
                 base_freq=440.0,
                 amplitude=.5,
                 max_gain=10.,
                 min_gain=-200.,
                 new_scale='C/a',
                 clef='violin'):

        # an important constant value for the conversion of musical halt tone steps to frequency values
        # is the twelfth root of 2
        self.__root__ = 1.0594630943592952645618252949463  # (2 ** (1 / 12))

        # *** parser definitions ***
        # helper
        no_whites = pp.NotAny(pp.White())
        tok_end = (pp.StringEnd() | pp.LineEnd()).suppress()

        # numbers
        real = pp.Combine(
            pp.Word(pp.nums) +
            pp.Optional(pp.Char(',.') + pp.Word(pp.nums))).setParseAction(
                lambda t: float(t[0].replace(',', '.')))

        integer = (pp.Optional(pp.Literal('-')) +
                   pp.Word(pp.nums)).setParseAction(
                       lambda t: int(t[0] + t[1]) if len(t) > 1 else int(t[0]))

        # signs
        must_sign = pp.Char('+-').setParseAction(lambda t: float(t[0] + '1'))
        may_sign = pp.Optional(pp.Char('+-')).setParseAction(
            lambda t: float(t[0] + '1' if len(t) > 0 else '1'))

        # note value cents
        cent = (must_sign + no_whites +
                real).setParseAction(lambda t: t[0] * t[1] / 100)

        # helpers for the note name parser
        note_name_offset = {
            'C': -9,
            'D': -7,
            'E': -5,
            'F': -4,
            'G': -2,
            'A': 0,
            'B': 2,
        }
        note_name = pp.Char('CDEFGABcdefgab').setParseAction(
            lambda t: note_name_offset[t[0]
                                       if t[0] in 'CDEFGAB' else t[0].upper()])

        flat_sharp = pp.Char('#b').setParseAction(lambda t: 1
                                                  if t[0] == '#' else -1)
        octave = pp.Char('0123456789').setParseAction(lambda t:
                                                      (int(t[0]) - 4) * 12)
        full_note = (note_name + no_whites +
                     pp.Optional(pp.FollowedBy(flat_sharp) + flat_sharp) +
                     no_whites + pp.FollowedBy(octave) +
                     octave).setParseAction(lambda t: sum(t))

        self.note_name_parser = (
            full_note + pp.Optional(pp.White()).suppress() +
            pp.Optional(cent) + tok_end
        ).setParseAction(lambda t: float(sum(t))).setResultsName('note_value')

        # frequency parsers
        hertz = real + pp.Literal('Hz').suppress()

        self.frequency_parser = (hertz + tok_end).setParseAction(
            lambda t: float(t[0])).setResultsName('frequency')

        self.base_freq_parser = (
            full_note + pp.Literal('=').suppress() + hertz + tok_end
        ).setParseAction(lambda t: t[1] * (1.0594630943592952645618252949463**
                                           -t[0])).setResultsName('base_freq')

        # parses a string like "sc -7:b" into a musical half tone step (using the MusicConverter.set method)
        sign = (pp.Keyword('##') | pp.Keyword('bb') | pp.Keyword('#')
                | pp.Keyword('b') | pp.Keyword('n') | pp.Keyword('_'))
        self.score_parser = (integer + pp.Literal(':').suppress() + sign +
                             tok_end).setResultsName('notation')

        # amplitude parser
        self.amp_parser = (
            real + pp.Literal('%').suppress() + tok_end
        ).setParseAction(lambda t: float(t[0])).setResultsName('amplitude')

        self.gain_parser = (
            may_sign + real + pp.Literal('dB').suppress() + tok_end
        ).setParseAction(lambda t: float(t[0] * t[1])).setResultsName('gain')

        # clef parser
        self.clef_parser = (pp.Keyword('violin') | pp.Keyword('alto')
                            | pp.Keyword('bass')).setResultsName('clef')

        # key parser
        key_token = pp.NoMatch()
        for key in self.keys:
            key_token = key_token | pp.Keyword(key)

        self.key_parser = (key_token).setResultsName('key')

        # complete parser
        self.input_parser = self.note_name_parser | \
                            self.frequency_parser | \
                            self.base_freq_parser | \
                            self.amp_parser | \
                            self.gain_parser | \
                            self.clef_parser | \
                            self.key_parser | \
                            self.score_parser

        # *** initializations ***
        self.__note_value__ = 0.
        self.__base_freq__ = 440.
        self.base_freq = base_freq

        self.key = new_scale
        self.__names__ = 'C D EF G A B'
        self.clef = clef
        self.__clef__ = 'violin'

        self.max_gain = max_gain
        self.min_gain = min_gain
        self.amplitude = amplitude
Exemplo n.º 19
0
ligature_transformer = pp.oneOf(ligature_map).add_parse_action(
    lambda t: random.choice(ligature_map[t[0]].split()))


def make_mixed_font(t):
    t_0 = t[0][0]
    ret = ['_' if t_0 == '_' else random.choice(ident_char_map.get(t_0, t_0))]
    t_rest = ligature_transformer.transform_string(t[0][1:])
    ret.extend(random.choice(ident_char_map.get(c, c)) for c in t_rest)
    return ''.join(ret)


identifier = pp.pyparsing_common.identifier
identifier.add_parse_action(make_mixed_font)

python_quoted_string = pp.Opt(pp.Char("fF")("f_string_prefix")) + (
    pp.quotedString
    | pp.QuotedString('"""', multiline=True, unquoteResults=False)
    | pp.QuotedString("'''", multiline=True,
                      unquoteResults=False))("quoted_string_body")


def mix_fstring_expressions(t):
    if not t.f_string_prefix:
        return
    fstring_arg = pp.QuotedString("{", end_quote_char="}")
    fstring_arg.add_parse_action(
        lambda tt: "{" + transformer.transform_string(tt[0]) + "}")
    ret = t.f_string_prefix + fstring_arg.transform_string(
        t.quoted_string_body)
    return ret