repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
wtolson/gnsq | gnsq/nsqd.py | NsqdTCPClient.publish | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over tcp.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
"""
if defer is None:
self.send(nsq.publish(topic, data))
else:
self.send(nsq.deferpublish(topic, data, defer)) | python | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over tcp.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
"""
if defer is None:
self.send(nsq.publish(topic, data))
else:
self.send(nsq.deferpublish(topic, data, defer)) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"data",
",",
"defer",
"=",
"None",
")",
":",
"if",
"defer",
"is",
"None",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"publish",
"(",
"topic",
",",
"data",
")",
")",
"else",
":",
"self",
".",
"se... | Publish a message to the given topic over tcp.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6) | [
"Publish",
"a",
"message",
"to",
"the",
"given",
"topic",
"over",
"tcp",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L418-L431 |
wtolson/gnsq | gnsq/nsqd.py | NsqdTCPClient.multipublish | def multipublish(self, topic, messages):
"""Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
"""
self.send(nsq.multipublish(topic, messages)) | python | def multipublish(self, topic, messages):
"""Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
"""
self.send(nsq.multipublish(topic, messages)) | [
"def",
"multipublish",
"(",
"self",
",",
"topic",
",",
"messages",
")",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"multipublish",
"(",
"topic",
",",
"messages",
")",
")"
] | Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish | [
"Publish",
"an",
"iterable",
"of",
"messages",
"to",
"the",
"given",
"topic",
"over",
"http",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L433-L440 |
wtolson/gnsq | gnsq/nsqd.py | NsqdTCPClient.ready | def ready(self, count):
"""Indicate you are ready to receive ``count`` messages."""
self.ready_count = count
self.send(nsq.ready(count)) | python | def ready(self, count):
"""Indicate you are ready to receive ``count`` messages."""
self.ready_count = count
self.send(nsq.ready(count)) | [
"def",
"ready",
"(",
"self",
",",
"count",
")",
":",
"self",
".",
"ready_count",
"=",
"count",
"self",
".",
"send",
"(",
"nsq",
".",
"ready",
"(",
"count",
")",
")"
] | Indicate you are ready to receive ``count`` messages. | [
"Indicate",
"you",
"are",
"ready",
"to",
"receive",
"count",
"messages",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L442-L445 |
wtolson/gnsq | gnsq/nsqd.py | NsqdTCPClient.finish | def finish(self, message_id):
"""Finish a message (indicate successful processing)."""
self.send(nsq.finish(message_id))
self.finish_inflight()
self.on_finish.send(self, message_id=message_id) | python | def finish(self, message_id):
"""Finish a message (indicate successful processing)."""
self.send(nsq.finish(message_id))
self.finish_inflight()
self.on_finish.send(self, message_id=message_id) | [
"def",
"finish",
"(",
"self",
",",
"message_id",
")",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"finish",
"(",
"message_id",
")",
")",
"self",
".",
"finish_inflight",
"(",
")",
"self",
".",
"on_finish",
".",
"send",
"(",
"self",
",",
"message_id",
"... | Finish a message (indicate successful processing). | [
"Finish",
"a",
"message",
"(",
"indicate",
"successful",
"processing",
")",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L447-L451 |
wtolson/gnsq | gnsq/nsqd.py | NsqdTCPClient.requeue | def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.finish_inflight()
self.on_requeue.send(
self,
message_id=message_id,
timeout=timeout,
backoff=backoff
) | python | def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.finish_inflight()
self.on_requeue.send(
self,
message_id=message_id,
timeout=timeout,
backoff=backoff
) | [
"def",
"requeue",
"(",
"self",
",",
"message_id",
",",
"timeout",
"=",
"0",
",",
"backoff",
"=",
"True",
")",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"requeue",
"(",
"message_id",
",",
"timeout",
")",
")",
"self",
".",
"finish_inflight",
"(",
")",... | Re-queue a message (indicate failure to process). | [
"Re",
"-",
"queue",
"a",
"message",
"(",
"indicate",
"failure",
"to",
"process",
")",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L453-L462 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.publish | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6)
"""
nsq.assert_valid_topic_name(topic)
fields = {'topic': topic}
if defer is not None:
fields['defer'] = '{}'.format(defer)
return self._request('POST', '/pub', fields=fields, body=data) | python | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6)
"""
nsq.assert_valid_topic_name(topic)
fields = {'topic': topic}
if defer is not None:
fields['defer'] = '{}'.format(defer)
return self._request('POST', '/pub', fields=fields, body=data) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"data",
",",
"defer",
"=",
"None",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
"if",
"defer",
"is",
"not",
"None",
":",
"field... | Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6) | [
"Publish",
"a",
"message",
"to",
"the",
"given",
"topic",
"over",
"http",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L507-L523 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.multipublish | def multipublish(self, topic, messages, binary=False):
"""Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param binary: enable binary mode. defaults to False
(requires nsq 1.0.0)
By default multipublish expects messages to be delimited by ``"\\n"``,
use the binary flag to enable binary mode where the POST body is
expected to be in the following wire protocol format.
"""
nsq.assert_valid_topic_name(topic)
fields = {'topic': topic}
if binary:
fields['binary'] = 'true'
body = nsq.multipublish_body(messages)
else:
body = b'\n'.join(self._validate_mpub_message(m) for m in messages)
return self._request('POST', '/mpub', fields=fields, body=body) | python | def multipublish(self, topic, messages, binary=False):
"""Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param binary: enable binary mode. defaults to False
(requires nsq 1.0.0)
By default multipublish expects messages to be delimited by ``"\\n"``,
use the binary flag to enable binary mode where the POST body is
expected to be in the following wire protocol format.
"""
nsq.assert_valid_topic_name(topic)
fields = {'topic': topic}
if binary:
fields['binary'] = 'true'
body = nsq.multipublish_body(messages)
else:
body = b'\n'.join(self._validate_mpub_message(m) for m in messages)
return self._request('POST', '/mpub', fields=fields, body=body) | [
"def",
"multipublish",
"(",
"self",
",",
"topic",
",",
"messages",
",",
"binary",
"=",
"False",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
"if",
"binary",
":",
"fields",
"[",
"'... | Publish an iterable of messages to the given topic over http.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param binary: enable binary mode. defaults to False
(requires nsq 1.0.0)
By default multipublish expects messages to be delimited by ``"\\n"``,
use the binary flag to enable binary mode where the POST body is
expected to be in the following wire protocol format. | [
"Publish",
"an",
"iterable",
"of",
"messages",
"to",
"the",
"given",
"topic",
"over",
"http",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L531-L554 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.create_topic | def create_topic(self, topic):
"""Create a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/create', fields={'topic': topic}) | python | def create_topic(self, topic):
"""Create a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/create', fields={'topic': topic}) | [
"def",
"create_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/create'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Create a topic. | [
"Create",
"a",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L556-L559 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.delete_topic | def delete_topic(self, topic):
"""Delete a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/delete', fields={'topic': topic}) | python | def delete_topic(self, topic):
"""Delete a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/delete', fields={'topic': topic}) | [
"def",
"delete_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/delete'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Delete a topic. | [
"Delete",
"a",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L561-L564 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.empty_topic | def empty_topic(self, topic):
"""Empty all the queued messages for an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/empty', fields={'topic': topic}) | python | def empty_topic(self, topic):
"""Empty all the queued messages for an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/empty', fields={'topic': topic}) | [
"def",
"empty_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/empty'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Empty all the queued messages for an existing topic. | [
"Empty",
"all",
"the",
"queued",
"messages",
"for",
"an",
"existing",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L580-L583 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.empty_channel | def empty_channel(self, topic, channel):
"""Empty all the queued messages for an existing channel."""
nsq.assert_valid_topic_name(topic)
nsq.assert_valid_channel_name(channel)
return self._request('POST', '/channel/empty',
fields={'topic': topic, 'channel': channel}) | python | def empty_channel(self, topic, channel):
"""Empty all the queued messages for an existing channel."""
nsq.assert_valid_topic_name(topic)
nsq.assert_valid_channel_name(channel)
return self._request('POST', '/channel/empty',
fields={'topic': topic, 'channel': channel}) | [
"def",
"empty_channel",
"(",
"self",
",",
"topic",
",",
"channel",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"nsq",
".",
"assert_valid_channel_name",
"(",
"channel",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/cha... | Empty all the queued messages for an existing channel. | [
"Empty",
"all",
"the",
"queued",
"messages",
"for",
"an",
"existing",
"channel",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L585-L590 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.pause_topic | def pause_topic(self, topic):
"""Pause message flow to all channels on an existing topic.
Messages will queue at topic.
"""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/pause', fields={'topic': topic}) | python | def pause_topic(self, topic):
"""Pause message flow to all channels on an existing topic.
Messages will queue at topic.
"""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/pause', fields={'topic': topic}) | [
"def",
"pause_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/pause'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Pause message flow to all channels on an existing topic.
Messages will queue at topic. | [
"Pause",
"message",
"flow",
"to",
"all",
"channels",
"on",
"an",
"existing",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L592-L598 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.unpause_topic | def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/unpause', fields={'topic': topic}) | python | def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/unpause', fields={'topic': topic}) | [
"def",
"unpause_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/unpause'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Resume message flow to channels of an existing, paused, topic. | [
"Resume",
"message",
"flow",
"to",
"channels",
"of",
"an",
"existing",
"paused",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L600-L603 |
wtolson/gnsq | gnsq/nsqd.py | NsqdHTTPClient.stats | def stats(self, topic=None, channel=None, text=False):
"""Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
"""
if text:
fields = {'format': 'text'}
else:
fields = {'format': 'json'}
if topic:
nsq.assert_valid_topic_name(topic)
fields['topic'] = topic
if channel:
nsq.assert_valid_channel_name(channel)
fields['channel'] = channel
return self._request('GET', '/stats', fields=fields) | python | def stats(self, topic=None, channel=None, text=False):
"""Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
"""
if text:
fields = {'format': 'text'}
else:
fields = {'format': 'json'}
if topic:
nsq.assert_valid_topic_name(topic)
fields['topic'] = topic
if channel:
nsq.assert_valid_channel_name(channel)
fields['channel'] = channel
return self._request('GET', '/stats', fields=fields) | [
"def",
"stats",
"(",
"self",
",",
"topic",
"=",
"None",
",",
"channel",
"=",
"None",
",",
"text",
"=",
"False",
")",
":",
"if",
"text",
":",
"fields",
"=",
"{",
"'format'",
":",
"'text'",
"}",
"else",
":",
"fields",
"=",
"{",
"'format'",
":",
"'j... | Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``) | [
"Return",
"internal",
"instrumented",
"statistics",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L622-L644 |
wtolson/gnsq | gnsq/nsqd.py | Nsqd.publish_tcp | def publish_tcp(self, topic, data, **kwargs):
"""Use :meth:`NsqdTCPClient.publish` instead.
.. deprecated:: 1.0.0
"""
return self.__tcp_client.publish(topic, data, **kwargs) | python | def publish_tcp(self, topic, data, **kwargs):
"""Use :meth:`NsqdTCPClient.publish` instead.
.. deprecated:: 1.0.0
"""
return self.__tcp_client.publish(topic, data, **kwargs) | [
"def",
"publish_tcp",
"(",
"self",
",",
"topic",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__tcp_client",
".",
"publish",
"(",
"topic",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Use :meth:`NsqdTCPClient.publish` instead.
.. deprecated:: 1.0.0 | [
"Use",
":",
"meth",
":",
"NsqdTCPClient",
".",
"publish",
"instead",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L682-L687 |
wtolson/gnsq | gnsq/nsqd.py | Nsqd.publish_http | def publish_http(self, topic, data, **kwargs):
"""Use :meth:`NsqdHTTPClient.publish` instead.
.. deprecated:: 1.0.0
"""
self.__http_client.publish(topic, data, **kwargs) | python | def publish_http(self, topic, data, **kwargs):
"""Use :meth:`NsqdHTTPClient.publish` instead.
.. deprecated:: 1.0.0
"""
self.__http_client.publish(topic, data, **kwargs) | [
"def",
"publish_http",
"(",
"self",
",",
"topic",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__http_client",
".",
"publish",
"(",
"topic",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Use :meth:`NsqdHTTPClient.publish` instead.
.. deprecated:: 1.0.0 | [
"Use",
":",
"meth",
":",
"NsqdHTTPClient",
".",
"publish",
"instead",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L690-L695 |
wtolson/gnsq | gnsq/nsqd.py | Nsqd.multipublish_tcp | def multipublish_tcp(self, topic, messages, **kwargs):
"""Use :meth:`NsqdTCPClient.multipublish` instead.
.. deprecated:: 1.0.0
"""
return self.__tcp_client.multipublish(topic, messages, **kwargs) | python | def multipublish_tcp(self, topic, messages, **kwargs):
"""Use :meth:`NsqdTCPClient.multipublish` instead.
.. deprecated:: 1.0.0
"""
return self.__tcp_client.multipublish(topic, messages, **kwargs) | [
"def",
"multipublish_tcp",
"(",
"self",
",",
"topic",
",",
"messages",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__tcp_client",
".",
"multipublish",
"(",
"topic",
",",
"messages",
",",
"*",
"*",
"kwargs",
")"
] | Use :meth:`NsqdTCPClient.multipublish` instead.
.. deprecated:: 1.0.0 | [
"Use",
":",
"meth",
":",
"NsqdTCPClient",
".",
"multipublish",
"instead",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L704-L709 |
wtolson/gnsq | gnsq/nsqd.py | Nsqd.multipublish_http | def multipublish_http(self, topic, messages, **kwargs):
"""Use :meth:`NsqdHTTPClient.multipublish` instead.
.. deprecated:: 1.0.0
"""
return self.__http_client.multipublish(topic, messages, **kwargs) | python | def multipublish_http(self, topic, messages, **kwargs):
"""Use :meth:`NsqdHTTPClient.multipublish` instead.
.. deprecated:: 1.0.0
"""
return self.__http_client.multipublish(topic, messages, **kwargs) | [
"def",
"multipublish_http",
"(",
"self",
",",
"topic",
",",
"messages",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__http_client",
".",
"multipublish",
"(",
"topic",
",",
"messages",
",",
"*",
"*",
"kwargs",
")"
] | Use :meth:`NsqdHTTPClient.multipublish` instead.
.. deprecated:: 1.0.0 | [
"Use",
":",
"meth",
":",
"NsqdHTTPClient",
".",
"multipublish",
"instead",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L712-L717 |
wtolson/gnsq | gnsq/producer.py | Producer.start | def start(self):
"""Start discovering and listing to connections."""
if self._state == CLOSED:
raise NSQException('producer already closed')
if self.is_running:
self.logger.warn('producer already started')
return
self.logger.debug('starting producer...')
self._state = RUNNING
for address in self.nsqd_tcp_addresses:
address, port = address.split(':')
self.connect_to_nsqd(address, int(port)) | python | def start(self):
"""Start discovering and listing to connections."""
if self._state == CLOSED:
raise NSQException('producer already closed')
if self.is_running:
self.logger.warn('producer already started')
return
self.logger.debug('starting producer...')
self._state = RUNNING
for address in self.nsqd_tcp_addresses:
address, port = address.split(':')
self.connect_to_nsqd(address, int(port)) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"CLOSED",
":",
"raise",
"NSQException",
"(",
"'producer already closed'",
")",
"if",
"self",
".",
"is_running",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"'producer already started... | Start discovering and listing to connections. | [
"Start",
"discovering",
"and",
"listing",
"to",
"connections",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L98-L112 |
wtolson/gnsq | gnsq/producer.py | Producer.close | def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('closing connection(s)')
while True:
try:
conn = self._connections.get(block=False)
except Empty:
break
conn.close_stream()
self.on_close.send(self) | python | def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('closing connection(s)')
while True:
try:
conn = self._connections.get(block=False)
except Empty:
break
conn.close_stream()
self.on_close.send(self) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
":",
"return",
"self",
".",
"_state",
"=",
"CLOSED",
"self",
".",
"logger",
".",
"debug",
"(",
"'closing connection(s)'",
")",
"while",
"True",
":",
"try",
":",
"conn",
"=",... | Immediately close all connections and stop workers. | [
"Immediately",
"close",
"all",
"connections",
"and",
"stop",
"workers",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L114-L130 |
wtolson/gnsq | gnsq/producer.py | Producer.join | def join(self, timeout=None, raise_error=False):
"""Block until all connections have closed and workers stopped."""
self._workers.join(timeout, raise_error) | python | def join(self, timeout=None, raise_error=False):
"""Block until all connections have closed and workers stopped."""
self._workers.join(timeout, raise_error) | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"False",
")",
":",
"self",
".",
"_workers",
".",
"join",
"(",
"timeout",
",",
"raise_error",
")"
] | Block until all connections have closed and workers stopped. | [
"Block",
"until",
"all",
"connections",
"have",
"closed",
"and",
"workers",
"stopped",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L132-L134 |
wtolson/gnsq | gnsq/producer.py | Producer.publish | def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.publish(topic, data, defer=defer)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result | python | def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.publish(topic, data, defer=defer)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"data",
",",
"defer",
"=",
"None",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"True",
")",
":",
"result",
"=",
"AsyncResult",
"(",
")",
"conn",
"=",
"self",
"."... | Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned | [
"Publish",
"a",
"message",
"to",
"the",
"given",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L252-L287 |
wtolson/gnsq | gnsq/producer.py | Producer.multipublish | def multipublish(self, topic, messages, block=True, timeout=None,
raise_error=True):
"""Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.multipublish(topic, messages)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result | python | def multipublish(self, topic, messages, block=True, timeout=None,
raise_error=True):
"""Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned
"""
result = AsyncResult()
conn = self._get_connection(block=block, timeout=timeout)
try:
self._response_queues[conn].append(result)
conn.multipublish(topic, messages)
finally:
self._put_connection(conn)
if raise_error:
return result.get()
return result | [
"def",
"multipublish",
"(",
"self",
",",
"topic",
",",
"messages",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"True",
")",
":",
"result",
"=",
"AsyncResult",
"(",
")",
"conn",
"=",
"self",
".",
"_get_connection",
"... | Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connection to become available before
publishing the message. If block is `False` and no connections
are available, :class:`~gnsq.errors.NSQNoConnections` is raised
:param timeout: if timeout is a positive number, it blocks at most
``timeout`` seconds before raising
:class:`~gnsq.errors.NSQNoConnections`
:param raise_error: if ``True``, it blocks until a response is received
from the nsqd server, and any error response is raised. Otherwise
an :class:`~gevent.event.AsyncResult` is returned | [
"Publish",
"an",
"iterable",
"of",
"messages",
"to",
"the",
"given",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L289-L321 |
wtolson/gnsq | gnsq/message.py | Message.finish | def finish(self):
"""
Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_finish.send(self) | python | def finish(self):
"""
Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_finish.send(self) | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_responded",
":",
"raise",
"NSQException",
"(",
"'already responded'",
")",
"self",
".",
"_has_responded",
"=",
"True",
"self",
".",
"on_finish",
".",
"send",
"(",
"self",
")"
] | Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it). | [
"Respond",
"to",
"nsqd",
"that",
"you’ve",
"processed",
"this",
"message",
"successfully",
"(",
"or",
"would",
"like",
"to",
"silently",
"discard",
"it",
")",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/message.py#L59-L67 |
wtolson/gnsq | gnsq/message.py | Message.requeue | def requeue(self, time_ms=0, backoff=True):
"""
Respond to nsqd that you’ve failed to process this message successfully
(and would like it to be requeued).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_requeue.send(self, timeout=time_ms, backoff=backoff) | python | def requeue(self, time_ms=0, backoff=True):
"""
Respond to nsqd that you’ve failed to process this message successfully
(and would like it to be requeued).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_requeue.send(self, timeout=time_ms, backoff=backoff) | [
"def",
"requeue",
"(",
"self",
",",
"time_ms",
"=",
"0",
",",
"backoff",
"=",
"True",
")",
":",
"if",
"self",
".",
"_has_responded",
":",
"raise",
"NSQException",
"(",
"'already responded'",
")",
"self",
".",
"_has_responded",
"=",
"True",
"self",
".",
"... | Respond to nsqd that you’ve failed to process this message successfully
(and would like it to be requeued). | [
"Respond",
"to",
"nsqd",
"that",
"you’ve",
"failed",
"to",
"process",
"this",
"message",
"successfully",
"(",
"and",
"would",
"like",
"it",
"to",
"be",
"requeued",
")",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/message.py#L69-L77 |
wtolson/gnsq | gnsq/lookupd.py | LookupdClient.lookup | def lookup(self, topic):
"""Returns producers for a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/lookup', fields={'topic': topic}) | python | def lookup(self, topic):
"""Returns producers for a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/lookup', fields={'topic': topic}) | [
"def",
"lookup",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'/lookup'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Returns producers for a topic. | [
"Returns",
"producers",
"for",
"a",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L26-L29 |
wtolson/gnsq | gnsq/lookupd.py | LookupdClient.channels | def channels(self, topic):
"""Returns all known channels of a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/channels', fields={'topic': topic}) | python | def channels(self, topic):
"""Returns all known channels of a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/channels', fields={'topic': topic}) | [
"def",
"channels",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'/channels'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Returns all known channels of a topic. | [
"Returns",
"all",
"known",
"channels",
"of",
"a",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L35-L38 |
wtolson/gnsq | gnsq/lookupd.py | LookupdClient.tombstone_topic | def tombstone_topic(self, topic, node):
"""Tombstones a specific producer of an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/tombstone',
fields={'topic': topic, 'node': node}) | python | def tombstone_topic(self, topic, node):
"""Tombstones a specific producer of an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/tombstone',
fields={'topic': topic, 'node': node}) | [
"def",
"tombstone_topic",
"(",
"self",
",",
"topic",
",",
"node",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/tombstone'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"top... | Tombstones a specific producer of an existing topic. | [
"Tombstones",
"a",
"specific",
"producer",
"of",
"an",
"existing",
"topic",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L68-L72 |
wtolson/gnsq | gnsq/consumer.py | Consumer.start | def start(self, block=True):
"""Start discovering and listing to connections."""
if self._state == INIT:
if not any(self.on_message.receivers_for(blinker.ANY)):
raise RuntimeError('no receivers connected to on_message')
self.logger.debug('starting %s...', self.name)
self._state = RUNNING
self.query_nsqd()
if self.lookupds:
self.query_lookupd()
self._killables.add(self._workers.spawn(self._poll_lookupd))
self._killables.add(self._workers.spawn(self._poll_ready))
else:
self.logger.warn('%s already started', self.name)
if block:
self.join() | python | def start(self, block=True):
"""Start discovering and listing to connections."""
if self._state == INIT:
if not any(self.on_message.receivers_for(blinker.ANY)):
raise RuntimeError('no receivers connected to on_message')
self.logger.debug('starting %s...', self.name)
self._state = RUNNING
self.query_nsqd()
if self.lookupds:
self.query_lookupd()
self._killables.add(self._workers.spawn(self._poll_lookupd))
self._killables.add(self._workers.spawn(self._poll_ready))
else:
self.logger.warn('%s already started', self.name)
if block:
self.join() | [
"def",
"start",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"if",
"self",
".",
"_state",
"==",
"INIT",
":",
"if",
"not",
"any",
"(",
"self",
".",
"on_message",
".",
"receivers_for",
"(",
"blinker",
".",
"ANY",
")",
")",
":",
"raise",
"Runtime... | Start discovering and listing to connections. | [
"Start",
"discovering",
"and",
"listing",
"to",
"connections",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/consumer.py#L229-L249 |
wtolson/gnsq | gnsq/consumer.py | Consumer.close | def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('killing %d worker(s)', len(self._killables))
self._killables.kill(block=False)
self.logger.debug('closing %d connection(s)', len(self._connections))
for conn in self._connections:
conn.close_stream()
self.on_close.send(self) | python | def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('killing %d worker(s)', len(self._killables))
self._killables.kill(block=False)
self.logger.debug('closing %d connection(s)', len(self._connections))
for conn in self._connections:
conn.close_stream()
self.on_close.send(self) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
":",
"return",
"self",
".",
"_state",
"=",
"CLOSED",
"self",
".",
"logger",
".",
"debug",
"(",
"'killing %d worker(s)'",
",",
"len",
"(",
"self",
".",
"_killables",
")",
")"... | Immediately close all connections and stop workers. | [
"Immediately",
"close",
"all",
"connections",
"and",
"stop",
"workers",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/consumer.py#L251-L265 |
wtolson/gnsq | gnsq/reader.py | Reader.publish | def publish(self, topic, message):
"""Use :class:`~gnsq.Producer` instead.
.. deprecated:: 1.0.0
"""
if not self.connections:
raise NSQNoConnections()
conn = random.choice(list(self.connections))
conn.publish(topic, message) | python | def publish(self, topic, message):
"""Use :class:`~gnsq.Producer` instead.
.. deprecated:: 1.0.0
"""
if not self.connections:
raise NSQNoConnections()
conn = random.choice(list(self.connections))
conn.publish(topic, message) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"connections",
":",
"raise",
"NSQNoConnections",
"(",
")",
"conn",
"=",
"random",
".",
"choice",
"(",
"list",
"(",
"self",
".",
"connections",
")",
")",
... | Use :class:`~gnsq.Producer` instead.
.. deprecated:: 1.0.0 | [
"Use",
":",
"class",
":",
"~gnsq",
".",
"Producer",
"instead",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/reader.py#L57-L65 |
wtolson/gnsq | gnsq/decorators.py | deprecated | def deprecated(fn):
"""Mark a function as deprecated and warn the user on use."""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn(fn.__doc__.split('\n')[0],
category=DeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return wrapper | python | def deprecated(fn):
"""Mark a function as deprecated and warn the user on use."""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn(fn.__doc__.split('\n')[0],
category=DeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return wrapper | [
"def",
"deprecated",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"fn",
".",
"__doc__",
".",
"split",
"(",
"'\\n'",
")",
... | Mark a function as deprecated and warn the user on use. | [
"Mark",
"a",
"function",
"as",
"deprecated",
"and",
"warn",
"the",
"user",
"on",
"use",
"."
] | train | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/decorators.py#L26-L33 |
llllllllll/codetransformer | codetransformer/core.py | _new_lnotab | def _new_lnotab(instrs, lnotab):
"""The updated lnotab after the instructions have been transformed.
Parameters
----------
instrs : iterable[Instruction]
The new instructions.
lnotab : dict[Instruction -> int]
The lnotab for the old code object.
Returns
-------
new_lnotab : dict[Instruction -> int]
The post transform lnotab.
"""
return {
lno: _a_if_not_none(instr._stolen_by, instr)
for lno, instr in lnotab.items()
} | python | def _new_lnotab(instrs, lnotab):
"""The updated lnotab after the instructions have been transformed.
Parameters
----------
instrs : iterable[Instruction]
The new instructions.
lnotab : dict[Instruction -> int]
The lnotab for the old code object.
Returns
-------
new_lnotab : dict[Instruction -> int]
The post transform lnotab.
"""
return {
lno: _a_if_not_none(instr._stolen_by, instr)
for lno, instr in lnotab.items()
} | [
"def",
"_new_lnotab",
"(",
"instrs",
",",
"lnotab",
")",
":",
"return",
"{",
"lno",
":",
"_a_if_not_none",
"(",
"instr",
".",
"_stolen_by",
",",
"instr",
")",
"for",
"lno",
",",
"instr",
"in",
"lnotab",
".",
"items",
"(",
")",
"}"
] | The updated lnotab after the instructions have been transformed.
Parameters
----------
instrs : iterable[Instruction]
The new instructions.
lnotab : dict[Instruction -> int]
The lnotab for the old code object.
Returns
-------
new_lnotab : dict[Instruction -> int]
The post transform lnotab. | [
"The",
"updated",
"lnotab",
"after",
"the",
"instructions",
"have",
"been",
"transformed",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L32-L50 |
llllllllll/codetransformer | codetransformer/core.py | CodeTransformer.transform_consts | def transform_consts(self, consts):
"""transformer for the co_consts field.
Override this method to transform the `co_consts` of the code object.
Parameters
----------
consts : tuple
The co_consts
Returns
-------
new_consts : tuple
The new constants.
"""
return tuple(
self.transform(Code.from_pycode(const)).to_pycode()
if isinstance(const, CodeType) else
const
for const in consts
) | python | def transform_consts(self, consts):
"""transformer for the co_consts field.
Override this method to transform the `co_consts` of the code object.
Parameters
----------
consts : tuple
The co_consts
Returns
-------
new_consts : tuple
The new constants.
"""
return tuple(
self.transform(Code.from_pycode(const)).to_pycode()
if isinstance(const, CodeType) else
const
for const in consts
) | [
"def",
"transform_consts",
"(",
"self",
",",
"consts",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"transform",
"(",
"Code",
".",
"from_pycode",
"(",
"const",
")",
")",
".",
"to_pycode",
"(",
")",
"if",
"isinstance",
"(",
"const",
",",
"CodeType",
"... | transformer for the co_consts field.
Override this method to transform the `co_consts` of the code object.
Parameters
----------
consts : tuple
The co_consts
Returns
-------
new_consts : tuple
The new constants. | [
"transformer",
"for",
"the",
"co_consts",
"field",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L104-L124 |
llllllllll/codetransformer | codetransformer/core.py | CodeTransformer.transform | def transform(self, code, *, name=None, filename=None):
"""Transform a codetransformer.Code object applying the transforms.
Parameters
----------
code : Code
The code object to transform.
name : str, optional
The new name for this code object.
filename : str, optional
The new filename for this code object.
Returns
-------
new_code : Code
The transformed code object.
"""
# reverse lookups from for constants and names.
reversed_consts = {}
reversed_names = {}
reversed_varnames = {}
for instr in code:
if isinstance(instr, LOAD_CONST):
reversed_consts[instr] = instr.arg
if instr.uses_name:
reversed_names[instr] = instr.arg
if isinstance(instr, (STORE_FAST, LOAD_FAST)):
reversed_varnames[instr] = instr.arg
instrs, consts = tuple(zip(*reversed_consts.items())) or ((), ())
for instr, const in zip(instrs, self.transform_consts(consts)):
instr.arg = const
instrs, names = tuple(zip(*reversed_names.items())) or ((), ())
for instr, name_ in zip(instrs, self.transform_names(names)):
instr.arg = name_
instrs, varnames = tuple(zip(*reversed_varnames.items())) or ((), ())
for instr, varname in zip(instrs, self.transform_varnames(varnames)):
instr.arg = varname
with self._new_context(code):
post_transform = self.patterndispatcher(code)
return Code(
post_transform,
code.argnames,
cellvars=self.transform_cellvars(code.cellvars),
freevars=self.transform_freevars(code.freevars),
name=name if name is not None else code.name,
filename=filename if filename is not None else code.filename,
firstlineno=code.firstlineno,
lnotab=_new_lnotab(post_transform, code.lnotab),
flags=code.flags,
) | python | def transform(self, code, *, name=None, filename=None):
"""Transform a codetransformer.Code object applying the transforms.
Parameters
----------
code : Code
The code object to transform.
name : str, optional
The new name for this code object.
filename : str, optional
The new filename for this code object.
Returns
-------
new_code : Code
The transformed code object.
"""
# reverse lookups from for constants and names.
reversed_consts = {}
reversed_names = {}
reversed_varnames = {}
for instr in code:
if isinstance(instr, LOAD_CONST):
reversed_consts[instr] = instr.arg
if instr.uses_name:
reversed_names[instr] = instr.arg
if isinstance(instr, (STORE_FAST, LOAD_FAST)):
reversed_varnames[instr] = instr.arg
instrs, consts = tuple(zip(*reversed_consts.items())) or ((), ())
for instr, const in zip(instrs, self.transform_consts(consts)):
instr.arg = const
instrs, names = tuple(zip(*reversed_names.items())) or ((), ())
for instr, name_ in zip(instrs, self.transform_names(names)):
instr.arg = name_
instrs, varnames = tuple(zip(*reversed_varnames.items())) or ((), ())
for instr, varname in zip(instrs, self.transform_varnames(varnames)):
instr.arg = varname
with self._new_context(code):
post_transform = self.patterndispatcher(code)
return Code(
post_transform,
code.argnames,
cellvars=self.transform_cellvars(code.cellvars),
freevars=self.transform_freevars(code.freevars),
name=name if name is not None else code.name,
filename=filename if filename is not None else code.filename,
firstlineno=code.firstlineno,
lnotab=_new_lnotab(post_transform, code.lnotab),
flags=code.flags,
) | [
"def",
"transform",
"(",
"self",
",",
"code",
",",
"*",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"# reverse lookups from for constants and names.",
"reversed_consts",
"=",
"{",
"}",
"reversed_names",
"=",
"{",
"}",
"reversed_varnames",
... | Transform a codetransformer.Code object applying the transforms.
Parameters
----------
code : Code
The code object to transform.
name : str, optional
The new name for this code object.
filename : str, optional
The new filename for this code object.
Returns
-------
new_code : Code
The transformed code object. | [
"Transform",
"a",
"codetransformer",
".",
"Code",
"object",
"applying",
"the",
"transforms",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L150-L204 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | pformat_ast | def pformat_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT):
"""
Pretty-format an AST tree element
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces.
"""
def _fmt(node, prefix, level):
def with_indent(*strs):
return ''.join(((indent * level,) + strs))
with_prefix = partial(with_indent, prefix)
if isinstance(node, Name):
# Special Case:
# Render Name nodes on a single line.
yield with_prefix(
type(node).__name__,
'(id=',
repr(node.id),
', ctx=',
type(node.ctx).__name__,
'()),',
)
elif isinstance(node, Num):
# Special Case:
# Render Num nodes on a single line without names.
yield with_prefix(
type(node).__name__,
'(%r),' % node.n,
)
elif isinstance(node, AST):
fields_attrs = list(
chain(
iter_fields(node),
iter_attributes(node) if include_attributes else (),
)
)
if not fields_attrs:
# Special Case:
# Render the whole expression on one line if there are no
# attributes.
yield with_prefix(type(node).__name__, '(),')
return
yield with_prefix(type(node).__name__, '(')
for name, value in fields_attrs:
yield from _fmt(value, name + '=', level + 1)
# Put a trailing comma if we're not at the top level.
yield with_indent(')', ',' if level > 0 else '')
elif isinstance(node, list):
if not node:
# Special Case:
# Render empty lists on one line.
yield with_prefix('[],')
return
yield with_prefix('[')
yield from chain.from_iterable(
map(partial(_fmt, prefix='', level=level + 1), node)
)
yield with_indent('],')
else:
yield with_prefix(repr(node), ',')
return '\n'.join(_fmt(node, prefix='', level=0)) | python | def pformat_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT):
"""
Pretty-format an AST tree element
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces.
"""
def _fmt(node, prefix, level):
def with_indent(*strs):
return ''.join(((indent * level,) + strs))
with_prefix = partial(with_indent, prefix)
if isinstance(node, Name):
# Special Case:
# Render Name nodes on a single line.
yield with_prefix(
type(node).__name__,
'(id=',
repr(node.id),
', ctx=',
type(node.ctx).__name__,
'()),',
)
elif isinstance(node, Num):
# Special Case:
# Render Num nodes on a single line without names.
yield with_prefix(
type(node).__name__,
'(%r),' % node.n,
)
elif isinstance(node, AST):
fields_attrs = list(
chain(
iter_fields(node),
iter_attributes(node) if include_attributes else (),
)
)
if not fields_attrs:
# Special Case:
# Render the whole expression on one line if there are no
# attributes.
yield with_prefix(type(node).__name__, '(),')
return
yield with_prefix(type(node).__name__, '(')
for name, value in fields_attrs:
yield from _fmt(value, name + '=', level + 1)
# Put a trailing comma if we're not at the top level.
yield with_indent(')', ',' if level > 0 else '')
elif isinstance(node, list):
if not node:
# Special Case:
# Render empty lists on one line.
yield with_prefix('[],')
return
yield with_prefix('[')
yield from chain.from_iterable(
map(partial(_fmt, prefix='', level=level + 1), node)
)
yield with_indent('],')
else:
yield with_prefix(repr(node), ',')
return '\n'.join(_fmt(node, prefix='', level=0)) | [
"def",
"pformat_ast",
"(",
"node",
",",
"include_attributes",
"=",
"INCLUDE_ATTRIBUTES_DEFAULT",
",",
"indent",
"=",
"INDENT_DEFAULT",
")",
":",
"def",
"_fmt",
"(",
"node",
",",
"prefix",
",",
"level",
")",
":",
"def",
"with_indent",
"(",
"*",
"strs",
")",
... | Pretty-format an AST tree element
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces. | [
"Pretty",
"-",
"format",
"an",
"AST",
"tree",
"element"
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L31-L108 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | pprint_ast | def pprint_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT,
file=None):
"""
Pretty-print an AST tree.
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
print(
pformat_ast(
node,
include_attributes=include_attributes,
indent=indent
),
file=file,
) | python | def pprint_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT,
file=None):
"""
Pretty-print an AST tree.
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
print(
pformat_ast(
node,
include_attributes=include_attributes,
indent=indent
),
file=file,
) | [
"def",
"pprint_ast",
"(",
"node",
",",
"include_attributes",
"=",
"INCLUDE_ATTRIBUTES_DEFAULT",
",",
"indent",
"=",
"INDENT_DEFAULT",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stdout",
"print",
"(",
"pfo... | Pretty-print an AST tree.
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include node attributes. Default False.
indent : str, optional.
Indentation string for nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout. | [
"Pretty",
"-",
"print",
"an",
"AST",
"tree",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L117-L146 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | walk_code | def walk_code(co, _prefix=''):
"""
Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object).
"""
name = _prefix + co.co_name
yield name, co
yield from chain.from_iterable(
walk_code(c, _prefix=_extend_name(name, co))
for c in co.co_consts
if isinstance(c, CodeType)
) | python | def walk_code(co, _prefix=''):
"""
Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object).
"""
name = _prefix + co.co_name
yield name, co
yield from chain.from_iterable(
walk_code(c, _prefix=_extend_name(name, co))
for c in co.co_consts
if isinstance(c, CodeType)
) | [
"def",
"walk_code",
"(",
"co",
",",
"_prefix",
"=",
"''",
")",
":",
"name",
"=",
"_prefix",
"+",
"co",
".",
"co_name",
"yield",
"name",
",",
"co",
"yield",
"from",
"chain",
".",
"from_iterable",
"(",
"walk_code",
"(",
"c",
",",
"_prefix",
"=",
"_exte... | Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object). | [
"Traverse",
"a",
"code",
"object",
"finding",
"all",
"consts",
"which",
"are",
"also",
"code",
"objects",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L149-L161 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | a | def a(text, mode='exec', indent=' ', file=None):
"""
Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse`. Default is 'exec'.
indent : str, optional
String to use for indenting nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
pprint_ast(parse(text, mode=mode), indent=indent, file=file) | python | def a(text, mode='exec', indent=' ', file=None):
"""
Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse`. Default is 'exec'.
indent : str, optional
String to use for indenting nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
pprint_ast(parse(text, mode=mode), indent=indent, file=file) | [
"def",
"a",
"(",
"text",
",",
"mode",
"=",
"'exec'",
",",
"indent",
"=",
"' '",
",",
"file",
"=",
"None",
")",
":",
"pprint_ast",
"(",
"parse",
"(",
"text",
",",
"mode",
"=",
"mode",
")",
",",
"indent",
"=",
"indent",
",",
"file",
"=",
"file",
... | Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse`. Default is 'exec'.
indent : str, optional
String to use for indenting nested expressions. Default is two spaces.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout. | [
"Interactive",
"convenience",
"for",
"displaying",
"the",
"AST",
"of",
"a",
"code",
"string",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L172-L190 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | d | def d(obj, mode='exec', file=None):
"""
Interactive convenience for displaying the disassembly of a function,
module, or code string.
Compiles `text` and recursively traverses the result looking for `code`
objects to render with `dis.dis`.
Parameters
----------
obj : str, CodeType, or object with __code__ attribute
Object to disassemble.
If `obj` is an instance of CodeType, we use it unchanged.
If `obj` is a string, we compile it with `mode` and then disassemble.
Otherwise, we look for a `__code__` attribute on `obj`.
mode : {'exec', 'eval'}, optional
Mode for `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
for name, co in walk_code(extract_code(obj, compile_mode=mode)):
print(name, file=file)
print('-' * len(name), file=file)
dis.dis(co, file=file)
print('', file=file) | python | def d(obj, mode='exec', file=None):
"""
Interactive convenience for displaying the disassembly of a function,
module, or code string.
Compiles `text` and recursively traverses the result looking for `code`
objects to render with `dis.dis`.
Parameters
----------
obj : str, CodeType, or object with __code__ attribute
Object to disassemble.
If `obj` is an instance of CodeType, we use it unchanged.
If `obj` is a string, we compile it with `mode` and then disassemble.
Otherwise, we look for a `__code__` attribute on `obj`.
mode : {'exec', 'eval'}, optional
Mode for `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
for name, co in walk_code(extract_code(obj, compile_mode=mode)):
print(name, file=file)
print('-' * len(name), file=file)
dis.dis(co, file=file)
print('', file=file) | [
"def",
"d",
"(",
"obj",
",",
"mode",
"=",
"'exec'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stdout",
"for",
"name",
",",
"co",
"in",
"walk_code",
"(",
"extract_code",
"(",
"obj",
",",
"compil... | Interactive convenience for displaying the disassembly of a function,
module, or code string.
Compiles `text` and recursively traverses the result looking for `code`
objects to render with `dis.dis`.
Parameters
----------
obj : str, CodeType, or object with __code__ attribute
Object to disassemble.
If `obj` is an instance of CodeType, we use it unchanged.
If `obj` is a string, we compile it with `mode` and then disassemble.
Otherwise, we look for a `__code__` attribute on `obj`.
mode : {'exec', 'eval'}, optional
Mode for `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout. | [
"Interactive",
"convenience",
"for",
"displaying",
"the",
"disassembly",
"of",
"a",
"function",
"module",
"or",
"code",
"string",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L193-L221 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | extract_code | def extract_code(obj, compile_mode):
"""
Generic function for converting objects into instances of `CodeType`.
"""
try:
code = obj.__code__
if isinstance(code, CodeType):
return code
raise ValueError(
"{obj} has a `__code__` attribute, "
"but it's an instance of {notcode!r}, not CodeType.".format(
obj=obj,
notcode=type(code).__name__,
)
)
except AttributeError:
raise ValueError("Don't know how to extract code from %s." % obj) | python | def extract_code(obj, compile_mode):
"""
Generic function for converting objects into instances of `CodeType`.
"""
try:
code = obj.__code__
if isinstance(code, CodeType):
return code
raise ValueError(
"{obj} has a `__code__` attribute, "
"but it's an instance of {notcode!r}, not CodeType.".format(
obj=obj,
notcode=type(code).__name__,
)
)
except AttributeError:
raise ValueError("Don't know how to extract code from %s." % obj) | [
"def",
"extract_code",
"(",
"obj",
",",
"compile_mode",
")",
":",
"try",
":",
"code",
"=",
"obj",
".",
"__code__",
"if",
"isinstance",
"(",
"code",
",",
"CodeType",
")",
":",
"return",
"code",
"raise",
"ValueError",
"(",
"\"{obj} has a `__code__` attribute, \"... | Generic function for converting objects into instances of `CodeType`. | [
"Generic",
"function",
"for",
"converting",
"objects",
"into",
"instances",
"of",
"CodeType",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L225-L241 |
llllllllll/codetransformer | codetransformer/utils/pretty.py | display | def display(text, mode='exec', file=None):
"""
Show `text`, rendered as AST and as Bytecode.
Parameters
----------
text : str
Text of Python code to render.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse` and `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
ast_section = StringIO()
a(text, mode=mode, file=ast_section)
code_section = StringIO()
d(text, mode=mode, file=code_section)
rendered = _DISPLAY_TEMPLATE.format(
text=text,
ast=ast_section.getvalue(),
code=code_section.getvalue(),
)
print(rendered, file=file) | python | def display(text, mode='exec', file=None):
"""
Show `text`, rendered as AST and as Bytecode.
Parameters
----------
text : str
Text of Python code to render.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse` and `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout.
"""
if file is None:
file = sys.stdout
ast_section = StringIO()
a(text, mode=mode, file=ast_section)
code_section = StringIO()
d(text, mode=mode, file=code_section)
rendered = _DISPLAY_TEMPLATE.format(
text=text,
ast=ast_section.getvalue(),
code=code_section.getvalue(),
)
print(rendered, file=file) | [
"def",
"display",
"(",
"text",
",",
"mode",
"=",
"'exec'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stdout",
"ast_section",
"=",
"StringIO",
"(",
")",
"a",
"(",
"text",
",",
"mode",
"=",
"mode... | Show `text`, rendered as AST and as Bytecode.
Parameters
----------
text : str
Text of Python code to render.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse` and `compile`. Default is 'exec'.
file : None or file-like object, optional
File to use to print output. If the default of `None` is passed, we
use sys.stdout. | [
"Show",
"text",
"rendered",
"as",
"AST",
"and",
"as",
"Bytecode",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L275-L304 |
llllllllll/codetransformer | codetransformer/transformers/pattern_matched_exceptions.py | match | def match(match_expr, exc_type, exc_value, exc_traceback):
"""
Called to determine whether or not an except block should be matched.
True -> enter except block
False -> don't enter except block
"""
# Emulate standard behavior when match_expr is an exception subclass.
if isinstance(match_expr, type) and issubclass(match_expr, BaseException):
return issubclass(exc_type, match_expr)
# Match on type and args when match_expr is an exception instance.
return (
issubclass(exc_type, type(match_expr))
and
match_expr.args == exc_value.args
) | python | def match(match_expr, exc_type, exc_value, exc_traceback):
"""
Called to determine whether or not an except block should be matched.
True -> enter except block
False -> don't enter except block
"""
# Emulate standard behavior when match_expr is an exception subclass.
if isinstance(match_expr, type) and issubclass(match_expr, BaseException):
return issubclass(exc_type, match_expr)
# Match on type and args when match_expr is an exception instance.
return (
issubclass(exc_type, type(match_expr))
and
match_expr.args == exc_value.args
) | [
"def",
"match",
"(",
"match_expr",
",",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"# Emulate standard behavior when match_expr is an exception subclass.",
"if",
"isinstance",
"(",
"match_expr",
",",
"type",
")",
"and",
"issubclass",
"(",
"match_expr"... | Called to determine whether or not an except block should be matched.
True -> enter except block
False -> don't enter except block | [
"Called",
"to",
"determine",
"whether",
"or",
"not",
"an",
"except",
"block",
"should",
"be",
"matched",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/pattern_matched_exceptions.py#L15-L31 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | decompile | def decompile(f):
"""
Decompile a function.
Parameters
----------
f : function
The function to decompile.
Returns
-------
ast : ast.FunctionDef
A FunctionDef node that compiles to f.
"""
co = f.__code__
args, kwonly, varargs, varkwargs = paramnames(co)
annotations = f.__annotations__ or {}
defaults = list(f.__defaults__ or ())
kw_defaults = f.__kwdefaults__ or {}
if f.__name__ == '<lambda>':
node = ast.Lambda
body = pycode_to_body(co, DecompilationContext(in_lambda=True))[0]
extra_kwargs = {}
else:
node = ast.FunctionDef
body = pycode_to_body(co, DecompilationContext(in_function_block=True))
extra_kwargs = {
'decorator_list': [],
'returns': annotations.get('return')
}
return node(
name=f.__name__,
args=make_function_arguments(
args=args,
kwonly=kwonly,
varargs=varargs,
varkwargs=varkwargs,
defaults=defaults,
kw_defaults=kw_defaults,
annotations=annotations,
),
body=body,
**extra_kwargs
) | python | def decompile(f):
"""
Decompile a function.
Parameters
----------
f : function
The function to decompile.
Returns
-------
ast : ast.FunctionDef
A FunctionDef node that compiles to f.
"""
co = f.__code__
args, kwonly, varargs, varkwargs = paramnames(co)
annotations = f.__annotations__ or {}
defaults = list(f.__defaults__ or ())
kw_defaults = f.__kwdefaults__ or {}
if f.__name__ == '<lambda>':
node = ast.Lambda
body = pycode_to_body(co, DecompilationContext(in_lambda=True))[0]
extra_kwargs = {}
else:
node = ast.FunctionDef
body = pycode_to_body(co, DecompilationContext(in_function_block=True))
extra_kwargs = {
'decorator_list': [],
'returns': annotations.get('return')
}
return node(
name=f.__name__,
args=make_function_arguments(
args=args,
kwonly=kwonly,
varargs=varargs,
varkwargs=varkwargs,
defaults=defaults,
kw_defaults=kw_defaults,
annotations=annotations,
),
body=body,
**extra_kwargs
) | [
"def",
"decompile",
"(",
"f",
")",
":",
"co",
"=",
"f",
".",
"__code__",
"args",
",",
"kwonly",
",",
"varargs",
",",
"varkwargs",
"=",
"paramnames",
"(",
"co",
")",
"annotations",
"=",
"f",
".",
"__annotations__",
"or",
"{",
"}",
"defaults",
"=",
"li... | Decompile a function.
Parameters
----------
f : function
The function to decompile.
Returns
-------
ast : ast.FunctionDef
A FunctionDef node that compiles to f. | [
"Decompile",
"a",
"function",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L52-L97 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | pycode_to_body | def pycode_to_body(co, context):
"""
Convert a Python code object to a list of AST body elements.
"""
code = Code.from_pycode(co)
# On each instruction, temporarily store all the jumps to the **next**
# instruction. This is used in _make_expr to determine when an expression
# is part of a short-circuiting expression.
for a, b in sliding_window(2, code.instrs):
a._next_target_of = b._target_of
b._next_target_of = set()
try:
body = instrs_to_body(deque(code.instrs), context)
if context.in_function_block:
return make_global_and_nonlocal_decls(code.instrs) + body
return body
finally:
# Clean up jump target data.
for i in code.instrs:
del i._next_target_of | python | def pycode_to_body(co, context):
"""
Convert a Python code object to a list of AST body elements.
"""
code = Code.from_pycode(co)
# On each instruction, temporarily store all the jumps to the **next**
# instruction. This is used in _make_expr to determine when an expression
# is part of a short-circuiting expression.
for a, b in sliding_window(2, code.instrs):
a._next_target_of = b._target_of
b._next_target_of = set()
try:
body = instrs_to_body(deque(code.instrs), context)
if context.in_function_block:
return make_global_and_nonlocal_decls(code.instrs) + body
return body
finally:
# Clean up jump target data.
for i in code.instrs:
del i._next_target_of | [
"def",
"pycode_to_body",
"(",
"co",
",",
"context",
")",
":",
"code",
"=",
"Code",
".",
"from_pycode",
"(",
"co",
")",
"# On each instruction, temporarily store all the jumps to the **next**",
"# instruction. This is used in _make_expr to determine when an expression",
"# is par... | Convert a Python code object to a list of AST body elements. | [
"Convert",
"a",
"Python",
"code",
"object",
"to",
"a",
"list",
"of",
"AST",
"body",
"elements",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L100-L121 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | instrs_to_body | def instrs_to_body(instrs, context):
"""
Convert a list of Instruction objects to a list of AST body nodes.
"""
stack = []
body = []
process_instrs(instrs, stack, body, context)
if stack:
raise DecompilationError(
"Non-empty stack at the end of instrs_to_body(): %s." % stack
)
return body | python | def instrs_to_body(instrs, context):
"""
Convert a list of Instruction objects to a list of AST body nodes.
"""
stack = []
body = []
process_instrs(instrs, stack, body, context)
if stack:
raise DecompilationError(
"Non-empty stack at the end of instrs_to_body(): %s." % stack
)
return body | [
"def",
"instrs_to_body",
"(",
"instrs",
",",
"context",
")",
":",
"stack",
"=",
"[",
"]",
"body",
"=",
"[",
"]",
"process_instrs",
"(",
"instrs",
",",
"stack",
",",
"body",
",",
"context",
")",
"if",
"stack",
":",
"raise",
"DecompilationError",
"(",
"\... | Convert a list of Instruction objects to a list of AST body nodes. | [
"Convert",
"a",
"list",
"of",
"Instruction",
"objects",
"to",
"a",
"list",
"of",
"AST",
"body",
"nodes",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L124-L136 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | process_instrs | def process_instrs(queue, stack, body, context):
"""
Process instructions from the instruction queue.
"""
next_instr = queue.popleft
while queue:
newcontext = _process_instr(next_instr(), queue, stack, body, context)
if newcontext is not None:
context = newcontext | python | def process_instrs(queue, stack, body, context):
"""
Process instructions from the instruction queue.
"""
next_instr = queue.popleft
while queue:
newcontext = _process_instr(next_instr(), queue, stack, body, context)
if newcontext is not None:
context = newcontext | [
"def",
"process_instrs",
"(",
"queue",
",",
"stack",
",",
"body",
",",
"context",
")",
":",
"next_instr",
"=",
"queue",
".",
"popleft",
"while",
"queue",
":",
"newcontext",
"=",
"_process_instr",
"(",
"next_instr",
"(",
")",
",",
"queue",
",",
"stack",
"... | Process instructions from the instruction queue. | [
"Process",
"instructions",
"from",
"the",
"instruction",
"queue",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L139-L147 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_if_statement | def make_if_statement(instr, queue, stack, context):
"""
Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
"""
test_expr = make_expr(stack)
if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)
first_block = popwhile(op.is_not(instr.arg), queue, side='left')
if isinstance(first_block[-1], instrs.RETURN_VALUE):
body = instrs_to_body(first_block, context)
return ast.If(test=test_expr, body=body, orelse=[])
jump_to_end = expect(
first_block.pop(), instrs.JUMP_FORWARD, "at end of if-block"
)
body = instrs_to_body(first_block, context)
# First instruction after the whole if-block.
end = jump_to_end.arg
if instr.arg is jump_to_end.arg:
orelse = []
else:
orelse = instrs_to_body(
popwhile(op.is_not(end), queue, side='left'),
context,
)
return ast.If(test=test_expr, body=body, orelse=orelse) | python | def make_if_statement(instr, queue, stack, context):
"""
Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
"""
test_expr = make_expr(stack)
if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)
first_block = popwhile(op.is_not(instr.arg), queue, side='left')
if isinstance(first_block[-1], instrs.RETURN_VALUE):
body = instrs_to_body(first_block, context)
return ast.If(test=test_expr, body=body, orelse=[])
jump_to_end = expect(
first_block.pop(), instrs.JUMP_FORWARD, "at end of if-block"
)
body = instrs_to_body(first_block, context)
# First instruction after the whole if-block.
end = jump_to_end.arg
if instr.arg is jump_to_end.arg:
orelse = []
else:
orelse = instrs_to_body(
popwhile(op.is_not(end), queue, side='left'),
context,
)
return ast.If(test=test_expr, body=body, orelse=orelse) | [
"def",
"make_if_statement",
"(",
"instr",
",",
"queue",
",",
"stack",
",",
"context",
")",
":",
"test_expr",
"=",
"make_expr",
"(",
"stack",
")",
"if",
"isinstance",
"(",
"instr",
",",
"instrs",
".",
"POP_JUMP_IF_TRUE",
")",
":",
"test_expr",
"=",
"ast",
... | Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. | [
"Make",
"an",
"ast",
".",
"If",
"block",
"from",
"a",
"POP_JUMP_IF_TRUE",
"or",
"POP_JUMP_IF_FALSE",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L182-L211 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _process_instr_import_name | def _process_instr_import_name(instr, queue, stack, body, context):
"""
Process an IMPORT_NAME instruction.
Side Effects
------------
Pops two instuctions from `stack`
Consumes instructions from `queue` to the end of the import statement.
Appends an ast.Import or ast.ImportFrom node to `body`.
"""
# If this is "import module", fromlist is None.
# If this this is "from module import a, b fromlist will be ('a', 'b').
fromlist = stack.pop().arg
# level argument to __import__. Should be 0, 1, or 2.
level = stack.pop().arg
module = instr.arg
if fromlist is None: # Regular import.
attr_loads = _pop_import_LOAD_ATTRs(module, queue)
store = queue.popleft()
# There are two cases where we should emit an alias:
# import a as <anything but a>
# import a.b.c as <anything (including a)>
if attr_loads or module.split('.')[0] != store.arg:
asname = store.arg
else:
asname = None
body.append(
ast.Import(
names=[
ast.alias(
name=module,
asname=(asname),
),
],
level=level,
),
)
return
elif fromlist == ('*',): # From module import *.
expect(queue.popleft(), instrs.IMPORT_STAR, "after IMPORT_NAME")
body.append(
ast.ImportFrom(
module=module,
names=[ast.alias(name='*', asname=None)],
level=level,
),
)
return
# Consume a pair of IMPORT_FROM, STORE_NAME instructions for each entry in
# fromlist.
names = list(map(make_importfrom_alias(queue, body, context), fromlist))
body.append(ast.ImportFrom(module=module, names=names, level=level))
# Remove the final POP_TOP of the imported module.
expect(queue.popleft(), instrs.POP_TOP, "after 'from import'") | python | def _process_instr_import_name(instr, queue, stack, body, context):
"""
Process an IMPORT_NAME instruction.
Side Effects
------------
Pops two instuctions from `stack`
Consumes instructions from `queue` to the end of the import statement.
Appends an ast.Import or ast.ImportFrom node to `body`.
"""
# If this is "import module", fromlist is None.
# If this this is "from module import a, b fromlist will be ('a', 'b').
fromlist = stack.pop().arg
# level argument to __import__. Should be 0, 1, or 2.
level = stack.pop().arg
module = instr.arg
if fromlist is None: # Regular import.
attr_loads = _pop_import_LOAD_ATTRs(module, queue)
store = queue.popleft()
# There are two cases where we should emit an alias:
# import a as <anything but a>
# import a.b.c as <anything (including a)>
if attr_loads or module.split('.')[0] != store.arg:
asname = store.arg
else:
asname = None
body.append(
ast.Import(
names=[
ast.alias(
name=module,
asname=(asname),
),
],
level=level,
),
)
return
elif fromlist == ('*',): # From module import *.
expect(queue.popleft(), instrs.IMPORT_STAR, "after IMPORT_NAME")
body.append(
ast.ImportFrom(
module=module,
names=[ast.alias(name='*', asname=None)],
level=level,
),
)
return
# Consume a pair of IMPORT_FROM, STORE_NAME instructions for each entry in
# fromlist.
names = list(map(make_importfrom_alias(queue, body, context), fromlist))
body.append(ast.ImportFrom(module=module, names=names, level=level))
# Remove the final POP_TOP of the imported module.
expect(queue.popleft(), instrs.POP_TOP, "after 'from import'") | [
"def",
"_process_instr_import_name",
"(",
"instr",
",",
"queue",
",",
"stack",
",",
"body",
",",
"context",
")",
":",
"# If this is \"import module\", fromlist is None.",
"# If this this is \"from module import a, b fromlist will be ('a', 'b').",
"fromlist",
"=",
"stack",
".",
... | Process an IMPORT_NAME instruction.
Side Effects
------------
Pops two instuctions from `stack`
Consumes instructions from `queue` to the end of the import statement.
Appends an ast.Import or ast.ImportFrom node to `body`. | [
"Process",
"an",
"IMPORT_NAME",
"instruction",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L226-L283 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _pop_import_LOAD_ATTRs | def _pop_import_LOAD_ATTRs(module_name, queue):
"""
Pop LOAD_ATTR instructions for an import of the form::
import a.b.c as d
which should generate bytecode like this::
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (a.b.c.d)
9 LOAD_ATTR 1 (b)
12 LOAD_ATTR 2 (c)
15 LOAD_ATTR 3 (d)
18 STORE_NAME 3 (d)
"""
popped = popwhile(is_a(instrs.LOAD_ATTR), queue, side='left')
if popped:
expected = module_name.split('.', maxsplit=1)[1]
actual = '.'.join(map(op.attrgetter('arg'), popped))
if expected != actual:
raise DecompilationError(
"Decompiling import of module %s, but LOAD_ATTRS imply %s" % (
expected, actual,
)
)
return popped | python | def _pop_import_LOAD_ATTRs(module_name, queue):
"""
Pop LOAD_ATTR instructions for an import of the form::
import a.b.c as d
which should generate bytecode like this::
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (a.b.c.d)
9 LOAD_ATTR 1 (b)
12 LOAD_ATTR 2 (c)
15 LOAD_ATTR 3 (d)
18 STORE_NAME 3 (d)
"""
popped = popwhile(is_a(instrs.LOAD_ATTR), queue, side='left')
if popped:
expected = module_name.split('.', maxsplit=1)[1]
actual = '.'.join(map(op.attrgetter('arg'), popped))
if expected != actual:
raise DecompilationError(
"Decompiling import of module %s, but LOAD_ATTRS imply %s" % (
expected, actual,
)
)
return popped | [
"def",
"_pop_import_LOAD_ATTRs",
"(",
"module_name",
",",
"queue",
")",
":",
"popped",
"=",
"popwhile",
"(",
"is_a",
"(",
"instrs",
".",
"LOAD_ATTR",
")",
",",
"queue",
",",
"side",
"=",
"'left'",
")",
"if",
"popped",
":",
"expected",
"=",
"module_name",
... | Pop LOAD_ATTR instructions for an import of the form::
import a.b.c as d
which should generate bytecode like this::
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (a.b.c.d)
9 LOAD_ATTR 1 (b)
12 LOAD_ATTR 2 (c)
15 LOAD_ATTR 3 (d)
18 STORE_NAME 3 (d) | [
"Pop",
"LOAD_ATTR",
"instructions",
"for",
"an",
"import",
"of",
"the",
"form",
"::"
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L286-L312 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_importfrom_alias | def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of the IMPORT_FROM node to be popped.
Returns
-------
alias : ast.alias
Side Effects
------------
Consumes IMPORT_FROM and STORE_NAME instructions from queue.
"""
import_from, store = queue.popleft(), queue.popleft()
expect(import_from, instrs.IMPORT_FROM, "after IMPORT_NAME")
if not import_from.arg == name:
raise DecompilationError(
"IMPORT_FROM name mismatch. Expected %r, but got %s." % (
name, import_from,
)
)
return ast.alias(
name=name,
asname=store.arg if store.arg != name else None,
) | python | def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of the IMPORT_FROM node to be popped.
Returns
-------
alias : ast.alias
Side Effects
------------
Consumes IMPORT_FROM and STORE_NAME instructions from queue.
"""
import_from, store = queue.popleft(), queue.popleft()
expect(import_from, instrs.IMPORT_FROM, "after IMPORT_NAME")
if not import_from.arg == name:
raise DecompilationError(
"IMPORT_FROM name mismatch. Expected %r, but got %s." % (
name, import_from,
)
)
return ast.alias(
name=name,
asname=store.arg if store.arg != name else None,
) | [
"def",
"make_importfrom_alias",
"(",
"queue",
",",
"body",
",",
"context",
",",
"name",
")",
":",
"import_from",
",",
"store",
"=",
"queue",
".",
"popleft",
"(",
")",
",",
"queue",
".",
"popleft",
"(",
")",
"expect",
"(",
"import_from",
",",
"instrs",
... | Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of the IMPORT_FROM node to be popped.
Returns
-------
alias : ast.alias
Side Effects
------------
Consumes IMPORT_FROM and STORE_NAME instructions from queue. | [
"Make",
"an",
"ast",
".",
"alias",
"node",
"for",
"the",
"names",
"list",
"of",
"an",
"ast",
".",
"ImportFrom",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L316-L350 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _make_function | def _make_function(instr, queue, stack, body, context):
"""
Set a make_function_context, then push onto the stack.
"""
assert stack, "Empty stack before MAKE_FUNCTION."
prev = stack[-1]
expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION")
stack.append(instr)
if is_lambda_name(prev.arg):
return
return context.update(
make_function_context=MakeFunctionContext(
closure=isinstance(instr, instrs.MAKE_CLOSURE),
)
) | python | def _make_function(instr, queue, stack, body, context):
"""
Set a make_function_context, then push onto the stack.
"""
assert stack, "Empty stack before MAKE_FUNCTION."
prev = stack[-1]
expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION")
stack.append(instr)
if is_lambda_name(prev.arg):
return
return context.update(
make_function_context=MakeFunctionContext(
closure=isinstance(instr, instrs.MAKE_CLOSURE),
)
) | [
"def",
"_make_function",
"(",
"instr",
",",
"queue",
",",
"stack",
",",
"body",
",",
"context",
")",
":",
"assert",
"stack",
",",
"\"Empty stack before MAKE_FUNCTION.\"",
"prev",
"=",
"stack",
"[",
"-",
"1",
"]",
"expect",
"(",
"prev",
",",
"instrs",
".",
... | Set a make_function_context, then push onto the stack. | [
"Set",
"a",
"make_function_context",
"then",
"push",
"onto",
"the",
"stack",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L385-L402 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_assignment | def make_assignment(instr, queue, stack):
"""
Make an ast.Assign node.
"""
value = make_expr(stack)
# Make assignment targets.
# If there are multiple assignments (e.g. 'a = b = c'),
# each LHS expression except the last is preceded by a DUP_TOP instruction.
# Thus, we make targets until we don't see a DUP_TOP, and then make one
# more.
targets = []
while isinstance(instr, instrs.DUP_TOP):
targets.append(make_assign_target(queue.popleft(), queue, stack))
instr = queue.popleft()
targets.append(make_assign_target(instr, queue, stack))
return ast.Assign(targets=targets, value=value) | python | def make_assignment(instr, queue, stack):
"""
Make an ast.Assign node.
"""
value = make_expr(stack)
# Make assignment targets.
# If there are multiple assignments (e.g. 'a = b = c'),
# each LHS expression except the last is preceded by a DUP_TOP instruction.
# Thus, we make targets until we don't see a DUP_TOP, and then make one
# more.
targets = []
while isinstance(instr, instrs.DUP_TOP):
targets.append(make_assign_target(queue.popleft(), queue, stack))
instr = queue.popleft()
targets.append(make_assign_target(instr, queue, stack))
return ast.Assign(targets=targets, value=value) | [
"def",
"make_assignment",
"(",
"instr",
",",
"queue",
",",
"stack",
")",
":",
"value",
"=",
"make_expr",
"(",
"stack",
")",
"# Make assignment targets.",
"# If there are multiple assignments (e.g. 'a = b = c'),",
"# each LHS expression except the last is preceded by a DUP_TOP ins... | Make an ast.Assign node. | [
"Make",
"an",
"ast",
".",
"Assign",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L429-L447 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | pop_with_body_instrs | def pop_with_body_instrs(setup_with_instr, queue):
"""
Pop instructions from `queue` that form the body of a with block.
"""
body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')
# Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
# These don't correspond to anything in the AST, so remove them here.
load_none = body_instrs.pop()
expect(load_none, instrs.LOAD_CONST, "at end of with-block")
pop_block = body_instrs.pop()
expect(pop_block, instrs.POP_BLOCK, "at end of with-block")
if load_none.arg is not None:
raise DecompilationError(
"Expected LOAD_CONST(None), but got "
"%r instead" % (load_none)
)
# Target of the setup_with should be a WITH_CLEANUP instruction followed by
# an END_FINALLY. Neither of these correspond to anything in the AST.
with_cleanup = queue.popleft()
expect(with_cleanup, instrs.WITH_CLEANUP, "at end of with-block")
end_finally = queue.popleft()
expect(end_finally, instrs.END_FINALLY, "at end of with-block")
return body_instrs | python | def pop_with_body_instrs(setup_with_instr, queue):
"""
Pop instructions from `queue` that form the body of a with block.
"""
body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')
# Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
# These don't correspond to anything in the AST, so remove them here.
load_none = body_instrs.pop()
expect(load_none, instrs.LOAD_CONST, "at end of with-block")
pop_block = body_instrs.pop()
expect(pop_block, instrs.POP_BLOCK, "at end of with-block")
if load_none.arg is not None:
raise DecompilationError(
"Expected LOAD_CONST(None), but got "
"%r instead" % (load_none)
)
# Target of the setup_with should be a WITH_CLEANUP instruction followed by
# an END_FINALLY. Neither of these correspond to anything in the AST.
with_cleanup = queue.popleft()
expect(with_cleanup, instrs.WITH_CLEANUP, "at end of with-block")
end_finally = queue.popleft()
expect(end_finally, instrs.END_FINALLY, "at end of with-block")
return body_instrs | [
"def",
"pop_with_body_instrs",
"(",
"setup_with_instr",
",",
"queue",
")",
":",
"body_instrs",
"=",
"popwhile",
"(",
"op",
".",
"is_not",
"(",
"setup_with_instr",
".",
"arg",
")",
",",
"queue",
",",
"side",
"=",
"'left'",
")",
"# Last two instructions should alw... | Pop instructions from `queue` that form the body of a with block. | [
"Pop",
"instructions",
"from",
"queue",
"that",
"form",
"the",
"body",
"of",
"a",
"with",
"block",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L574-L599 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_withitem | def make_withitem(queue, stack):
"""
Make an ast.withitem node.
"""
context_expr = make_expr(stack)
# This is a POP_TOP for just "with <expr>:".
# This is a STORE_NAME(name) for "with <expr> as <name>:".
as_instr = queue.popleft()
if isinstance(as_instr, (instrs.STORE_FAST,
instrs.STORE_NAME,
instrs.STORE_DEREF,
instrs.STORE_GLOBAL)):
return ast.withitem(
context_expr=context_expr,
optional_vars=make_assign_target(as_instr, queue, stack),
)
elif isinstance(as_instr, instrs.POP_TOP):
return ast.withitem(context_expr=context_expr, optional_vars=None)
else:
raise DecompilationError(
"Don't know how to make withitem from %s" % as_instr,
) | python | def make_withitem(queue, stack):
"""
Make an ast.withitem node.
"""
context_expr = make_expr(stack)
# This is a POP_TOP for just "with <expr>:".
# This is a STORE_NAME(name) for "with <expr> as <name>:".
as_instr = queue.popleft()
if isinstance(as_instr, (instrs.STORE_FAST,
instrs.STORE_NAME,
instrs.STORE_DEREF,
instrs.STORE_GLOBAL)):
return ast.withitem(
context_expr=context_expr,
optional_vars=make_assign_target(as_instr, queue, stack),
)
elif isinstance(as_instr, instrs.POP_TOP):
return ast.withitem(context_expr=context_expr, optional_vars=None)
else:
raise DecompilationError(
"Don't know how to make withitem from %s" % as_instr,
) | [
"def",
"make_withitem",
"(",
"queue",
",",
"stack",
")",
":",
"context_expr",
"=",
"make_expr",
"(",
"stack",
")",
"# This is a POP_TOP for just \"with <expr>:\".",
"# This is a STORE_NAME(name) for \"with <expr> as <name>:\".",
"as_instr",
"=",
"queue",
".",
"popleft",
"("... | Make an ast.withitem node. | [
"Make",
"an",
"ast",
".",
"withitem",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L602-L623 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_for_loop | def make_for_loop(loop_body_instrs, else_body_instrs, context):
"""
Make an ast.For node.
"""
# Instructions from start until GET_ITER are the builders for the iterator
# expression.
iterator_expr = make_expr(
popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left')
)
# Next is the GET_ITER instruction, which we don't need.
loop_body_instrs.popleft()
# Next is FOR_ITER, which is the jump target for Continue nodes.
top_of_loop = loop_body_instrs.popleft()
# This can be a STORE_* or an UNPACK_SEQUENCE followed by some number of
# stores.
target = make_assign_target(
loop_body_instrs.popleft(),
loop_body_instrs,
stack=[],
)
body, orelse_body = make_loop_body_and_orelse(
top_of_loop, loop_body_instrs, else_body_instrs, context
)
return ast.For(
target=target,
iter=iterator_expr,
body=body,
orelse=orelse_body,
) | python | def make_for_loop(loop_body_instrs, else_body_instrs, context):
"""
Make an ast.For node.
"""
# Instructions from start until GET_ITER are the builders for the iterator
# expression.
iterator_expr = make_expr(
popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left')
)
# Next is the GET_ITER instruction, which we don't need.
loop_body_instrs.popleft()
# Next is FOR_ITER, which is the jump target for Continue nodes.
top_of_loop = loop_body_instrs.popleft()
# This can be a STORE_* or an UNPACK_SEQUENCE followed by some number of
# stores.
target = make_assign_target(
loop_body_instrs.popleft(),
loop_body_instrs,
stack=[],
)
body, orelse_body = make_loop_body_and_orelse(
top_of_loop, loop_body_instrs, else_body_instrs, context
)
return ast.For(
target=target,
iter=iterator_expr,
body=body,
orelse=orelse_body,
) | [
"def",
"make_for_loop",
"(",
"loop_body_instrs",
",",
"else_body_instrs",
",",
"context",
")",
":",
"# Instructions from start until GET_ITER are the builders for the iterator",
"# expression.",
"iterator_expr",
"=",
"make_expr",
"(",
"popwhile",
"(",
"not_a",
"(",
"instrs",
... | Make an ast.For node. | [
"Make",
"an",
"ast",
".",
"For",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L636-L669 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_loop_body_and_orelse | def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context):
"""
Make body and orelse lists for a for/while loop whose first instruction is
`top_of_loop`.
Parameters
----------
top_of_loop : Instruction
The first body of the loop. For a for-loop, this should always be a
FOR_ITER. For a while loop, it's the first instruction of the stack
builders for the loop test expression
body_instrs : deque
Queue of Instructions that form the body of the loop. The last two
elements of body_instrs should be a JUMP_ABSOLUTE to `top_of_loop` and
a POP_BLOCK.
else_instrs : deque
Queue of Instructions that form the else block of the loop. Should be
an empty deque if there is no else block.
context : DecompilationContext
Returns
-------
body : list[ast.AST]
List of ast nodes forming the loop body.
orelse_body : list[ast.AST]
List of ast nodes forming the else-block body.
"""
# Remove the JUMP_ABSOLUTE and POP_BLOCK instructions at the bottom of the
# loop.
body_instrs.pop()
body_instrs.pop()
body = instrs_to_body(body_instrs, context.update(top_of_loop=top_of_loop))
if else_instrs:
else_body = instrs_to_body(else_instrs, context)
else:
else_body = []
return body, else_body | python | def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context):
"""
Make body and orelse lists for a for/while loop whose first instruction is
`top_of_loop`.
Parameters
----------
top_of_loop : Instruction
The first body of the loop. For a for-loop, this should always be a
FOR_ITER. For a while loop, it's the first instruction of the stack
builders for the loop test expression
body_instrs : deque
Queue of Instructions that form the body of the loop. The last two
elements of body_instrs should be a JUMP_ABSOLUTE to `top_of_loop` and
a POP_BLOCK.
else_instrs : deque
Queue of Instructions that form the else block of the loop. Should be
an empty deque if there is no else block.
context : DecompilationContext
Returns
-------
body : list[ast.AST]
List of ast nodes forming the loop body.
orelse_body : list[ast.AST]
List of ast nodes forming the else-block body.
"""
# Remove the JUMP_ABSOLUTE and POP_BLOCK instructions at the bottom of the
# loop.
body_instrs.pop()
body_instrs.pop()
body = instrs_to_body(body_instrs, context.update(top_of_loop=top_of_loop))
if else_instrs:
else_body = instrs_to_body(else_instrs, context)
else:
else_body = []
return body, else_body | [
"def",
"make_loop_body_and_orelse",
"(",
"top_of_loop",
",",
"body_instrs",
",",
"else_instrs",
",",
"context",
")",
":",
"# Remove the JUMP_ABSOLUTE and POP_BLOCK instructions at the bottom of the",
"# loop.",
"body_instrs",
".",
"pop",
"(",
")",
"body_instrs",
".",
"pop",... | Make body and orelse lists for a for/while loop whose first instruction is
`top_of_loop`.
Parameters
----------
top_of_loop : Instruction
The first body of the loop. For a for-loop, this should always be a
FOR_ITER. For a while loop, it's the first instruction of the stack
builders for the loop test expression
body_instrs : deque
Queue of Instructions that form the body of the loop. The last two
elements of body_instrs should be a JUMP_ABSOLUTE to `top_of_loop` and
a POP_BLOCK.
else_instrs : deque
Queue of Instructions that form the else block of the loop. Should be
an empty deque if there is no else block.
context : DecompilationContext
Returns
-------
body : list[ast.AST]
List of ast nodes forming the loop body.
orelse_body : list[ast.AST]
List of ast nodes forming the else-block body. | [
"Make",
"body",
"and",
"orelse",
"lists",
"for",
"a",
"for",
"/",
"while",
"loop",
"whose",
"first",
"instruction",
"is",
"top_of_loop",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L672-L710 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_while_loop | def make_while_loop(test_and_body_instrs, else_body_instrs, context):
"""
Make an ast.While node.
Parameters
----------
test_and_body_instrs : deque
Queue of instructions forming the loop test expression and body.
else_body_instrs : deque
Queue of instructions forming the else block of the loop.
context : DecompilationContext
"""
top_of_loop = test_and_body_instrs[0]
# The popped elements are the stack_builders for the loop test expression.
# The top of the loop_body_instrs is either a POP_JUMP_IF_TRUE or a
# POP_JUMP_IF_FALSE.
test, body_instrs = make_while_loop_test_expr(test_and_body_instrs)
body, orelse_body = make_loop_body_and_orelse(
top_of_loop, body_instrs, else_body_instrs, context,
)
# while-else blocks are not yet supported or handled.
return ast.While(test=test, body=body, orelse=orelse_body) | python | def make_while_loop(test_and_body_instrs, else_body_instrs, context):
"""
Make an ast.While node.
Parameters
----------
test_and_body_instrs : deque
Queue of instructions forming the loop test expression and body.
else_body_instrs : deque
Queue of instructions forming the else block of the loop.
context : DecompilationContext
"""
top_of_loop = test_and_body_instrs[0]
# The popped elements are the stack_builders for the loop test expression.
# The top of the loop_body_instrs is either a POP_JUMP_IF_TRUE or a
# POP_JUMP_IF_FALSE.
test, body_instrs = make_while_loop_test_expr(test_and_body_instrs)
body, orelse_body = make_loop_body_and_orelse(
top_of_loop, body_instrs, else_body_instrs, context,
)
# while-else blocks are not yet supported or handled.
return ast.While(test=test, body=body, orelse=orelse_body) | [
"def",
"make_while_loop",
"(",
"test_and_body_instrs",
",",
"else_body_instrs",
",",
"context",
")",
":",
"top_of_loop",
"=",
"test_and_body_instrs",
"[",
"0",
"]",
"# The popped elements are the stack_builders for the loop test expression.",
"# The top of the loop_body_instrs is e... | Make an ast.While node.
Parameters
----------
test_and_body_instrs : deque
Queue of instructions forming the loop test expression and body.
else_body_instrs : deque
Queue of instructions forming the else block of the loop.
context : DecompilationContext | [
"Make",
"an",
"ast",
".",
"While",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L713-L736 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | pop_loop_instrs | def pop_loop_instrs(setup_loop_instr, queue):
"""
Determine whether setup_loop_instr is setting up a for-loop or a
while-loop. Then pop the loop instructions from queue.
The easiest way to tell the difference is to look at the target of the
JUMP_ABSOLUTE instruction at the end of the loop. If it jumps to a
FOR_ITER, then this is a for-loop. Otherwise it's a while-loop.
The jump we want to inspect is the first JUMP_ABSOLUTE instruction prior to
the jump target of `setup_loop_instr`.
Parameters
----------
setup_loop_instr : instructions.SETUP_LOOP
First instruction of the loop being parsed.
queue : collections.deque
Queue of unprocessed instructions.
Returns
-------
loop_type : str, {'for', 'while'}
The kind of loop being constructed.
loop_instrs : deque
The instructions forming body of the loop.
else_instrs : deque
The instructions forming the else-block of the loop.
Side Effects
------------
Pops all returned instructions from `queue`.
"""
# Grab everything from left side of the queue until the jump target of
# SETUP_LOOP.
body = popwhile(op.is_not(setup_loop_instr.arg), queue, side='left')
# Anything after the last POP_BLOCK instruction is the else-block.
else_body = popwhile(not_a(instrs.POP_BLOCK), body, side='right')
jump_to_top, pop_block = body[-2], body[-1]
if not isinstance(jump_to_top, instrs.JUMP_ABSOLUTE):
raise DecompilationError(
"Penultimate instruction of loop body is "
"%s, not JUMP_ABSOLUTE." % jump_to_top,
)
if not isinstance(pop_block, instrs.POP_BLOCK):
raise DecompilationError(
"Last instruction of loop body is "
"%s, not pop_block." % pop_block,
)
loop_expr = jump_to_top.arg
if isinstance(loop_expr, instrs.FOR_ITER):
return 'for', body, else_body
return 'while', body, else_body | python | def pop_loop_instrs(setup_loop_instr, queue):
"""
Determine whether setup_loop_instr is setting up a for-loop or a
while-loop. Then pop the loop instructions from queue.
The easiest way to tell the difference is to look at the target of the
JUMP_ABSOLUTE instruction at the end of the loop. If it jumps to a
FOR_ITER, then this is a for-loop. Otherwise it's a while-loop.
The jump we want to inspect is the first JUMP_ABSOLUTE instruction prior to
the jump target of `setup_loop_instr`.
Parameters
----------
setup_loop_instr : instructions.SETUP_LOOP
First instruction of the loop being parsed.
queue : collections.deque
Queue of unprocessed instructions.
Returns
-------
loop_type : str, {'for', 'while'}
The kind of loop being constructed.
loop_instrs : deque
The instructions forming body of the loop.
else_instrs : deque
The instructions forming the else-block of the loop.
Side Effects
------------
Pops all returned instructions from `queue`.
"""
# Grab everything from left side of the queue until the jump target of
# SETUP_LOOP.
body = popwhile(op.is_not(setup_loop_instr.arg), queue, side='left')
# Anything after the last POP_BLOCK instruction is the else-block.
else_body = popwhile(not_a(instrs.POP_BLOCK), body, side='right')
jump_to_top, pop_block = body[-2], body[-1]
if not isinstance(jump_to_top, instrs.JUMP_ABSOLUTE):
raise DecompilationError(
"Penultimate instruction of loop body is "
"%s, not JUMP_ABSOLUTE." % jump_to_top,
)
if not isinstance(pop_block, instrs.POP_BLOCK):
raise DecompilationError(
"Last instruction of loop body is "
"%s, not pop_block." % pop_block,
)
loop_expr = jump_to_top.arg
if isinstance(loop_expr, instrs.FOR_ITER):
return 'for', body, else_body
return 'while', body, else_body | [
"def",
"pop_loop_instrs",
"(",
"setup_loop_instr",
",",
"queue",
")",
":",
"# Grab everything from left side of the queue until the jump target of",
"# SETUP_LOOP.",
"body",
"=",
"popwhile",
"(",
"op",
".",
"is_not",
"(",
"setup_loop_instr",
".",
"arg",
")",
",",
"queue... | Determine whether setup_loop_instr is setting up a for-loop or a
while-loop. Then pop the loop instructions from queue.
The easiest way to tell the difference is to look at the target of the
JUMP_ABSOLUTE instruction at the end of the loop. If it jumps to a
FOR_ITER, then this is a for-loop. Otherwise it's a while-loop.
The jump we want to inspect is the first JUMP_ABSOLUTE instruction prior to
the jump target of `setup_loop_instr`.
Parameters
----------
setup_loop_instr : instructions.SETUP_LOOP
First instruction of the loop being parsed.
queue : collections.deque
Queue of unprocessed instructions.
Returns
-------
loop_type : str, {'for', 'while'}
The kind of loop being constructed.
loop_instrs : deque
The instructions forming body of the loop.
else_instrs : deque
The instructions forming the else-block of the loop.
Side Effects
------------
Pops all returned instructions from `queue`. | [
"Determine",
"whether",
"setup_loop_instr",
"is",
"setting",
"up",
"a",
"for",
"-",
"loop",
"or",
"a",
"while",
"-",
"loop",
".",
"Then",
"pop",
"the",
"loop",
"instructions",
"from",
"queue",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L784-L839 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _make_expr | def _make_expr(toplevel, stack_builders):
"""
Override the single-dispatched make_expr with wrapper logic for handling
short-circuiting expressions.
"""
base_expr = _make_expr_internal(toplevel, stack_builders)
if not toplevel._next_target_of:
return base_expr
subexprs = deque([base_expr])
ops = deque([])
while stack_builders and stack_builders[-1] in toplevel._next_target_of:
jump = stack_builders.pop()
if not isinstance(jump, _BOOLOP_JUMP_TYPES):
raise DecompilationError(
"Don't know how to decompile %s inside expression." % jump,
)
subexprs.appendleft(make_expr(stack_builders))
ops.appendleft(_BOOLOP_JUMP_TO_AST_OP[type(jump)]())
if len(subexprs) <= 1:
raise DecompilationError(
"Expected at least one JUMP instruction before expression."
)
return normalize_boolop(make_boolop(subexprs, ops)) | python | def _make_expr(toplevel, stack_builders):
"""
Override the single-dispatched make_expr with wrapper logic for handling
short-circuiting expressions.
"""
base_expr = _make_expr_internal(toplevel, stack_builders)
if not toplevel._next_target_of:
return base_expr
subexprs = deque([base_expr])
ops = deque([])
while stack_builders and stack_builders[-1] in toplevel._next_target_of:
jump = stack_builders.pop()
if not isinstance(jump, _BOOLOP_JUMP_TYPES):
raise DecompilationError(
"Don't know how to decompile %s inside expression." % jump,
)
subexprs.appendleft(make_expr(stack_builders))
ops.appendleft(_BOOLOP_JUMP_TO_AST_OP[type(jump)]())
if len(subexprs) <= 1:
raise DecompilationError(
"Expected at least one JUMP instruction before expression."
)
return normalize_boolop(make_boolop(subexprs, ops)) | [
"def",
"_make_expr",
"(",
"toplevel",
",",
"stack_builders",
")",
":",
"base_expr",
"=",
"_make_expr_internal",
"(",
"toplevel",
",",
"stack_builders",
")",
"if",
"not",
"toplevel",
".",
"_next_target_of",
":",
"return",
"base_expr",
"subexprs",
"=",
"deque",
"(... | Override the single-dispatched make_expr with wrapper logic for handling
short-circuiting expressions. | [
"Override",
"the",
"single",
"-",
"dispatched",
"make_expr",
"with",
"wrapper",
"logic",
"for",
"handling",
"short",
"-",
"circuiting",
"expressions",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L856-L881 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_boolop | def make_boolop(exprs, op_types):
"""
Parameters
----------
exprs : deque
op_types : deque[{ast.And, ast.Or}]
"""
if len(op_types) > 1:
return ast.BoolOp(
op=op_types.popleft(),
values=[exprs.popleft(), make_boolop(exprs, op_types)],
)
assert len(exprs) == 2
return ast.BoolOp(op=op_types.popleft(), values=list(exprs)) | python | def make_boolop(exprs, op_types):
"""
Parameters
----------
exprs : deque
op_types : deque[{ast.And, ast.Or}]
"""
if len(op_types) > 1:
return ast.BoolOp(
op=op_types.popleft(),
values=[exprs.popleft(), make_boolop(exprs, op_types)],
)
assert len(exprs) == 2
return ast.BoolOp(op=op_types.popleft(), values=list(exprs)) | [
"def",
"make_boolop",
"(",
"exprs",
",",
"op_types",
")",
":",
"if",
"len",
"(",
"op_types",
")",
">",
"1",
":",
"return",
"ast",
".",
"BoolOp",
"(",
"op",
"=",
"op_types",
".",
"popleft",
"(",
")",
",",
"values",
"=",
"[",
"exprs",
".",
"popleft",... | Parameters
----------
exprs : deque
op_types : deque[{ast.And, ast.Or}] | [
"Parameters",
"----------",
"exprs",
":",
"deque",
"op_types",
":",
"deque",
"[",
"{",
"ast",
".",
"And",
"ast",
".",
"Or",
"}",
"]"
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L884-L898 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | normalize_boolop | def normalize_boolop(expr):
"""
Normalize a boolop by folding together nested And/Or exprs.
"""
optype = expr.op
newvalues = []
for subexpr in expr.values:
if not isinstance(subexpr, ast.BoolOp):
newvalues.append(subexpr)
elif type(subexpr.op) != type(optype):
newvalues.append(normalize_boolop(subexpr))
else:
# Normalize subexpression, then inline its values into the
# top-level subexpr.
newvalues.extend(normalize_boolop(subexpr).values)
return ast.BoolOp(op=optype, values=newvalues) | python | def normalize_boolop(expr):
"""
Normalize a boolop by folding together nested And/Or exprs.
"""
optype = expr.op
newvalues = []
for subexpr in expr.values:
if not isinstance(subexpr, ast.BoolOp):
newvalues.append(subexpr)
elif type(subexpr.op) != type(optype):
newvalues.append(normalize_boolop(subexpr))
else:
# Normalize subexpression, then inline its values into the
# top-level subexpr.
newvalues.extend(normalize_boolop(subexpr).values)
return ast.BoolOp(op=optype, values=newvalues) | [
"def",
"normalize_boolop",
"(",
"expr",
")",
":",
"optype",
"=",
"expr",
".",
"op",
"newvalues",
"=",
"[",
"]",
"for",
"subexpr",
"in",
"expr",
".",
"values",
":",
"if",
"not",
"isinstance",
"(",
"subexpr",
",",
"ast",
".",
"BoolOp",
")",
":",
"newva... | Normalize a boolop by folding together nested And/Or exprs. | [
"Normalize",
"a",
"boolop",
"by",
"folding",
"together",
"nested",
"And",
"/",
"Or",
"exprs",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L901-L916 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_call_keywords | def make_call_keywords(stack_builders, count):
"""
Make the keywords entry for an ast.Call node.
"""
out = []
for _ in range(count):
value = make_expr(stack_builders)
load_kwname = stack_builders.pop()
if not isinstance(load_kwname, instrs.LOAD_CONST):
raise DecompilationError(
"Expected a LOAD_CONST, but got %r" % load_kwname
)
if not isinstance(load_kwname.arg, str):
raise DecompilationError(
"Expected LOAD_CONST of a str, but got %r." % load_kwname,
)
out.append(ast.keyword(arg=load_kwname.arg, value=value))
out.reverse()
return out | python | def make_call_keywords(stack_builders, count):
"""
Make the keywords entry for an ast.Call node.
"""
out = []
for _ in range(count):
value = make_expr(stack_builders)
load_kwname = stack_builders.pop()
if not isinstance(load_kwname, instrs.LOAD_CONST):
raise DecompilationError(
"Expected a LOAD_CONST, but got %r" % load_kwname
)
if not isinstance(load_kwname.arg, str):
raise DecompilationError(
"Expected LOAD_CONST of a str, but got %r." % load_kwname,
)
out.append(ast.keyword(arg=load_kwname.arg, value=value))
out.reverse()
return out | [
"def",
"make_call_keywords",
"(",
"stack_builders",
",",
"count",
")",
":",
"out",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"value",
"=",
"make_expr",
"(",
"stack_builders",
")",
"load_kwname",
"=",
"stack_builders",
".",
"pop",
... | Make the keywords entry for an ast.Call node. | [
"Make",
"the",
"keywords",
"entry",
"for",
"an",
"ast",
".",
"Call",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1040-L1058 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_call_positionals | def make_call_positionals(stack_builders, count):
"""
Make the args entry for an ast.Call node.
"""
out = [make_expr(stack_builders) for _ in range(count)]
out.reverse()
return out | python | def make_call_positionals(stack_builders, count):
"""
Make the args entry for an ast.Call node.
"""
out = [make_expr(stack_builders) for _ in range(count)]
out.reverse()
return out | [
"def",
"make_call_positionals",
"(",
"stack_builders",
",",
"count",
")",
":",
"out",
"=",
"[",
"make_expr",
"(",
"stack_builders",
")",
"for",
"_",
"in",
"range",
"(",
"count",
")",
"]",
"out",
".",
"reverse",
"(",
")",
"return",
"out"
] | Make the args entry for an ast.Call node. | [
"Make",
"the",
"args",
"entry",
"for",
"an",
"ast",
".",
"Call",
"node",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1061-L1067 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_exprs | def make_exprs(stack_builders, count):
"""
Make elements of set/list/tuple literal.
"""
exprs = [make_expr(stack_builders) for _ in range(count)]
# Elements are on the stack from right to left, but we want them from right
# to left.
exprs.reverse()
return exprs | python | def make_exprs(stack_builders, count):
"""
Make elements of set/list/tuple literal.
"""
exprs = [make_expr(stack_builders) for _ in range(count)]
# Elements are on the stack from right to left, but we want them from right
# to left.
exprs.reverse()
return exprs | [
"def",
"make_exprs",
"(",
"stack_builders",
",",
"count",
")",
":",
"exprs",
"=",
"[",
"make_expr",
"(",
"stack_builders",
")",
"for",
"_",
"in",
"range",
"(",
"count",
")",
"]",
"# Elements are on the stack from right to left, but we want them from right",
"# to left... | Make elements of set/list/tuple literal. | [
"Make",
"elements",
"of",
"set",
"/",
"list",
"/",
"tuple",
"literal",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1094-L1102 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _make_expr_empty_dict | def _make_expr_empty_dict(toplevel, stack_builders):
"""
This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead.
"""
if toplevel.arg:
raise DecompilationError(
"make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
)
if stack_builders:
raise DecompilationError(
"Unexpected stack_builders for BUILD_MAP(0): %s" % stack_builders
)
return ast.Dict(keys=[], values=[]) | python | def _make_expr_empty_dict(toplevel, stack_builders):
"""
This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead.
"""
if toplevel.arg:
raise DecompilationError(
"make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
)
if stack_builders:
raise DecompilationError(
"Unexpected stack_builders for BUILD_MAP(0): %s" % stack_builders
)
return ast.Dict(keys=[], values=[]) | [
"def",
"_make_expr_empty_dict",
"(",
"toplevel",
",",
"stack_builders",
")",
":",
"if",
"toplevel",
".",
"arg",
":",
"raise",
"DecompilationError",
"(",
"\"make_expr() called with nonzero BUILD_MAP arg %d\"",
"%",
"toplevel",
".",
"arg",
")",
"if",
"stack_builders",
"... | This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead. | [
"This",
"should",
"only",
"be",
"hit",
"for",
"empty",
"dicts",
".",
"Anything",
"else",
"should",
"hit",
"the",
"STORE_MAP",
"handler",
"instead",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1106-L1120 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | find_build_map | def find_build_map(stack_builders):
"""
Find the BUILD_MAP instruction for which the last element of
``stack_builders`` is a store.
"""
assert isinstance(stack_builders[-1], instrs.STORE_MAP)
to_consume = 0
for instr in reversed(stack_builders):
if isinstance(instr, instrs.STORE_MAP):
# NOTE: This branch should always be hit on the first iteration.
to_consume += 1
elif isinstance(instr, instrs.BUILD_MAP):
to_consume -= instr.arg
if to_consume <= 0:
return instr
else:
raise DecompilationError(
"Couldn't find BUILD_MAP for last element of %s." % stack_builders
) | python | def find_build_map(stack_builders):
"""
Find the BUILD_MAP instruction for which the last element of
``stack_builders`` is a store.
"""
assert isinstance(stack_builders[-1], instrs.STORE_MAP)
to_consume = 0
for instr in reversed(stack_builders):
if isinstance(instr, instrs.STORE_MAP):
# NOTE: This branch should always be hit on the first iteration.
to_consume += 1
elif isinstance(instr, instrs.BUILD_MAP):
to_consume -= instr.arg
if to_consume <= 0:
return instr
else:
raise DecompilationError(
"Couldn't find BUILD_MAP for last element of %s." % stack_builders
) | [
"def",
"find_build_map",
"(",
"stack_builders",
")",
":",
"assert",
"isinstance",
"(",
"stack_builders",
"[",
"-",
"1",
"]",
",",
"instrs",
".",
"STORE_MAP",
")",
"to_consume",
"=",
"0",
"for",
"instr",
"in",
"reversed",
"(",
"stack_builders",
")",
":",
"i... | Find the BUILD_MAP instruction for which the last element of
``stack_builders`` is a store. | [
"Find",
"the",
"BUILD_MAP",
"instruction",
"for",
"which",
"the",
"last",
"element",
"of",
"stack_builders",
"is",
"a",
"store",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1143-L1162 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _make_dict_elems | def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):
raise DecompilationError(
"Expected a STORE_MAP but got %s" % popped
)
keys.append(make_expr(builders))
values.append(make_expr(builders))
# Keys and values are emitted in reverse order of how they appear in the
# AST.
keys.reverse()
values.reverse()
return keys, values | python | def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):
raise DecompilationError(
"Expected a STORE_MAP but got %s" % popped
)
keys.append(make_expr(builders))
values.append(make_expr(builders))
# Keys and values are emitted in reverse order of how they appear in the
# AST.
keys.reverse()
values.reverse()
return keys, values | [
"def",
"_make_dict_elems",
"(",
"build_instr",
",",
"builders",
")",
":",
"keys",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"build_instr",
".",
"arg",
")",
":",
"popped",
"=",
"builders",
".",
"pop",
"(",
")",
"if",
"n... | Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``. | [
"Return",
"a",
"list",
"of",
"keys",
"and",
"a",
"list",
"of",
"values",
"for",
"the",
"dictionary",
"literal",
"generated",
"by",
"build_instr",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1165-L1186 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | normalize_tuple_slice | def normalize_tuple_slice(node):
"""
Normalize an ast.Tuple node representing the internals of a slice.
Returns the node wrapped in an ast.Index.
Returns an ExtSlice node built from the tuple elements if there are any
slices.
"""
if not any(isinstance(elt, ast.Slice) for elt in node.elts):
return ast.Index(value=node)
return ast.ExtSlice(
[
# Wrap non-Slice nodes in Index nodes.
elt if isinstance(elt, ast.Slice) else ast.Index(value=elt)
for elt in node.elts
]
) | python | def normalize_tuple_slice(node):
"""
Normalize an ast.Tuple node representing the internals of a slice.
Returns the node wrapped in an ast.Index.
Returns an ExtSlice node built from the tuple elements if there are any
slices.
"""
if not any(isinstance(elt, ast.Slice) for elt in node.elts):
return ast.Index(value=node)
return ast.ExtSlice(
[
# Wrap non-Slice nodes in Index nodes.
elt if isinstance(elt, ast.Slice) else ast.Index(value=elt)
for elt in node.elts
]
) | [
"def",
"normalize_tuple_slice",
"(",
"node",
")",
":",
"if",
"not",
"any",
"(",
"isinstance",
"(",
"elt",
",",
"ast",
".",
"Slice",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
")",
":",
"return",
"ast",
".",
"Index",
"(",
"value",
"=",
"node",
")... | Normalize an ast.Tuple node representing the internals of a slice.
Returns the node wrapped in an ast.Index.
Returns an ExtSlice node built from the tuple elements if there are any
slices. | [
"Normalize",
"an",
"ast",
".",
"Tuple",
"node",
"representing",
"the",
"internals",
"of",
"a",
"slice",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1244-L1261 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _binop_handler | def _binop_handler(nodetype):
"""
Factory function for binary operator handlers.
"""
def _handler(toplevel, stack_builders):
right = make_expr(stack_builders)
left = make_expr(stack_builders)
return ast.BinOp(left=left, op=nodetype(), right=right)
return _handler | python | def _binop_handler(nodetype):
"""
Factory function for binary operator handlers.
"""
def _handler(toplevel, stack_builders):
right = make_expr(stack_builders)
left = make_expr(stack_builders)
return ast.BinOp(left=left, op=nodetype(), right=right)
return _handler | [
"def",
"_binop_handler",
"(",
"nodetype",
")",
":",
"def",
"_handler",
"(",
"toplevel",
",",
"stack_builders",
")",
":",
"right",
"=",
"make_expr",
"(",
"stack_builders",
")",
"left",
"=",
"make_expr",
"(",
"stack_builders",
")",
"return",
"ast",
".",
"BinOp... | Factory function for binary operator handlers. | [
"Factory",
"function",
"for",
"binary",
"operator",
"handlers",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1344-L1352 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_function | def make_function(function_builders, *, closure):
"""
Construct a FunctionDef AST node from a sequence of the form:
LOAD_CLOSURE, N times (when handling MAKE_CLOSURE)
BUILD_TUPLE(N) (when handling MAKE_CLOSURE)
<decorator builders> (optional)
<default builders>, (optional)
<annotation builders> (optional)
LOAD_CONST(<tuple of annotated names>) (optional)
LOAD_CONST(code),
LOAD_CONST(name),
MAKE_FUNCTION | MAKE_CLOSURE
<decorator calls> (optional)
"""
decorator_calls = deque()
while isinstance(function_builders[-1], instrs.CALL_FUNCTION):
decorator_calls.appendleft(function_builders.pop())
*builders, load_code_instr, load_name_instr, make_function_instr = (
function_builders
)
_check_make_function_instrs(
load_code_instr, load_name_instr, make_function_instr,
)
co = load_code_instr.arg
name = load_name_instr.arg
args, kwonly, varargs, varkwargs = paramnames(co)
# Convert default and annotation builders to AST nodes.
defaults, kw_defaults, annotations = make_defaults_and_annotations(
make_function_instr,
builders,
)
# Convert decorator function builders. The stack is in reverse order.
decorators = [make_expr(builders) for _ in decorator_calls]
decorators.reverse()
if closure:
# There should be a tuple of closure cells still on the stack here.
# These don't appear in the AST, but we need to consume them to ensure
# correctness down the line.
closure_cells = make_closure_cells(builders) # noqa
# We should have consumed all our builders by this point.
if builders:
raise DecompilationError(
"Unexpected leftover builders for %s: %s." % (
make_function_instr, builders
)
)
return ast.FunctionDef(
body_code=co,
name=name.split('.')[-1],
args=make_function_arguments(
args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations,
),
body=pycode_to_body(co, DecompilationContext(in_function_block=True)),
decorator_list=decorators,
returns=annotations.get('return'),
) | python | def make_function(function_builders, *, closure):
"""
Construct a FunctionDef AST node from a sequence of the form:
LOAD_CLOSURE, N times (when handling MAKE_CLOSURE)
BUILD_TUPLE(N) (when handling MAKE_CLOSURE)
<decorator builders> (optional)
<default builders>, (optional)
<annotation builders> (optional)
LOAD_CONST(<tuple of annotated names>) (optional)
LOAD_CONST(code),
LOAD_CONST(name),
MAKE_FUNCTION | MAKE_CLOSURE
<decorator calls> (optional)
"""
decorator_calls = deque()
while isinstance(function_builders[-1], instrs.CALL_FUNCTION):
decorator_calls.appendleft(function_builders.pop())
*builders, load_code_instr, load_name_instr, make_function_instr = (
function_builders
)
_check_make_function_instrs(
load_code_instr, load_name_instr, make_function_instr,
)
co = load_code_instr.arg
name = load_name_instr.arg
args, kwonly, varargs, varkwargs = paramnames(co)
# Convert default and annotation builders to AST nodes.
defaults, kw_defaults, annotations = make_defaults_and_annotations(
make_function_instr,
builders,
)
# Convert decorator function builders. The stack is in reverse order.
decorators = [make_expr(builders) for _ in decorator_calls]
decorators.reverse()
if closure:
# There should be a tuple of closure cells still on the stack here.
# These don't appear in the AST, but we need to consume them to ensure
# correctness down the line.
closure_cells = make_closure_cells(builders) # noqa
# We should have consumed all our builders by this point.
if builders:
raise DecompilationError(
"Unexpected leftover builders for %s: %s." % (
make_function_instr, builders
)
)
return ast.FunctionDef(
body_code=co,
name=name.split('.')[-1],
args=make_function_arguments(
args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations,
),
body=pycode_to_body(co, DecompilationContext(in_function_block=True)),
decorator_list=decorators,
returns=annotations.get('return'),
) | [
"def",
"make_function",
"(",
"function_builders",
",",
"*",
",",
"closure",
")",
":",
"decorator_calls",
"=",
"deque",
"(",
")",
"while",
"isinstance",
"(",
"function_builders",
"[",
"-",
"1",
"]",
",",
"instrs",
".",
"CALL_FUNCTION",
")",
":",
"decorator_ca... | Construct a FunctionDef AST node from a sequence of the form:
LOAD_CLOSURE, N times (when handling MAKE_CLOSURE)
BUILD_TUPLE(N) (when handling MAKE_CLOSURE)
<decorator builders> (optional)
<default builders>, (optional)
<annotation builders> (optional)
LOAD_CONST(<tuple of annotated names>) (optional)
LOAD_CONST(code),
LOAD_CONST(name),
MAKE_FUNCTION | MAKE_CLOSURE
<decorator calls> (optional) | [
"Construct",
"a",
"FunctionDef",
"AST",
"node",
"from",
"a",
"sequence",
"of",
"the",
"form",
":"
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1360-L1430 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_function_arguments | def make_function_arguments(args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations):
"""
Make an ast.arguments from the args parsed out of a code object.
"""
return ast.arguments(
args=[ast.arg(arg=a, annotation=annotations.get(a)) for a in args],
kwonlyargs=[
ast.arg(arg=a, annotation=annotations.get(a)) for a in kwonly
],
defaults=defaults,
kw_defaults=list(map(kw_defaults.get, kwonly)),
vararg=None if varargs is None else ast.arg(
arg=varargs, annotation=annotations.get(varargs),
),
kwarg=None if varkwargs is None else ast.arg(
arg=varkwargs, annotation=annotations.get(varkwargs)
),
) | python | def make_function_arguments(args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations):
"""
Make an ast.arguments from the args parsed out of a code object.
"""
return ast.arguments(
args=[ast.arg(arg=a, annotation=annotations.get(a)) for a in args],
kwonlyargs=[
ast.arg(arg=a, annotation=annotations.get(a)) for a in kwonly
],
defaults=defaults,
kw_defaults=list(map(kw_defaults.get, kwonly)),
vararg=None if varargs is None else ast.arg(
arg=varargs, annotation=annotations.get(varargs),
),
kwarg=None if varkwargs is None else ast.arg(
arg=varkwargs, annotation=annotations.get(varkwargs)
),
) | [
"def",
"make_function_arguments",
"(",
"args",
",",
"kwonly",
",",
"varargs",
",",
"varkwargs",
",",
"defaults",
",",
"kw_defaults",
",",
"annotations",
")",
":",
"return",
"ast",
".",
"arguments",
"(",
"args",
"=",
"[",
"ast",
".",
"arg",
"(",
"arg",
"=... | Make an ast.arguments from the args parsed out of a code object. | [
"Make",
"an",
"ast",
".",
"arguments",
"from",
"the",
"args",
"parsed",
"out",
"of",
"a",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1433-L1456 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_global_and_nonlocal_decls | def make_global_and_nonlocal_decls(code_instrs):
"""
Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations.
"""
globals_ = sorted(set(
i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOBAL)
))
nonlocals = sorted(set(
i.arg for i in code_instrs
if isinstance(i, instrs.STORE_DEREF) and i.vartype == 'free'
))
out = []
if globals_:
out.append(ast.Global(names=globals_))
if nonlocals:
out.append(ast.Nonlocal(names=nonlocals))
return out | python | def make_global_and_nonlocal_decls(code_instrs):
"""
Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations.
"""
globals_ = sorted(set(
i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOBAL)
))
nonlocals = sorted(set(
i.arg for i in code_instrs
if isinstance(i, instrs.STORE_DEREF) and i.vartype == 'free'
))
out = []
if globals_:
out.append(ast.Global(names=globals_))
if nonlocals:
out.append(ast.Nonlocal(names=nonlocals))
return out | [
"def",
"make_global_and_nonlocal_decls",
"(",
"code_instrs",
")",
":",
"globals_",
"=",
"sorted",
"(",
"set",
"(",
"i",
".",
"arg",
"for",
"i",
"in",
"code_instrs",
"if",
"isinstance",
"(",
"i",
",",
"instrs",
".",
"STORE_GLOBAL",
")",
")",
")",
"nonlocals... | Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations. | [
"Find",
"all",
"STORE_GLOBAL",
"and",
"STORE_DEREF",
"instructions",
"in",
"instrs",
"and",
"convert",
"them",
"into",
"a",
"canonical",
"list",
"of",
"ast",
".",
"Global",
"and",
"ast",
".",
"Nonlocal",
"declarations",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1469-L1487 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | make_defaults_and_annotations | def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_arg(
make_function_instr.arg
)
if n_annotations:
# TOS should be a tuple of annotation names.
load_annotation_names = builders.pop()
annotations = dict(zip(
reversed(load_annotation_names.arg),
(make_expr(builders) for _ in range(n_annotations - 1))
))
else:
annotations = {}
kwonlys = {}
while n_kwonlydefaults:
default_expr = make_expr(builders)
key_instr = builders.pop()
if not isinstance(key_instr, instrs.LOAD_CONST):
raise DecompilationError(
"kwonlydefault key is not a LOAD_CONST: %s" % key_instr
)
if not isinstance(key_instr.arg, str):
raise DecompilationError(
"kwonlydefault key builder is not a "
"'LOAD_CONST of a string: %s" % key_instr
)
kwonlys[key_instr.arg] = default_expr
n_kwonlydefaults -= 1
defaults = make_exprs(builders, n_defaults)
return defaults, kwonlys, annotations | python | def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_arg(
make_function_instr.arg
)
if n_annotations:
# TOS should be a tuple of annotation names.
load_annotation_names = builders.pop()
annotations = dict(zip(
reversed(load_annotation_names.arg),
(make_expr(builders) for _ in range(n_annotations - 1))
))
else:
annotations = {}
kwonlys = {}
while n_kwonlydefaults:
default_expr = make_expr(builders)
key_instr = builders.pop()
if not isinstance(key_instr, instrs.LOAD_CONST):
raise DecompilationError(
"kwonlydefault key is not a LOAD_CONST: %s" % key_instr
)
if not isinstance(key_instr.arg, str):
raise DecompilationError(
"kwonlydefault key builder is not a "
"'LOAD_CONST of a string: %s" % key_instr
)
kwonlys[key_instr.arg] = default_expr
n_kwonlydefaults -= 1
defaults = make_exprs(builders, n_defaults)
return defaults, kwonlys, annotations | [
"def",
"make_defaults_and_annotations",
"(",
"make_function_instr",
",",
"builders",
")",
":",
"# Integer counts.",
"n_defaults",
",",
"n_kwonlydefaults",
",",
"n_annotations",
"=",
"unpack_make_function_arg",
"(",
"make_function_instr",
".",
"arg",
")",
"if",
"n_annotati... | Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`. | [
"Get",
"the",
"AST",
"expressions",
"corresponding",
"to",
"the",
"defaults",
"kwonly",
"defaults",
"and",
"annotations",
"for",
"a",
"function",
"created",
"by",
"make_function_instr",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1490-L1527 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _check_make_function_instrs | def _check_make_function_instrs(load_code_instr,
load_name_instr,
make_function_instr,
*,
expect_lambda=False):
"""
Validate the instructions passed to a make_function call.
"""
# Validate load_code_instr.
if not isinstance(load_code_instr, instrs.LOAD_CONST):
raise TypeError(
"make_function expected 'load_code_instr` to be a "
"LOAD_CONST, but got %s" % load_code_instr,
)
if not isinstance(load_code_instr.arg, types.CodeType):
raise TypeError(
"make_function expected load_code_instr "
"to load a code object, but got %s" % load_code_instr.arg,
)
# Validate load_name_instr
if not isinstance(load_name_instr, instrs.LOAD_CONST):
raise TypeError(
"make_function expected 'load_name_instr` to be a "
"LOAD_CONST, but got %s" % load_code_instr,
)
if not isinstance(load_name_instr.arg, str):
raise TypeError(
"make_function expected load_name_instr "
"to load a string, but got %r instead" % load_name_instr.arg
)
# This is an endswith rather than '==' because the arg is the
# fully-qualified name.
is_lambda = is_lambda_name(load_name_instr.arg)
if expect_lambda and not is_lambda:
raise ValueError(
"Expected to make a function named <lambda>, but "
"got %r instead." % load_name_instr.arg
)
if not expect_lambda and is_lambda:
raise ValueError("Unexpectedly received lambda function.")
# Validate make_function_instr
if not isinstance(make_function_instr, (instrs.MAKE_FUNCTION,
instrs.MAKE_CLOSURE)):
raise TypeError(
"make_function expected a MAKE_FUNCTION or MAKE_CLOSURE"
"instruction, but got %s instead." % make_function_instr
) | python | def _check_make_function_instrs(load_code_instr,
load_name_instr,
make_function_instr,
*,
expect_lambda=False):
"""
Validate the instructions passed to a make_function call.
"""
# Validate load_code_instr.
if not isinstance(load_code_instr, instrs.LOAD_CONST):
raise TypeError(
"make_function expected 'load_code_instr` to be a "
"LOAD_CONST, but got %s" % load_code_instr,
)
if not isinstance(load_code_instr.arg, types.CodeType):
raise TypeError(
"make_function expected load_code_instr "
"to load a code object, but got %s" % load_code_instr.arg,
)
# Validate load_name_instr
if not isinstance(load_name_instr, instrs.LOAD_CONST):
raise TypeError(
"make_function expected 'load_name_instr` to be a "
"LOAD_CONST, but got %s" % load_code_instr,
)
if not isinstance(load_name_instr.arg, str):
raise TypeError(
"make_function expected load_name_instr "
"to load a string, but got %r instead" % load_name_instr.arg
)
# This is an endswith rather than '==' because the arg is the
# fully-qualified name.
is_lambda = is_lambda_name(load_name_instr.arg)
if expect_lambda and not is_lambda:
raise ValueError(
"Expected to make a function named <lambda>, but "
"got %r instead." % load_name_instr.arg
)
if not expect_lambda and is_lambda:
raise ValueError("Unexpectedly received lambda function.")
# Validate make_function_instr
if not isinstance(make_function_instr, (instrs.MAKE_FUNCTION,
instrs.MAKE_CLOSURE)):
raise TypeError(
"make_function expected a MAKE_FUNCTION or MAKE_CLOSURE"
"instruction, but got %s instead." % make_function_instr
) | [
"def",
"_check_make_function_instrs",
"(",
"load_code_instr",
",",
"load_name_instr",
",",
"make_function_instr",
",",
"*",
",",
"expect_lambda",
"=",
"False",
")",
":",
"# Validate load_code_instr.",
"if",
"not",
"isinstance",
"(",
"load_code_instr",
",",
"instrs",
"... | Validate the instructions passed to a make_function call. | [
"Validate",
"the",
"instructions",
"passed",
"to",
"a",
"make_function",
"call",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1550-L1601 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | pop_arguments | def pop_arguments(instr, stack):
"""
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
"""
needed = instr.stack_effect
if needed >= 0:
raise DecompilationError(
"%s is does not have a negative stack effect" % instr
)
for popcount, to_pop in enumerate(reversed(stack), start=1):
needed += to_pop.stack_effect
if not needed:
break
else:
raise DecompilationError(
"Reached end of stack without finding inputs to %s" % instr,
)
popped = stack[-popcount:]
stack[:] = stack[:-popcount]
return popped | python | def pop_arguments(instr, stack):
"""
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
"""
needed = instr.stack_effect
if needed >= 0:
raise DecompilationError(
"%s is does not have a negative stack effect" % instr
)
for popcount, to_pop in enumerate(reversed(stack), start=1):
needed += to_pop.stack_effect
if not needed:
break
else:
raise DecompilationError(
"Reached end of stack without finding inputs to %s" % instr,
)
popped = stack[-popcount:]
stack[:] = stack[:-popcount]
return popped | [
"def",
"pop_arguments",
"(",
"instr",
",",
"stack",
")",
":",
"needed",
"=",
"instr",
".",
"stack_effect",
"if",
"needed",
">=",
"0",
":",
"raise",
"DecompilationError",
"(",
"\"%s is does not have a negative stack effect\"",
"%",
"instr",
")",
"for",
"popcount",
... | Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`. | [
"Pop",
"instructions",
"off",
"stack",
"until",
"we",
"pop",
"all",
"instructions",
"that",
"will",
"produce",
"values",
"popped",
"by",
"instr",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1604-L1627 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | _check_stack_for_module_return | def _check_stack_for_module_return(stack):
"""
Verify that the stack is in the expected state before the dummy
RETURN_VALUE instruction of a module or class.
"""
fail = (
len(stack) != 1
or not isinstance(stack[0], instrs.LOAD_CONST)
or stack[0].arg is not None
)
if fail:
raise DecompilationError(
"Reached end of non-function code "
"block with unexpected stack: %s." % stack
) | python | def _check_stack_for_module_return(stack):
"""
Verify that the stack is in the expected state before the dummy
RETURN_VALUE instruction of a module or class.
"""
fail = (
len(stack) != 1
or not isinstance(stack[0], instrs.LOAD_CONST)
or stack[0].arg is not None
)
if fail:
raise DecompilationError(
"Reached end of non-function code "
"block with unexpected stack: %s." % stack
) | [
"def",
"_check_stack_for_module_return",
"(",
"stack",
")",
":",
"fail",
"=",
"(",
"len",
"(",
"stack",
")",
"!=",
"1",
"or",
"not",
"isinstance",
"(",
"stack",
"[",
"0",
"]",
",",
"instrs",
".",
"LOAD_CONST",
")",
"or",
"stack",
"[",
"0",
"]",
".",
... | Verify that the stack is in the expected state before the dummy
RETURN_VALUE instruction of a module or class. | [
"Verify",
"that",
"the",
"stack",
"is",
"in",
"the",
"expected",
"state",
"before",
"the",
"dummy",
"RETURN_VALUE",
"instruction",
"of",
"a",
"module",
"or",
"class",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1630-L1645 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | expect | def expect(instr, expected, context):
"""
Check that an instruction is of the expected type.
"""
if not isinstance(instr, expected):
raise DecompilationError(
"Expected a {expected} instruction {context}. Got {instr}.".format(
instr=instr, expected=expected, context=context,
)
)
return instr | python | def expect(instr, expected, context):
"""
Check that an instruction is of the expected type.
"""
if not isinstance(instr, expected):
raise DecompilationError(
"Expected a {expected} instruction {context}. Got {instr}.".format(
instr=instr, expected=expected, context=context,
)
)
return instr | [
"def",
"expect",
"(",
"instr",
",",
"expected",
",",
"context",
")",
":",
"if",
"not",
"isinstance",
"(",
"instr",
",",
"expected",
")",
":",
"raise",
"DecompilationError",
"(",
"\"Expected a {expected} instruction {context}. Got {instr}.\"",
".",
"format",
"(",
"... | Check that an instruction is of the expected type. | [
"Check",
"that",
"an",
"instruction",
"is",
"of",
"the",
"expected",
"type",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1648-L1658 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | popwhile | def popwhile(cond, queue, *, side):
"""
Pop elements off a queue while `cond(nextelem)` is True.
Parameters
----------
cond : predicate
queue : deque
side : {'left', 'right'}
Returns
-------
popped : deque
Examples
--------
>>> from collections import deque
>>> d = deque([1, 2, 3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='left')
deque([1, 2])
>>> d
deque([3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='right')
deque([2, 1])
>>> d
deque([3])
"""
if side not in ('left', 'right'):
raise ValueError("`side` must be one of 'left' or 'right'")
out = deque()
if side == 'left':
popnext = queue.popleft
pushnext = out.append
nextidx = 0
else:
popnext = queue.pop
pushnext = out.appendleft
nextidx = -1
while queue:
if not cond(queue[nextidx]):
break
pushnext(popnext())
return out | python | def popwhile(cond, queue, *, side):
"""
Pop elements off a queue while `cond(nextelem)` is True.
Parameters
----------
cond : predicate
queue : deque
side : {'left', 'right'}
Returns
-------
popped : deque
Examples
--------
>>> from collections import deque
>>> d = deque([1, 2, 3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='left')
deque([1, 2])
>>> d
deque([3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='right')
deque([2, 1])
>>> d
deque([3])
"""
if side not in ('left', 'right'):
raise ValueError("`side` must be one of 'left' or 'right'")
out = deque()
if side == 'left':
popnext = queue.popleft
pushnext = out.append
nextidx = 0
else:
popnext = queue.pop
pushnext = out.appendleft
nextidx = -1
while queue:
if not cond(queue[nextidx]):
break
pushnext(popnext())
return out | [
"def",
"popwhile",
"(",
"cond",
",",
"queue",
",",
"*",
",",
"side",
")",
":",
"if",
"side",
"not",
"in",
"(",
"'left'",
",",
"'right'",
")",
":",
"raise",
"ValueError",
"(",
"\"`side` must be one of 'left' or 'right'\"",
")",
"out",
"=",
"deque",
"(",
"... | Pop elements off a queue while `cond(nextelem)` is True.
Parameters
----------
cond : predicate
queue : deque
side : {'left', 'right'}
Returns
-------
popped : deque
Examples
--------
>>> from collections import deque
>>> d = deque([1, 2, 3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='left')
deque([1, 2])
>>> d
deque([3, 2, 1])
>>> popwhile(lambda x: x < 3, d, side='right')
deque([2, 1])
>>> d
deque([3]) | [
"Pop",
"elements",
"off",
"a",
"queue",
"while",
"cond",
"(",
"nextelem",
")",
"is",
"True",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1668-L1713 |
llllllllll/codetransformer | codetransformer/transformers/literals.py | overloaded_constants | def overloaded_constants(type_, __doc__=None):
"""A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types.
"""
typename = type_.__name__
if typename.endswith('x'):
typename += 'es'
elif not typename.endswith('s'):
typename += 's'
if __doc__ is None:
__doc__ = _format_constant_docstring(type_)
return type(
"overloaded_" + typename,
(_ConstantTransformerBase,), {
'_type': type_,
'__doc__': __doc__,
},
) | python | def overloaded_constants(type_, __doc__=None):
"""A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types.
"""
typename = type_.__name__
if typename.endswith('x'):
typename += 'es'
elif not typename.endswith('s'):
typename += 's'
if __doc__ is None:
__doc__ = _format_constant_docstring(type_)
return type(
"overloaded_" + typename,
(_ConstantTransformerBase,), {
'_type': type_,
'__doc__': __doc__,
},
) | [
"def",
"overloaded_constants",
"(",
"type_",
",",
"__doc__",
"=",
"None",
")",
":",
"typename",
"=",
"type_",
".",
"__name__",
"if",
"typename",
".",
"endswith",
"(",
"'x'",
")",
":",
"typename",
"+=",
"'es'",
"elif",
"not",
"typename",
".",
"endswith",
... | A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types. | [
"A",
"factory",
"for",
"transformers",
"that",
"apply",
"functions",
"to",
"literals",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/literals.py#L237-L268 |
llllllllll/codetransformer | codetransformer/transformers/literals.py | overloaded_build | def overloaded_build(type_, add_name=None):
"""Factory for constant transformers that apply to a given
build instruction.
Parameters
----------
type_ : type
The object type to overload the construction of. This must be one of
"buildable" types, or types with a "BUILD_*" instruction.
add_name : str, optional
The suffix of the instruction tha adds elements to the collection.
For example: 'add' or 'append'
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types.
"""
typename = type_.__name__
instrname = 'BUILD_' + typename.upper()
dict_ = OrderedDict(
__doc__=dedent(
"""
A CodeTransformer for overloading {name} instructions.
""".format(name=instrname)
)
)
try:
build_instr = getattr(instructions, instrname)
except AttributeError:
raise TypeError("type %s is not buildable" % typename)
if add_name is not None:
try:
add_instr = getattr(
instructions,
'_'.join((typename, add_name)).upper(),
)
except AttributeError:
TypeError("type %s is not addable" % typename)
dict_['_start_comprehension'] = pattern(
build_instr, matchany[var], add_instr,
)(_start_comprehension)
dict_['_return_value'] = pattern(
instructions.RETURN_VALUE, startcodes=(IN_COMPREHENSION,),
)(_return_value)
else:
add_instr = None
dict_['_build'] = pattern(build_instr)(_build)
if not typename.endswith('s'):
typename = typename + 's'
return type(
'overloaded_' + typename,
(overloaded_constants(type_),),
dict_,
) | python | def overloaded_build(type_, add_name=None):
"""Factory for constant transformers that apply to a given
build instruction.
Parameters
----------
type_ : type
The object type to overload the construction of. This must be one of
"buildable" types, or types with a "BUILD_*" instruction.
add_name : str, optional
The suffix of the instruction tha adds elements to the collection.
For example: 'add' or 'append'
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types.
"""
typename = type_.__name__
instrname = 'BUILD_' + typename.upper()
dict_ = OrderedDict(
__doc__=dedent(
"""
A CodeTransformer for overloading {name} instructions.
""".format(name=instrname)
)
)
try:
build_instr = getattr(instructions, instrname)
except AttributeError:
raise TypeError("type %s is not buildable" % typename)
if add_name is not None:
try:
add_instr = getattr(
instructions,
'_'.join((typename, add_name)).upper(),
)
except AttributeError:
TypeError("type %s is not addable" % typename)
dict_['_start_comprehension'] = pattern(
build_instr, matchany[var], add_instr,
)(_start_comprehension)
dict_['_return_value'] = pattern(
instructions.RETURN_VALUE, startcodes=(IN_COMPREHENSION,),
)(_return_value)
else:
add_instr = None
dict_['_build'] = pattern(build_instr)(_build)
if not typename.endswith('s'):
typename = typename + 's'
return type(
'overloaded_' + typename,
(overloaded_constants(type_),),
dict_,
) | [
"def",
"overloaded_build",
"(",
"type_",
",",
"add_name",
"=",
"None",
")",
":",
"typename",
"=",
"type_",
".",
"__name__",
"instrname",
"=",
"'BUILD_'",
"+",
"typename",
".",
"upper",
"(",
")",
"dict_",
"=",
"OrderedDict",
"(",
"__doc__",
"=",
"dedent",
... | Factory for constant transformers that apply to a given
build instruction.
Parameters
----------
type_ : type
The object type to overload the construction of. This must be one of
"buildable" types, or types with a "BUILD_*" instruction.
add_name : str, optional
The suffix of the instruction tha adds elements to the collection.
For example: 'add' or 'append'
Returns
-------
transformer : subclass of CodeTransformer
A new code transformer class that will overload the provided
literal types. | [
"Factory",
"for",
"constant",
"transformers",
"that",
"apply",
"to",
"a",
"given",
"build",
"instruction",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/literals.py#L350-L411 |
llllllllll/codetransformer | codetransformer/decompiler/__init__.py | paramnames | def paramnames(co):
"""
Get the parameter names from a pycode object.
Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs).
varargs and varkwargs will be None if the function doesn't take *args or
**kwargs, respectively.
"""
flags = co.co_flags
varnames = co.co_varnames
argcount, kwonlyargcount = co.co_argcount, co.co_kwonlyargcount
total = argcount + kwonlyargcount
args = varnames[:argcount]
kwonlyargs = varnames[argcount:total]
varargs, varkwargs = None, None
if flags & Flag.CO_VARARGS:
varargs = varnames[total]
total += 1
if flags & Flag.CO_VARKEYWORDS:
varkwargs = varnames[total]
return args, kwonlyargs, varargs, varkwargs | python | def paramnames(co):
"""
Get the parameter names from a pycode object.
Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs).
varargs and varkwargs will be None if the function doesn't take *args or
**kwargs, respectively.
"""
flags = co.co_flags
varnames = co.co_varnames
argcount, kwonlyargcount = co.co_argcount, co.co_kwonlyargcount
total = argcount + kwonlyargcount
args = varnames[:argcount]
kwonlyargs = varnames[argcount:total]
varargs, varkwargs = None, None
if flags & Flag.CO_VARARGS:
varargs = varnames[total]
total += 1
if flags & Flag.CO_VARKEYWORDS:
varkwargs = varnames[total]
return args, kwonlyargs, varargs, varkwargs | [
"def",
"paramnames",
"(",
"co",
")",
":",
"flags",
"=",
"co",
".",
"co_flags",
"varnames",
"=",
"co",
".",
"co_varnames",
"argcount",
",",
"kwonlyargcount",
"=",
"co",
".",
"co_argcount",
",",
"co",
".",
"co_kwonlyargcount",
"total",
"=",
"argcount",
"+",
... | Get the parameter names from a pycode object.
Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs).
varargs and varkwargs will be None if the function doesn't take *args or
**kwargs, respectively. | [
"Get",
"the",
"parameter",
"names",
"from",
"a",
"pycode",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/__init__.py#L6-L29 |
llllllllll/codetransformer | codetransformer/code.py | _freevar_argname | def _freevar_argname(arg, cellvars, freevars):
"""
Get the name of the variable manipulated by a 'uses_free' instruction.
Parameters
----------
arg : int
The raw argument to a uses_free instruction that we want to resolve to
a name.
cellvars : list[str]
The co_cellvars of the function for which we want to resolve `arg`.
freevars : list[str]
The co_freevars of the function for which we want to resolve `arg`.
Notes
-----
From https://docs.python.org/3.5/library/dis.html#opcode-LOAD_CLOSURE:
The name of the variable is co_cellvars[i] if i is less than the length
of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)]
"""
len_cellvars = len(cellvars)
if arg < len_cellvars:
return cellvars[arg]
return freevars[arg - len_cellvars] | python | def _freevar_argname(arg, cellvars, freevars):
"""
Get the name of the variable manipulated by a 'uses_free' instruction.
Parameters
----------
arg : int
The raw argument to a uses_free instruction that we want to resolve to
a name.
cellvars : list[str]
The co_cellvars of the function for which we want to resolve `arg`.
freevars : list[str]
The co_freevars of the function for which we want to resolve `arg`.
Notes
-----
From https://docs.python.org/3.5/library/dis.html#opcode-LOAD_CLOSURE:
The name of the variable is co_cellvars[i] if i is less than the length
of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)]
"""
len_cellvars = len(cellvars)
if arg < len_cellvars:
return cellvars[arg]
return freevars[arg - len_cellvars] | [
"def",
"_freevar_argname",
"(",
"arg",
",",
"cellvars",
",",
"freevars",
")",
":",
"len_cellvars",
"=",
"len",
"(",
"cellvars",
")",
"if",
"arg",
"<",
"len_cellvars",
":",
"return",
"cellvars",
"[",
"arg",
"]",
"return",
"freevars",
"[",
"arg",
"-",
"len... | Get the name of the variable manipulated by a 'uses_free' instruction.
Parameters
----------
arg : int
The raw argument to a uses_free instruction that we want to resolve to
a name.
cellvars : list[str]
The co_cellvars of the function for which we want to resolve `arg`.
freevars : list[str]
The co_freevars of the function for which we want to resolve `arg`.
Notes
-----
From https://docs.python.org/3.5/library/dis.html#opcode-LOAD_CLOSURE:
The name of the variable is co_cellvars[i] if i is less than the length
of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)] | [
"Get",
"the",
"name",
"of",
"the",
"variable",
"manipulated",
"by",
"a",
"uses_free",
"instruction",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L193-L217 |
llllllllll/codetransformer | codetransformer/code.py | pycode | def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars=(),
cellvars=()):
"""types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType
"""
return CodeType(
argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars,
cellvars,
) | python | def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars=(),
cellvars=()):
"""types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType
"""
return CodeType(
argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars,
cellvars,
) | [
"def",
"pycode",
"(",
"argcount",
",",
"kwonlyargcount",
",",
"nlocals",
",",
"stacksize",
",",
"flags",
",",
"codestring",
",",
"constants",
",",
"names",
",",
"varnames",
",",
"filename",
",",
"name",
",",
"firstlineno",
",",
"lnotab",
",",
"freevars",
"... | types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType | [
"types",
".",
"CodeType",
"constructor",
"that",
"accepts",
"keyword",
"arguments",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L220-L257 |
llllllllll/codetransformer | codetransformer/code.py | Code.from_pycode | def from_pycode(cls, co):
"""Create a Code object from a python code object.
Parameters
----------
co : CodeType
The python code object.
Returns
-------
code : Code
The codetransformer Code object.
"""
# Make it sparse to instrs[n] is the instruction at bytecode[n]
sparse_instrs = tuple(
_sparse_args(
Instruction.from_opcode(
b.opcode,
Instruction._no_arg if b.arg is None else _RawArg(b.arg),
) for b in Bytecode(co)
),
)
for idx, instr in enumerate(sparse_instrs):
if instr is None:
# The sparse value
continue
if instr.absjmp:
instr.arg = sparse_instrs[instr.arg]
elif instr.reljmp:
instr.arg = sparse_instrs[instr.arg + idx + argsize + 1]
elif isinstance(instr, LOAD_CONST):
instr.arg = co.co_consts[instr.arg]
elif instr.uses_name:
instr.arg = co.co_names[instr.arg]
elif instr.uses_varname:
instr.arg = co.co_varnames[instr.arg]
elif instr.uses_free:
instr.arg = _freevar_argname(
instr.arg,
co.co_freevars,
co.co_cellvars,
)
elif instr.have_arg and isinstance(instr.arg, _RawArg):
instr.arg = int(instr.arg)
flags = Flag.unpack(co.co_flags)
has_vargs = flags['CO_VARARGS']
has_kwargs = flags['CO_VARKEYWORDS']
# Here we convert the varnames format into our argnames format.
paramnames = co.co_varnames[
:(co.co_argcount +
co.co_kwonlyargcount +
has_vargs +
has_kwargs)
]
# We start with the positional arguments.
new_paramnames = list(paramnames[:co.co_argcount])
# Add *args next.
if has_vargs:
new_paramnames.append('*' + paramnames[-1 - has_kwargs])
# Add positional only arguments next.
new_paramnames.extend(paramnames[
co.co_argcount:co.co_argcount + co.co_kwonlyargcount
])
# Add **kwargs last.
if has_kwargs:
new_paramnames.append('**' + paramnames[-1])
return cls(
filter(bool, sparse_instrs),
argnames=new_paramnames,
cellvars=co.co_cellvars,
freevars=co.co_freevars,
name=co.co_name,
filename=co.co_filename,
firstlineno=co.co_firstlineno,
lnotab={
lno: sparse_instrs[off] for off, lno in findlinestarts(co)
},
flags=flags,
) | python | def from_pycode(cls, co):
"""Create a Code object from a python code object.
Parameters
----------
co : CodeType
The python code object.
Returns
-------
code : Code
The codetransformer Code object.
"""
# Make it sparse to instrs[n] is the instruction at bytecode[n]
sparse_instrs = tuple(
_sparse_args(
Instruction.from_opcode(
b.opcode,
Instruction._no_arg if b.arg is None else _RawArg(b.arg),
) for b in Bytecode(co)
),
)
for idx, instr in enumerate(sparse_instrs):
if instr is None:
# The sparse value
continue
if instr.absjmp:
instr.arg = sparse_instrs[instr.arg]
elif instr.reljmp:
instr.arg = sparse_instrs[instr.arg + idx + argsize + 1]
elif isinstance(instr, LOAD_CONST):
instr.arg = co.co_consts[instr.arg]
elif instr.uses_name:
instr.arg = co.co_names[instr.arg]
elif instr.uses_varname:
instr.arg = co.co_varnames[instr.arg]
elif instr.uses_free:
instr.arg = _freevar_argname(
instr.arg,
co.co_freevars,
co.co_cellvars,
)
elif instr.have_arg and isinstance(instr.arg, _RawArg):
instr.arg = int(instr.arg)
flags = Flag.unpack(co.co_flags)
has_vargs = flags['CO_VARARGS']
has_kwargs = flags['CO_VARKEYWORDS']
# Here we convert the varnames format into our argnames format.
paramnames = co.co_varnames[
:(co.co_argcount +
co.co_kwonlyargcount +
has_vargs +
has_kwargs)
]
# We start with the positional arguments.
new_paramnames = list(paramnames[:co.co_argcount])
# Add *args next.
if has_vargs:
new_paramnames.append('*' + paramnames[-1 - has_kwargs])
# Add positional only arguments next.
new_paramnames.extend(paramnames[
co.co_argcount:co.co_argcount + co.co_kwonlyargcount
])
# Add **kwargs last.
if has_kwargs:
new_paramnames.append('**' + paramnames[-1])
return cls(
filter(bool, sparse_instrs),
argnames=new_paramnames,
cellvars=co.co_cellvars,
freevars=co.co_freevars,
name=co.co_name,
filename=co.co_filename,
firstlineno=co.co_firstlineno,
lnotab={
lno: sparse_instrs[off] for off, lno in findlinestarts(co)
},
flags=flags,
) | [
"def",
"from_pycode",
"(",
"cls",
",",
"co",
")",
":",
"# Make it sparse to instrs[n] is the instruction at bytecode[n]",
"sparse_instrs",
"=",
"tuple",
"(",
"_sparse_args",
"(",
"Instruction",
".",
"from_opcode",
"(",
"b",
".",
"opcode",
",",
"Instruction",
".",
"_... | Create a Code object from a python code object.
Parameters
----------
co : CodeType
The python code object.
Returns
-------
code : Code
The codetransformer Code object. | [
"Create",
"a",
"Code",
"object",
"from",
"a",
"python",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L429-L510 |
llllllllll/codetransformer | codetransformer/code.py | Code.to_pycode | def to_pycode(self):
"""Create a python code object from the more abstract
codetransfomer.Code object.
Returns
-------
co : CodeType
The python code object.
"""
consts = self.consts
names = self.names
varnames = self.varnames
freevars = self.freevars
cellvars = self.cellvars
bc = bytearray()
for instr in self.instrs:
bc.append(instr.opcode) # Write the opcode byte.
if isinstance(instr, LOAD_CONST):
# Resolve the constant index.
bc.extend(consts.index(instr.arg).to_bytes(argsize, 'little'))
elif instr.uses_name:
# Resolve the name index.
bc.extend(names.index(instr.arg).to_bytes(argsize, 'little'))
elif instr.uses_varname:
# Resolve the local variable index.
bc.extend(
varnames.index(instr.arg).to_bytes(argsize, 'little'),
)
elif instr.uses_free:
# uses_free is really "uses freevars **or** cellvars".
try:
# look for the name in cellvars
bc.extend(
cellvars.index(instr.arg).to_bytes(argsize, 'little'),
)
except ValueError:
# fall back to freevars, incrementing the length of
# cellvars.
bc.extend(
(freevars.index(instr.arg) + len(cellvars)).to_bytes(
argsize,
'little',
)
)
elif instr.absjmp:
# Resolve the absolute jump target.
bc.extend(
self.bytecode_offset(instr.arg).to_bytes(
argsize,
'little',
),
)
elif instr.reljmp:
# Resolve the relative jump target.
# We do this by subtracting the curren't instructions's
# sparse index from the sparse index of the argument.
# We then subtract argsize - 1 to account for the bytes the
# current instruction takes up.
bytecode_offset = self.bytecode_offset
bc.extend((
bytecode_offset(instr.arg) -
bytecode_offset(instr) -
argsize -
1
).to_bytes(argsize, 'little',))
elif instr.have_arg:
# Write any other arg here.
bc.extend(instr.arg.to_bytes(argsize, 'little'))
elif WORDCODE:
# with wordcode, all instructions are padded to 2 bytes
bc.append(0)
return CodeType(
self.argcount,
self.kwonlyargcount,
len(varnames),
self.stacksize,
self.py_flags,
bytes(bc),
consts,
names,
varnames,
self.filename,
self.name,
self.firstlineno,
self.py_lnotab,
freevars,
cellvars,
) | python | def to_pycode(self):
"""Create a python code object from the more abstract
codetransfomer.Code object.
Returns
-------
co : CodeType
The python code object.
"""
consts = self.consts
names = self.names
varnames = self.varnames
freevars = self.freevars
cellvars = self.cellvars
bc = bytearray()
for instr in self.instrs:
bc.append(instr.opcode) # Write the opcode byte.
if isinstance(instr, LOAD_CONST):
# Resolve the constant index.
bc.extend(consts.index(instr.arg).to_bytes(argsize, 'little'))
elif instr.uses_name:
# Resolve the name index.
bc.extend(names.index(instr.arg).to_bytes(argsize, 'little'))
elif instr.uses_varname:
# Resolve the local variable index.
bc.extend(
varnames.index(instr.arg).to_bytes(argsize, 'little'),
)
elif instr.uses_free:
# uses_free is really "uses freevars **or** cellvars".
try:
# look for the name in cellvars
bc.extend(
cellvars.index(instr.arg).to_bytes(argsize, 'little'),
)
except ValueError:
# fall back to freevars, incrementing the length of
# cellvars.
bc.extend(
(freevars.index(instr.arg) + len(cellvars)).to_bytes(
argsize,
'little',
)
)
elif instr.absjmp:
# Resolve the absolute jump target.
bc.extend(
self.bytecode_offset(instr.arg).to_bytes(
argsize,
'little',
),
)
elif instr.reljmp:
# Resolve the relative jump target.
# We do this by subtracting the curren't instructions's
# sparse index from the sparse index of the argument.
# We then subtract argsize - 1 to account for the bytes the
# current instruction takes up.
bytecode_offset = self.bytecode_offset
bc.extend((
bytecode_offset(instr.arg) -
bytecode_offset(instr) -
argsize -
1
).to_bytes(argsize, 'little',))
elif instr.have_arg:
# Write any other arg here.
bc.extend(instr.arg.to_bytes(argsize, 'little'))
elif WORDCODE:
# with wordcode, all instructions are padded to 2 bytes
bc.append(0)
return CodeType(
self.argcount,
self.kwonlyargcount,
len(varnames),
self.stacksize,
self.py_flags,
bytes(bc),
consts,
names,
varnames,
self.filename,
self.name,
self.firstlineno,
self.py_lnotab,
freevars,
cellvars,
) | [
"def",
"to_pycode",
"(",
"self",
")",
":",
"consts",
"=",
"self",
".",
"consts",
"names",
"=",
"self",
".",
"names",
"varnames",
"=",
"self",
".",
"varnames",
"freevars",
"=",
"self",
".",
"freevars",
"cellvars",
"=",
"self",
".",
"cellvars",
"bc",
"="... | Create a python code object from the more abstract
codetransfomer.Code object.
Returns
-------
co : CodeType
The python code object. | [
"Create",
"a",
"python",
"code",
"object",
"from",
"the",
"more",
"abstract",
"codetransfomer",
".",
"Code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L512-L600 |
llllllllll/codetransformer | codetransformer/code.py | Code.consts | def consts(self):
"""The constants referenced in this code object.
"""
# We cannot use a set comprehension because consts do not need
# to be hashable.
consts = []
append_const = consts.append
for instr in self.instrs:
if isinstance(instr, LOAD_CONST) and instr.arg not in consts:
append_const(instr.arg)
return tuple(consts) | python | def consts(self):
"""The constants referenced in this code object.
"""
# We cannot use a set comprehension because consts do not need
# to be hashable.
consts = []
append_const = consts.append
for instr in self.instrs:
if isinstance(instr, LOAD_CONST) and instr.arg not in consts:
append_const(instr.arg)
return tuple(consts) | [
"def",
"consts",
"(",
"self",
")",
":",
"# We cannot use a set comprehension because consts do not need",
"# to be hashable.",
"consts",
"=",
"[",
"]",
"append_const",
"=",
"consts",
".",
"append",
"for",
"instr",
"in",
"self",
".",
"instrs",
":",
"if",
"isinstance"... | The constants referenced in this code object. | [
"The",
"constants",
"referenced",
"in",
"this",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L634-L644 |
llllllllll/codetransformer | codetransformer/code.py | Code.names | def names(self):
"""The names referenced in this code object.
Names come from instructions like LOAD_GLOBAL or STORE_ATTR
where the name of the global or attribute is needed at runtime.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to drop the duplicates.
return tuple(sorted({
instr.arg for instr in self.instrs if instr.uses_name
})) | python | def names(self):
"""The names referenced in this code object.
Names come from instructions like LOAD_GLOBAL or STORE_ATTR
where the name of the global or attribute is needed at runtime.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to drop the duplicates.
return tuple(sorted({
instr.arg for instr in self.instrs if instr.uses_name
})) | [
"def",
"names",
"(",
"self",
")",
":",
"# We must sort to preserve the order between calls.",
"# The set comprehension is to drop the duplicates.",
"return",
"tuple",
"(",
"sorted",
"(",
"{",
"instr",
".",
"arg",
"for",
"instr",
"in",
"self",
".",
"instrs",
"if",
"ins... | The names referenced in this code object.
Names come from instructions like LOAD_GLOBAL or STORE_ATTR
where the name of the global or attribute is needed at runtime. | [
"The",
"names",
"referenced",
"in",
"this",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L647-L657 |
llllllllll/codetransformer | codetransformer/code.py | Code.varnames | def varnames(self):
"""The names of all of the local variables in this code object.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to drop the duplicates.
return self._argnames + tuple(sorted({
instr.arg
for instr in self.instrs
if instr.uses_varname and instr.arg not in self._argnames
})) | python | def varnames(self):
"""The names of all of the local variables in this code object.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to drop the duplicates.
return self._argnames + tuple(sorted({
instr.arg
for instr in self.instrs
if instr.uses_varname and instr.arg not in self._argnames
})) | [
"def",
"varnames",
"(",
"self",
")",
":",
"# We must sort to preserve the order between calls.",
"# The set comprehension is to drop the duplicates.",
"return",
"self",
".",
"_argnames",
"+",
"tuple",
"(",
"sorted",
"(",
"{",
"instr",
".",
"arg",
"for",
"instr",
"in",
... | The names of all of the local variables in this code object. | [
"The",
"names",
"of",
"all",
"of",
"the",
"local",
"variables",
"in",
"this",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L669-L678 |
llllllllll/codetransformer | codetransformer/code.py | Code.py_lnotab | def py_lnotab(self):
"""The encoded lnotab that python uses to compute when lines start.
Note
----
See Objects/lnotab_notes.txt in the cpython source for more details.
"""
reverse_lnotab = reverse_dict(self.lnotab)
py_lnotab = []
prev_instr = 0
prev_lno = self.firstlineno
for addr, instr in enumerate(_sparse_args(self.instrs)):
lno = reverse_lnotab.get(instr)
if lno is None:
continue
delta = lno - prev_lno
py_lnotab.append(addr - prev_instr)
py_lnotab.append(min(delta, max_lnotab_increment))
delta -= max_lnotab_increment
while delta > 0:
py_lnotab.append(0)
py_lnotab.append(min(delta, max_lnotab_increment))
delta -= max_lnotab_increment
prev_lno = lno
prev_instr = addr
return bytes(py_lnotab) | python | def py_lnotab(self):
"""The encoded lnotab that python uses to compute when lines start.
Note
----
See Objects/lnotab_notes.txt in the cpython source for more details.
"""
reverse_lnotab = reverse_dict(self.lnotab)
py_lnotab = []
prev_instr = 0
prev_lno = self.firstlineno
for addr, instr in enumerate(_sparse_args(self.instrs)):
lno = reverse_lnotab.get(instr)
if lno is None:
continue
delta = lno - prev_lno
py_lnotab.append(addr - prev_instr)
py_lnotab.append(min(delta, max_lnotab_increment))
delta -= max_lnotab_increment
while delta > 0:
py_lnotab.append(0)
py_lnotab.append(min(delta, max_lnotab_increment))
delta -= max_lnotab_increment
prev_lno = lno
prev_instr = addr
return bytes(py_lnotab) | [
"def",
"py_lnotab",
"(",
"self",
")",
":",
"reverse_lnotab",
"=",
"reverse_dict",
"(",
"self",
".",
"lnotab",
")",
"py_lnotab",
"=",
"[",
"]",
"prev_instr",
"=",
"0",
"prev_lno",
"=",
"self",
".",
"firstlineno",
"for",
"addr",
",",
"instr",
"in",
"enumer... | The encoded lnotab that python uses to compute when lines start.
Note
----
See Objects/lnotab_notes.txt in the cpython source for more details. | [
"The",
"encoded",
"lnotab",
"that",
"python",
"uses",
"to",
"compute",
"when",
"lines",
"start",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L783-L811 |
llllllllll/codetransformer | codetransformer/code.py | Code.stacksize | def stacksize(self):
"""The maximum amount of stack space used by this code object.
"""
return max(scanl(
op.add,
0,
map(op.attrgetter('stack_effect'), self.instrs),
)) | python | def stacksize(self):
"""The maximum amount of stack space used by this code object.
"""
return max(scanl(
op.add,
0,
map(op.attrgetter('stack_effect'), self.instrs),
)) | [
"def",
"stacksize",
"(",
"self",
")",
":",
"return",
"max",
"(",
"scanl",
"(",
"op",
".",
"add",
",",
"0",
",",
"map",
"(",
"op",
".",
"attrgetter",
"(",
"'stack_effect'",
")",
",",
"self",
".",
"instrs",
")",
",",
")",
")"
] | The maximum amount of stack space used by this code object. | [
"The",
"maximum",
"amount",
"of",
"stack",
"space",
"used",
"by",
"this",
"code",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L814-L821 |
llllllllll/codetransformer | codetransformer/utils/immutable.py | initialize_slot | def initialize_slot(obj, name, value):
"""Initalize an unitialized slot to a value.
If there is already a value for this slot, this is a nop.
Parameters
----------
obj : immutable
An immutable object.
name : str
The name of the slot to initialize.
value : any
The value to initialize the slot to.
"""
if not hasattr(obj, name):
object_setattr(obj, name, value) | python | def initialize_slot(obj, name, value):
"""Initalize an unitialized slot to a value.
If there is already a value for this slot, this is a nop.
Parameters
----------
obj : immutable
An immutable object.
name : str
The name of the slot to initialize.
value : any
The value to initialize the slot to.
"""
if not hasattr(obj, name):
object_setattr(obj, name, value) | [
"def",
"initialize_slot",
"(",
"obj",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"name",
")",
":",
"object_setattr",
"(",
"obj",
",",
"name",
",",
"value",
")"
] | Initalize an unitialized slot to a value.
If there is already a value for this slot, this is a nop.
Parameters
----------
obj : immutable
An immutable object.
name : str
The name of the slot to initialize.
value : any
The value to initialize the slot to. | [
"Initalize",
"an",
"unitialized",
"slot",
"to",
"a",
"value",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L61-L76 |
llllllllll/codetransformer | codetransformer/utils/immutable.py | _create_init | def _create_init(name, slots, defaults):
"""Create the __init__ function for an immutable object.
Parameters
----------
name : str
The name of the immutable class.
slots : iterable of str
The __slots__ field from the class.
defaults : dict or None
The default values for the arguments to __init__.
Returns
-------
init : callable
The __init__ function for the new immutable class.
"""
if any(s.startswith('__') for s in slots):
raise TypeError(
"immutable classes may not have slots that start with '__'",
)
# If we have no defaults, ignore all of this.
kwdefaults = None
if defaults is not None:
hit_default = False
_defaults = [] # positional defaults
kwdefaults = {} # kwonly defaults
kwdefs = False
for s in slots:
if s not in defaults and hit_default:
raise SyntaxError(
'non-default argument follows default argument'
)
if not kwdefs:
try:
# Try to grab the next default.
# Pop so that we know they were all consumed when we
# are done.
_defaults.append(defaults.pop(s))
except KeyError:
# Not in the dict, we haven't hit any defaults yet.
pass
else:
# We are now consuming default arguments.
hit_default = True
if s.startswith('*'):
if s in defaults:
raise TypeError(
'cannot set default for var args or var kwargs',
)
if not s.startswith('**'):
kwdefs = True
else:
kwdefaults[s] = defaults.pop(s)
if defaults:
# We didn't consume all of the defaults.
raise TypeError(
'default value for non-existent argument%s: %s' % (
's' if len(defaults) > 1 else '',
', '.join(starmap('{0}={1!r}'.format, defaults.items())),
)
)
# cast back to tuples
defaults = tuple(_defaults)
if not slots:
return _no_arg_init, ()
ns = {'__initialize_slot': initialize_slot}
# filter out lone star
slotnames = tuple(filter(None, (s.strip('*') for s in slots)))
# We are using exec here so that we can later inspect the call signature
# of the __init__. This makes the positional vs keywords work as intended.
# This is totally reasonable, no h8 m8!
exec(
'def __init__(_{name}__self, {args}): \n {assign}'.format(
name=name,
args=', '.join(slots),
assign='\n '.join(
map(
'__initialize_slot(_{1}__self, "{0}", {0})'.format,
slotnames,
repeat(name),
),
),
),
ns,
)
init = ns['__init__']
init.__defaults__ = defaults
init.__kwdefaults__ = kwdefaults
return init, slotnames | python | def _create_init(name, slots, defaults):
"""Create the __init__ function for an immutable object.
Parameters
----------
name : str
The name of the immutable class.
slots : iterable of str
The __slots__ field from the class.
defaults : dict or None
The default values for the arguments to __init__.
Returns
-------
init : callable
The __init__ function for the new immutable class.
"""
if any(s.startswith('__') for s in slots):
raise TypeError(
"immutable classes may not have slots that start with '__'",
)
# If we have no defaults, ignore all of this.
kwdefaults = None
if defaults is not None:
hit_default = False
_defaults = [] # positional defaults
kwdefaults = {} # kwonly defaults
kwdefs = False
for s in slots:
if s not in defaults and hit_default:
raise SyntaxError(
'non-default argument follows default argument'
)
if not kwdefs:
try:
# Try to grab the next default.
# Pop so that we know they were all consumed when we
# are done.
_defaults.append(defaults.pop(s))
except KeyError:
# Not in the dict, we haven't hit any defaults yet.
pass
else:
# We are now consuming default arguments.
hit_default = True
if s.startswith('*'):
if s in defaults:
raise TypeError(
'cannot set default for var args or var kwargs',
)
if not s.startswith('**'):
kwdefs = True
else:
kwdefaults[s] = defaults.pop(s)
if defaults:
# We didn't consume all of the defaults.
raise TypeError(
'default value for non-existent argument%s: %s' % (
's' if len(defaults) > 1 else '',
', '.join(starmap('{0}={1!r}'.format, defaults.items())),
)
)
# cast back to tuples
defaults = tuple(_defaults)
if not slots:
return _no_arg_init, ()
ns = {'__initialize_slot': initialize_slot}
# filter out lone star
slotnames = tuple(filter(None, (s.strip('*') for s in slots)))
# We are using exec here so that we can later inspect the call signature
# of the __init__. This makes the positional vs keywords work as intended.
# This is totally reasonable, no h8 m8!
exec(
'def __init__(_{name}__self, {args}): \n {assign}'.format(
name=name,
args=', '.join(slots),
assign='\n '.join(
map(
'__initialize_slot(_{1}__self, "{0}", {0})'.format,
slotnames,
repeat(name),
),
),
),
ns,
)
init = ns['__init__']
init.__defaults__ = defaults
init.__kwdefaults__ = kwdefaults
return init, slotnames | [
"def",
"_create_init",
"(",
"name",
",",
"slots",
",",
"defaults",
")",
":",
"if",
"any",
"(",
"s",
".",
"startswith",
"(",
"'__'",
")",
"for",
"s",
"in",
"slots",
")",
":",
"raise",
"TypeError",
"(",
"\"immutable classes may not have slots that start with '__... | Create the __init__ function for an immutable object.
Parameters
----------
name : str
The name of the immutable class.
slots : iterable of str
The __slots__ field from the class.
defaults : dict or None
The default values for the arguments to __init__.
Returns
-------
init : callable
The __init__ function for the new immutable class. | [
"Create",
"the",
"__init__",
"function",
"for",
"an",
"immutable",
"object",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L79-L174 |
llllllllll/codetransformer | codetransformer/utils/immutable.py | _wrapinit | def _wrapinit(init):
"""Wrap an existing initialize function by thawing self for the duration
of the init.
Parameters
----------
init : callable
The user-provided init.
Returns
-------
wrapped : callable
The wrapped init method.
"""
try:
spec = getfullargspec(init)
except TypeError:
# we cannot preserve the type signature.
def __init__(*args, **kwargs):
self = args[0]
__setattr__._initializing.add(self)
init(*args, **kwargs)
__setattr__._initializing.remove(self)
_check_missing_slots(self)
return __init__
args = spec.args
varargs = spec.varargs
if not (args or varargs):
raise TypeError(
"%r must accept at least one positional argument for 'self'" %
getattr(init, '__qualname__', getattr(init, '__name__', init)),
)
if not args:
self = '%s[0]' % varargs
forward = argspec = '*' + varargs
else:
self = args[0]
forward = argspec = ', '.join(args)
if args and varargs:
forward = '%s, *%s' % (forward, spec.varargs)
argspec = '%s, *%s' % (argspec, spec.varargs)
if spec.kwonlyargs:
forward = '%s, %s' % (
forward,
', '.join(map('{0}={0}'.format, spec.kwonlyargs))
)
argspec = '%s,%s%s' % (
argspec,
'*, ' if not spec.varargs else '',
', '.join(spec.kwonlyargs),
)
if spec.varkw:
forward = '%s, **%s' % (forward, spec.varkw)
argspec = '%s, **%s' % (argspec, spec.varkw)
ns = {
'__init': init,
'__initializing': __setattr__._initializing,
'__check_missing_slots': _check_missing_slots,
}
exec(
dedent(
"""\
def __init__({argspec}):
__initializing.add({self})
__init({forward})
__initializing.remove({self})
__check_missing_slots({self})
""".format(
argspec=argspec,
self=self,
forward=forward,
),
),
ns,
)
__init__ = ns['__init__']
__init__.__defaults__ = spec.defaults
__init__.__kwdefaults__ = spec.kwonlydefaults
__init__.__annotations__ = spec.annotations
return __init__ | python | def _wrapinit(init):
"""Wrap an existing initialize function by thawing self for the duration
of the init.
Parameters
----------
init : callable
The user-provided init.
Returns
-------
wrapped : callable
The wrapped init method.
"""
try:
spec = getfullargspec(init)
except TypeError:
# we cannot preserve the type signature.
def __init__(*args, **kwargs):
self = args[0]
__setattr__._initializing.add(self)
init(*args, **kwargs)
__setattr__._initializing.remove(self)
_check_missing_slots(self)
return __init__
args = spec.args
varargs = spec.varargs
if not (args or varargs):
raise TypeError(
"%r must accept at least one positional argument for 'self'" %
getattr(init, '__qualname__', getattr(init, '__name__', init)),
)
if not args:
self = '%s[0]' % varargs
forward = argspec = '*' + varargs
else:
self = args[0]
forward = argspec = ', '.join(args)
if args and varargs:
forward = '%s, *%s' % (forward, spec.varargs)
argspec = '%s, *%s' % (argspec, spec.varargs)
if spec.kwonlyargs:
forward = '%s, %s' % (
forward,
', '.join(map('{0}={0}'.format, spec.kwonlyargs))
)
argspec = '%s,%s%s' % (
argspec,
'*, ' if not spec.varargs else '',
', '.join(spec.kwonlyargs),
)
if spec.varkw:
forward = '%s, **%s' % (forward, spec.varkw)
argspec = '%s, **%s' % (argspec, spec.varkw)
ns = {
'__init': init,
'__initializing': __setattr__._initializing,
'__check_missing_slots': _check_missing_slots,
}
exec(
dedent(
"""\
def __init__({argspec}):
__initializing.add({self})
__init({forward})
__initializing.remove({self})
__check_missing_slots({self})
""".format(
argspec=argspec,
self=self,
forward=forward,
),
),
ns,
)
__init__ = ns['__init__']
__init__.__defaults__ = spec.defaults
__init__.__kwdefaults__ = spec.kwonlydefaults
__init__.__annotations__ = spec.annotations
return __init__ | [
"def",
"_wrapinit",
"(",
"init",
")",
":",
"try",
":",
"spec",
"=",
"getfullargspec",
"(",
"init",
")",
"except",
"TypeError",
":",
"# we cannot preserve the type signature.",
"def",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
... | Wrap an existing initialize function by thawing self for the duration
of the init.
Parameters
----------
init : callable
The user-provided init.
Returns
-------
wrapped : callable
The wrapped init method. | [
"Wrap",
"an",
"existing",
"initialize",
"function",
"by",
"thawing",
"self",
"for",
"the",
"duration",
"of",
"the",
"init",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L177-L261 |
llllllllll/codetransformer | codetransformer/utils/immutable.py | _check_missing_slots | def _check_missing_slots(ob):
"""Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that are named in the
__slots__.
"""
missing_slots = tuple(
filter(lambda s: not hasattr(ob, s), ob.__slots__),
)
if missing_slots:
raise TypeError(
'not all slots initialized in __init__, missing: {0}'.format(
missing_slots,
),
) | python | def _check_missing_slots(ob):
"""Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that are named in the
__slots__.
"""
missing_slots = tuple(
filter(lambda s: not hasattr(ob, s), ob.__slots__),
)
if missing_slots:
raise TypeError(
'not all slots initialized in __init__, missing: {0}'.format(
missing_slots,
),
) | [
"def",
"_check_missing_slots",
"(",
"ob",
")",
":",
"missing_slots",
"=",
"tuple",
"(",
"filter",
"(",
"lambda",
"s",
":",
"not",
"hasattr",
"(",
"ob",
",",
"s",
")",
",",
"ob",
".",
"__slots__",
")",
",",
")",
"if",
"missing_slots",
":",
"raise",
"T... | Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that are named in the
__slots__. | [
"Check",
"that",
"all",
"slots",
"have",
"been",
"initialized",
"when",
"a",
"custom",
"__init__",
"method",
"is",
"provided",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L264-L287 |
llllllllll/codetransformer | codetransformer/utils/functional.py | scanl | def scanl(f, n, ns):
"""Reduce ns by f starting with n yielding each intermediate value.
tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n)
Parameters
----------
f : callable
A binary function.
n : any
The starting value.
ns : iterable of any
The iterable to scan over.
Yields
------
p : any
The value of reduce(f, ns[:idx]) where idx is the current index.
Examples
--------
>>> import operator as op
>>> tuple(scanl(op.add, 0, (1, 2, 3, 4)))
(0, 1, 3, 6, 10)
"""
yield n
for m in ns:
n = f(n, m)
yield n | python | def scanl(f, n, ns):
"""Reduce ns by f starting with n yielding each intermediate value.
tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n)
Parameters
----------
f : callable
A binary function.
n : any
The starting value.
ns : iterable of any
The iterable to scan over.
Yields
------
p : any
The value of reduce(f, ns[:idx]) where idx is the current index.
Examples
--------
>>> import operator as op
>>> tuple(scanl(op.add, 0, (1, 2, 3, 4)))
(0, 1, 3, 6, 10)
"""
yield n
for m in ns:
n = f(n, m)
yield n | [
"def",
"scanl",
"(",
"f",
",",
"n",
",",
"ns",
")",
":",
"yield",
"n",
"for",
"m",
"in",
"ns",
":",
"n",
"=",
"f",
"(",
"n",
",",
"m",
")",
"yield",
"n"
] | Reduce ns by f starting with n yielding each intermediate value.
tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n)
Parameters
----------
f : callable
A binary function.
n : any
The starting value.
ns : iterable of any
The iterable to scan over.
Yields
------
p : any
The value of reduce(f, ns[:idx]) where idx is the current index.
Examples
--------
>>> import operator as op
>>> tuple(scanl(op.add, 0, (1, 2, 3, 4)))
(0, 1, 3, 6, 10) | [
"Reduce",
"ns",
"by",
"f",
"starting",
"with",
"n",
"yielding",
"each",
"intermediate",
"value",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L21-L49 |
llllllllll/codetransformer | codetransformer/utils/functional.py | ffill | def ffill(iterable):
"""Forward fill non None values in some iterable.
Parameters
----------
iterable : iterable
The iterable to forward fill.
Yields
------
e : any
The last non None value or None if there has not been a non None value.
"""
it = iter(iterable)
previous = next(it)
yield previous
for e in it:
if e is None:
yield previous
else:
previous = e
yield e | python | def ffill(iterable):
"""Forward fill non None values in some iterable.
Parameters
----------
iterable : iterable
The iterable to forward fill.
Yields
------
e : any
The last non None value or None if there has not been a non None value.
"""
it = iter(iterable)
previous = next(it)
yield previous
for e in it:
if e is None:
yield previous
else:
previous = e
yield e | [
"def",
"ffill",
"(",
"iterable",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"previous",
"=",
"next",
"(",
"it",
")",
"yield",
"previous",
"for",
"e",
"in",
"it",
":",
"if",
"e",
"is",
"None",
":",
"yield",
"previous",
"else",
":",
"previous... | Forward fill non None values in some iterable.
Parameters
----------
iterable : iterable
The iterable to forward fill.
Yields
------
e : any
The last non None value or None if there has not been a non None value. | [
"Forward",
"fill",
"non",
"None",
"values",
"in",
"some",
"iterable",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L75-L96 |
llllllllll/codetransformer | codetransformer/utils/functional.py | flatten | def flatten(seq, *, recurse_types=(tuple, list, set, frozenset)):
"""
Convert a (possibly nested) iterator into a flattened iterator.
Parameters
----------
seq : iterable
The sequence to flatten.
recurse_types, optional
Types to recursively flatten.
Defaults to (tuple, list, set, frozenset).
>>> list(flatten((1, (2, 3), ((4,), 5))))
[1, 2, 3, 4, 5]
>>> list(flatten(["abc", "def"], recurse_types=(str,)))
['a', 'b', 'c', 'd', 'e', 'f']
"""
for elem in seq:
if isinstance(elem, recurse_types):
yield from flatten(elem)
else:
yield elem | python | def flatten(seq, *, recurse_types=(tuple, list, set, frozenset)):
"""
Convert a (possibly nested) iterator into a flattened iterator.
Parameters
----------
seq : iterable
The sequence to flatten.
recurse_types, optional
Types to recursively flatten.
Defaults to (tuple, list, set, frozenset).
>>> list(flatten((1, (2, 3), ((4,), 5))))
[1, 2, 3, 4, 5]
>>> list(flatten(["abc", "def"], recurse_types=(str,)))
['a', 'b', 'c', 'd', 'e', 'f']
"""
for elem in seq:
if isinstance(elem, recurse_types):
yield from flatten(elem)
else:
yield elem | [
"def",
"flatten",
"(",
"seq",
",",
"*",
",",
"recurse_types",
"=",
"(",
"tuple",
",",
"list",
",",
"set",
",",
"frozenset",
")",
")",
":",
"for",
"elem",
"in",
"seq",
":",
"if",
"isinstance",
"(",
"elem",
",",
"recurse_types",
")",
":",
"yield",
"f... | Convert a (possibly nested) iterator into a flattened iterator.
Parameters
----------
seq : iterable
The sequence to flatten.
recurse_types, optional
Types to recursively flatten.
Defaults to (tuple, list, set, frozenset).
>>> list(flatten((1, (2, 3), ((4,), 5))))
[1, 2, 3, 4, 5]
>>> list(flatten(["abc", "def"], recurse_types=(str,)))
['a', 'b', 'c', 'd', 'e', 'f'] | [
"Convert",
"a",
"(",
"possibly",
"nested",
")",
"iterator",
"into",
"a",
"flattened",
"iterator",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L99-L121 |
llllllllll/codetransformer | codetransformer/transformers/interpolated_strings.py | interpolated_strings.types | def types(self):
"""
Tuple containing types transformed by this transformer.
"""
out = []
if self._transform_bytes:
out.append(bytes)
if self._transform_str:
out.append(str)
return tuple(out) | python | def types(self):
"""
Tuple containing types transformed by this transformer.
"""
out = []
if self._transform_bytes:
out.append(bytes)
if self._transform_str:
out.append(str)
return tuple(out) | [
"def",
"types",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"if",
"self",
".",
"_transform_bytes",
":",
"out",
".",
"append",
"(",
"bytes",
")",
"if",
"self",
".",
"_transform_str",
":",
"out",
".",
"append",
"(",
"str",
")",
"return",
"tuple",
"(... | Tuple containing types transformed by this transformer. | [
"Tuple",
"containing",
"types",
"transformed",
"by",
"this",
"transformer",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L55-L64 |
llllllllll/codetransformer | codetransformer/transformers/interpolated_strings.py | interpolated_strings._transform_constant_sequence | def _transform_constant_sequence(self, seq):
"""
Transform a frozenset or tuple.
"""
should_transform = is_a(self.types)
if not any(filter(should_transform, flatten(seq))):
# Tuple doesn't contain any transformable strings. Ignore.
yield LOAD_CONST(seq)
return
for const in seq:
if should_transform(const):
yield from self.transform_stringlike(const)
elif isinstance(const, (tuple, frozenset)):
yield from self._transform_constant_sequence(const)
else:
yield LOAD_CONST(const)
if isinstance(seq, tuple):
yield BUILD_TUPLE(len(seq))
else:
assert isinstance(seq, frozenset)
yield BUILD_TUPLE(len(seq))
yield LOAD_CONST(frozenset)
yield ROT_TWO()
yield CALL_FUNCTION(1) | python | def _transform_constant_sequence(self, seq):
"""
Transform a frozenset or tuple.
"""
should_transform = is_a(self.types)
if not any(filter(should_transform, flatten(seq))):
# Tuple doesn't contain any transformable strings. Ignore.
yield LOAD_CONST(seq)
return
for const in seq:
if should_transform(const):
yield from self.transform_stringlike(const)
elif isinstance(const, (tuple, frozenset)):
yield from self._transform_constant_sequence(const)
else:
yield LOAD_CONST(const)
if isinstance(seq, tuple):
yield BUILD_TUPLE(len(seq))
else:
assert isinstance(seq, frozenset)
yield BUILD_TUPLE(len(seq))
yield LOAD_CONST(frozenset)
yield ROT_TWO()
yield CALL_FUNCTION(1) | [
"def",
"_transform_constant_sequence",
"(",
"self",
",",
"seq",
")",
":",
"should_transform",
"=",
"is_a",
"(",
"self",
".",
"types",
")",
"if",
"not",
"any",
"(",
"filter",
"(",
"should_transform",
",",
"flatten",
"(",
"seq",
")",
")",
")",
":",
"# Tupl... | Transform a frozenset or tuple. | [
"Transform",
"a",
"frozenset",
"or",
"tuple",
"."
] | train | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L81-L107 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.