index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
0
websocket
WebSocket
null
class WebSocket(object): @classmethod def is_socket(self, environ): if 'upgrade' not in environ.get("HTTP_CONNECTION").lower(): return False if environ.get("HTTP_UPGRADE") != "WebSocket": return False if not environ.get("HTTP_ORIGIN"): return False ...
(environ, socket, rfile)
1
websocket
__init__
null
def __init__(self, environ, socket, rfile): # QQQ should reply Bad Request when IOError is raised above # should only log the error message, traceback is not necessary self.origin = environ['HTTP_ORIGIN'] self.protocol = environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', 'unknown') self.path_info = envi...
(self, environ, socket, rfile)
2
websocket
__repr__
null
def __repr__(self): try: info = ' ' + self.socket._formatinfo() except Exception: info = '' return '<%s at %s%s>' % (type(self).__name__, hex(id(self)), info)
(self)
3
websocket
_get_challenge
null
def _get_challenge(self): part1 = self._get_key_value(self.key1) part2 = self._get_key_value(self.key2) # This request should have 8 bytes of data in the body key3 = self.rfile.read(8) challenge = "" challenge += struct.pack("!I", part1) challenge += struct.pack("!I", part2) challenge +=...
(self)
4
websocket
_get_key_value
null
def _get_key_value(self, key_value): key_number = int(re.sub("\\D", "", key_value)) spaces = re.subn(" ", "", key_value)[1] if key_number % spaces != 0: self._reply_400('Invalid key') raise IOError("key_number %r is not an intergral multiple of spaces %r" % (key_number, spaces)) return k...
(self, key_value)
5
websocket
_message_length
null
def _message_length(self): # TODO: buildin security agains lengths greater than 2**31 or 2**32 length = 0 while True: byte_str = self.rfile.read(1) if not byte_str: return 0 else: byte = ord(byte_str) if byte != 0x00: length = length * 128 ...
(self)
6
websocket
_read_until
null
def _read_until(self): bytes = [] while True: byte = self.rfile.read(1) if ord(byte) != 0xff: bytes.append(byte) else: break return ''.join(bytes)
(self)
7
websocket
_reply_400
null
def _reply_400(self, message): self._send_reply('400 Bad Request', [('Content-Length', str(len(message))), ('Content-Type', 'text/plain')], message) self.socket = None self.rfile = None
(self, message)
8
websocket
_send_reply
null
def _send_reply(self, status, headers, message=None): self.status = status self.headers_sent = True towrite = ['HTTP/1.1 %s\r\n' % self.status] for header in headers: towrite.append("%s: %s\r\n" % header) towrite.append("\r\n") if message: towrite.append(message) self.socket....
(self, status, headers, message=None)
9
websocket
close
null
def close(self): # XXX implement graceful close with 0xFF frame if self.socket is not None: try: self.socket.close() except Exception: pass self.socket = None self.rfile = None
(self)
10
websocket
do_handshake
This method is called automatically in the first send() or receive()
def do_handshake(self): """This method is called automatically in the first send() or receive()""" assert not self.handshaked, 'Already did handshake' if self.key1 is not None: # version 76 if not self.key1: message = "Missing HTTP_SEC_WEBSOCKET_KEY1 header in the request" ...
(self)
11
websocket
getpeername
null
def getpeername(self): return self.socket.getpeername()
(self)
12
websocket
getsockname
null
def getsockname(self): return self.socket.getsockname()
(self)
13
websocket
receive
null
def receive(self): if not self.handshaked: self.do_handshake() while self.socket is not None: frame_str = self.rfile.read(1) if not frame_str: self.close() break else: frame_type = ord(frame_str) if (frame_type & 0x80) == 0x00: # most ...
(self)
14
websocket
send
null
def send(self, message): if not self.handshaked: self.do_handshake() if isinstance(message, str): pass elif isinstance(message, unicode): message = message.encode('utf-8') else: raise TypeError("Expected string or unicode: %r" % (message, )) self.socket.sendall("\x00"...
(self, message)
15
builtins
str
str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if ...
from builtins import str
null
17
moscow_yandex_transport
YandexMapsRequester
null
class YandexMapsRequester(object): def __init__(self, user_agent: str = None): """ :type user_agent: set user agent for data requester """ self._config = CONFIG if user_agent is not None: CONFIG['headers']['User-Agent'] = user_agent self.set_new_session()...
(user_agent: str = None)
18
moscow_yandex_transport
__init__
:type user_agent: set user agent for data requester
def __init__(self, user_agent: str = None): """ :type user_agent: set user agent for data requester """ self._config = CONFIG if user_agent is not None: CONFIG['headers']['User-Agent'] = user_agent self.set_new_session()
(self, user_agent: Optional[str] = None)
19
moscow_yandex_transport
get_stop_info
" get transport data for stop_id in json
def get_stop_info(self, stop_id): """" get transport data for stop_id in json """ self._config["params"]["id"] = f"stop__{stop_id}" req = requests.get(self._config["uri"], params=self._config["params"], cookies=self._config["cookies"], headers=self._config["headers"]) retu...
(self, stop_id)
20
moscow_yandex_transport
set_new_session
Create new http session to Yandex, with valid csrf_token and session_id
def set_new_session(self): """ Create new http session to Yandex, with valid csrf_token and session_id """ ya_request = requests.get(url=self._config["init_url"], headers=self._config["headers"]) reply = ya_request.content.decode('utf8') self._config["params"][CSRF_TOKEN_KEY] = re.search(f'"{CSR...
(self)
21
json
loads
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict...
def loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be...
(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
26
pycookiecheat.chrome
chrome_cookies
Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) cookie_file: Path to alternate file to search for cookies browser: Name of the browser's cookies to read ('Chrome' or 'Chromium') curl_cookie_file: Path to ...
def chrome_cookies( url: str, cookie_file: t.Optional[str] = None, browser: str = "Chrome", curl_cookie_file: t.Optional[str] = None, password: t.Optional[t.Union[bytes, str]] = None, ) -> dict: """Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which t...
(url: str, cookie_file: Optional[str] = None, browser: str = 'Chrome', curl_cookie_file: Optional[str] = None, password: Union[bytes, str, NoneType] = None) -> dict
29
pycookiecheat.firefox
firefox_cookies
Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) profile_name: Name (or glob pattern) of the Firefox profile to search for cookies -- if none given it will find the configured d...
def firefox_cookies( url: str, profile_name: Optional[str] = None, browser: str = "Firefox", curl_cookie_file: Optional[str] = None, ) -> Dict[str, str]: """Retrieve cookies from Chrome/Chromium on OSX or Linux. Args: url: Domain from which to retrieve cookies, starting with http(s) ...
(url: str, profile_name: Optional[str] = None, browser: str = 'Firefox', curl_cookie_file: Optional[str] = None) -> Dict[str, str]
30
arpeggio
And
This predicate will succeed if the specified expression matches current input.
class And(SyntaxPredicate): """ This predicate will succeed if the specified expression matches current input. """ def _parse(self, parser): c_pos = parser.position for e in self.nodes: try: e.parse(parser) except NoMatch: parse...
(*elements, **kwargs)
31
arpeggio
__init__
null
def __init__(self, *elements, **kwargs): if len(elements) == 1: elements = elements[0] self.elements = elements self.rule_name = kwargs.get('rule_name', '') self.root = kwargs.get('root', False) nodes = kwargs.get('nodes', []) if not hasattr(nodes, '__iter__'): nodes = [nodes] ...
(self, *elements, **kwargs)
32
arpeggio
_clear_cache
Clears memoization cache. Should be called on input change and end of parsing. Args: processed (set): Set of processed nodes to prevent infinite loops.
def _clear_cache(self, processed=None): """ Clears memoization cache. Should be called on input change and end of parsing. Args: processed (set): Set of processed nodes to prevent infinite loops. """ self._result_cache = {} if not processed: processed = set() for node in ...
(self, processed=None)
33
arpeggio
_parse
null
def _parse(self, parser): c_pos = parser.position for e in self.nodes: try: e.parse(parser) except NoMatch: parser.position = c_pos raise parser.position = c_pos
(self, parser)
34
arpeggio
parse
null
def parse(self, parser): if parser.debug: name = self.name if name.startswith('__asgn'): name = "{}[{}]".format(self.name, self._attr_name) parser.dprint(">> Matching rule {}{} at position {} => {}" .format(name, " in {}".format...
(self, parser)
35
arpeggio
ArpeggioError
Base class for arpeggio errors.
class ArpeggioError(Exception): """ Base class for arpeggio errors. """ def __init__(self, message): self.message = message def __str__(self): return repr(self.message)
(message)
36
arpeggio
__init__
null
def __init__(self, message): self.message = message
(self, message)
37
arpeggio
__str__
null
def __str__(self): return repr(self.message)
(self)
38
arpeggio
Combine
This decorator defines pexpression that represents a lexeme rule. This rules will always return a Terminal parse tree node. Whitespaces will be preserved. Comments will not be matched.
class Combine(Decorator): """ This decorator defines pexpression that represents a lexeme rule. This rules will always return a Terminal parse tree node. Whitespaces will be preserved. Comments will not be matched. """ def _parse(self, parser): results = [] oldin_lex_rule = pars...
(*elements, **kwargs)
41
arpeggio
_parse
null
def _parse(self, parser): results = [] oldin_lex_rule = parser.in_lex_rule parser.in_lex_rule = True c_pos = parser.position try: for parser_model_node in self.nodes: results.append(parser_model_node.parse(parser)) results = flatten(results) # Create terminal from...
(self, parser)
43
arpeggio
CrossRef
Used for rule reference resolving.
class CrossRef(object): ''' Used for rule reference resolving. ''' def __init__(self, target_rule_name, position=-1): self.target_rule_name = target_rule_name self.position = position
(target_rule_name, position=-1)
44
arpeggio
__init__
null
def __init__(self, target_rule_name, position=-1): self.target_rule_name = target_rule_name self.position = position
(self, target_rule_name, position=-1)
45
arpeggio
DebugPrinter
Mixin class for adding debug print support. Attributes: debug (bool): If true debugging messages will be printed. _current_indent(int): Current indentation level for prints.
class DebugPrinter(object): """ Mixin class for adding debug print support. Attributes: debug (bool): If true debugging messages will be printed. _current_indent(int): Current indentation level for prints. """ def __init__(self, **kwargs): self.debug = kwargs.pop("debug", ...
(**kwargs)
46
arpeggio
__init__
null
def __init__(self, **kwargs): self.debug = kwargs.pop("debug", False) self.file = kwargs.pop("file", sys.stdout) self._current_indent = 0 super(DebugPrinter, self).__init__(**kwargs)
(self, **kwargs)
47
arpeggio
dprint
Handle debug message. Print to the stream specified by the 'file' keyword argument at the current indentation level. Default stream is stdout.
def dprint(self, message, indent_change=0): """ Handle debug message. Print to the stream specified by the 'file' keyword argument at the current indentation level. Default stream is stdout. """ if indent_change < 0: self._current_indent += indent_change print(("%s%s" % (" " * self...
(self, message, indent_change=0)
48
arpeggio
Decorator
Decorator are special kind of parsing expression used to mark a containing pexpression and give it some special semantics. For example, decorators are used to mark pexpression as lexical rules (see :class:Lex).
class Decorator(ParsingExpression): """ Decorator are special kind of parsing expression used to mark a containing pexpression and give it some special semantics. For example, decorators are used to mark pexpression as lexical rules (see :class:Lex). """
(*elements, **kwargs)
52
arpeggio
EOF
null
def EOF(): return EndOfFile()
()
53
arpeggio
Empty
This predicate will always succeed without consuming input.
class Empty(SyntaxPredicate): """ This predicate will always succeed without consuming input. """ def _parse(self, parser): pass
(*elements, **kwargs)
56
arpeggio
_parse
null
def _parse(self, parser): pass
(self, parser)
58
arpeggio
EndOfFile
The Match class that will succeed in case end of input is reached.
class EndOfFile(Match): """ The Match class that will succeed in case end of input is reached. """ def __init__(self): super(EndOfFile, self).__init__("EOF") @property def name(self): return "EOF" def _parse(self, parser): c_pos = parser.position if len(pars...
()
59
arpeggio
__init__
null
def __init__(self): super(EndOfFile, self).__init__("EOF")
(self)
61
arpeggio
_parse
null
def _parse(self, parser): c_pos = parser.position if len(parser.input) == c_pos: return Terminal(EOF(), c_pos, '', suppress=True) else: if parser.debug: parser.dprint("!! EOF not matched.") parser._nm_raise(self, c_pos, parser)
(self, parser)
62
arpeggio
_parse_comments
Parse comments.
def _parse_comments(self, parser): """Parse comments.""" try: parser.in_parse_comments = True if parser.comments_model: try: while True: # TODO: Consumed whitespaces and comments should be # attached to the first match ahe...
(self, parser)
63
arpeggio
parse
null
def parse(self, parser): if parser.skipws and not parser.in_lex_rule: # Whitespace skipping pos = parser.position ws = parser.ws i = parser.input length = len(i) while pos < length and i[pos] in ws: pos += 1 parser.position = pos if parser.debu...
(self, parser)
64
arpeggio
GrammarError
Error raised during parser building phase used to indicate error in the grammar definition.
class GrammarError(ArpeggioError): """ Error raised during parser building phase used to indicate error in the grammar definition. """
(message)
67
arpeggio
Kwd
A specialization of StrMatch to specify keywords of the language.
class Kwd(StrMatch): """ A specialization of StrMatch to specify keywords of the language. """ def __init__(self, to_match): super(Kwd, self).__init__(to_match) self.to_match = to_match self.root = True self.rule_name = 'keyword'
(to_match)
68
arpeggio
__eq__
null
def __eq__(self, other): return self.to_match == text(other)
(self, other)
69
arpeggio
__hash__
null
def __hash__(self): return hash(self.to_match)
(self)
70
arpeggio
__init__
null
def __init__(self, to_match): super(Kwd, self).__init__(to_match) self.to_match = to_match self.root = True self.rule_name = 'keyword'
(self, to_match)
71
arpeggio
__str__
null
def __str__(self): return self.to_match
(self)
72
arpeggio
__unicode__
null
def __unicode__(self): return self.__str__()
(self)
74
arpeggio
_parse
null
def _parse(self, parser): c_pos = parser.position input_frag = parser.input[c_pos:c_pos+len(self.to_match)] if self.ignore_case: match = input_frag.lower() == self.to_match.lower() else: match = input_frag == self.to_match if match: if parser.debug: parser.dprint(...
(self, parser)
77
arpeggio
Match
Base class for all classes that will try to match something from the input.
class Match(ParsingExpression): """ Base class for all classes that will try to match something from the input. """ def __init__(self, rule_name, root=False, **kwargs): super(Match, self).__init__(rule_name=rule_name, root=root, **kwargs) @property def name(self): if self.root: ...
(rule_name, root=False, **kwargs)
78
arpeggio
__init__
null
def __init__(self, rule_name, root=False, **kwargs): super(Match, self).__init__(rule_name=rule_name, root=root, **kwargs)
(self, rule_name, root=False, **kwargs)
82
arpeggio
NoMatch
Exception raised by the Match classes during parsing to indicate that the match is not successful. Args: rules (list of ParsingExpression): Rules that are tried at the position of the exception. position (int): A position in the input stream where exception occurred...
class NoMatch(Exception): """ Exception raised by the Match classes during parsing to indicate that the match is not successful. Args: rules (list of ParsingExpression): Rules that are tried at the position of the exception. position (int): A position in the input stream whe...
(rules, position, parser)
83
arpeggio
__init__
null
def __init__(self, rules, position, parser): self.rules = rules self.position = position self.parser = parser
(self, rules, position, parser)
84
arpeggio
__str__
null
def __str__(self): self.eval_attrs() return "{} at position {}{} => '{}'."\ .format(self.message, "{}:".format(self.parser.file_name) if self.parser.file_name else "", (self.line, self.col), self.context)
(self)
86
arpeggio
eval_attrs
Call this to evaluate `message`, `context`, `line` and `col`. Called by __str__.
def eval_attrs(self): """ Call this to evaluate `message`, `context`, `line` and `col`. Called by __str__. """ def rule_to_exp_str(rule): if hasattr(rule, '_exp_str'): # Rule may override expected report string return rule._exp_str elif rule.root: retu...
(self)
87
arpeggio
NonTerminal
Non-leaf node of the Parse Tree. Represents language syntax construction. At the same time used in ParseTreeNode navigation expressions. See test_ptnode_navigation_expressions.py for examples of navigation expressions. Attributes: nodes (list of ParseTreeNode): Children parse tree nodes. ...
class NonTerminal(ParseTreeNode, list): """ Non-leaf node of the Parse Tree. Represents language syntax construction. At the same time used in ParseTreeNode navigation expressions. See test_ptnode_navigation_expressions.py for examples of navigation expressions. Attributes: nodes (list ...
(rule, nodes, error=False, _filtered=False)
88
arpeggio
__getattr__
Find a child (non)terminal by the rule name. Args: rule_name(str): The name of the rule that is referenced from this node rule.
def __getattr__(self, rule_name): """ Find a child (non)terminal by the rule name. Args: rule_name(str): The name of the rule that is referenced from this node rule. """ # Prevent infinite recursion if rule_name in ['_expr_cache', '_filtered', 'rule', 'rule_name', ...
(self, rule_name)
89
arpeggio
__init__
null
def __init__(self, rule, nodes, error=False, _filtered=False): # Inherit position from the first child node position = nodes[0].position if nodes else 0 super(NonTerminal, self).__init__(rule, position, error) self.extend(flatten([nodes])) self._filtered = _filtered
(self, rule, nodes, error=False, _filtered=False)
90
arpeggio
__repr__
null
def __repr__(self): return "[ %s ]" % ", ".join([repr(x) for x in self])
(self)
91
arpeggio
__str__
null
def __str__(self): return " | ".join([text(x) for x in self])
(self)
93
arpeggio
flat_str
Return flatten string representation.
def flat_str(self): """ Return flatten string representation. """ return "".join([x.flat_str() for x in self])
(self)
94
arpeggio
tree_str
null
def tree_str(self, indent=0): return '{}\n{}'.format(super(NonTerminal, self).tree_str(indent), '\n'.join([c.tree_str(indent + 1) for c in self]))
(self, indent=0)
95
arpeggio
visit
Visitor pattern implementation. Args: visitor(PTNodeVisitor): The visitor object.
def visit(self, visitor): """ Visitor pattern implementation. Args: visitor(PTNodeVisitor): The visitor object. """ if visitor.debug: visitor.dprint("Visiting {} type:{} str:{}" .format(self.name, type(self).__name__, text(self))) children = SemanticAction...
(self, visitor)
96
arpeggio
Not
This predicate will succeed if the specified expression doesn't match current input.
class Not(SyntaxPredicate): """ This predicate will succeed if the specified expression doesn't match current input. """ def _parse(self, parser): c_pos = parser.position old_in_not = parser.in_not parser.in_not = True try: for e in self.nodes: ...
(*elements, **kwargs)
99
arpeggio
_parse
null
def _parse(self, parser): c_pos = parser.position old_in_not = parser.in_not parser.in_not = True try: for e in self.nodes: try: e.parse(parser) except NoMatch: parser.position = c_pos return parser.position = c_pos ...
(self, parser)
101
arpeggio
OneOrMore
OneOrMore will try to match parser expression specified one or more times.
class OneOrMore(Repetition): """ OneOrMore will try to match parser expression specified one or more times. """ def _parse(self, parser): results = [] first = True if self.eolterm: # Remember current eolterm and set eolterm of # this repetition ...
(*elements, **kwargs)
102
arpeggio
__init__
null
def __init__(self, *elements, **kwargs): super(Repetition, self).__init__(*elements, **kwargs) self.eolterm = kwargs.get('eolterm', False) self.sep = kwargs.get('sep', None)
(self, *elements, **kwargs)
104
arpeggio
_parse
null
def _parse(self, parser): results = [] first = True if self.eolterm: # Remember current eolterm and set eolterm of # this repetition old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append p = self.nodes[0].parse sep = ...
(self, parser)
106
arpeggio
Optional
Optional will try to match parser expression specified and will not fail in case match is not successful.
class Optional(Repetition): """ Optional will try to match parser expression specified and will not fail in case match is not successful. """ def _parse(self, parser): result = None c_pos = parser.position try: result = [self.nodes[0].parse(parser)] excep...
(*elements, **kwargs)
109
arpeggio
_parse
null
def _parse(self, parser): result = None c_pos = parser.position try: result = [self.nodes[0].parse(parser)] except NoMatch: parser.position = c_pos # Backtracking return result
(self, parser)
111
arpeggio
OrderedChoice
Will match one of the parser expressions specified. Parser will try to match expressions in the order they are defined.
class OrderedChoice(Sequence): """ Will match one of the parser expressions specified. Parser will try to match expressions in the order they are defined. """ def _parse(self, parser): result = None match = False c_pos = parser.position if self.ws is not None: ...
(*elements, **kwargs)
112
arpeggio
__init__
null
def __init__(self, *elements, **kwargs): super(Sequence, self).__init__(*elements, **kwargs) self.ws = kwargs.pop('ws', None) self.skipws = kwargs.pop('skipws', None)
(self, *elements, **kwargs)
114
arpeggio
_parse
null
def _parse(self, parser): result = None match = False c_pos = parser.position if self.ws is not None: old_ws = parser.ws parser.ws = self.ws if self.skipws is not None: old_skipws = parser.skipws parser.skipws = self.skipws try: for e in self.nodes: ...
(self, parser)
116
collections
OrderedDict
Dictionary that remembers insertion order
class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as regular dictionaries...
null
117
arpeggio
PTNodeVisitor
Base class for all parse tree visitors.
class PTNodeVisitor(DebugPrinter): """ Base class for all parse tree visitors. """ def __init__(self, defaults=True, **kwargs): """ Args: defaults(bool): If the default visit method should be applied in case no method is defined. """ self.for_s...
(defaults=True, **kwargs)
118
arpeggio
__init__
Args: defaults(bool): If the default visit method should be applied in case no method is defined.
def __init__(self, defaults=True, **kwargs): """ Args: defaults(bool): If the default visit method should be applied in case no method is defined. """ self.for_second_pass = [] self.defaults = defaults super(PTNodeVisitor, self).__init__(**kwargs)
(self, defaults=True, **kwargs)
120
arpeggio
visit__default__
Called if no visit method is defined for the node. Args: node(ParseTreeNode): children(processed children ParseTreeNode-s):
def visit__default__(self, node, children): """ Called if no visit method is defined for the node. Args: node(ParseTreeNode): children(processed children ParseTreeNode-s): """ if isinstance(node, Terminal): # Default for Terminal is to convert to string unless suppress flag ...
(self, node, children)
121
arpeggio
ParseTreeNode
Abstract base class representing node of the Parse Tree. The node can be terminal(the leaf of the parse tree) or non-terminal. Attributes: rule (ParsingExpression): The rule that created this node. rule_name (str): The name of the rule that created this node if root rule or emp...
class ParseTreeNode(object): """ Abstract base class representing node of the Parse Tree. The node can be terminal(the leaf of the parse tree) or non-terminal. Attributes: rule (ParsingExpression): The rule that created this node. rule_name (str): The name of the rule that created this ...
(rule, position, error)
122
arpeggio
__init__
null
def __init__(self, rule, position, error): assert rule assert rule.rule_name is not None self.rule = rule self.rule_name = rule.rule_name self.position = position self.error = error self.comments = None
(self, rule, position, error)
123
arpeggio
tree_str
null
def tree_str(self, indent=0): return '{}{} [{}-{}]'.format(' ' * indent, self.rule.name, self.position, self.position_end)
(self, indent=0)
125
arpeggio
Parser
Abstract base class for all parsers. Attributes: comments_model: parser model for comments. comments(list): A list of ParseTreeNode for matched comments. sem_actions(dict): A dictionary of semantic actions keyed by the rule name. parse_tree(NonTerminal): The parse t...
class Parser(DebugPrinter): """ Abstract base class for all parsers. Attributes: comments_model: parser model for comments. comments(list): A list of ParseTreeNode for matched comments. sem_actions(dict): A dictionary of semantic actions keyed by the rule name. p...
(skipws=True, ws=None, reduce_tree=False, autokwd=False, ignore_case=False, memoization=False, **kwargs)
126
arpeggio
__init__
Args: skipws (bool): Should the whitespace skipping be done. Default is True. ws (str): A string consisting of whitespace characters. reduce_tree (bool): If true non-terminals with single child will be eliminated from the parse tree. Default ...
def __init__(self, skipws=True, ws=None, reduce_tree=False, autokwd=False, ignore_case=False, memoization=False, **kwargs): """ Args: skipws (bool): Should the whitespace skipping be done. Default is True. ws (str): A string consisting of whitespace characters. ...
(self, skipws=True, ws=None, reduce_tree=False, autokwd=False, ignore_case=False, memoization=False, **kwargs)
127
arpeggio
_clear_caches
Clear memoization caches if packrat parser is used.
def _clear_caches(self): """ Clear memoization caches if packrat parser is used. """ self.parser_model._clear_cache() if self.comments_model: self.comments_model._clear_cache()
(self)
128
arpeggio
_nm_raise
Register new NoMatch object if the input is consumed from the last NoMatch and raise last NoMatch. Args: args: A NoMatch instance or (value, position, parser)
def _nm_raise(self, *args): """ Register new NoMatch object if the input is consumed from the last NoMatch and raise last NoMatch. Args: args: A NoMatch instance or (value, position, parser) """ rule, position, parser = args if self.nm is None or not parser.in_parse_comments: ...
(self, *args)
129
arpeggio
context
Returns current context substring, i.e. the substring around current position. Args: length(int): If given used to mark with asterisk a length chars from the current position. position(int): The position in the input stream.
def context(self, length=None, position=None): """ Returns current context substring, i.e. the substring around current position. Args: length(int): If given used to mark with asterisk a length chars from the current position. position(int): The position in the input stream. ...
(self, length=None, position=None)
131
arpeggio
getASG
Creates Abstract Semantic Graph (ASG) from the parse tree. Args: sem_actions (dict): The semantic actions dictionary to use for semantic analysis. Rule names are the keys and semantic action objects are values. defaults (bool): If True a default ...
def getASG(self, sem_actions=None, defaults=True): """ Creates Abstract Semantic Graph (ASG) from the parse tree. Args: sem_actions (dict): The semantic actions dictionary to use for semantic analysis. Rule names are the keys and semantic action objects are values. de...
(self, sem_actions=None, defaults=True)
132
arpeggio
parse
Parses input and produces parse tree. Args: _input(str): An input string to parse. file_name(str): If input is loaded from file this can be set to file name. It is used in error messages.
def parse(self, _input, file_name=None): """ Parses input and produces parse tree. Args: _input(str): An input string to parse. file_name(str): If input is loaded from file this can be set to file name. It is used in error messages. """ self.position = 0 # Input position...
(self, _input, file_name=None)
133
arpeggio
parse_file
Parses content from the given file. Args: file_name(str): A file name.
def parse_file(self, file_name): """ Parses content from the given file. Args: file_name(str): A file name. """ with codecs.open(file_name, 'r', 'utf-8') as f: content = f.read() return self.parse(content, file_name=file_name)
(self, file_name)
134
arpeggio
pos_to_linecol
Calculate (line, column) tuple for the given position in the stream.
def pos_to_linecol(self, pos): """ Calculate (line, column) tuple for the given position in the stream. """ if not self.line_ends: try: # TODO: Check this implementation on Windows. self.line_ends.append(self.input.index("\n")) while True: try:...
(self, pos)
135
arpeggio
ParserPython
null
class ParserPython(Parser): def __init__(self, language_def, comment_def=None, syntax_classes=None, *args, **kwargs): """ Constructs parser from python statements and expressions. Args: language_def (python function): A python function that defines ...
(language_def, comment_def=None, syntax_classes=None, *args, **kwargs)
136
arpeggio
__init__
Constructs parser from python statements and expressions. Args: language_def (python function): A python function that defines the root rule of the grammar. comment_def (python function): A python function that defines the root rule of the commen...
def __init__(self, language_def, comment_def=None, syntax_classes=None, *args, **kwargs): """ Constructs parser from python statements and expressions. Args: language_def (python function): A python function that defines the root rule of the grammar. comment_def (pyt...
(self, language_def, comment_def=None, syntax_classes=None, *args, **kwargs)
138
arpeggio
_from_python
Create parser model from the definition given in the form of python functions returning lists, tuples, callables, strings and ParsingExpression objects. Returns: Parser Model (PEG Abstract Semantic Graph)
def _from_python(self, expression): """ Create parser model from the definition given in the form of python functions returning lists, tuples, callables, strings and ParsingExpression objects. Returns: Parser Model (PEG Abstract Semantic Graph) """ __rule_cache = {"EndOfFile": EndOfF...
(self, expression)
140
arpeggio
_parse
null
def _parse(self): return self.parser_model.parse(self)
(self)
143
arpeggio
errors
null
def errors(self): pass
(self)