index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
8.19k
signature
stringlengths
2
42.8k
embed_func_code
listlengths
768
768
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 return True 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 = environ['PATH_INFO'] self.host = environ['HTTP_HOST'] self.key1 = environ.get('HTTP_SEC_WEBSOCKET_KEY1') self.key2 = environ.get('HTTP_SEC_WEBSOCKET_KEY2') self.socket = socket self.rfile = rfile self.handshaked = False def __repr__(self): try: info = ' ' + self.socket._formatinfo() except Exception: info = '' return '<%s at %s%s>' % (type(self).__name__, hex(id(self)), info) 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._reply_400(message) raise IOError(message) if not self.key2: message = "Missing HTTP_SEC_WEBSOCKET_KEY2 header in the request" self._reply_400(message) raise IOError(message) headers = [ ("Upgrade", "WebSocket"), ("Connection", "Upgrade"), ("Sec-WebSocket-Origin", self.origin), ("Sec-WebSocket-Protocol", self.protocol), ("Sec-WebSocket-Location", "ws://" + self.host + self.path_info), ] self._send_reply("101 Web Socket Protocol Handshake", headers) challenge = self._get_challenge() self.socket.sendall(challenge) else: # version 75 headers = [ ("Upgrade", "WebSocket"), ("Connection", "Upgrade"), ("WebSocket-Origin", self.websocket.origin), ("WebSocket-Protocol", self.websocket.protocol), ("WebSocket-Location", "ws://" + self.host + self.path_info), ] self._send_reply("101 Web Socket Protocol Handshake", headers) self.handshaked = True 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.sendall(''.join(towrite)) 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 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 key_number / spaces 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 += key3 return md5(challenge).digest() 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" + message + "\xFF") 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 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 + (byte & 0x7f) if (byte & 0x80) != 0x80: break return length def _read_until(self): bytes = [] while True: byte = self.rfile.read(1) if ord(byte) != 0xff: bytes.append(byte) else: break return ''.join(bytes) 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 significant byte is not set if frame_type == 0x00: bytes = self._read_until() return bytes.decode("utf-8") else: self.close() elif (frame_type & 0x80) == 0x80: # most significant byte is set # Read binary data (forward-compatibility) if frame_type != 0xff: self.close() break else: length = self._message_length() if length == 0: self.close() break else: self.rfile.read(length) # discard the bytes else: raise IOError("Received invalid message") def getsockname(self): return self.socket.getsockname() def getpeername(self): return self.socket.getpeername()
(environ, socket, rfile)
[ -0.011135046370327473, -0.039216987788677216, -0.11918970197439194, 0.02561788447201252, -0.013432754203677177, -0.03643062710762024, -0.034663159400224686, 0.05181799456477165, -0.037116821855306625, -0.04019429534673691, 0.01584482751786709, 0.04815829545259476, 0.008078367449343204, 0.0...
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 = environ['PATH_INFO'] self.host = environ['HTTP_HOST'] self.key1 = environ.get('HTTP_SEC_WEBSOCKET_KEY1') self.key2 = environ.get('HTTP_SEC_WEBSOCKET_KEY2') self.socket = socket self.rfile = rfile self.handshaked = False
(self, environ, socket, rfile)
[ -0.04108428582549095, -0.035939496010541916, -0.10785550624132156, 0.00980841089040041, -0.02004246972501278, -0.019283706322312355, -0.020967790856957436, 0.0590355284512043, -0.05041152983903885, 0.008832195773720741, 0.04315700754523277, 0.08831270784139633, 0.015961799770593643, 0.0338...
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)
[ 0.024408552795648575, -0.017195727676153183, 0.03823239728808403, 0.006221614312380552, 0.046834684908390045, -0.07320795953273773, 0.012089225463569164, 0.0142220975831151, 0.014363698661327362, -0.048144496977329254, -0.02463865466415882, 0.02154112234711647, -0.026373272761702538, 0.007...
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 += key3 return md5(challenge).digest()
(self)
[ -0.011837348341941833, -0.009784940630197525, -0.03544903174042702, 0.08029592782258987, 0.004467136226594448, -0.03681730479001999, 0.005230037495493889, -0.015285031870007515, 0.00002579222564236261, 0.016059186309576035, 0.043424613773822784, 0.09117008745670319, -0.015186012722551823, ...
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 key_number / spaces
(self, key_value)
[ 0.05641850829124451, 0.027373693883419037, -0.09503594040870667, 0.05205906182527542, 0.04908010736107826, 0.020798195153474808, 0.0279912818223238, -0.026883255690336227, 0.07080468535423279, -0.06430184096097946, 0.012669642455875874, 0.021706413477659225, 0.01685652881860733, 0.01363235...
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 + (byte & 0x7f) if (byte & 0x80) != 0x80: break return length
(self)
[ -0.02438482828438282, 0.007201713044196367, 0.015868335962295532, 0.0898963063955307, 0.04178176447749138, 0.007552017457783222, 0.01111875381320715, -0.006705827545374632, 0.03311968967318535, -0.026040812954306602, 0.0299896989017725, 0.04280083253979683, -0.013548137620091438, -0.008107...
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)
[ -0.03385533019900322, -0.02092122659087181, -0.08310925960540771, 0.058140505105257034, 0.017107555642724037, 0.023763492703437805, 0.008913557976484299, 0.021263018250465393, 0.060299187898635864, -0.0532115139067173, 0.06288960576057434, 0.011584927327930927, -0.00976803619414568, 0.0283...
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)
[ -0.02454221248626709, 0.03832029551267624, -0.024057826027274132, 0.03781796991825104, -0.04542462155222893, -0.03065982647240162, -0.019823936745524406, 0.0740572065114975, 0.06634291261434555, -0.06196549907326698, 0.0227481909096241, -0.00874585472047329, 0.014056157320737839, -0.014989...
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.sendall(''.join(towrite))
(self, status, headers, message=None)
[ -0.0509067103266716, 0.02246098965406418, -0.10590055584907532, -0.03526977449655533, 0.025362124666571617, -0.029978396371006966, -0.07984507828950882, 0.08320236951112747, 0.016914164647459984, 0.0071342382580041885, -0.016731703653931618, -0.037057895213365555, 0.03156581148505211, -0.0...
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)
[ 0.007682926952838898, -0.054943498224020004, -0.016643404960632324, 0.04507552087306976, -0.049657080322504044, -0.057903893291950226, -0.05441485717892647, 0.09325240552425385, -0.008537564426660538, -0.016229301691055298, -0.006141054909676313, -0.0436658076941967, 0.03767453506588936, -...
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._reply_400(message) raise IOError(message) if not self.key2: message = "Missing HTTP_SEC_WEBSOCKET_KEY2 header in the request" self._reply_400(message) raise IOError(message) headers = [ ("Upgrade", "WebSocket"), ("Connection", "Upgrade"), ("Sec-WebSocket-Origin", self.origin), ("Sec-WebSocket-Protocol", self.protocol), ("Sec-WebSocket-Location", "ws://" + self.host + self.path_info), ] self._send_reply("101 Web Socket Protocol Handshake", headers) challenge = self._get_challenge() self.socket.sendall(challenge) else: # version 75 headers = [ ("Upgrade", "WebSocket"), ("Connection", "Upgrade"), ("WebSocket-Origin", self.websocket.origin), ("WebSocket-Protocol", self.websocket.protocol), ("WebSocket-Location", "ws://" + self.host + self.path_info), ] self._send_reply("101 Web Socket Protocol Handshake", headers) self.handshaked = True
(self)
[ -0.06672488152980804, -0.039717189967632294, -0.09143780171871185, -0.0036539817228913307, -0.0361514687538147, -0.01620461419224739, -0.02319484017789364, 0.055180419236421585, -0.03968188911676407, 0.009505648165941238, 0.022418148815631866, -0.00009508681978331879, 0.021747369319200516, ...
11
websocket
getpeername
null
def getpeername(self): return self.socket.getpeername()
(self)
[ 0.012900936417281628, 0.01073470152914524, 0.013269283808767796, 0.05276140943169594, -0.03658919408917427, -0.02645086497068405, 0.06865297257900238, 0.008397447876632214, 0.06381183862686157, -0.039851702749729156, -0.028239982202649117, -0.040553316473960876, -0.04058839753270149, -0.02...
12
websocket
getsockname
null
def getsockname(self): return self.socket.getsockname()
(self)
[ 0.038244377821683884, 0.020540641620755196, 0.004740148317068815, 0.015342638827860355, -0.011087278835475445, -0.006131669040769339, 0.04240996390581131, -0.005682791117578745, 0.060688260942697525, -0.03589225932955742, -0.038244377821683884, -0.047365572303533554, -0.03337854519486427, ...
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 significant byte is not set if frame_type == 0x00: bytes = self._read_until() return bytes.decode("utf-8") else: self.close() elif (frame_type & 0x80) == 0x80: # most significant byte is set # Read binary data (forward-compatibility) if frame_type != 0xff: self.close() break else: length = self._message_length() if length == 0: self.close() break else: self.rfile.read(length) # discard the bytes else: raise IOError("Received invalid message")
(self)
[ 0.006777434144169092, -0.030777743086218834, -0.06136929243803024, 0.01589159294962883, -0.014653408899903297, -0.03710831329226494, 0.014904769137501717, 0.043308548629283905, 0.019140666350722313, -0.0334775447845459, -0.007177749648690224, 0.015016485005617142, -0.029660584405064583, 0....
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" + message + "\xFF")
(self, message)
[ -0.031467147171497345, 0.02515200525522232, -0.03248046711087227, 0.016737844794988632, -0.013001234270632267, -0.05475537106394768, -0.059749580919742584, 0.08026927709579468, 0.05670962855219841, -0.037637531757354736, 0.00583562720566988, 0.021080637350678444, -0.0348690040409565, 0.008...
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 defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
from builtins import str
null
[ -0.014316649176180363, -0.004014108795672655, -0.004127926658838987, -0.003099501831457019, 0.020162004977464676, 0.011243569664657116, 0.03778750076889992, 0.035153429955244064, 0.03827529028058052, -0.06913616508245468, 0.004442957695573568, 0.029478801414370537, -0.026275645941495895, 0...
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() 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"]) return loads(req.content.decode('utf8')) 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'"{CSRF_TOKEN_KEY}":"(\w+.\w+)"', reply).group(1) self._config["cookies"] = dict(ya_request.cookies) self._config["params"][SESSION_KEY] = re.search(f'"{SESSION_KEY}":"(\d+.\d+)"', reply).group(1)
(user_agent: str = None)
[ 0.07295291125774384, 0.005364458542317152, -0.09431769698858261, 0.002149505540728569, -0.05966506153345108, 0.018554605543613434, -0.11084376275539398, 0.04741939529776573, -0.011510555632412434, -0.011985121294856071, -0.007090576458722353, 0.0048945448361337185, -0.027990097180008888, 0...
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)
[ -0.02888535149395466, -0.025036437436938286, -0.05573521926999092, -0.03934032842516899, -0.0070177894085645676, -0.019004007801413536, -0.030587755143642426, 0.03512132912874222, -0.024721862748265266, -0.00706867640838027, -0.01147272065281868, 0.026849867776036263, -0.009872091002762318, ...
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"]) return loads(req.content.decode('utf8'))
(self, stop_id)
[ 0.06164545193314552, 0.029862787574529648, -0.006518849637359381, -0.019251113757491112, 0.004660061094909906, -0.008094020187854767, -0.010725121945142746, 0.05728209763765335, -0.004481163807213306, -0.00844308827072382, -0.08670855313539505, -0.053581975400447845, -0.009136861190199852, ...
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'"{CSRF_TOKEN_KEY}":"(\w+.\w+)"', reply).group(1) self._config["cookies"] = dict(ya_request.cookies) self._config["params"][SESSION_KEY] = re.search(f'"{SESSION_KEY}":"(\d+.\d+)"', reply).group(1)
(self)
[ -0.030743589624762535, -0.011363360099494457, -0.01755988597869873, -0.03578171506524086, -0.04931477829813957, 0.03392459452152252, -0.08737652003765106, 0.07634413242340088, 0.018543606624007225, -0.011528845876455307, 0.02072250284254551, 0.0063987853936851025, 0.009478660300374031, 0.0...
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``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used.
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 called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. """ if isinstance(s, str): if s.startswith('\ufeff'): raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", s, 0) else: if not isinstance(s, (bytes, bytearray)): raise TypeError(f'the JSON object must be str, bytes or bytearray, ' f'not {s.__class__.__name__}') s = s.decode(detect_encoding(s), 'surrogatepass') if (cls is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(**kw).decode(s)
(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
[ 0.013135293498635292, -0.004011943936347961, -0.014931323938071728, -0.018455427139997482, -0.02184361405670643, 0.06139511987566948, 0.010271352715790272, 0.0801515057682991, -0.01885346695780754, -0.009630607441067696, 0.032114967703819275, 0.075608029961586, -0.02242611162364483, 0.0034...
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 save the cookie file to be used with cURL password: Optional system password Returns: Dictionary of cookie values for URL
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 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 save the cookie file to be used with cURL password: Optional system password Returns: Dictionary of cookie values for URL """ parsed_url = urllib.parse.urlparse(url) if parsed_url.scheme: domain = parsed_url.netloc else: raise urllib.error.URLError("You must include a scheme with your URL.") # If running Chrome on OSX if sys.platform == "darwin": config = get_osx_config(browser) elif sys.platform.startswith("linux"): config = get_linux_config(browser) else: raise OSError("This script only works on OSX or Linux.") config.update( {"init_vector": b" " * 16, "length": 16, "salt": b"saltysalt"} ) if cookie_file: cookie_file = str(pathlib.Path(cookie_file).expanduser()) else: cookie_file = str(pathlib.Path(config["cookie_file"]).expanduser()) if isinstance(password, bytes): config["my_pass"] = password elif isinstance(password, str): config["my_pass"] = password.encode("utf8") elif isinstance(config["my_pass"], str): config["my_pass"] = config["my_pass"].encode("utf8") kdf = PBKDF2HMAC( algorithm=SHA1(), iterations=config["iterations"], length=config["length"], salt=config["salt"], ) enc_key = kdf.derive(config["my_pass"]) try: conn = sqlite3.connect("file:{}?mode=ro".format(cookie_file), uri=True) except sqlite3.OperationalError: print("Unable to connect to cookie_file at: {}\n".format(cookie_file)) raise conn.row_factory = sqlite3.Row # Check whether the column name is `secure` or `is_secure` secure_column_name = "is_secure" for ( sl_no, column_name, data_type, is_null, default_val, pk, ) in conn.execute("PRAGMA table_info(cookies)"): if column_name == "secure": secure_column_name = "secure AS is_secure" break sql = ( "select host_key, path, " + secure_column_name + ", expires_utc, name, value, encrypted_value " "from cookies where host_key like ?" ) cookies: list[Cookie] = [] for host_key in generate_host_keys(domain): for db_row in conn.execute(sql, (host_key,)): # if there is a not encrypted value or if the encrypted value # doesn't start with the 'v1[01]' prefix, return v row = dict(db_row) if not row["value"] and ( row["encrypted_value"][:3] in {b"v10", b"v11"} ): row["value"] = chrome_decrypt( row["encrypted_value"], key=enc_key, init_vector=config["init_vector"], ) del row["encrypted_value"] cookies.append(Cookie(**row)) conn.rollback() if curl_cookie_file: with open(curl_cookie_file, "w") as text_file: for c in cookies: print(c.as_cookie_file_line(), file=text_file) return {c.name: c.value for c in cookies}
(url: str, cookie_file: Optional[str] = None, browser: str = 'Chrome', curl_cookie_file: Optional[str] = None, password: Union[bytes, str, NoneType] = None) -> dict
[ -0.0022437821608036757, -0.013052857480943203, -0.05988230183720589, 0.03348790109157562, 0.0006553493440151215, 0.03223004192113876, -0.044994208961725235, -0.0014434439362958074, -0.002313376637175679, -0.0028688448946923018, 0.04755116626620293, 0.09254537522792816, -0.0091658690944314, ...
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 default profile browser: Name of the browser's cookies to read (must be 'Firefox') curl_cookie_file: Path to save the cookie file to be used with cURL Returns: Dictionary of cookie values for URL
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) profile_name: Name (or glob pattern) of the Firefox profile to search for cookies -- if none given it will find the configured default profile browser: Name of the browser's cookies to read (must be 'Firefox') curl_cookie_file: Path to save the cookie file to be used with cURL Returns: Dictionary of cookie values for URL """ parsed_url = urllib.parse.urlparse(url) if parsed_url.scheme: domain = parsed_url.netloc else: raise urllib.error.URLError("You must include a scheme with your URL.") if sys.platform.startswith("linux"): os = "linux" elif sys.platform == "darwin": os = "osx" elif sys.platform == "win32": os = "windows" else: raise OSError( "This script only works on " + ", ".join(FIREFOX_OS_PROFILE_DIRS.keys()) ) profiles_dir = _get_profiles_dir_for_os(os, browser) cookies: list[Cookie] = [] with tempfile.TemporaryDirectory() as tmp_dir: db_file = _load_firefox_cookie_db( profiles_dir, Path(tmp_dir), profile_name ) for host_key in generate_host_keys(domain): with sqlite3.connect(db_file) as con: con.row_factory = sqlite3.Row res = con.execute(FIREFOX_COOKIE_SELECT_SQL, (host_key,)) for row in res.fetchall(): cookies.append(Cookie(**row)) if curl_cookie_file: with open(curl_cookie_file, "w") as text_file: for c in cookies: print(c.as_cookie_file_line(), file=text_file) return {c.name: c.value for c in cookies}
(url: str, profile_name: Optional[str] = None, browser: str = 'Firefox', curl_cookie_file: Optional[str] = None) -> Dict[str, str]
[ -0.021233027800917625, -0.005046120844781399, -0.08807774633169174, 0.009464986622333527, -0.016196267679333687, 0.03697992116212845, -0.035219863057136536, -0.0013844064669683576, 0.0037611855659633875, -0.030819719657301903, 0.0506671704351902, 0.0872538834810257, -0.011693144217133522, ...
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: parser.position = c_pos raise parser.position = c_pos
(*elements, **kwargs)
[ -0.013290684670209885, -0.05642320215702057, 0.037649787962436676, -0.006353616248816252, -0.022394245490431786, 0.02711333893239498, 0.004886407405138016, 0.0001563199912197888, 0.018790574744343758, -0.05628592148423195, 0.05961502715945244, 0.018155641853809357, 0.0745445266366005, 0.02...
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.nodes = nodes if 'suppress' in kwargs: self.suppress = kwargs['suppress'] # Memoization. Every node cache the parsing results for the given input # positions. self._result_cache = {} # position -> parse tree at the position
(self, *elements, **kwargs)
[ -0.04748739302158356, 0.03818536549806595, 0.011527999304234982, -0.054581549018621445, -0.04075518622994423, 0.05722375959157944, -0.03340767323970795, -0.005750426556915045, 0.0006215301691554487, 0.010957933031022549, 0.01874883472919464, 0.06743065267801285, 0.003890926018357277, 0.053...
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.nodes: if node not in processed: processed.add(node) node._clear_cache(processed)
(self, processed=None)
[ -0.029383104294538498, 0.041659727692604065, 0.009975853376090527, 0.028785957023501396, -0.025396274402737617, 0.03175412490963936, -0.056658633053302765, 0.030278822407126427, 0.0812821313738823, -0.0010664107976481318, 0.008698136545717716, 0.01988145522773266, 0.027398470789194107, 0.0...
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)
[ -0.03182803839445114, 0.004330886527895927, -0.0503428615629673, 0.0445956289768219, -0.07529604434967041, 0.055071599781513214, 0.06056420877575874, 0.033901408314704895, 0.005051564425230026, 0.014149836264550686, 0.01226743496954441, -0.006015499122440815, 0.02602624148130417, 0.0117854...
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(parser.in_rule) if parser.in_rule else "", parser.position, parser.context()), 1) # Current position could change in recursive calls # so save it. c_pos = parser.position # Memoization. # If this position is already parsed by this parser expression use # the result if parser.memoization: try: result, new_pos = self._result_cache[c_pos] parser.position = new_pos parser.cache_hits += 1 if parser.debug: parser.dprint( "** Cache hit for [{}, {}] = '{}' : new_pos={}" .format(name, c_pos, text(result), text(new_pos))) parser.dprint( "<<+ Matched rule {} at position {}" .format(name, new_pos), -1) # If NoMatch is recorded at this position raise. if result is NOMATCH_MARKER: raise parser.nm # else return cached result return result except KeyError: parser.cache_misses += 1 # Remember last parsing expression and set this as # the new last. last_pexpression = parser.last_pexpression parser.last_pexpression = self if self.rule_name: # If we are entering root rule # remember previous root rule name and set # this one on the parser to be available for # debugging messages previous_root_rule_name = parser.in_rule parser.in_rule = self.rule_name try: result = self._parse(parser) if self.suppress or (type(result) is list and result and result[0] is None): result = None except NoMatch: parser.position = c_pos # Backtracking # Memoize NoMatch at this position for this rule if parser.memoization: self._result_cache[c_pos] = (NOMATCH_MARKER, c_pos) raise finally: # Recover last parsing expression. parser.last_pexpression = last_pexpression if parser.debug: parser.dprint("<<{} rule {}{} at position {} => {}" .format("- Not matched" if parser.position is c_pos else "+ Matched", name, " in {}".format(parser.in_rule) if parser.in_rule else "", parser.position, parser.context()), -1) # If leaving root rule restore previous root rule name. if self.rule_name: parser.in_rule = previous_root_rule_name # For root rules flatten non-terminal/list if self.root and result and not isinstance(result, Terminal): if not isinstance(result, NonTerminal): result = flatten(result) # Tree reduction will eliminate Non-terminal with single child. if parser.reduce_tree and len(result) == 1: result = result[0] # If the result is not parse tree node it must be a plain list # so create a new NonTerminal. if not isinstance(result, ParseTreeNode): result = NonTerminal(self, result) # Result caching for use by memoization. if parser.memoization: self._result_cache[c_pos] = (result, parser.position) return result
(self, parser)
[ 0.012238399125635624, 0.019728176295757294, 0.005976537242531776, 0.01964665576815605, 0.02024787664413452, 0.01945304311811924, 0.009476861916482449, -0.03858000040054321, 0.0008343204972334206, -0.039639778435230255, 0.015213930048048496, -0.005410982295870781, 0.03586941212415695, -0.00...
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)
[ -0.004440890159457922, -0.01787634566426277, -0.030602198094129562, 0.030188655480742455, 0.024511834606528282, -0.084287628531456, -0.02251930721104145, 0.02436145581305027, 0.06488869339227676, -0.06624210625886917, 0.04673038423061371, 0.02547050267457962, 0.02310202829539776, 0.0396625...
36
arpeggio
__init__
null
def __init__(self, message): self.message = message
(self, message)
[ -0.009976469911634922, 0.007533252704888582, -0.005081183277070522, -0.004908564500510693, -0.0019474918954074383, -0.061576150357723236, 0.011224634945392609, 0.07818294316530228, 0.06412559747695923, -0.021493228152394295, -0.011490201577544212, 0.0315493680536747, -0.03101823478937149, ...
37
arpeggio
__str__
null
def __str__(self): return repr(self.message)
(self)
[ -0.007524884771555662, -0.012334287166595459, 0.047997038811445236, 0.014000605791807175, 0.021388834342360497, -0.10283568501472473, 0.0238927211612463, -0.0061671435832977295, 0.10593909025192261, -0.06862765550613403, -0.015517043881118298, -0.0035861122887581587, -0.041931286454200745, ...
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 = 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 result return Terminal(self, c_pos, "".join([x.flat_str() for x in results])) except NoMatch: parser.position = c_pos # Backtracking raise finally: parser.in_lex_rule = oldin_lex_rule
(*elements, **kwargs)
[ -0.05922330543398857, -0.030612409114837646, 0.08327718824148178, -0.003739431733265519, 0.026609385386109352, -0.013304692693054676, -0.01745961792767048, -0.06747954338788986, 0.01296515017747879, -0.005289710126817226, 0.0566856749355793, 0.011553370393812656, 0.03088046982884407, 0.066...
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 result return Terminal(self, c_pos, "".join([x.flat_str() for x in results])) except NoMatch: parser.position = c_pos # Backtracking raise finally: parser.in_lex_rule = oldin_lex_rule
(self, parser)
[ -0.040420107543468475, 0.008437789976596832, -0.024071024730801582, -0.007223154883831739, 0.01093633659183979, 0.0470336377620697, 0.025585854426026344, 0.002034398727118969, 0.015120593830943108, 0.018593618646264076, 0.051430340856313705, -0.005126407835632563, 0.010511444881558418, 0.0...
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)
[ -0.0085365641862154, 0.016391251236200333, -0.034705743193626404, -0.01582302153110504, -0.05304646119475365, 0.0020194021053612232, -0.012256285175681114, -0.0008955086814239621, 0.04437439516186714, -0.02912834659218788, -0.009686136618256569, 0.0047337934374809265, 0.04168185964226723, ...
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)
[ -0.013945668935775757, 0.04656492918729782, -0.016828341409564018, -0.05265340581536293, -0.06557866185903549, -0.0031675377395004034, -0.014472883194684982, 0.03557846322655678, 0.016938885673880577, -0.03537438064813614, -0.01425179373472929, 0.034830160439014435, 0.03717711195349693, 0....
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", False) self.file = kwargs.pop("file", sys.stdout) self._current_indent = 0 super(DebugPrinter, self).__init__(**kwargs) 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._current_indent, message)), file=self.file) if indent_change > 0: self._current_indent += indent_change
(**kwargs)
[ 0.0032352276612073183, -0.008535398170351982, -0.021309124305844307, 0.010654562152922153, 0.04514859616756439, -0.0239659883081913, -0.025339603424072266, -0.0039378502406179905, -0.0020378318149596453, -0.026442112401127815, -0.006036681588739157, -0.019339069724082947, 0.00632134545594453...
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)
[ -0.015898343175649643, 0.006948361173272133, 0.02070399932563305, -0.00010987702262355015, 0.002435894450172782, -0.023155324161052704, -0.01061653159558773, 0.02476014941930771, -0.021144885569810867, -0.017000557854771614, -0.020351290702819824, 0.026382610201835632, -0.04034987464547157, ...
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._current_indent, message)), file=self.file) if indent_change > 0: self._current_indent += indent_change
(self, message, indent_change=0)
[ 0.036453042179346085, 0.03736087679862976, 0.0026864041574299335, 0.024965446442365646, 0.03676729276776314, -0.06473557651042938, -0.005617225542664528, -0.006145340856164694, 0.013600057922303677, -0.01887248083949089, -0.04588055610656738, -0.043715719133615494, -0.012369244359433651, 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)
[ -0.008225926198065281, -0.03104683756828308, 0.06291069835424423, 0.005570604931563139, 0.034816280007362366, -0.023099441081285477, -0.026627490296959877, 0.016414714977145195, -0.030322657898068428, -0.013870805501937866, 0.05466620251536369, 0.017120325937867165, 0.032365214079618454, 0...
52
arpeggio
EOF
null
def EOF(): return EndOfFile()
()
[ -0.0026046994607895613, -0.005787263158708811, -0.01718929223716259, 0.015697196125984192, -0.02559850364923477, -0.01718929223716259, -0.019302375614643097, 0.03556881099939346, -0.020647849887609482, -0.022424565628170967, 0.0022446129005402327, -0.05599241703748703, -0.009694312699139118,...
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)
[ -0.010340261273086071, -0.020059781149029732, 0.011312213726341724, -0.0375712513923645, -0.013541985303163528, 0.022428402677178383, -0.000194109627045691, -0.002213436644524336, 0.05753301829099655, -0.05024746432900429, 0.027819061651825905, 0.02236306108534336, 0.037309885025024414, -0...
56
arpeggio
_parse
null
def _parse(self, parser): pass
(self, parser)
[ -0.02065032161772251, 0.00662621995434165, -0.03313110023736954, 0.01763077825307846, -0.044152431190013885, 0.04270976409316063, 0.05606285482645035, 0.0833393931388855, -0.01914054900407791, 0.008123409934341908, 0.033332403749227524, -0.0005981421563774347, -0.0005860849632881582, 0.026...
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(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)
()
[ 0.01780737191438675, -0.04980388283729553, -0.006615686696022749, -0.006584648042917252, -0.05171941965818405, -0.03242218494415283, 0.023358874022960663, 0.016228830441832542, -0.0356147438287735, -0.04047452285885811, 0.02979719638824463, -0.019226286560297012, 0.014011777006089687, 0.03...
59
arpeggio
__init__
null
def __init__(self): super(EndOfFile, self).__init__("EOF")
(self)
[ -0.015111256390810013, -0.01410889346152544, -0.01693067140877247, -0.002122651319950819, -0.04541800171136856, -0.019356559962034225, 0.012938065454363823, 0.08086290955543518, -0.015717728063464165, -0.027527082711458206, 0.02506750263273716, -0.025151735171675682, 0.012836987152695656, ...
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)
[ -0.023549366742372513, -0.022830970585346222, -0.023742107674479485, -0.013176431879401207, -0.0226382315158844, 0.014078807085752487, 0.043208882212638855, 0.03555183485150337, -0.021464267745614052, -0.028157614171504974, 0.049306485801935196, 0.0058742002584040165, -0.009742149151861668, ...
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 ahead. parser.comments.append( parser.comments_model.parse(parser)) if parser.skipws: # 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 except NoMatch: # NoMatch in comment matching is perfectly # legal and no action should be taken. pass finally: parser.in_parse_comments = False
(self, parser)
[ -0.06787128001451492, 0.014636634849011898, -0.02299152873456478, 0.024628696963191032, -0.006548671051859856, 0.009502691216766834, 0.0839938223361969, 0.06402749568223953, -0.042815495282411575, 0.014627737924456596, 0.010241195559501648, -0.040395334362983704, -0.017991049215197563, 0.0...
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.debug: parser.dprint( "?? Try match rule {}{} at position {} => {}" .format(self.name, " in {}".format(parser.in_rule) if parser.in_rule else "", parser.position, parser.context())) if parser.skipws and parser.position in parser.comment_positions: # Skip comments if already parsed. parser.position = parser.comment_positions[parser.position] else: if not parser.in_parse_comments and not parser.in_lex_rule: comment_start = parser.position self._parse_comments(parser) parser.comment_positions[comment_start] = parser.position result = self._parse(parser) if not self.suppress: return result
(self, parser)
[ -0.03486403450369835, 0.0416378378868103, -0.022541072219610214, 0.0302716251462698, -0.00474788062274456, 0.03494057431817055, 0.06260983645915985, 0.038308341056108475, -0.019221141934394836, -0.02361263334751129, 0.026176728308200836, -0.033696796745061874, 0.017068451270461082, -0.0230...
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)
[ 0.012882431969046593, 0.017769478261470795, 0.0040505253709852695, 0.021274063736200333, -0.01457308605313301, -0.04487277567386627, -0.025800084695219994, -0.014898888766765594, 0.036349061876535416, -0.058257121592760086, 0.053889598697423935, -0.0005591486115008593, 0.024373596534132957, ...
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)
[ 0.02232425846159458, -0.047333624213933945, 0.02494051679968834, -0.008748114109039307, -0.046541862189769745, -0.019811272621154785, 0.013666508719325066, 0.004729059524834156, 0.042169954627752304, -0.005495003424584866, -0.0031519890762865543, 0.046886105090379715, -0.00926878396421671, ...
68
arpeggio
__eq__
null
def __eq__(self, other): return self.to_match == text(other)
(self, other)
[ 0.07091177254915237, -0.05394723266363144, 0.03019687905907631, 0.02768612839281559, -0.04129168763756752, -0.07891903817653656, -0.0025764894671738148, 0.03691483661532402, 0.035863034427165985, -0.01981458067893982, 0.02079852484166622, -0.017337758094072342, 0.053641870617866516, 0.0378...
69
arpeggio
__hash__
null
def __hash__(self): return hash(self.to_match)
(self)
[ 0.06711853295564651, -0.05359514430165291, -0.007359779439866543, 0.07044123113155365, -0.03787877410650253, -0.07243485003709793, -0.02890748716890812, -0.006117920856922865, -0.006994282826781273, 0.006001626141369343, -0.017477400600910187, -0.013456933200359344, 0.04093565791845322, 0....
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)
[ 0.022983137518167496, -0.018535858020186424, 0.03591011464595795, 0.01730787754058838, -0.05977274850010872, -0.005953213199973106, 0.009633004665374756, -0.00781592633575201, 0.04062290117144585, 0.02459278516471386, 0.0013119885697960854, 0.021356893703341484, 0.010545692406594753, 0.017...
71
arpeggio
__str__
null
def __str__(self): return self.to_match
(self)
[ 0.0522305890917778, -0.054390501230955124, 0.03822388872504234, 0.012664935551583767, -0.013826706446707249, -0.07330609112977982, 0.0408419631421566, -0.0027755682822316885, 0.06541913747787476, -0.05043066293001175, -0.029355160892009735, -0.01791744865477085, -0.011789517477154732, 0.01...
72
arpeggio
__unicode__
null
def __unicode__(self): return self.__str__()
(self)
[ -0.02335135079920292, -0.02636389061808586, 0.062414512038230896, 0.009412108920514584, -0.005197048652917147, -0.04653625935316086, 0.025515053421258926, -0.027928413823246956, 0.10106158256530762, -0.05638943240046501, -0.04314091056585312, -0.01600308157503605, -0.018557915464043617, -0...
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( "++ Match '{}' at {} => '{}'" .format(self.to_match, c_pos, parser.context(len(self.to_match)))) parser.position += len(self.to_match) # If this match is inside sequence than mark for suppression suppress = type(parser.last_pexpression) is Sequence return Terminal(self, c_pos, self.to_match, suppress=suppress) else: if parser.debug: parser.dprint( "-- No match '{}' at {} => '{}'" .format(self.to_match, c_pos, parser.context(len(self.to_match)))) parser._nm_raise(self, c_pos, parser)
(self, parser)
[ 0.01833045668900013, -0.018817521631717682, -0.014246614649891853, 0.021074874326586723, -0.04155028611421585, -0.01478051207959652, 0.09381597489118576, 0.03739150986075401, -0.06950025260448456, -0.019370151683688164, 0.030460217967629433, 0.01683180034160614, 0.008294133469462395, 0.002...
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: return "%s=%s(%s)" % (self.rule_name, self.__class__.__name__, self.to_match) else: return "%s(%s)" % (self.__class__.__name__, self.to_match) 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 ahead. parser.comments.append( parser.comments_model.parse(parser)) if parser.skipws: # 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 except NoMatch: # NoMatch in comment matching is perfectly # legal and no action should be taken. pass finally: parser.in_parse_comments = False 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.debug: parser.dprint( "?? Try match rule {}{} at position {} => {}" .format(self.name, " in {}".format(parser.in_rule) if parser.in_rule else "", parser.position, parser.context())) if parser.skipws and parser.position in parser.comment_positions: # Skip comments if already parsed. parser.position = parser.comment_positions[parser.position] else: if not parser.in_parse_comments and not parser.in_lex_rule: comment_start = parser.position self._parse_comments(parser) parser.comment_positions[comment_start] = parser.position result = self._parse(parser) if not self.suppress: return result
(rule_name, root=False, **kwargs)
[ 0.012286120094358921, -0.02359927073121071, 0.01569151133298874, 0.023389413952827454, -0.0297995638102293, -0.01806670054793358, 0.04384084418416023, 0.002036557998508215, -0.014842548407614231, -0.06631451845169067, 0.007077873218804598, 0.009352903813123703, 0.03819380700588226, -0.0129...
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)
[ 0.011618467047810555, -0.0017572414362803102, 0.03979221731424332, -0.0004168280283920467, -0.08461221307516098, -0.012354440987110138, 0.004684599116444588, 0.03565753251314163, 0.027917398139834404, 0.011940972879529, 0.016762016341090202, 0.05189857631921768, 0.028479715809226036, 0.038...
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. parser (Parser): An instance of a parser.
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 where exception occurred. parser (Parser): An instance of a parser. """ def __init__(self, rules, position, parser): self.rules = rules self.position = position self.parser = parser 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: return rule.rule_name elif isinstance(rule, Match) and \ not isinstance(rule, EndOfFile): return "'{}'".format(rule.to_match.replace('\n', '\\n')) else: return rule.name if not self.rules: self.message = "Not expected input" else: what_is_expected = OrderedDict.fromkeys( ["{}".format(rule_to_exp_str(r)) for r in self.rules]) what_str = " or ".join(what_is_expected) self.message = "Expected {}".format(what_str) self.context = self.parser.context(position=self.position) self.line, self.col = self.parser.pos_to_linecol(self.position) 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) def __unicode__(self): return self.__str__()
(rules, position, parser)
[ 0.02290913090109825, -0.020248349756002426, 0.019946416839957237, 0.015832586213946342, -0.03681689873337746, -0.07001060247421265, 0.026003938168287277, 0.022965742275118828, 0.0214938223361969, -0.05230981111526489, 0.034099504351615906, 0.035552553832530975, -0.0033495640382170677, -0.0...
83
arpeggio
__init__
null
def __init__(self, rules, position, parser): self.rules = rules self.position = position self.parser = parser
(self, rules, position, parser)
[ -0.01200826931744814, 0.0341448113322258, -0.03431418165564537, -0.058296848088502884, -0.047084610909223557, 0.03148571774363518, -0.010577100329101086, 0.0069695389829576015, -0.010687191039323807, -0.0003638789348769933, 0.020493661984801292, 0.020188797265291214, 0.0002330148417968303, ...
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)
[ 0.026909107342362404, -0.015834445133805275, 0.050209712237119675, 0.0020093766506761312, 0.054127514362335205, -0.09361482411623001, 0.04890378192067146, -0.004115409683436155, 0.03371370956301689, -0.04962547868490219, -0.006521076895296574, -0.022114956751465797, -0.015009645372629166, ...
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: return rule.rule_name elif isinstance(rule, Match) and \ not isinstance(rule, EndOfFile): return "'{}'".format(rule.to_match.replace('\n', '\\n')) else: return rule.name if not self.rules: self.message = "Not expected input" else: what_is_expected = OrderedDict.fromkeys( ["{}".format(rule_to_exp_str(r)) for r in self.rules]) what_str = " or ".join(what_is_expected) self.message = "Expected {}".format(what_str) self.context = self.parser.context(position=self.position) self.line, self.col = self.parser.pos_to_linecol(self.position)
(self)
[ 0.03782946243882179, 0.03445693105459213, 0.041077084839344025, -0.041077084839344025, 0.017888696864247322, -0.06902092695236206, 0.05028463527560234, -0.0036758817732334137, 0.011598655954003334, -0.02632002718746662, 0.014962266199290752, 0.035991519689559937, 0.02644493617117405, 0.065...
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. _filtered (bool): Is this NT a dynamically created filtered NT. This is used internally.
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 of ParseTreeNode): Children parse tree nodes. _filtered (bool): Is this NT a dynamically created filtered NT. This is used internally. """ __slots__ = ['rule', 'rule_name', 'position', 'error', 'comments', '_filtered', '_expr_cache'] 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 @property def value(self): """Terminal protocol.""" return text(self) @property def desc(self): return self.name @property def position_end(self): return self[-1].position_end if self else self.position def flat_str(self): """ Return flatten string representation. """ return "".join([x.flat_str() for x in self]) def __str__(self): return " | ".join([text(x) for x in self]) def __unicode__(self): return self.__str__() def __repr__(self): return "[ %s ]" % ", ".join([repr(x) for x in self]) 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])) 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', 'position', 'append', 'extend']: raise AttributeError try: # First check the cache if rule_name in self._expr_cache: return self._expr_cache[rule_name] except AttributeError: # Navigation expression cache. Used for lookup by rule name. self._expr_cache = {} # If result is not found in the cache collect all nodes # with the given rule name and create new NonTerminal # and cache it for later access. nodes = [] rule = None for n in self: if self._filtered: # For filtered NT rule_name is a rule on # each of its children for m in n: if m.rule_name == rule_name: nodes.append(m) rule = m.rule else: if n.rule_name == rule_name: nodes.append(n) rule = n.rule if rule is None: # If rule is not found resort to default behavior return self.__getattribute__(rule_name) result = NonTerminal(rule=rule, nodes=nodes, _filtered=True) self._expr_cache[rule_name] = result return result
(rule, nodes, error=False, _filtered=False)
[ 0.009248190559446812, 0.016575051471590996, 0.0029465164989233017, -0.03701188042759895, 0.005897812079638243, 0.0317545086145401, -0.025101548060774803, -0.05540311336517334, 0.031257450580596924, -0.08029436320066452, 0.03773835301399231, 0.01978682540357113, -0.006327960640192032, 0.000...
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', 'position', 'append', 'extend']: raise AttributeError try: # First check the cache if rule_name in self._expr_cache: return self._expr_cache[rule_name] except AttributeError: # Navigation expression cache. Used for lookup by rule name. self._expr_cache = {} # If result is not found in the cache collect all nodes # with the given rule name and create new NonTerminal # and cache it for later access. nodes = [] rule = None for n in self: if self._filtered: # For filtered NT rule_name is a rule on # each of its children for m in n: if m.rule_name == rule_name: nodes.append(m) rule = m.rule else: if n.rule_name == rule_name: nodes.append(n) rule = n.rule if rule is None: # If rule is not found resort to default behavior return self.__getattribute__(rule_name) result = NonTerminal(rule=rule, nodes=nodes, _filtered=True) self._expr_cache[rule_name] = result return result
(self, rule_name)
[ 0.02293778955936432, 0.017422493547201157, 0.01802515797317028, -0.03254390135407448, -0.002933425595983863, 0.01632673852145672, -0.022371649742126465, -0.051756128668785095, 0.03787657245993614, -0.04576600342988968, 0.026919031515717506, 0.045218128710985184, 0.02673640474677086, 0.0054...
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)
[ -0.03222524747252464, 0.049210455268621445, 0.05612203851342201, -0.05473972111940384, -0.049590595066547394, 0.008527163416147232, -0.02325746975839138, -0.008436448872089386, 0.048864878714084625, -0.018246574327349663, 0.04236799106001854, 0.032812729477882385, 0.020682906731963158, 0.0...
90
arpeggio
__repr__
null
def __repr__(self): return "[ %s ]" % ", ".join([repr(x) for x in self])
(self)
[ -0.003070969134569168, -0.02858916111290455, 0.04193752631545067, -0.009952137246727943, 0.010273173451423645, -0.04382995516061783, 0.005981420166790485, -0.047276873141527176, 0.0844157487154007, -0.00007247085886774585, -0.025547761470079422, -0.009571962058544159, 0.00455365190282464, ...
91
arpeggio
__str__
null
def __str__(self): return " | ".join([text(x) for x in self])
(self)
[ 0.02631305158138275, -0.06113915145397186, 0.021619100123643875, -0.004773867316544056, 0.013989323750138283, -0.05319812521338463, 0.005047260783612728, -0.04670398309826851, 0.14603407680988312, -0.005320653785020113, 0.0014290056424215436, -0.018355203792452812, 0.0062628090381622314, 0...
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)
[ -0.025107938796281815, -0.037306126207113266, 0.06858092546463013, -0.0058153169229626656, -0.013401065953075886, -0.06492146849632263, 0.006179568357765675, -0.03683175519108772, 0.12455706298351288, -0.018534470349550247, -0.015137613750994205, -0.023396803066134453, 0.00030018980032764375...
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)
[ -0.00897137075662613, -0.012900122441351414, 0.06945688277482986, -0.014825643040239811, 0.024107860401272774, -0.051427800208330154, -0.026162900030612946, -0.056643109768629074, 0.05198041349649429, -0.01257200725376606, 0.01965239644050598, -0.026421938091516495, -0.023088974878191948, ...
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 = SemanticActionResults() if isinstance(self, NonTerminal): for node in self: child = node.visit(visitor) # If visit returns None suppress that child node if child is not None: children.append_result(node.rule_name, child) visit_name = "visit_%s" % self.rule_name if hasattr(visitor, visit_name): # Call visit method. result = getattr(visitor, visit_name)(self, children) # If there is a method with 'second' prefix save # the result of visit for post-processing if hasattr(visitor, "second_%s" % self.rule_name): visitor.for_second_pass.append((self.rule_name, result)) return result elif visitor.defaults: # If default actions are enabled return visitor.visit__default__(self, children)
(self, visitor)
[ -0.0035997088998556137, -0.04074256867170334, 0.0036606062203645706, -0.014245464466512203, -0.03444533422589302, -0.02610916644334793, 0.022969570010900497, -0.036845140159130096, 0.013216976076364517, 0.011340436525642872, 0.045145221054553986, -0.0011130678467452526, 0.05369791388511658, ...
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: try: e.parse(parser) except NoMatch: parser.position = c_pos return parser.position = c_pos parser._nm_raise(self, c_pos, parser) finally: parser.in_not = old_in_not
(*elements, **kwargs)
[ 0.02581929787993431, -0.004615641664713621, 0.07858970016241074, 0.0024581386242061853, -0.049834780395030975, 0.010690250433981419, -0.0003567285311874002, -0.013219126500189304, 0.04194751754403114, -0.05818184092640877, 0.017834767699241638, 0.00037524194340221584, 0.024210013449192047, ...
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 parser._nm_raise(self, c_pos, parser) finally: parser.in_not = old_in_not
(self, parser)
[ -0.016562046483159065, 0.017697054892778397, -0.04394753277301788, 0.047071076929569244, -0.07968668639659882, 0.04917765408754349, 0.06501329690217972, 0.018105657771229744, -0.0013506602263078094, -0.03096303530037403, 0.006210767198354006, -0.025297071784734726, 0.017224891111254692, -0...
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 old_eolterm = parser.eolterm parser.eolterm = self.eolterm # Prefetching append = results.append p = self.nodes[0].parse sep = self.sep.parse if self.sep else None result = None try: while True: try: c_pos = parser.position if sep and result: sep_result = sep(parser) if sep_result: append(sep_result) result = p(parser) if not result: break append(result) first = False except NoMatch: parser.position = c_pos # Backtracking if first: raise break finally: if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm return results
(*elements, **kwargs)
[ -0.012550849467515945, -0.031394802033901215, 0.009209848940372467, 0.02220262959599495, -0.02172534354031086, 0.0073669953271746635, 0.032862015068531036, -0.03652120381593704, 0.03003365360200405, -0.028159864246845245, 0.05989053472876549, 0.03526611998677254, 0.03592017665505409, 0.028...
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)
[ -0.014996781013906002, 0.0034398059360682964, 0.0021420903503894806, -0.01549524161964655, -0.05293992534279823, -0.0031368625350296497, -0.007545658387243748, -0.008216001093387604, 0.018322713673114777, 0.045617714524269104, 0.025043334811925888, 0.0435551218688488, 0.027398129925131798, ...
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.sep.parse if self.sep else None result = None try: while True: try: c_pos = parser.position if sep and result: sep_result = sep(parser) if sep_result: append(sep_result) result = p(parser) if not result: break append(result) first = False except NoMatch: parser.position = c_pos # Backtracking if first: raise break finally: if self.eolterm: # Restore previous eolterm parser.eolterm = old_eolterm return results
(self, parser)
[ -0.033073700964450836, 0.019352838397026062, -0.07899889349937439, 0.018105488270521164, -0.01622501201927662, 0.056508779525756836, 0.048382099717855453, 0.015497391112148762, 0.02262241020798683, 0.001475323224440217, 0.06036422774195671, -0.01109386421740055, -0.01267195213586092, 0.003...
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)] except NoMatch: parser.position = c_pos # Backtracking return result
(*elements, **kwargs)
[ 0.0072034671902656555, -0.007490388583391905, 0.00846852920949459, -0.0037125893868505955, -0.030135445296764374, -0.005364561453461647, 0.03957776725292206, -0.029283376410603523, 0.03888220340013504, -0.0396125465631485, 0.06806124001741409, 0.017441345378756523, 0.017893463373184204, -0...
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)
[ -0.032378166913986206, -0.0030214544385671616, -0.051174346357584, 0.015006482601165771, -0.03511964902281761, 0.058377455919981, 0.060276784002780914, 0.02988753840327263, 0.03646351397037506, -0.008094541728496552, 0.04318283125758171, -0.00004927501504425891, -0.021609334275126457, -0.0...
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: 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: try: result = e.parse(parser) if result is not None: match = True result = [result] break except NoMatch: parser.position = c_pos # Backtracking finally: if self.ws is not None: parser.ws = old_ws if self.skipws is not None: parser.skipws = old_skipws if not match: parser._nm_raise(self, c_pos, parser) return result
(*elements, **kwargs)
[ 0.0010942205553874373, 0.006109679117798805, -0.02302015759050846, -0.04665083438158035, -0.00938224047422409, 0.009489978663623333, 0.04661491885781288, -0.0012726627755910158, 0.025228798389434814, -0.06123146414756775, 0.026988530531525612, 0.05052942410111427, 0.009750347584486008, -0....
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)
[ -0.03280884027481079, 0.04515661671757698, -0.04407258704304695, -0.048882968723773956, -0.052338313311338425, 0.032842714339494705, -0.028997795656323433, 0.04654552787542343, 0.04959436133503914, 0.05006862431764603, -0.004725692328065634, 0.049560487270355225, 0.02098613977432251, 0.050...
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: try: result = e.parse(parser) if result is not None: match = True result = [result] break except NoMatch: parser.position = c_pos # Backtracking finally: if self.ws is not None: parser.ws = old_ws if self.skipws is not None: parser.skipws = old_skipws if not match: parser._nm_raise(self, c_pos, parser) return result
(self, parser)
[ -0.028918320313096046, 0.006832717917859554, -0.057109855115413666, 0.02671884372830391, -0.04670538008213043, 0.0391506627202034, 0.061700064688920975, 0.05469999834895134, 0.019441450014710426, 0.0036100083962082863, 0.04345398396253586, -0.02780901826918125, -0.0001408291864208877, -0.0...
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. # The internal self.__map dict maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # The sentinel is in self.__hardroot with a weakref proxy in self.__root. # The prev links are weakref proxies (to prevent circular references). # Individual links are kept alive by the hard reference in self.__map. # Those hard references disappear when a key is deleted from an OrderedDict. def __init__(self, other=(), /, **kwds): '''Initialize an ordered dictionary. The signature is the same as regular dictionaries. Keyword argument order is preserved. ''' try: self.__root except AttributeError: self.__hardroot = _Link() self.__root = root = _proxy(self.__hardroot) root.prev = root.next = root self.__map = {} self.__update(other, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link at the end of the linked list, # and the inherited dictionary is updated with the new key/value pair. if key not in self: self.__map[key] = link = Link() root = self.__root last = root.prev link.prev, link.next, link.key = last, root, key last.next = link root.prev = proxy(link) dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which gets # removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link = self.__map.pop(key) link_prev = link.prev link_next = link.next link_prev.next = link_next link_next.prev = link_prev link.prev = None link.next = None def __iter__(self): 'od.__iter__() <==> iter(od)' # Traverse the linked list in order. root = self.__root curr = root.next while curr is not root: yield curr.key curr = curr.next def __reversed__(self): 'od.__reversed__() <==> reversed(od)' # Traverse the linked list in reverse order. root = self.__root curr = root.prev while curr is not root: yield curr.key curr = curr.prev def clear(self): 'od.clear() -> None. Remove all items from od.' root = self.__root root.prev = root.next = root self.__map.clear() dict.clear(self) def popitem(self, last=True): '''Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root.prev link_prev = link.prev link_prev.next = root root.prev = link_prev else: link = root.next link_next = link.next root.next = link_next link_next.prev = root key = link.key del self.__map[key] value = dict.pop(self, key) return key, value def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not exist. ''' link = self.__map[key] link_prev = link.prev link_next = link.next soft_link = link_next.prev link_prev.next = link_next link_next.prev = link_prev root = self.__root if last: last = root.prev link.prev = last link.next = root root.prev = soft_link last.next = link else: first = root.next link.prev = root link.next = first first.prev = soft_link root.next = link def __sizeof__(self): sizeof = _sys.getsizeof n = len(self) + 1 # number of links including root size = sizeof(self.__dict__) # instance dictionary size += sizeof(self.__map) * 2 # internal dict and inherited dict size += sizeof(self.__hardroot) * n # link objects size += sizeof(self.__root) * n # proxy objects return size update = __update = _collections_abc.MutableMapping.update def keys(self): "D.keys() -> a set-like object providing a view on D's keys" return _OrderedDictKeysView(self) def items(self): "D.items() -> a set-like object providing a view on D's items" return _OrderedDictItemsView(self) def values(self): "D.values() -> an object providing a view on D's values" return _OrderedDictValuesView(self) __ne__ = _collections_abc.MutableMapping.__ne__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): '''Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ''' if key in self: return self[key] self[key] = default return default @_recursive_repr() def __repr__(self): 'od.__repr__() <==> repr(od)' if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self.items())) def __reduce__(self): 'Return state information for pickling' inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) return self.__class__, (), inst_dict or None, None, iter(self.items()) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''Create a new ordered dictionary with keys from iterable and values set to value. ''' self = cls() for key in iterable: self[key] = value return self def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return dict.__eq__(self, other) and all(map(_eq, self, other)) return dict.__eq__(self, other) def __ior__(self, other): self.update(other) return self def __or__(self, other): if not isinstance(other, dict): return NotImplemented new = self.__class__(self) new.update(other) return new def __ror__(self, other): if not isinstance(other, dict): return NotImplemented new = self.__class__(other) new.update(self) return new
null
[ 0.024522457271814346, 0.027011176571249962, -0.06758157908916473, 0.011113414540886879, -0.0021923785097897053, 0.009831510484218597, -0.05758379399776459, 0.010898870415985584, 0.043359480798244476, -0.07457573711872101, -0.045011475682258606, 0.013848859816789627, 0.0438314788043499, 0.0...
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_second_pass = [] self.defaults = defaults super(PTNodeVisitor, self).__init__(**kwargs) 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 # is set in which case it is suppressed by setting to None. retval = text(node) if not node.suppress else None else: retval = node # Special case. If only one child exist return it. if len(children) == 1: retval = children[0] else: # If there is only one non-string child return # that by default. This will support e.g. bracket # removals. last_non_str = None for c in children: if not isstr(c): if last_non_str is None: last_non_str = c else: # If there is multiple non-string objects # by default convert non-terminal to string if self.debug: self.dprint("*** Warning: Multiple " "non-string objects found in " "default visit. Converting non-" "terminal to a string.") retval = text(node) break else: # Return the only non-string child retval = last_non_str return retval
(defaults=True, **kwargs)
[ 0.005401585716754198, -0.002232098486274481, 0.015480833128094673, -0.004352824296802282, -0.032261017709970474, -0.018571430817246437, 0.028251592069864273, -0.002120725577697158, 0.03324481099843979, -0.06340830028057098, 0.04146784171462059, -0.006914400961250067, -0.024947529658675194, ...
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)
[ -0.009669993072748184, -0.022516770288348198, 0.028102325275540352, 0.011005289852619171, -0.07952434569597244, 0.012131128460168839, -0.016154473647475243, 0.01897343248128891, 0.009067799896001816, 0.015883922576904297, 0.03471771627664566, 0.03456062451004982, -0.002251676982268691, 0.0...
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 # is set in which case it is suppressed by setting to None. retval = text(node) if not node.suppress else None else: retval = node # Special case. If only one child exist return it. if len(children) == 1: retval = children[0] else: # If there is only one non-string child return # that by default. This will support e.g. bracket # removals. last_non_str = None for c in children: if not isstr(c): if last_non_str is None: last_non_str = c else: # If there is multiple non-string objects # by default convert non-terminal to string if self.debug: self.dprint("*** Warning: Multiple " "non-string objects found in " "default visit. Converting non-" "terminal to a string.") retval = text(node) break else: # Return the only non-string child retval = last_non_str return retval
(self, node, children)
[ -0.001998333726078272, -0.022265203297138214, 0.056688256561756134, -0.011586252599954605, -0.03582030162215233, -0.01416299119591713, 0.024442728608846664, 0.026819860562682152, 0.06866464763879776, -0.057377807796001434, 0.04580063000321388, 0.023626156151294708, -0.015669113025069237, -...
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 empty string otherwise. position (int): A position in the input stream where the match occurred. position_end (int, read-only): A position in the input stream where the node ends. This position is one char behind the last char contained in this node. Thus, position_end - position = length of the node. error (bool): Is this a false parse tree node created during error recovery. comments : A parse tree of comment(s) attached to this node.
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 node if root rule or empty string otherwise. position (int): A position in the input stream where the match occurred. position_end (int, read-only): A position in the input stream where the node ends. This position is one char behind the last char contained in this node. Thus, position_end - position = length of the node. error (bool): Is this a false parse tree node created during error recovery. comments : A parse tree of comment(s) attached to this node. """ 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 @property def name(self): return "%s [%s]" % (self.rule_name, self.position) @property def position_end(self): "Must be implemented in subclasses." raise NotImplementedError 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 = SemanticActionResults() if isinstance(self, NonTerminal): for node in self: child = node.visit(visitor) # If visit returns None suppress that child node if child is not None: children.append_result(node.rule_name, child) visit_name = "visit_%s" % self.rule_name if hasattr(visitor, visit_name): # Call visit method. result = getattr(visitor, visit_name)(self, children) # If there is a method with 'second' prefix save # the result of visit for post-processing if hasattr(visitor, "second_%s" % self.rule_name): visitor.for_second_pass.append((self.rule_name, result)) return result elif visitor.defaults: # If default actions are enabled return visitor.visit__default__(self, children) def tree_str(self, indent=0): return '{}{} [{}-{}]'.format(' ' * indent, self.rule.name, self.position, self.position_end)
(rule, position, error)
[ -0.013159584254026413, 0.01258290745317936, -0.001381425536237657, 0.000578154344111681, 0.008324004709720612, 0.004119460470974445, 0.008872320875525475, -0.007005210034549236, 0.01213858276605606, -0.07767180353403091, 0.050898853689432144, -0.00010362168541178107, 0.01213858276605606, 0...
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)
[ -0.03471238911151886, 0.0687619298696518, 0.0018817080417647958, -0.03408442810177803, -0.04448070004582405, -0.017417246475815773, 0.0079236701130867, 0.018542347475886345, 0.0018130246317014098, -0.05644688010215759, 0.021472839638590813, 0.03047364018857479, 0.02862463891506195, 0.03820...
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)
[ 0.011475485749542713, 0.03272978961467743, 0.055262863636016846, -0.03383304178714752, 0.02084476500749588, -0.04008479788899422, -0.005616552196443081, -0.04108775407075882, 0.02208174392580986, -0.022633368149399757, 0.01032208651304245, -0.02465599589049816, -0.013431249186396599, 0.026...
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 tree consisting of NonTerminal and Terminal instances. in_rule (str): Current rule name. in_parse_comments (bool): True if parsing comments. in_lex_rule (bool): True if in lexical rule. Currently used in Combine decorator to convert match to a single Terminal. in_not (bool): True if in Not parsing expression. Used for better error reporting. last_pexpression (ParsingExpression): Last parsing expression traversed.
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. parse_tree(NonTerminal): The parse tree consisting of NonTerminal and Terminal instances. in_rule (str): Current rule name. in_parse_comments (bool): True if parsing comments. in_lex_rule (bool): True if in lexical rule. Currently used in Combine decorator to convert match to a single Terminal. in_not (bool): True if in Not parsing expression. Used for better error reporting. last_pexpression (ParsingExpression): Last parsing expression traversed. """ # Not marker for NoMatch rules list. Used if the first unsuccessful rule # match is Not. FIRST_NOT = Not() 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. reduce_tree (bool): If true non-terminals with single child will be eliminated from the parse tree. Default is False. autokwd(bool): If keyword-like StrMatches are matched on word boundaries. Default is False. ignore_case(bool): If case is ignored (default=False) memoization(bool): If memoization should be used (a.k.a. packrat parsing) """ super(Parser, self).__init__(**kwargs) # Used to indicate state in which parser should not # treat newlines as whitespaces. self._eolterm = False self.skipws = skipws if ws is not None: self.ws = ws else: self.ws = DEFAULT_WS self.reduce_tree = reduce_tree self.autokwd = autokwd self.ignore_case = ignore_case self.memoization = memoization self.comments_model = None self.comments = [] self.comment_positions = {} self.sem_actions = {} self.parse_tree = None # Create regex used for autokwd matching flags = 0 if ignore_case: flags = re.IGNORECASE self.keyword_regex = re.compile(r'[^\d\W]\w*', flags) # Keep track of root rule we are currently in. # Used for debugging purposes self.in_rule = '' self.in_parse_comments = False # Are we in lexical rule? If so do not # skip whitespaces. self.in_lex_rule = False # Are we in Not parsing expression? self.in_not = False # Last parsing expression traversed self.last_pexpression = None @property def ws(self): return self._ws @ws.setter def ws(self, new_value): self._real_ws = new_value self._ws = new_value if self.eolterm: self._ws = self._ws.replace('\n', '').replace('\r', '') @property def eolterm(self): return self._eolterm @eolterm.setter def eolterm(self, new_value): # Toggle newline char in ws on eolterm property set. # During eolterm state parser should not treat # newline as a whitespace. self._eolterm = new_value if self._eolterm: self._ws = self._ws.replace('\n', '').replace('\r', '') else: self._ws = self._real_ws 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.nm = None # Last NoMatch exception self.line_ends = [] self.input = _input self.file_name = file_name self.comment_positions = {} self.cache_hits = 0 self.cache_misses = 0 try: self.parse_tree = self._parse() except NoMatch as e: # Remove Not marker if e.rules[0] is Parser.FIRST_NOT: del e.rules[0] # Get line and column from position e.line, e.col = self.pos_to_linecol(e.position) raise finally: # At end of parsing clear all memoization caches. # Do this here to free memory. if self.memoization: self._clear_caches() # In debug mode export parse tree to dot file for # visualization if self.debug and self.parse_tree: from arpeggio.export import PTDOTExporter root_rule_name = self.parse_tree.rule_name PTDOTExporter().exportFile( self.parse_tree, "{}_parse_tree.dot".format(root_rule_name)) return self.parse_tree 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) 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. defaults (bool): If True a default semantic action will be applied in case no action is defined for the node. """ if not self.parse_tree: raise Exception( "Parse tree is empty. You did call parse(), didn't you?") if sem_actions is None: if not self.sem_actions: raise Exception("Semantic actions not defined.") else: sem_actions = self.sem_actions if type(sem_actions) is not dict: raise Exception("Semantic actions parameter must be a dictionary.") for_second_pass = [] def tree_walk(node): """ Walking the parse tree and calling first_pass for every registered semantic actions and creating list of object that needs to be called in the second pass. """ if self.debug: self.dprint( "Walking down %s type: %s str: %s" % (node.name, type(node).__name__, text(node))) children = SemanticActionResults() if isinstance(node, NonTerminal): for n in node: child = tree_walk(n) if child is not None: children.append_result(n.rule_name, child) if self.debug: self.dprint("Processing %s = '%s' type:%s len:%d" % (node.name, text(node), type(node).__name__, len(node) if isinstance(node, list) else 0)) for i, a in enumerate(children): self.dprint(" %d:%s type:%s" % (i+1, text(a), type(a).__name__)) if node.rule_name in sem_actions: sem_action = sem_actions[node.rule_name] if isinstance(sem_action, types.FunctionType): retval = sem_action(self, node, children) else: retval = sem_action.first_pass(self, node, children) if hasattr(sem_action, "second_pass"): for_second_pass.append((node.rule_name, retval)) if self.debug: action_name = sem_action.__name__ \ if hasattr(sem_action
(skipws=True, ws=None, reduce_tree=False, autokwd=False, ignore_case=False, memoization=False, **kwargs)
[ 0.016667991876602173, 0.013366344384849072, -0.013036179356276989, 0.026264067739248276, 0.00934579037129879, -0.013408945873379707, -0.019958987832069397, -0.011545113287866116, -0.019958987832069397, -0.07314745336771011, 0.012173491530120373, -0.001209494424983859, 0.009904940612614155, ...
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 is False. autokwd(bool): If keyword-like StrMatches are matched on word boundaries. Default is False. ignore_case(bool): If case is ignored (default=False) memoization(bool): If memoization should be used (a.k.a. packrat parsing)
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. reduce_tree (bool): If true non-terminals with single child will be eliminated from the parse tree. Default is False. autokwd(bool): If keyword-like StrMatches are matched on word boundaries. Default is False. ignore_case(bool): If case is ignored (default=False) memoization(bool): If memoization should be used (a.k.a. packrat parsing) """ super(Parser, self).__init__(**kwargs) # Used to indicate state in which parser should not # treat newlines as whitespaces. self._eolterm = False self.skipws = skipws if ws is not None: self.ws = ws else: self.ws = DEFAULT_WS self.reduce_tree = reduce_tree self.autokwd = autokwd self.ignore_case = ignore_case self.memoization = memoization self.comments_model = None self.comments = [] self.comment_positions = {} self.sem_actions = {} self.parse_tree = None # Create regex used for autokwd matching flags = 0 if ignore_case: flags = re.IGNORECASE self.keyword_regex = re.compile(r'[^\d\W]\w*', flags) # Keep track of root rule we are currently in. # Used for debugging purposes self.in_rule = '' self.in_parse_comments = False # Are we in lexical rule? If so do not # skip whitespaces. self.in_lex_rule = False # Are we in Not parsing expression? self.in_not = False # Last parsing expression traversed self.last_pexpression = None
(self, skipws=True, ws=None, reduce_tree=False, autokwd=False, ignore_case=False, memoization=False, **kwargs)
[ 0.007551553193479776, 0.01457416731864214, -0.00006423572631319985, 0.010890482924878597, -0.021780965849757195, 0.009572857059538364, 0.02646585740149021, 0.007523217238485813, -0.03239753469824791, -0.03354986384510994, 0.006838429719209671, 0.04076610878109932, -0.03328539431095123, 0.0...
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)
[ -0.036129217594861984, -0.009107536636292934, 0.026216251775622368, 0.03802330046892166, -0.02920784242451191, -0.012240741401910782, -0.02936715818941593, 0.048821352422237396, 0.02041008695960045, 0.003923144191503525, 0.013364801183342934, -0.0065496377646923065, -0.000784407602623105, ...
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: if self.nm is None or position > self.nm.position: if self.in_not: self.nm = NoMatch([Parser.FIRST_NOT], position, parser) else: self.nm = NoMatch([rule], position, parser) elif position == self.nm.position and isinstance(rule, Match) \ and not self.in_not: self.nm.rules.append(rule) raise self.nm
(self, *args)
[ 0.009480617009103298, 0.020035523921251297, 0.06202239170670509, 0.039999429136514664, -0.06900528073310852, -0.02977576106786728, 0.0286298505961895, 0.007622988894581795, 0.019176091998815536, -0.06127038970589638, 0.017591511830687523, -0.005420692730695009, 0.05579150468111038, -0.0363...
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. """ if not position: position = self.position if length: retval = "{}*{}*{}".format( text(self.input[max(position - 10, 0):position]), text(self.input[position:position + length]), text(self.input[position + length:position + 10])) else: retval = "{}*{}".format( text(self.input[max(position - 10, 0):position]), text(self.input[position:position + 10])) return retval.replace('\n', ' ').replace('\r', '')
(self, length=None, position=None)
[ 0.043570324778556824, -0.018046172335743904, 0.041419126093387604, -0.05487265810370445, 0.07341394573450089, -0.030611908063292503, 0.015015712939202785, -0.014623033814132214, 0.08830161392688751, -0.048965394496917725, -0.00728590739890933, -0.02424367517232895, -0.024926595389842987, 0...
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 semantic action will be applied in case no action is defined for the node.
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. defaults (bool): If True a default semantic action will be applied in case no action is defined for the node. """ if not self.parse_tree: raise Exception( "Parse tree is empty. You did call parse(), didn't you?") if sem_actions is None: if not self.sem_actions: raise Exception("Semantic actions not defined.") else: sem_actions = self.sem_actions if type(sem_actions) is not dict: raise Exception("Semantic actions parameter must be a dictionary.") for_second_pass = [] def tree_walk(node): """ Walking the parse tree and calling first_pass for every registered semantic actions and creating list of object that needs to be called in the second pass. """ if self.debug: self.dprint( "Walking down %s type: %s str: %s" % (node.name, type(node).__name__, text(node))) children = SemanticActionResults() if isinstance(node, NonTerminal): for n in node: child = tree_walk(n) if child is not None: children.append_result(n.rule_name, child) if self.debug: self.dprint("Processing %s = '%s' type:%s len:%d" % (node.name, text(node), type(node).__name__, len(node) if isinstance(node, list) else 0)) for i, a in enumerate(children): self.dprint(" %d:%s type:%s" % (i+1, text(a), type(a).__name__)) if node.rule_name in sem_actions: sem_action = sem_actions[node.rule_name] if isinstance(sem_action, types.FunctionType): retval = sem_action(self, node, children) else: retval = sem_action.first_pass(self, node, children) if hasattr(sem_action, "second_pass"): for_second_pass.append((node.rule_name, retval)) if self.debug: action_name = sem_action.__name__ \ if hasattr(sem_action, '__name__') \ else sem_action.__class__.__name__ self.dprint(" Applying semantic action %s" % action_name) else: if defaults: # If no rule is present use some sane defaults if self.debug: self.dprint(" Applying default semantic action.") retval = SemanticAction().first_pass(self, node, children) else: retval = node if self.debug: if retval is None: self.dprint(" Suppressed.") else: self.dprint(" Resolved to = %s type:%s" % (text(retval), type(retval).__name__)) return retval if self.debug: self.dprint("ASG: First pass") asg = tree_walk(self.parse_tree) # Second pass if self.debug: self.dprint("ASG: Second pass") for sa_name, asg_node in for_second_pass: sem_actions[sa_name].second_pass(self, asg_node) return asg
(self, sem_actions=None, defaults=True)
[ 0.0213755015283823, 0.007098297588527203, -0.008411743678152561, 0.002162206918001175, 0.027008619159460068, 0.0012482476886361837, -0.04442007467150688, 0.0026197792030870914, 0.042106132954359055, -0.034898776561021805, 0.0238601416349411, 0.03230033442378044, 0.0025628788862377405, 0.02...
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.nm = None # Last NoMatch exception self.line_ends = [] self.input = _input self.file_name = file_name self.comment_positions = {} self.cache_hits = 0 self.cache_misses = 0 try: self.parse_tree = self._parse() except NoMatch as e: # Remove Not marker if e.rules[0] is Parser.FIRST_NOT: del e.rules[0] # Get line and column from position e.line, e.col = self.pos_to_linecol(e.position) raise finally: # At end of parsing clear all memoization caches. # Do this here to free memory. if self.memoization: self._clear_caches() # In debug mode export parse tree to dot file for # visualization if self.debug and self.parse_tree: from arpeggio.export import PTDOTExporter root_rule_name = self.parse_tree.rule_name PTDOTExporter().exportFile( self.parse_tree, "{}_parse_tree.dot".format(root_rule_name)) return self.parse_tree
(self, _input, file_name=None)
[ -0.014961645007133484, 0.008483551442623138, -0.02887858636677265, 0.014299377799034119, -0.034699078649282455, -0.011417116038501263, -0.02865472249686718, 0.03988528251647949, -0.04671316593885422, -0.08148686587810516, 0.01843155361711979, 0.008236367255449295, -0.02115524373948574, 0.0...
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)
[ -0.005220502149313688, -0.058818548917770386, -0.0429033599793911, 0.022270582616329193, -0.03795434162020683, 0.01840749941766262, -0.006115064024925232, 0.04087390378117561, 0.0565042570233345, -0.020312337204813957, 0.01766870729625225, 0.014686834998428822, -0.026062455028295517, 0.049...
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.line_ends.append( self.input.index("\n", self.line_ends[-1] + 1)) except ValueError: break except ValueError: pass line = bisect.bisect_left(self.line_ends, pos) col = pos if line > 0: col -= self.line_ends[line - 1] if self.input[self.line_ends[line - 1]] in '\n\r': col -= 1 return line + 1, col + 1
(self, pos)
[ 0.010561449453234673, -0.003563291858881712, -0.0047539579682052135, 0.041096486151218414, 0.030648227781057358, -0.014244460500776768, 0.04217614233493805, 0.09493985027074814, 0.0030147582292556763, -0.0024270436260849237, 0.0008113726507872343, -0.014209632761776447, 0.0003436497936490923...
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 the root rule of the grammar. comment_def (python function): A python function that defines the root rule of the comments grammar. syntax_classes (dict): Overrides of special syntax parser expression classes (StrMatch, Sequence, OrderedChoice). """ super(ParserPython, self).__init__(*args, **kwargs) self.syntax_classes = syntax_classes if syntax_classes else {} # PEG Abstract Syntax Graph self.parser_model = self._from_python(language_def) self.comments_model = None if comment_def: self.comments_model = self._from_python(comment_def) self.comments_model.root = True self.comments_model.rule_name = comment_def.__name__ # In debug mode export parser model to dot for # visualization if self.debug: from arpeggio.export import PMDOTExporter root_rule = language_def.__name__ PMDOTExporter().exportFile(self.parser_model, "{}_parser_model.dot".format(root_rule)) def _parse(self): return self.parser_model.parse(self) 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": EndOfFile()} __for_resolving = [] # Expressions that needs crossref resolvnih self.__cross_refs = 0 _StrMatch = self.syntax_classes.get('StrMatch', StrMatch) _OrderedChoice = self.syntax_classes.get('OrderedChoice', OrderedChoice) _Sequence = self.syntax_classes.get('Sequence', Sequence) def inner_from_python(expression): retval = None if isinstance(expression, types.FunctionType): # If this expression is a parser rule rule_name = expression.__name__ if rule_name in __rule_cache: c_rule = __rule_cache.get(rule_name) if self.debug: self.dprint("Rule {} founded in cache." .format(rule_name)) if isinstance(c_rule, CrossRef): self.__cross_refs += 1 if self.debug: self.dprint("CrossRef usage: {}" .format(c_rule.target_rule_name)) return c_rule # Semantic action for the rule if hasattr(expression, "sem"): self.sem_actions[rule_name] = expression.sem # Register rule cross-ref to support recursion __rule_cache[rule_name] = CrossRef(rule_name) curr_expr = expression while isinstance(curr_expr, types.FunctionType): # If function directly returns another function # go into until non-function is returned. curr_expr = curr_expr() retval = inner_from_python(curr_expr) retval.rule_name = rule_name retval.root = True # Update cache __rule_cache[rule_name] = retval if self.debug: self.dprint("New rule: {} -> {}" .format(rule_name, retval.__class__.__name__)) elif type(expression) is text or isinstance(expression, _StrMatch): if type(expression) is text: retval = _StrMatch(expression, ignore_case=self.ignore_case) else: retval = expression if expression.ignore_case is None: expression.ignore_case = self.ignore_case if self.autokwd: to_match = retval.to_match match = self.keyword_regex.match(to_match) if match and match.span() == (0, len(to_match)): retval = RegExMatch(r'{}\b'.format(to_match), ignore_case=self.ignore_case, str_repr=to_match) retval.compile() elif isinstance(expression, RegExMatch): # Regular expression are not compiled yet # to support global settings propagation from # parser. if expression.ignore_case is None: expression.ignore_case = self.ignore_case expression.compile() retval = expression elif isinstance(expression, Match): retval = expression elif isinstance(expression, UnorderedGroup): retval = expression for n in retval.elements: retval.nodes.append(inner_from_python(n)) if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) elif isinstance(expression, _Sequence) or \ isinstance(expression, Repetition) or \ isinstance(expression, SyntaxPredicate) or \ isinstance(expression, Decorator): retval = expression retval.nodes.append(inner_from_python(retval.elements)) if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) elif type(expression) in [list, tuple]: if type(expression) is list: retval = _OrderedChoice(expression) else: retval = _Sequence(expression) retval.nodes = [inner_from_python(e) for e in expression] if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) else: raise GrammarError("Unrecognized grammar element '%s'." % text(expression)) # Translate separator expression. if isinstance(expression, Repetition) and expression.sep: expression.sep = inner_from_python(expression.sep) return retval # Cross-ref resolving def resolve(): for e in __for_resolving: for i, node in enumerate(e.nodes): if isinstance(node, CrossRef): self.__cross_refs -= 1 e.nodes[i] = __rule_cache[node.target_rule_name] parser_model = inner_from_python(expression) resolve() assert self.__cross_refs == 0, "Not all crossrefs are resolved!" return parser_model def errors(self): pass
(language_def, comment_def=None, syntax_classes=None, *args, **kwargs)
[ 0.0019864856731146574, -0.03709803521633148, -0.005660402588546276, 0.02115524560213089, -0.01754114031791687, 0.023496780544519424, -0.010516539216041565, -0.01625838689506054, 0.007752512115985155, -0.07289295643568039, 0.018874796107411385, 0.0018821348203346133, 0.019505992531776428, 0...
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 comments grammar. syntax_classes (dict): Overrides of special syntax parser expression classes (StrMatch, Sequence, OrderedChoice).
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 (python function): A python function that defines the root rule of the comments grammar. syntax_classes (dict): Overrides of special syntax parser expression classes (StrMatch, Sequence, OrderedChoice). """ super(ParserPython, self).__init__(*args, **kwargs) self.syntax_classes = syntax_classes if syntax_classes else {} # PEG Abstract Syntax Graph self.parser_model = self._from_python(language_def) self.comments_model = None if comment_def: self.comments_model = self._from_python(comment_def) self.comments_model.root = True self.comments_model.rule_name = comment_def.__name__ # In debug mode export parser model to dot for # visualization if self.debug: from arpeggio.export import PMDOTExporter root_rule = language_def.__name__ PMDOTExporter().exportFile(self.parser_model, "{}_parser_model.dot".format(root_rule))
(self, language_def, comment_def=None, syntax_classes=None, *args, **kwargs)
[ 0.0088828569278121, -0.021396059542894363, 0.02678183652460575, 0.014934963546693325, -0.029998598620295525, 0.005330633372068405, -0.02159825526177883, 0.028399407863616943, -0.03512703627347946, -0.031799983233213425, 0.01658010669052601, 0.006824129726737738, -0.028160449117422104, 0.07...
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": EndOfFile()} __for_resolving = [] # Expressions that needs crossref resolvnih self.__cross_refs = 0 _StrMatch = self.syntax_classes.get('StrMatch', StrMatch) _OrderedChoice = self.syntax_classes.get('OrderedChoice', OrderedChoice) _Sequence = self.syntax_classes.get('Sequence', Sequence) def inner_from_python(expression): retval = None if isinstance(expression, types.FunctionType): # If this expression is a parser rule rule_name = expression.__name__ if rule_name in __rule_cache: c_rule = __rule_cache.get(rule_name) if self.debug: self.dprint("Rule {} founded in cache." .format(rule_name)) if isinstance(c_rule, CrossRef): self.__cross_refs += 1 if self.debug: self.dprint("CrossRef usage: {}" .format(c_rule.target_rule_name)) return c_rule # Semantic action for the rule if hasattr(expression, "sem"): self.sem_actions[rule_name] = expression.sem # Register rule cross-ref to support recursion __rule_cache[rule_name] = CrossRef(rule_name) curr_expr = expression while isinstance(curr_expr, types.FunctionType): # If function directly returns another function # go into until non-function is returned. curr_expr = curr_expr() retval = inner_from_python(curr_expr) retval.rule_name = rule_name retval.root = True # Update cache __rule_cache[rule_name] = retval if self.debug: self.dprint("New rule: {} -> {}" .format(rule_name, retval.__class__.__name__)) elif type(expression) is text or isinstance(expression, _StrMatch): if type(expression) is text: retval = _StrMatch(expression, ignore_case=self.ignore_case) else: retval = expression if expression.ignore_case is None: expression.ignore_case = self.ignore_case if self.autokwd: to_match = retval.to_match match = self.keyword_regex.match(to_match) if match and match.span() == (0, len(to_match)): retval = RegExMatch(r'{}\b'.format(to_match), ignore_case=self.ignore_case, str_repr=to_match) retval.compile() elif isinstance(expression, RegExMatch): # Regular expression are not compiled yet # to support global settings propagation from # parser. if expression.ignore_case is None: expression.ignore_case = self.ignore_case expression.compile() retval = expression elif isinstance(expression, Match): retval = expression elif isinstance(expression, UnorderedGroup): retval = expression for n in retval.elements: retval.nodes.append(inner_from_python(n)) if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) elif isinstance(expression, _Sequence) or \ isinstance(expression, Repetition) or \ isinstance(expression, SyntaxPredicate) or \ isinstance(expression, Decorator): retval = expression retval.nodes.append(inner_from_python(retval.elements)) if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) elif type(expression) in [list, tuple]: if type(expression) is list: retval = _OrderedChoice(expression) else: retval = _Sequence(expression) retval.nodes = [inner_from_python(e) for e in expression] if any((isinstance(x, CrossRef) for x in retval.nodes)): __for_resolving.append(retval) else: raise GrammarError("Unrecognized grammar element '%s'." % text(expression)) # Translate separator expression. if isinstance(expression, Repetition) and expression.sep: expression.sep = inner_from_python(expression.sep) return retval # Cross-ref resolving def resolve(): for e in __for_resolving: for i, node in enumerate(e.nodes): if isinstance(node, CrossRef): self.__cross_refs -= 1 e.nodes[i] = __rule_cache[node.target_rule_name] parser_model = inner_from_python(expression) resolve() assert self.__cross_refs == 0, "Not all crossrefs are resolved!" return parser_model
(self, expression)
[ 0.00931098498404026, -0.029538296163082123, -0.008654029108583927, 0.015895357355475426, -0.023334266617894173, 0.04789353162050247, 0.006080542225390673, -0.02181289531290531, 0.023393539711833, -0.06484594941139221, 0.007646368350833654, 0.019669147208333015, 0.015529833734035492, 0.0216...
140
arpeggio
_parse
null
def _parse(self): return self.parser_model.parse(self)
(self)
[ 0.009995485655963421, -0.01713148131966591, -0.03100467287003994, 0.008748170919716358, -0.027339095249772072, 0.0036083024460822344, 0.05909046158194542, 0.04398692399263382, 0.018395766615867615, 0.012515570037066936, 0.022468630224466324, -0.0075772227719426155, -0.008892418816685677, 0...
143
arpeggio
errors
null
def errors(self): pass
(self)
[ -0.02931283786892891, -0.0007189589668996632, 0.03275556489825249, 0.05263400450348854, -0.01214885525405407, -0.014706073328852654, -0.0006336149526759982, -0.0024289435241371393, 0.10857832431793213, -0.009517154656350613, 0.03965757042169571, -0.02138463407754898, 0.05773188918828964, -...