index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
55,022 |
coreapi.document
|
Document
|
The Core API document type.
Expresses the data that the client may access,
and the actions that the client may perform.
|
class Document(itypes.Dict):
"""
The Core API document type.
Expresses the data that the client may access,
and the actions that the client may perform.
"""
def __init__(self, url=None, title=None, description=None, media_type=None, content=None):
content = {} if (content is None) else content
if url is not None and not isinstance(url, string_types):
raise TypeError("'url' must be a string.")
if title is not None and not isinstance(title, string_types):
raise TypeError("'title' must be a string.")
if description is not None and not isinstance(description, string_types):
raise TypeError("'description' must be a string.")
if media_type is not None and not isinstance(media_type, string_types):
raise TypeError("'media_type' must be a string.")
if not isinstance(content, dict):
raise TypeError("'content' must be a dict.")
if any([not isinstance(key, string_types) for key in content.keys()]):
raise TypeError('content keys must be strings.')
self._url = '' if (url is None) else url
self._title = '' if (title is None) else title
self._description = '' if (description is None) else description
self._media_type = '' if (media_type is None) else media_type
self._data = {key: _to_immutable(value) for key, value in content.items()}
def clone(self, data):
return self.__class__(self.url, self.title, self.description, self.media_type, data)
def __iter__(self):
items = sorted(self._data.items(), key=_key_sorting)
return iter([key for key, value in items])
def __repr__(self):
return _repr(self)
def __str__(self):
return _str(self)
def __eq__(self, other):
if self.__class__ == other.__class__:
return (
self.url == other.url and
self.title == other.title and
self._data == other._data
)
return super(Document, self).__eq__(other)
@property
def url(self):
return self._url
@property
def title(self):
return self._title
@property
def description(self):
return self._description
@property
def media_type(self):
return self._media_type
@property
def data(self):
return OrderedDict([
(key, value) for key, value in self.items()
if not isinstance(value, Link)
])
@property
def links(self):
return OrderedDict([
(key, value) for key, value in self.items()
if isinstance(value, Link)
])
|
(url=None, title=None, description=None, media_type=None, content=None)
|
55,024 |
coreapi.document
|
__eq__
| null |
def __eq__(self, other):
if self.__class__ == other.__class__:
return (
self.url == other.url and
self.title == other.title and
self._data == other._data
)
return super(Document, self).__eq__(other)
|
(self, other)
|
55,025 |
itypes
|
__getitem__
| null |
def __getitem__(self, key):
return self._data[key]
|
(self, key)
|
55,026 |
coreapi.document
|
__init__
| null |
def __init__(self, url=None, title=None, description=None, media_type=None, content=None):
content = {} if (content is None) else content
if url is not None and not isinstance(url, string_types):
raise TypeError("'url' must be a string.")
if title is not None and not isinstance(title, string_types):
raise TypeError("'title' must be a string.")
if description is not None and not isinstance(description, string_types):
raise TypeError("'description' must be a string.")
if media_type is not None and not isinstance(media_type, string_types):
raise TypeError("'media_type' must be a string.")
if not isinstance(content, dict):
raise TypeError("'content' must be a dict.")
if any([not isinstance(key, string_types) for key in content.keys()]):
raise TypeError('content keys must be strings.')
self._url = '' if (url is None) else url
self._title = '' if (title is None) else title
self._description = '' if (description is None) else description
self._media_type = '' if (media_type is None) else media_type
self._data = {key: _to_immutable(value) for key, value in content.items()}
|
(self, url=None, title=None, description=None, media_type=None, content=None)
|
55,027 |
coreapi.document
|
__iter__
| null |
def __iter__(self):
items = sorted(self._data.items(), key=_key_sorting)
return iter([key for key, value in items])
|
(self)
|
55,028 |
itypes
|
__len__
| null |
def __len__(self):
return len(self._data)
|
(self)
|
55,031 |
coreapi.document
|
__str__
| null |
def __str__(self):
return _str(self)
|
(self)
|
55,032 |
coreapi.document
|
clone
| null |
def clone(self, data):
return self.__class__(self.url, self.title, self.description, self.media_type, data)
|
(self, data)
|
55,033 |
itypes
|
delete
| null |
def delete(self, key):
data = dict(self._data)
data.pop(key)
if hasattr(self, 'clone'):
return self.clone(data)
return type(self)(data)
|
(self, key)
|
55,034 |
itypes
|
delete_in
| null |
def delete_in(self, keys):
return _delete_in(self, keys)
|
(self, keys)
|
55,036 |
itypes
|
get_in
| null |
def get_in(self, keys, default=None):
return _get_in(self, keys, default=default)
|
(self, keys, default=None)
|
55,039 |
itypes
|
set
| null |
def set(self, key, value):
data = dict(self._data)
data[key] = value
if hasattr(self, 'clone'):
return self.clone(data)
return type(self)(data)
|
(self, key, value)
|
55,040 |
itypes
|
set_in
| null |
def set_in(self, keys, value):
return _set_in(self, keys, value)
|
(self, keys, value)
|
55,042 |
openapi_codec
|
OpenAPICodec
| null |
class OpenAPICodec(BaseCodec):
media_type = 'application/openapi+json'
format = 'openapi'
def decode(self, bytes, **options):
"""
Takes a bytestring and returns a document.
"""
try:
data = json.loads(bytes.decode('utf-8'))
except ValueError as exc:
raise ParseError('Malformed JSON. %s' % exc)
base_url = options.get('base_url')
doc = _parse_document(data, base_url)
if not isinstance(doc, Document):
raise ParseError('Top level node must be a document.')
return doc
def encode(self, document, **options):
if not isinstance(document, Document):
raise TypeError('Expected a `coreapi.Document` instance')
data = generate_swagger_object(document)
return force_bytes(json.dumps(data))
|
()
|
55,044 |
openapi_codec
|
decode
|
Takes a bytestring and returns a document.
|
def decode(self, bytes, **options):
"""
Takes a bytestring and returns a document.
"""
try:
data = json.loads(bytes.decode('utf-8'))
except ValueError as exc:
raise ParseError('Malformed JSON. %s' % exc)
base_url = options.get('base_url')
doc = _parse_document(data, base_url)
if not isinstance(doc, Document):
raise ParseError('Top level node must be a document.')
return doc
|
(self, bytes, **options)
|
55,046 |
openapi_codec
|
encode
| null |
def encode(self, document, **options):
if not isinstance(document, Document):
raise TypeError('Expected a `coreapi.Document` instance')
data = generate_swagger_object(document)
return force_bytes(json.dumps(data))
|
(self, document, **options)
|
55,049 |
coreapi.exceptions
|
ParseError
|
Raised when an invalid Core API encoding is encountered.
|
class ParseError(CoreAPIException):
"""
Raised when an invalid Core API encoding is encountered.
"""
pass
| null |
55,050 |
openapi_codec.decode
|
_parse_document
| null |
def _parse_document(data, base_url=None):
schema_url = base_url
base_url = _get_document_base_url(data, base_url)
info = _get_dict(data, 'info')
title = _get_string(info, 'title')
description = _get_string(info, 'description')
consumes = get_strings(_get_list(data, 'consumes'))
paths = _get_dict(data, 'paths')
content = {}
for path in paths.keys():
url = base_url + path.lstrip('/')
spec = _get_dict(paths, path)
default_parameters = get_dicts(_get_list(spec, 'parameters'))
for action in spec.keys():
action = action.lower()
if action not in ('get', 'put', 'post', 'delete', 'options', 'head', 'patch'):
continue
operation = _get_dict(spec, action)
# Determine any fields on the link.
has_body = False
has_form = False
fields = []
parameters = get_dicts(_get_list(operation, 'parameters', default_parameters), dereference_using=data)
for parameter in parameters:
name = _get_string(parameter, 'name')
location = _get_string(parameter, 'in')
required = _get_bool(parameter, 'required', default=(location == 'path'))
if location == 'body':
has_body = True
schema = _get_dict(parameter, 'schema', dereference_using=data)
expanded = _expand_schema(schema)
if expanded is not None:
# TODO: field schemas.
expanded_fields = [
Field(
name=field_name,
location='form',
required=is_required,
schema=coreschema.String(description=field_description)
)
for field_name, is_required, field_description in expanded
if not any([field.name == field_name for field in fields])
]
fields += expanded_fields
else:
# TODO: field schemas.
field_description = _get_string(parameter, 'description')
field = Field(
name=name,
location='body',
required=required,
schema=coreschema.String(description=field_description)
)
fields.append(field)
else:
if location == 'formData':
has_form = True
location = 'form'
field_description = _get_string(parameter, 'description')
# TODO: field schemas.
field = Field(
name=name,
location=location,
required=required,
schema=coreschema.String(description=field_description)
)
fields.append(field)
link_consumes = get_strings(_get_list(operation, 'consumes', consumes))
encoding = ''
if has_body:
encoding = _select_encoding(link_consumes)
elif has_form:
encoding = _select_encoding(link_consumes, form=True)
link_title = _get_string(operation, 'summary')
link_description = _get_string(operation, 'description')
link = Link(url=url, action=action, encoding=encoding, fields=fields, title=link_title, description=link_description)
# Add the link to the document content.
tags = get_strings(_get_list(operation, 'tags'))
operation_id = _get_string(operation, 'operationId')
if tags:
tag = tags[0]
prefix = tag + '_'
if operation_id.startswith(prefix):
operation_id = operation_id[len(prefix):]
if tag not in content:
content[tag] = {}
content[tag][operation_id] = link
else:
content[operation_id] = link
return Document(
url=schema_url,
title=title,
description=description,
content=content,
media_type='application/openapi+json'
)
|
(data, base_url=None)
|
55,053 |
coreapi.compat
|
force_bytes
| null |
def force_bytes(string):
if isinstance(string, string_types):
return string.encode('utf-8')
return string
|
(string)
|
55,054 |
openapi_codec.encode
|
generate_swagger_object
|
Generates root of the Swagger spec.
|
def generate_swagger_object(document):
"""
Generates root of the Swagger spec.
"""
parsed_url = urlparse.urlparse(document.url)
swagger = OrderedDict()
swagger['swagger'] = '2.0'
swagger['info'] = OrderedDict()
swagger['info']['title'] = document.title
swagger['info']['description'] = document.description
swagger['info']['version'] = '' # Required by the spec
if parsed_url.netloc:
swagger['host'] = parsed_url.netloc
if parsed_url.scheme:
swagger['schemes'] = [parsed_url.scheme]
swagger['paths'] = _get_paths_object(document)
return swagger
|
(document)
|
55,057 |
beniget.beniget
|
Ancestors
|
Build the ancestor tree, that associates a node to the list of node visited
from the root node (the Module) to the current node
>>> import gast as ast
>>> code = 'def foo(x): return x + 1'
>>> module = ast.parse(code)
>>> from beniget import Ancestors
>>> ancestors = Ancestors()
>>> ancestors.visit(module)
>>> binop = module.body[0].body[0].value
>>> for n in ancestors.parents(binop):
... print(type(n))
<class 'gast.gast.Module'>
<class 'gast.gast.FunctionDef'>
<class 'gast.gast.Return'>
|
class Ancestors(ast.NodeVisitor):
"""
Build the ancestor tree, that associates a node to the list of node visited
from the root node (the Module) to the current node
>>> import gast as ast
>>> code = 'def foo(x): return x + 1'
>>> module = ast.parse(code)
>>> from beniget import Ancestors
>>> ancestors = Ancestors()
>>> ancestors.visit(module)
>>> binop = module.body[0].body[0].value
>>> for n in ancestors.parents(binop):
... print(type(n))
<class 'gast.gast.Module'>
<class 'gast.gast.FunctionDef'>
<class 'gast.gast.Return'>
"""
def __init__(self):
self._parents = dict()
self._current = list()
def generic_visit(self, node):
self._parents[node] = list(self._current)
self._current.append(node)
super(Ancestors, self).generic_visit(node)
self._current.pop()
def parent(self, node):
return self._parents[node][-1]
def parents(self, node):
return self._parents[node]
def parentInstance(self, node, cls):
for n in reversed(self._parents[node]):
if isinstance(n, cls):
return n
raise ValueError("{} has no parent of type {}".format(node, cls))
def parentFunction(self, node):
return self.parentInstance(node, (ast.FunctionDef,
ast.AsyncFunctionDef))
def parentStmt(self, node):
return self.parentInstance(node, ast.stmt)
|
()
|
55,058 |
beniget.beniget
|
__init__
| null |
def __init__(self):
self._parents = dict()
self._current = list()
|
(self)
|
55,059 |
beniget.beniget
|
generic_visit
| null |
def generic_visit(self, node):
self._parents[node] = list(self._current)
self._current.append(node)
super(Ancestors, self).generic_visit(node)
self._current.pop()
|
(self, node)
|
55,060 |
beniget.beniget
|
parent
| null |
def parent(self, node):
return self._parents[node][-1]
|
(self, node)
|
55,061 |
beniget.beniget
|
parentFunction
| null |
def parentFunction(self, node):
return self.parentInstance(node, (ast.FunctionDef,
ast.AsyncFunctionDef))
|
(self, node)
|
55,062 |
beniget.beniget
|
parentInstance
| null |
def parentInstance(self, node, cls):
for n in reversed(self._parents[node]):
if isinstance(n, cls):
return n
raise ValueError("{} has no parent of type {}".format(node, cls))
|
(self, node, cls)
|
55,063 |
beniget.beniget
|
parentStmt
| null |
def parentStmt(self, node):
return self.parentInstance(node, ast.stmt)
|
(self, node)
|
55,064 |
beniget.beniget
|
parents
| null |
def parents(self, node):
return self._parents[node]
|
(self, node)
|
55,065 |
ast
|
visit
|
Visit a node.
|
def visit(self, node):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
|
(self, node)
|
55,067 |
beniget.beniget
|
DefUseChains
|
Module visitor that gathers two kinds of informations:
- locals: Dict[node, List[Def]], a mapping between a node and the list
of variable defined in this node,
- chains: Dict[node, Def], a mapping between nodes and their chains.
>>> import gast as ast
>>> module = ast.parse("from b import c, d; c()")
>>> duc = DefUseChains()
>>> duc.visit(module)
>>> for head in duc.locals[module]:
... print("{}: {}".format(head.name(), len(head.users())))
c: 1
d: 0
>>> alias_def = duc.chains[module.body[0].names[0]]
>>> print(alias_def)
c -> (c -> (Call -> ()))
|
class DefUseChains(ast.NodeVisitor):
"""
Module visitor that gathers two kinds of informations:
- locals: Dict[node, List[Def]], a mapping between a node and the list
of variable defined in this node,
- chains: Dict[node, Def], a mapping between nodes and their chains.
>>> import gast as ast
>>> module = ast.parse("from b import c, d; c()")
>>> duc = DefUseChains()
>>> duc.visit(module)
>>> for head in duc.locals[module]:
... print("{}: {}".format(head.name(), len(head.users())))
c: 1
d: 0
>>> alias_def = duc.chains[module.body[0].names[0]]
>>> print(alias_def)
c -> (c -> (Call -> ()))
"""
def __init__(self, filename=None):
"""
- filename: str, included in error messages if specified
"""
self.chains = {}
self.locals = defaultdict(list)
self.filename = filename
# deep copy of builtins, to remain reentrant
self._builtins = {k: Def(v) for k, v in Builtins.items()}
# function body are not executed when the function definition is met
# this holds a stack of the functions met during body processing
self._defered = []
# stack of mapping between an id and Names
self._definitions = []
# stack of variable defined with the global keywords
self._promoted_locals = []
# stack of variable that were undefined when we met them, but that may
# be defined in another path of the control flow (esp. in loop)
self._undefs = []
# stack of current node holding definitions: class, module, function...
self._currenthead = []
self._breaks = []
self._continues = []
# dead code levels
self.deadcode = 0
# helpers
def dump_definitions(self, node, ignore_builtins=True):
if isinstance(node, ast.Module) and not ignore_builtins:
builtins = {d for d in self._builtins.values()}
return sorted(d.name()
for d in self.locals[node] if d not in builtins)
else:
return sorted(d.name() for d in self.locals[node])
def dump_chains(self, node):
chains = []
for d in self.locals[node]:
chains.append(str(d))
return chains
def unbound_identifier(self, name, node):
if hasattr(node, "lineno"):
filename = "{}:".format(
"<unknown>" if self.filename is None else self.filename
)
location = " at {}{}:{}".format(filename,
node.lineno,
node.col_offset)
else:
location = ""
print("W: unbound identifier '{}'{}".format(name, location))
def lookup_identifier(self, name):
for d in reversed(self._definitions):
if name in d:
return d[name]
return []
def defs(self, node):
name = node.id
stars = []
for d in reversed(self._definitions):
if name in d:
return d[name] if not stars else stars + list(d[name])
if "*" in d:
stars.extend(d["*"])
d = self.chains.setdefault(node, Def(node))
if self._undefs:
self._undefs[-1][name].append((d, stars))
if stars:
return stars + [d]
else:
if not self._undefs:
self.unbound_identifier(name, node)
return [d]
def process_body(self, stmts):
deadcode = False
for stmt in stmts:
if isinstance(stmt, (ast.Break, ast.Continue, ast.Raise)):
if not deadcode:
deadcode = True
self.deadcode += 1
self.visit(stmt)
if deadcode:
self.deadcode -= 1
def process_undefs(self):
for undef_name, _undefs in self._undefs[-1].items():
if undef_name in self._definitions[-1]:
for newdef in self._definitions[-1][undef_name]:
for undef, _ in _undefs:
for user in undef.users():
newdef.add_user(user)
else:
for undef, stars in _undefs:
if not stars:
self.unbound_identifier(undef_name, undef.node)
self._undefs.pop()
@contextmanager
def DefinitionContext(self, node):
self._currenthead.append(node)
self._definitions.append(defaultdict(ordered_set))
self._promoted_locals.append(set())
yield
self._promoted_locals.pop()
self._definitions.pop()
self._currenthead.pop()
@contextmanager
def CompDefinitionContext(self, node):
if sys.version_info.major >= 3:
self._currenthead.append(node)
self._definitions.append(defaultdict(ordered_set))
self._promoted_locals.append(set())
yield
if sys.version_info.major >= 3:
self._promoted_locals.pop()
self._definitions.pop()
self._currenthead.pop()
# stmt
def visit_Module(self, node):
self.module = node
with self.DefinitionContext(node):
self._definitions[-1].update(
{k: ordered_set((v,)) for k, v in self._builtins.items()}
)
self._defered.append([])
self.process_body(node.body)
# handle `global' keyword specifically
cg = CollectGlobals()
cg.visit(node)
for nodes in cg.Globals.values():
for n, name in nodes:
if name not in self._definitions[-1]:
dnode = Def((n, name))
self.set_definition(name, dnode)
self.locals[node].append(dnode)
# handle function bodies
for fnode, ctx in self._defered[-1]:
visitor = getattr(self,
"visit_{}".format(type(fnode).__name__))
defs, self._definitions = self._definitions, ctx
visitor(fnode, step=DefinitionStep)
self._definitions = defs
self._defered.pop()
# various sanity checks
if __debug__:
overloaded_builtins = set()
for d in self.locals[node]:
name = d.name()
if name in self._builtins:
overloaded_builtins.add(name)
assert name in self._definitions[0], (name, d.node)
nb_defs = len(self._definitions[0])
nb_bltns = len(self._builtins)
nb_overloaded_bltns = len(overloaded_builtins)
nb_heads = len({d.name() for d in self.locals[node]})
assert nb_defs == nb_heads + nb_bltns - nb_overloaded_bltns
assert not self._definitions
assert not self._defered
def set_definition(self, name, dnode_or_dnodes):
if self.deadcode:
return
if isinstance(dnode_or_dnodes, Def):
self._definitions[-1][name] = ordered_set((dnode_or_dnodes,))
else:
self._definitions[-1][name] = ordered_set(dnode_or_dnodes)
@staticmethod
def add_to_definition(definition, name, dnode_or_dnodes):
if isinstance(dnode_or_dnodes, Def):
definition[name].add(dnode_or_dnodes)
else:
definition[name].update(dnode_or_dnodes)
def extend_definition(self, name, dnode_or_dnodes):
if self.deadcode:
return
DefUseChains.add_to_definition(self._definitions[-1], name,
dnode_or_dnodes)
def visit_FunctionDef(self, node, step=DeclarationStep):
if step is DeclarationStep:
dnode = self.chains.setdefault(node, Def(node))
self.set_definition(node.name, dnode)
self.locals[self._currenthead[-1]].append(dnode)
for kw_default in filter(None, node.args.kw_defaults):
self.visit(kw_default).add_user(dnode)
for default in node.args.defaults:
self.visit(default).add_user(dnode)
for decorator in node.decorator_list:
self.visit(decorator)
definitions = list(self._definitions)
if isinstance(self._currenthead[-1], ast.ClassDef):
definitions.pop()
self._defered[-1].append((node, definitions))
elif step is DefinitionStep:
# function is not considered as defined when evaluating returns
if node.returns:
self.visit(node.returns)
with self.DefinitionContext(node):
self.visit(node.args)
self.process_body(node.body)
else:
raise NotImplementedError()
visit_AsyncFunctionDef = visit_FunctionDef
def visit_ClassDef(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.locals[self._currenthead[-1]].append(dnode)
self.set_definition(node.name, dnode)
for base in node.bases:
self.visit(base).add_user(dnode)
for keyword in node.keywords:
self.visit(keyword.value).add_user(dnode)
for decorator in node.decorator_list:
self.visit(decorator).add_user(dnode)
with self.DefinitionContext(node):
self.set_definition("__class__", Def("__class__"))
self.process_body(node.body)
def visit_Return(self, node):
if node.value:
self.visit(node.value)
def visit_Break(self, _):
for k, v in self._definitions[-1].items():
DefUseChains.add_to_definition(self._breaks[-1], k, v)
self._definitions[-1].clear()
def visit_Continue(self, _):
for k, v in self._definitions[-1].items():
DefUseChains.add_to_definition(self._continues[-1], k, v)
self._definitions[-1].clear()
def visit_Delete(self, node):
for target in node.targets:
self.visit(target)
def visit_Assign(self, node):
# link is implicit through ctx
self.visit(node.value)
for target in node.targets:
self.visit(target)
def visit_AnnAssign(self, node):
if node.value:
dvalue = self.visit(node.value)
dannotation = self.visit(node.annotation)
dtarget = self.visit(node.target)
dtarget.add_user(dannotation)
if node.value:
dvalue.add_user(dtarget)
def visit_AugAssign(self, node):
dvalue = self.visit(node.value)
if isinstance(node.target, ast.Name):
ctx, node.target.ctx = node.target.ctx, ast.Load()
dtarget = self.visit(node.target)
dvalue.add_user(dtarget)
node.target.ctx = ctx
if node.target.id in self._promoted_locals[-1]:
self.extend_definition(node.target.id, dtarget)
else:
loaded_from = [d.name() for d in self.defs(node.target)]
self.set_definition(node.target.id, dtarget)
# If we augassign from a value that comes from '*', let's use
# this node as the definition point.
if '*' in loaded_from:
self.locals[self._currenthead[-1]].append(dtarget)
else:
self.visit(node.target).add_user(dvalue)
def visit_Print(self, node):
if node.dest:
self.visit(node.dest)
for value in node.values:
self.visit(value)
def visit_For(self, node):
self.visit(node.iter)
self._breaks.append(defaultdict(ordered_set))
self._continues.append(defaultdict(ordered_set))
self._undefs.append(defaultdict(list))
self._definitions.append(self._definitions[-1].copy())
self.visit(node.target)
self.process_body(node.body)
self.process_undefs()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
self._continues.append(defaultdict(ordered_set))
# extra round to ``emulate'' looping
self.visit(node.target)
self.process_body(node.body)
# process else clause in case of late break
self._definitions.append(defaultdict(ordered_set))
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
break_defs = self._breaks.pop()
continue_defs = self._continues.pop()
body_defs = self._definitions.pop()
for d, u in orelse_defs.items():
self.extend_definition(d, u)
for d, u in continue_defs.items():
self.extend_definition(d, u)
for d, u in break_defs.items():
self.extend_definition(d, u)
for d, u in body_defs.items():
self.extend_definition(d, u)
visit_AsyncFor = visit_For
def visit_While(self, node):
self._definitions.append(self._definitions[-1].copy())
self._undefs.append(defaultdict(list))
self._breaks.append(defaultdict(ordered_set))
self._continues.append(defaultdict(ordered_set))
self.process_body(node.orelse)
self._definitions.pop()
self._definitions.append(self._definitions[-1].copy())
self.visit(node.test)
self.process_body(node.body)
self.process_undefs()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
self._continues.append(defaultdict(ordered_set))
# extra round to simulate loop
self.visit(node.test)
self.process_body(node.body)
# the false branch of the eval
self.visit(node.test)
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
body_defs = self._definitions.pop()
break_defs = self._breaks.pop()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
for d, u in break_defs.items():
self.extend_definition(d, u)
for d, u in orelse_defs.items():
self.extend_definition(d, u)
for d, u in body_defs.items():
self.extend_definition(d, u)
def visit_If(self, node):
self.visit(node.test)
# putting a copy of current level to handle nested conditions
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.body)
body_defs = self._definitions.pop()
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
for d in body_defs:
if d in orelse_defs:
self.set_definition(d, body_defs[d] + orelse_defs[d])
else:
self.extend_definition(d, body_defs[d])
for d in orelse_defs:
if d in body_defs:
pass # already done in the previous loop
else:
self.extend_definition(d, orelse_defs[d])
def visit_With(self, node):
for withitem in node.items:
self.visit(withitem)
self.process_body(node.body)
visit_AsyncWith = visit_With
def visit_Raise(self, node):
if node.exc:
self.visit(node.exc)
if node.cause:
self.visit(node.cause)
def visit_Try(self, node):
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.body)
self.process_body(node.orelse)
failsafe_defs = self._definitions.pop()
# handle the fact that definitions may have fail
for d in failsafe_defs:
self.extend_definition(d, failsafe_defs[d])
for excepthandler in node.handlers:
self._definitions.append(defaultdict(ordered_set))
self.visit(excepthandler)
handler_def = self._definitions.pop()
for hd in handler_def:
self.extend_definition(hd, handler_def[hd])
self.process_body(node.finalbody)
def visit_Assert(self, node):
self.visit(node.test)
if node.msg:
self.visit(node.msg)
def visit_Import(self, node):
for alias in node.names:
dalias = self.chains.setdefault(alias, Def(alias))
base = alias.name.split(".", 1)[0]
self.set_definition(alias.asname or base, dalias)
self.locals[self._currenthead[-1]].append(dalias)
def visit_ImportFrom(self, node):
for alias in node.names:
dalias = self.chains.setdefault(alias, Def(alias))
self.set_definition(alias.asname or alias.name, dalias)
self.locals[self._currenthead[-1]].append(dalias)
def visit_Exec(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.body)
if node.globals:
self.visit(node.globals)
else:
# any global may be used by this exec!
for defs in self._definitions[0].values():
for d in defs:
d.add_user(dnode)
if node.locals:
self.visit(node.locals)
else:
# any local may be used by this exec!
visible_locals = set()
for _definitions in reversed(self._definitions[1:]):
for dname, defs in _definitions.items():
if dname not in visible_locals:
visible_locals.add(dname)
for d in defs:
d.add_user(dnode)
self.extend_definition("*", dnode)
def visit_Global(self, node):
for name in node.names:
self._promoted_locals[-1].add(name)
def visit_Nonlocal(self, node):
for name in node.names:
for d in reversed(self._definitions[:-1]):
if name not in d:
continue
else:
# this rightfully creates aliasing
self.set_definition(name, d[name])
break
else:
self.unbound_identifier(name, node)
def visit_Expr(self, node):
self.generic_visit(node)
# expr
def visit_BoolOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
def visit_BinOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.left).add_user(dnode)
self.visit(node.right).add_user(dnode)
return dnode
def visit_UnaryOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.operand).add_user(dnode)
return dnode
def visit_Lambda(self, node, step=DeclarationStep):
if step is DeclarationStep:
dnode = self.chains.setdefault(node, Def(node))
self._defered[-1].append((node, list(self._definitions)))
return dnode
elif step is DefinitionStep:
dnode = self.chains[node]
with self.DefinitionContext(node):
self.visit(node.args)
self.visit(node.body).add_user(dnode)
return dnode
else:
raise NotImplementedError()
def visit_IfExp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.test).add_user(dnode)
self.visit(node.body).add_user(dnode)
self.visit(node.orelse).add_user(dnode)
return dnode
def visit_Dict(self, node):
dnode = self.chains.setdefault(node, Def(node))
for key in filter(None, node.keys):
self.visit(key).add_user(dnode)
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
def visit_Set(self, node):
dnode = self.chains.setdefault(node, Def(node))
for elt in node.elts:
self.visit(elt).add_user(dnode)
return dnode
def visit_ListComp(self, node):
dnode = self.chains.setdefault(node, Def(node))
with self.CompDefinitionContext(node):
for comprehension in node.generators:
self.visit(comprehension).add_user(dnode)
self.visit(node.elt).add_user(dnode)
return dnode
visit_SetComp = visit_ListComp
def visit_DictComp(self, node):
dnode = self.chains.setdefault(node, Def(node))
with self.CompDefinitionContext(node):
for comprehension in node.generators:
self.visit(comprehension).add_user(dnode)
self.visit(node.key).add_user(dnode)
self.visit(node.value).add_user(dnode)
return dnode
visit_GeneratorExp = visit_ListComp
def visit_Await(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
return dnode
def visit_Yield(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.value:
self.visit(node.value).add_user(dnode)
return dnode
visit_YieldFrom = visit_Await
def visit_Compare(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.left).add_user(dnode)
for expr in node.comparators:
self.visit(expr).add_user(dnode)
return dnode
def visit_Call(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.func).add_user(dnode)
for arg in node.args:
self.visit(arg).add_user(dnode)
for kw in node.keywords:
self.visit(kw.value).add_user(dnode)
return dnode
visit_Repr = visit_Await
def visit_Constant(self, node):
dnode = self.chains.setdefault(node, Def(node))
return dnode
def visit_FormattedValue(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
if node.format_spec:
self.visit(node.format_spec).add_user(dnode)
return dnode
def visit_JoinedStr(self, node):
dnode = self.chains.setdefault(node, Def(node))
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
visit_Attribute = visit_Await
def visit_Subscript(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
self.visit(node.slice).add_user(dnode)
return dnode
visit_Starred = visit_Await
def visit_NamedExpr(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
self.visit(node.target)
return dnode
def visit_Name(self, node):
if isinstance(node.ctx, (ast.Param, ast.Store)):
dnode = self.chains.setdefault(node, Def(node))
if node.id in self._promoted_locals[-1]:
self.extend_definition(node.id, dnode)
if dnode not in self.locals[self.module]:
self.locals[self.module].append(dnode)
else:
self.set_definition(node.id, dnode)
if dnode not in self.locals[self._currenthead[-1]]:
self.locals[self._currenthead[-1]].append(dnode)
if node.annotation is not None:
self.visit(node.annotation)
elif isinstance(node.ctx, (ast.Load, ast.Del)):
node_in_chains = node in self.chains
if node_in_chains:
dnode = self.chains[node]
else:
dnode = Def(node)
for d in self.defs(node):
d.add_user(dnode)
if not node_in_chains:
self.chains[node] = dnode
# currently ignore the effect of a del
else:
raise NotImplementedError()
return dnode
def visit_Destructured(self, node):
dnode = self.chains.setdefault(node, Def(node))
tmp_store = ast.Store()
for elt in node.elts:
if isinstance(elt, ast.Name):
tmp_store, elt.ctx = elt.ctx, tmp_store
self.visit(elt)
tmp_store, elt.ctx = elt.ctx, tmp_store
elif isinstance(elt, ast.Subscript):
self.visit(elt)
elif isinstance(elt, (ast.List, ast.Tuple)):
self.visit_Destructured(elt)
return dnode
def visit_List(self, node):
if isinstance(node.ctx, ast.Load):
dnode = self.chains.setdefault(node, Def(node))
for elt in node.elts:
self.visit(elt).add_user(dnode)
return dnode
# unfortunately, destructured node are marked as Load,
# only the parent List/Tuple is marked as Store
elif isinstance(node.ctx, ast.Store):
return self.visit_Destructured(node)
visit_Tuple = visit_List
# slice
def visit_Slice(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.lower:
self.visit(node.lower).add_user(dnode)
if node.upper:
self.visit(node.upper).add_user(dnode)
if node.step:
self.visit(node.step).add_user(dnode)
return dnode
# misc
def visit_comprehension(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.iter).add_user(dnode)
self.visit(node.target)
for if_ in node.ifs:
self.visit(if_).add_user(dnode)
return dnode
def visit_excepthandler(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.type:
self.visit(node.type).add_user(dnode)
if node.name:
self.visit(node.name).add_user(dnode)
self.process_body(node.body)
return dnode
def visit_arguments(self, node):
for arg in node.args:
self.visit(arg)
for arg in node.posonlyargs:
self.visit(arg)
if node.vararg:
self.visit(node.vararg)
for arg in node.kwonlyargs:
self.visit(arg)
if node.kwarg:
self.visit(node.kwarg)
def visit_withitem(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.context_expr).add_user(dnode)
if node.optional_vars:
self.visit(node.optional_vars)
return dnode
|
(filename=None)
|
55,068 |
beniget.beniget
|
CompDefinitionContext
| null |
def defs(self, node):
name = node.id
stars = []
for d in reversed(self._definitions):
if name in d:
return d[name] if not stars else stars + list(d[name])
if "*" in d:
stars.extend(d["*"])
d = self.chains.setdefault(node, Def(node))
if self._undefs:
self._undefs[-1][name].append((d, stars))
if stars:
return stars + [d]
else:
if not self._undefs:
self.unbound_identifier(name, node)
return [d]
|
(self, node)
|
55,070 |
beniget.beniget
|
__init__
|
- filename: str, included in error messages if specified
|
def __init__(self, filename=None):
"""
- filename: str, included in error messages if specified
"""
self.chains = {}
self.locals = defaultdict(list)
self.filename = filename
# deep copy of builtins, to remain reentrant
self._builtins = {k: Def(v) for k, v in Builtins.items()}
# function body are not executed when the function definition is met
# this holds a stack of the functions met during body processing
self._defered = []
# stack of mapping between an id and Names
self._definitions = []
# stack of variable defined with the global keywords
self._promoted_locals = []
# stack of variable that were undefined when we met them, but that may
# be defined in another path of the control flow (esp. in loop)
self._undefs = []
# stack of current node holding definitions: class, module, function...
self._currenthead = []
self._breaks = []
self._continues = []
# dead code levels
self.deadcode = 0
|
(self, filename=None)
|
55,071 |
beniget.beniget
|
add_to_definition
| null |
@staticmethod
def add_to_definition(definition, name, dnode_or_dnodes):
if isinstance(dnode_or_dnodes, Def):
definition[name].add(dnode_or_dnodes)
else:
definition[name].update(dnode_or_dnodes)
|
(definition, name, dnode_or_dnodes)
|
55,073 |
beniget.beniget
|
dump_chains
| null |
def dump_chains(self, node):
chains = []
for d in self.locals[node]:
chains.append(str(d))
return chains
|
(self, node)
|
55,074 |
beniget.beniget
|
dump_definitions
| null |
def dump_definitions(self, node, ignore_builtins=True):
if isinstance(node, ast.Module) and not ignore_builtins:
builtins = {d for d in self._builtins.values()}
return sorted(d.name()
for d in self.locals[node] if d not in builtins)
else:
return sorted(d.name() for d in self.locals[node])
|
(self, node, ignore_builtins=True)
|
55,075 |
beniget.beniget
|
extend_definition
| null |
def extend_definition(self, name, dnode_or_dnodes):
if self.deadcode:
return
DefUseChains.add_to_definition(self._definitions[-1], name,
dnode_or_dnodes)
|
(self, name, dnode_or_dnodes)
|
55,076 |
ast
|
generic_visit
|
Called if no explicit visitor function exists for a node.
|
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for field, value in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value)
|
(self, node)
|
55,077 |
beniget.beniget
|
lookup_identifier
| null |
def lookup_identifier(self, name):
for d in reversed(self._definitions):
if name in d:
return d[name]
return []
|
(self, name)
|
55,078 |
beniget.beniget
|
process_body
| null |
def process_body(self, stmts):
deadcode = False
for stmt in stmts:
if isinstance(stmt, (ast.Break, ast.Continue, ast.Raise)):
if not deadcode:
deadcode = True
self.deadcode += 1
self.visit(stmt)
if deadcode:
self.deadcode -= 1
|
(self, stmts)
|
55,079 |
beniget.beniget
|
process_undefs
| null |
def process_undefs(self):
for undef_name, _undefs in self._undefs[-1].items():
if undef_name in self._definitions[-1]:
for newdef in self._definitions[-1][undef_name]:
for undef, _ in _undefs:
for user in undef.users():
newdef.add_user(user)
else:
for undef, stars in _undefs:
if not stars:
self.unbound_identifier(undef_name, undef.node)
self._undefs.pop()
|
(self)
|
55,080 |
beniget.beniget
|
set_definition
| null |
def set_definition(self, name, dnode_or_dnodes):
if self.deadcode:
return
if isinstance(dnode_or_dnodes, Def):
self._definitions[-1][name] = ordered_set((dnode_or_dnodes,))
else:
self._definitions[-1][name] = ordered_set(dnode_or_dnodes)
|
(self, name, dnode_or_dnodes)
|
55,081 |
beniget.beniget
|
unbound_identifier
| null |
def unbound_identifier(self, name, node):
if hasattr(node, "lineno"):
filename = "{}:".format(
"<unknown>" if self.filename is None else self.filename
)
location = " at {}{}:{}".format(filename,
node.lineno,
node.col_offset)
else:
location = ""
print("W: unbound identifier '{}'{}".format(name, location))
|
(self, name, node)
|
55,083 |
beniget.beniget
|
visit_AnnAssign
| null |
def visit_AnnAssign(self, node):
if node.value:
dvalue = self.visit(node.value)
dannotation = self.visit(node.annotation)
dtarget = self.visit(node.target)
dtarget.add_user(dannotation)
if node.value:
dvalue.add_user(dtarget)
|
(self, node)
|
55,084 |
beniget.beniget
|
visit_Assert
| null |
def visit_Assert(self, node):
self.visit(node.test)
if node.msg:
self.visit(node.msg)
|
(self, node)
|
55,085 |
beniget.beniget
|
visit_Assign
| null |
def visit_Assign(self, node):
# link is implicit through ctx
self.visit(node.value)
for target in node.targets:
self.visit(target)
|
(self, node)
|
55,086 |
beniget.beniget
|
visit_For
| null |
def visit_For(self, node):
self.visit(node.iter)
self._breaks.append(defaultdict(ordered_set))
self._continues.append(defaultdict(ordered_set))
self._undefs.append(defaultdict(list))
self._definitions.append(self._definitions[-1].copy())
self.visit(node.target)
self.process_body(node.body)
self.process_undefs()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
self._continues.append(defaultdict(ordered_set))
# extra round to ``emulate'' looping
self.visit(node.target)
self.process_body(node.body)
# process else clause in case of late break
self._definitions.append(defaultdict(ordered_set))
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
break_defs = self._breaks.pop()
continue_defs = self._continues.pop()
body_defs = self._definitions.pop()
for d, u in orelse_defs.items():
self.extend_definition(d, u)
for d, u in continue_defs.items():
self.extend_definition(d, u)
for d, u in break_defs.items():
self.extend_definition(d, u)
for d, u in body_defs.items():
self.extend_definition(d, u)
|
(self, node)
|
55,087 |
beniget.beniget
|
visit_FunctionDef
| null |
def visit_FunctionDef(self, node, step=DeclarationStep):
if step is DeclarationStep:
dnode = self.chains.setdefault(node, Def(node))
self.set_definition(node.name, dnode)
self.locals[self._currenthead[-1]].append(dnode)
for kw_default in filter(None, node.args.kw_defaults):
self.visit(kw_default).add_user(dnode)
for default in node.args.defaults:
self.visit(default).add_user(dnode)
for decorator in node.decorator_list:
self.visit(decorator)
definitions = list(self._definitions)
if isinstance(self._currenthead[-1], ast.ClassDef):
definitions.pop()
self._defered[-1].append((node, definitions))
elif step is DefinitionStep:
# function is not considered as defined when evaluating returns
if node.returns:
self.visit(node.returns)
with self.DefinitionContext(node):
self.visit(node.args)
self.process_body(node.body)
else:
raise NotImplementedError()
|
(self, node, step=<object object at 0x7f0e88f919b0>)
|
55,088 |
beniget.beniget
|
visit_With
| null |
def visit_With(self, node):
for withitem in node.items:
self.visit(withitem)
self.process_body(node.body)
|
(self, node)
|
55,089 |
beniget.beniget
|
visit_Await
| null |
def visit_Await(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
return dnode
|
(self, node)
|
55,090 |
beniget.beniget
|
visit_AugAssign
| null |
def visit_AugAssign(self, node):
dvalue = self.visit(node.value)
if isinstance(node.target, ast.Name):
ctx, node.target.ctx = node.target.ctx, ast.Load()
dtarget = self.visit(node.target)
dvalue.add_user(dtarget)
node.target.ctx = ctx
if node.target.id in self._promoted_locals[-1]:
self.extend_definition(node.target.id, dtarget)
else:
loaded_from = [d.name() for d in self.defs(node.target)]
self.set_definition(node.target.id, dtarget)
# If we augassign from a value that comes from '*', let's use
# this node as the definition point.
if '*' in loaded_from:
self.locals[self._currenthead[-1]].append(dtarget)
else:
self.visit(node.target).add_user(dvalue)
|
(self, node)
|
55,092 |
beniget.beniget
|
visit_BinOp
| null |
def visit_BinOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.left).add_user(dnode)
self.visit(node.right).add_user(dnode)
return dnode
|
(self, node)
|
55,093 |
beniget.beniget
|
visit_BoolOp
| null |
def visit_BoolOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
|
(self, node)
|
55,094 |
beniget.beniget
|
visit_Break
| null |
def visit_Break(self, _):
for k, v in self._definitions[-1].items():
DefUseChains.add_to_definition(self._breaks[-1], k, v)
self._definitions[-1].clear()
|
(self, _)
|
55,095 |
beniget.beniget
|
visit_Call
| null |
def visit_Call(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.func).add_user(dnode)
for arg in node.args:
self.visit(arg).add_user(dnode)
for kw in node.keywords:
self.visit(kw.value).add_user(dnode)
return dnode
|
(self, node)
|
55,096 |
beniget.beniget
|
visit_ClassDef
| null |
def visit_ClassDef(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.locals[self._currenthead[-1]].append(dnode)
self.set_definition(node.name, dnode)
for base in node.bases:
self.visit(base).add_user(dnode)
for keyword in node.keywords:
self.visit(keyword.value).add_user(dnode)
for decorator in node.decorator_list:
self.visit(decorator).add_user(dnode)
with self.DefinitionContext(node):
self.set_definition("__class__", Def("__class__"))
self.process_body(node.body)
|
(self, node)
|
55,097 |
beniget.beniget
|
visit_Compare
| null |
def visit_Compare(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.left).add_user(dnode)
for expr in node.comparators:
self.visit(expr).add_user(dnode)
return dnode
|
(self, node)
|
55,098 |
beniget.beniget
|
visit_Constant
| null |
def visit_Constant(self, node):
dnode = self.chains.setdefault(node, Def(node))
return dnode
|
(self, node)
|
55,099 |
beniget.beniget
|
visit_Continue
| null |
def visit_Continue(self, _):
for k, v in self._definitions[-1].items():
DefUseChains.add_to_definition(self._continues[-1], k, v)
self._definitions[-1].clear()
|
(self, _)
|
55,100 |
beniget.beniget
|
visit_Delete
| null |
def visit_Delete(self, node):
for target in node.targets:
self.visit(target)
|
(self, node)
|
55,101 |
beniget.beniget
|
visit_Destructured
| null |
def visit_Destructured(self, node):
dnode = self.chains.setdefault(node, Def(node))
tmp_store = ast.Store()
for elt in node.elts:
if isinstance(elt, ast.Name):
tmp_store, elt.ctx = elt.ctx, tmp_store
self.visit(elt)
tmp_store, elt.ctx = elt.ctx, tmp_store
elif isinstance(elt, ast.Subscript):
self.visit(elt)
elif isinstance(elt, (ast.List, ast.Tuple)):
self.visit_Destructured(elt)
return dnode
|
(self, node)
|
55,102 |
beniget.beniget
|
visit_Dict
| null |
def visit_Dict(self, node):
dnode = self.chains.setdefault(node, Def(node))
for key in filter(None, node.keys):
self.visit(key).add_user(dnode)
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
|
(self, node)
|
55,103 |
beniget.beniget
|
visit_DictComp
| null |
def visit_DictComp(self, node):
dnode = self.chains.setdefault(node, Def(node))
with self.CompDefinitionContext(node):
for comprehension in node.generators:
self.visit(comprehension).add_user(dnode)
self.visit(node.key).add_user(dnode)
self.visit(node.value).add_user(dnode)
return dnode
|
(self, node)
|
55,104 |
beniget.beniget
|
visit_Exec
| null |
def visit_Exec(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.body)
if node.globals:
self.visit(node.globals)
else:
# any global may be used by this exec!
for defs in self._definitions[0].values():
for d in defs:
d.add_user(dnode)
if node.locals:
self.visit(node.locals)
else:
# any local may be used by this exec!
visible_locals = set()
for _definitions in reversed(self._definitions[1:]):
for dname, defs in _definitions.items():
if dname not in visible_locals:
visible_locals.add(dname)
for d in defs:
d.add_user(dnode)
self.extend_definition("*", dnode)
|
(self, node)
|
55,105 |
beniget.beniget
|
visit_Expr
| null |
def visit_Expr(self, node):
self.generic_visit(node)
|
(self, node)
|
55,107 |
beniget.beniget
|
visit_FormattedValue
| null |
def visit_FormattedValue(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
if node.format_spec:
self.visit(node.format_spec).add_user(dnode)
return dnode
|
(self, node)
|
55,109 |
beniget.beniget
|
visit_ListComp
| null |
def visit_ListComp(self, node):
dnode = self.chains.setdefault(node, Def(node))
with self.CompDefinitionContext(node):
for comprehension in node.generators:
self.visit(comprehension).add_user(dnode)
self.visit(node.elt).add_user(dnode)
return dnode
|
(self, node)
|
55,110 |
beniget.beniget
|
visit_Global
| null |
def visit_Global(self, node):
for name in node.names:
self._promoted_locals[-1].add(name)
|
(self, node)
|
55,111 |
beniget.beniget
|
visit_If
| null |
def visit_If(self, node):
self.visit(node.test)
# putting a copy of current level to handle nested conditions
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.body)
body_defs = self._definitions.pop()
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
for d in body_defs:
if d in orelse_defs:
self.set_definition(d, body_defs[d] + orelse_defs[d])
else:
self.extend_definition(d, body_defs[d])
for d in orelse_defs:
if d in body_defs:
pass # already done in the previous loop
else:
self.extend_definition(d, orelse_defs[d])
|
(self, node)
|
55,112 |
beniget.beniget
|
visit_IfExp
| null |
def visit_IfExp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.test).add_user(dnode)
self.visit(node.body).add_user(dnode)
self.visit(node.orelse).add_user(dnode)
return dnode
|
(self, node)
|
55,113 |
beniget.beniget
|
visit_Import
| null |
def visit_Import(self, node):
for alias in node.names:
dalias = self.chains.setdefault(alias, Def(alias))
base = alias.name.split(".", 1)[0]
self.set_definition(alias.asname or base, dalias)
self.locals[self._currenthead[-1]].append(dalias)
|
(self, node)
|
55,114 |
beniget.beniget
|
visit_ImportFrom
| null |
def visit_ImportFrom(self, node):
for alias in node.names:
dalias = self.chains.setdefault(alias, Def(alias))
self.set_definition(alias.asname or alias.name, dalias)
self.locals[self._currenthead[-1]].append(dalias)
|
(self, node)
|
55,115 |
beniget.beniget
|
visit_JoinedStr
| null |
def visit_JoinedStr(self, node):
dnode = self.chains.setdefault(node, Def(node))
for value in node.values:
self.visit(value).add_user(dnode)
return dnode
|
(self, node)
|
55,116 |
beniget.beniget
|
visit_Lambda
| null |
def visit_Lambda(self, node, step=DeclarationStep):
if step is DeclarationStep:
dnode = self.chains.setdefault(node, Def(node))
self._defered[-1].append((node, list(self._definitions)))
return dnode
elif step is DefinitionStep:
dnode = self.chains[node]
with self.DefinitionContext(node):
self.visit(node.args)
self.visit(node.body).add_user(dnode)
return dnode
else:
raise NotImplementedError()
|
(self, node, step=<object object at 0x7f0e88f919b0>)
|
55,117 |
beniget.beniget
|
visit_List
| null |
def visit_List(self, node):
if isinstance(node.ctx, ast.Load):
dnode = self.chains.setdefault(node, Def(node))
for elt in node.elts:
self.visit(elt).add_user(dnode)
return dnode
# unfortunately, destructured node are marked as Load,
# only the parent List/Tuple is marked as Store
elif isinstance(node.ctx, ast.Store):
return self.visit_Destructured(node)
|
(self, node)
|
55,119 |
beniget.beniget
|
visit_Module
| null |
def visit_Module(self, node):
self.module = node
with self.DefinitionContext(node):
self._definitions[-1].update(
{k: ordered_set((v,)) for k, v in self._builtins.items()}
)
self._defered.append([])
self.process_body(node.body)
# handle `global' keyword specifically
cg = CollectGlobals()
cg.visit(node)
for nodes in cg.Globals.values():
for n, name in nodes:
if name not in self._definitions[-1]:
dnode = Def((n, name))
self.set_definition(name, dnode)
self.locals[node].append(dnode)
# handle function bodies
for fnode, ctx in self._defered[-1]:
visitor = getattr(self,
"visit_{}".format(type(fnode).__name__))
defs, self._definitions = self._definitions, ctx
visitor(fnode, step=DefinitionStep)
self._definitions = defs
self._defered.pop()
# various sanity checks
if __debug__:
overloaded_builtins = set()
for d in self.locals[node]:
name = d.name()
if name in self._builtins:
overloaded_builtins.add(name)
assert name in self._definitions[0], (name, d.node)
nb_defs = len(self._definitions[0])
nb_bltns = len(self._builtins)
nb_overloaded_bltns = len(overloaded_builtins)
nb_heads = len({d.name() for d in self.locals[node]})
assert nb_defs == nb_heads + nb_bltns - nb_overloaded_bltns
assert not self._definitions
assert not self._defered
|
(self, node)
|
55,120 |
beniget.beniget
|
visit_Name
| null |
def visit_Name(self, node):
if isinstance(node.ctx, (ast.Param, ast.Store)):
dnode = self.chains.setdefault(node, Def(node))
if node.id in self._promoted_locals[-1]:
self.extend_definition(node.id, dnode)
if dnode not in self.locals[self.module]:
self.locals[self.module].append(dnode)
else:
self.set_definition(node.id, dnode)
if dnode not in self.locals[self._currenthead[-1]]:
self.locals[self._currenthead[-1]].append(dnode)
if node.annotation is not None:
self.visit(node.annotation)
elif isinstance(node.ctx, (ast.Load, ast.Del)):
node_in_chains = node in self.chains
if node_in_chains:
dnode = self.chains[node]
else:
dnode = Def(node)
for d in self.defs(node):
d.add_user(dnode)
if not node_in_chains:
self.chains[node] = dnode
# currently ignore the effect of a del
else:
raise NotImplementedError()
return dnode
|
(self, node)
|
55,121 |
beniget.beniget
|
visit_NamedExpr
| null |
def visit_NamedExpr(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
self.visit(node.target)
return dnode
|
(self, node)
|
55,122 |
beniget.beniget
|
visit_Nonlocal
| null |
def visit_Nonlocal(self, node):
for name in node.names:
for d in reversed(self._definitions[:-1]):
if name not in d:
continue
else:
# this rightfully creates aliasing
self.set_definition(name, d[name])
break
else:
self.unbound_identifier(name, node)
|
(self, node)
|
55,123 |
beniget.beniget
|
visit_Print
| null |
def visit_Print(self, node):
if node.dest:
self.visit(node.dest)
for value in node.values:
self.visit(value)
|
(self, node)
|
55,124 |
beniget.beniget
|
visit_Raise
| null |
def visit_Raise(self, node):
if node.exc:
self.visit(node.exc)
if node.cause:
self.visit(node.cause)
|
(self, node)
|
55,126 |
beniget.beniget
|
visit_Return
| null |
def visit_Return(self, node):
if node.value:
self.visit(node.value)
|
(self, node)
|
55,127 |
beniget.beniget
|
visit_Set
| null |
def visit_Set(self, node):
dnode = self.chains.setdefault(node, Def(node))
for elt in node.elts:
self.visit(elt).add_user(dnode)
return dnode
|
(self, node)
|
55,129 |
beniget.beniget
|
visit_Slice
| null |
def visit_Slice(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.lower:
self.visit(node.lower).add_user(dnode)
if node.upper:
self.visit(node.upper).add_user(dnode)
if node.step:
self.visit(node.step).add_user(dnode)
return dnode
|
(self, node)
|
55,131 |
beniget.beniget
|
visit_Subscript
| null |
def visit_Subscript(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.value).add_user(dnode)
self.visit(node.slice).add_user(dnode)
return dnode
|
(self, node)
|
55,132 |
beniget.beniget
|
visit_Try
| null |
def visit_Try(self, node):
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.body)
self.process_body(node.orelse)
failsafe_defs = self._definitions.pop()
# handle the fact that definitions may have fail
for d in failsafe_defs:
self.extend_definition(d, failsafe_defs[d])
for excepthandler in node.handlers:
self._definitions.append(defaultdict(ordered_set))
self.visit(excepthandler)
handler_def = self._definitions.pop()
for hd in handler_def:
self.extend_definition(hd, handler_def[hd])
self.process_body(node.finalbody)
|
(self, node)
|
55,134 |
beniget.beniget
|
visit_UnaryOp
| null |
def visit_UnaryOp(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.operand).add_user(dnode)
return dnode
|
(self, node)
|
55,135 |
beniget.beniget
|
visit_While
| null |
def visit_While(self, node):
self._definitions.append(self._definitions[-1].copy())
self._undefs.append(defaultdict(list))
self._breaks.append(defaultdict(ordered_set))
self._continues.append(defaultdict(ordered_set))
self.process_body(node.orelse)
self._definitions.pop()
self._definitions.append(self._definitions[-1].copy())
self.visit(node.test)
self.process_body(node.body)
self.process_undefs()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
self._continues.append(defaultdict(ordered_set))
# extra round to simulate loop
self.visit(node.test)
self.process_body(node.body)
# the false branch of the eval
self.visit(node.test)
self._definitions.append(self._definitions[-1].copy())
self.process_body(node.orelse)
orelse_defs = self._definitions.pop()
body_defs = self._definitions.pop()
break_defs = self._breaks.pop()
continue_defs = self._continues.pop()
for d, u in continue_defs.items():
self.extend_definition(d, u)
for d, u in break_defs.items():
self.extend_definition(d, u)
for d, u in orelse_defs.items():
self.extend_definition(d, u)
for d, u in body_defs.items():
self.extend_definition(d, u)
|
(self, node)
|
55,137 |
beniget.beniget
|
visit_Yield
| null |
def visit_Yield(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.value:
self.visit(node.value).add_user(dnode)
return dnode
|
(self, node)
|
55,139 |
beniget.beniget
|
visit_arguments
| null |
def visit_arguments(self, node):
for arg in node.args:
self.visit(arg)
for arg in node.posonlyargs:
self.visit(arg)
if node.vararg:
self.visit(node.vararg)
for arg in node.kwonlyargs:
self.visit(arg)
if node.kwarg:
self.visit(node.kwarg)
|
(self, node)
|
55,140 |
beniget.beniget
|
visit_comprehension
| null |
def visit_comprehension(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.iter).add_user(dnode)
self.visit(node.target)
for if_ in node.ifs:
self.visit(if_).add_user(dnode)
return dnode
|
(self, node)
|
55,141 |
beniget.beniget
|
visit_excepthandler
| null |
def visit_excepthandler(self, node):
dnode = self.chains.setdefault(node, Def(node))
if node.type:
self.visit(node.type).add_user(dnode)
if node.name:
self.visit(node.name).add_user(dnode)
self.process_body(node.body)
return dnode
|
(self, node)
|
55,142 |
beniget.beniget
|
visit_withitem
| null |
def visit_withitem(self, node):
dnode = self.chains.setdefault(node, Def(node))
self.visit(node.context_expr).add_user(dnode)
if node.optional_vars:
self.visit(node.optional_vars)
return dnode
|
(self, node)
|
55,143 |
beniget.beniget
|
UseDefChains
|
DefUseChains adaptor that builds a mapping between each user
and the Def that defines this user:
- chains: Dict[node, List[Def]], a mapping between nodes and the Defs
that define it.
|
class UseDefChains(object):
"""
DefUseChains adaptor that builds a mapping between each user
and the Def that defines this user:
- chains: Dict[node, List[Def]], a mapping between nodes and the Defs
that define it.
"""
def __init__(self, defuses):
self.chains = {}
for chain in defuses.chains.values():
if isinstance(chain.node, ast.Name):
self.chains.setdefault(chain.node, [])
for use in chain.users():
self.chains.setdefault(use.node, []).append(chain)
for chain in defuses._builtins.values():
for use in chain.users():
self.chains.setdefault(use.node, []).append(chain)
def __str__(self):
out = []
for k, uses in self.chains.items():
kname = Def(k).name()
kstr = "{} <- {{{}}}".format(
kname, ", ".join(sorted(use.name() for use in uses))
)
out.append((kname, kstr))
out.sort()
return ", ".join(s for k, s in out)
|
(defuses)
|
55,144 |
beniget.beniget
|
__init__
| null |
def __init__(self, defuses):
self.chains = {}
for chain in defuses.chains.values():
if isinstance(chain.node, ast.Name):
self.chains.setdefault(chain.node, [])
for use in chain.users():
self.chains.setdefault(use.node, []).append(chain)
for chain in defuses._builtins.values():
for use in chain.users():
self.chains.setdefault(use.node, []).append(chain)
|
(self, defuses)
|
55,145 |
beniget.beniget
|
__str__
| null |
def __str__(self):
out = []
for k, uses in self.chains.items():
kname = Def(k).name()
kstr = "{} <- {{{}}}".format(
kname, ", ".join(sorted(use.name() for use in uses))
)
out.append((kname, kstr))
out.sort()
return ", ".join(s for k, s in out)
|
(self)
|
55,147 |
config_formatter
|
ConfigFormatter
|
A class used to reformat .ini/.cfg configurations.
|
class ConfigFormatter:
"""A class used to reformat .ini/.cfg configurations."""
def prettify(self, string: str) -> str:
"""Transform the content of a .ini/.cfg file to make it more pleasing to the eye.
It preserves comments and ensures that it stays semantically identical to the input string
(the built-in Python module "configparser" serves as reference).
The accepted entry format is relatively strict, in particular:
- no duplicated section or option are allowed ;
- only "=" and ":" delimiters are considered ;
- only "#" and ";" comment prefixes are considered ;
- comments next to values are left untouched ;
- options without assigned value are not allowed ;
- empty lines in values are allowed but discouraged.
These settings are those used by default in the "ConfigParser" from the standard library.
"""
string = string.strip()
if not string:
return "\n"
base_config, has_dummy_top_section = self._load_config(string)
return self._format_config(base_config, has_dummy_top_section=has_dummy_top_section)
def _load_config(self, string: str) -> Tuple[configupdater.parser.Document, bool]:
"""Load the given string as a configuration document.
It also implements a workaround to handle configs that do not have a top section header.
"""
parser = configupdater.parser.Parser(
strict=True,
delimiters=("=", ":"),
comment_prefixes=("#", ";"),
inline_comment_prefixes=None,
allow_no_value=False,
empty_lines_in_values=True,
)
try:
return parser.read_string(string), False
except configupdater.MissingSectionHeaderError:
i = 1
while True:
dummy_section = f"[config-formatter-dummy-section-name-{i}]"
if dummy_section in string:
i += 1
continue
return parser.read_string(f"{dummy_section}\n{string}"), True
def _format_config(
self, source: configupdater.container.Container, *, has_dummy_top_section: bool
) -> str:
"""Recursively construct a normalized string of the given configuration."""
output = ""
for block in source.iter_blocks():
if isinstance(block, configupdater.Section):
if has_dummy_top_section:
has_dummy_top_section = False
else:
comment = block.raw_comment.strip()
if comment:
output += f"[{block.name}] {comment}\n"
else:
output += f"[{block.name}]\n"
output += self._format_config(block, has_dummy_top_section=False)
elif isinstance(block, configupdater.Comment):
for line in block.lines:
comment = line.strip()
output += f"{comment}\n"
elif isinstance(block, configupdater.Space):
if block.lines:
output += "\n"
elif isinstance(block, configupdater.Option):
key = block.raw_key
value = block.value
if value is None: # Should never happen in theory as "allow_no_value" is disabled.
output += f"{key}\n"
elif "\n" in value:
first, *lines = (line.strip() for line in value.splitlines())
if not first:
output += f"{key} =\n"
indent = 4
else:
output += f"{key} = {first}\n"
indent = len(key) + 3
for line in lines:
if line:
output += f"{' ' * indent}{line}\n"
else:
output += "\n"
else:
value = value.strip()
if value:
output += f"{key} = {value}\n"
else:
output += f"{key} =\n"
else:
raise ValueError("Encountered an unexpected block type: '%s'", type(block).__name__)
return output
|
()
|
55,148 |
config_formatter
|
_format_config
|
Recursively construct a normalized string of the given configuration.
|
def _format_config(
self, source: configupdater.container.Container, *, has_dummy_top_section: bool
) -> str:
"""Recursively construct a normalized string of the given configuration."""
output = ""
for block in source.iter_blocks():
if isinstance(block, configupdater.Section):
if has_dummy_top_section:
has_dummy_top_section = False
else:
comment = block.raw_comment.strip()
if comment:
output += f"[{block.name}] {comment}\n"
else:
output += f"[{block.name}]\n"
output += self._format_config(block, has_dummy_top_section=False)
elif isinstance(block, configupdater.Comment):
for line in block.lines:
comment = line.strip()
output += f"{comment}\n"
elif isinstance(block, configupdater.Space):
if block.lines:
output += "\n"
elif isinstance(block, configupdater.Option):
key = block.raw_key
value = block.value
if value is None: # Should never happen in theory as "allow_no_value" is disabled.
output += f"{key}\n"
elif "\n" in value:
first, *lines = (line.strip() for line in value.splitlines())
if not first:
output += f"{key} =\n"
indent = 4
else:
output += f"{key} = {first}\n"
indent = len(key) + 3
for line in lines:
if line:
output += f"{' ' * indent}{line}\n"
else:
output += "\n"
else:
value = value.strip()
if value:
output += f"{key} = {value}\n"
else:
output += f"{key} =\n"
else:
raise ValueError("Encountered an unexpected block type: '%s'", type(block).__name__)
return output
|
(self, source: configupdater.container.Container, *, has_dummy_top_section: bool) -> str
|
55,149 |
config_formatter
|
_load_config
|
Load the given string as a configuration document.
It also implements a workaround to handle configs that do not have a top section header.
|
def _load_config(self, string: str) -> Tuple[configupdater.parser.Document, bool]:
"""Load the given string as a configuration document.
It also implements a workaround to handle configs that do not have a top section header.
"""
parser = configupdater.parser.Parser(
strict=True,
delimiters=("=", ":"),
comment_prefixes=("#", ";"),
inline_comment_prefixes=None,
allow_no_value=False,
empty_lines_in_values=True,
)
try:
return parser.read_string(string), False
except configupdater.MissingSectionHeaderError:
i = 1
while True:
dummy_section = f"[config-formatter-dummy-section-name-{i}]"
if dummy_section in string:
i += 1
continue
return parser.read_string(f"{dummy_section}\n{string}"), True
|
(self, string: str) -> Tuple[configupdater.document.Document, bool]
|
55,150 |
config_formatter
|
prettify
|
Transform the content of a .ini/.cfg file to make it more pleasing to the eye.
It preserves comments and ensures that it stays semantically identical to the input string
(the built-in Python module "configparser" serves as reference).
The accepted entry format is relatively strict, in particular:
- no duplicated section or option are allowed ;
- only "=" and ":" delimiters are considered ;
- only "#" and ";" comment prefixes are considered ;
- comments next to values are left untouched ;
- options without assigned value are not allowed ;
- empty lines in values are allowed but discouraged.
These settings are those used by default in the "ConfigParser" from the standard library.
|
def prettify(self, string: str) -> str:
"""Transform the content of a .ini/.cfg file to make it more pleasing to the eye.
It preserves comments and ensures that it stays semantically identical to the input string
(the built-in Python module "configparser" serves as reference).
The accepted entry format is relatively strict, in particular:
- no duplicated section or option are allowed ;
- only "=" and ":" delimiters are considered ;
- only "#" and ";" comment prefixes are considered ;
- comments next to values are left untouched ;
- options without assigned value are not allowed ;
- empty lines in values are allowed but discouraged.
These settings are those used by default in the "ConfigParser" from the standard library.
"""
string = string.strip()
if not string:
return "\n"
base_config, has_dummy_top_section = self._load_config(string)
return self._format_config(base_config, has_dummy_top_section=has_dummy_top_section)
|
(self, string: str) -> str
|
55,152 |
pem._object_types
|
AbstractPEMObject
|
Base class for parsed objects.
|
class AbstractPEMObject(metaclass=ABCMeta):
"""
Base class for parsed objects.
"""
_pattern: ClassVar[tuple[bytes, ...]] = NotImplemented
_pem_bytes: bytes
def __init__(self, pem_bytes: bytes | str):
self._pem_bytes = (
pem_bytes.encode("ascii")
if isinstance(pem_bytes, str)
else pem_bytes
)
self._sha1_hexdigest = None
def __str__(self) -> str:
"""
Return the PEM-encoded content as a native :obj:`str`.
"""
return self._pem_bytes.decode("ascii")
def __repr__(self) -> str:
return "<{}(PEM string with SHA-1 digest {!r})>".format(
self.__class__.__name__, self.sha1_hexdigest
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, type(self)):
return NotImplemented
return (
type(self) == type(other) and self._pem_bytes == other._pem_bytes
)
def __hash__(self) -> int:
return hash(self._pem_bytes)
@cached_property
def sha1_hexdigest(self) -> str:
"""
A SHA-1 digest of the whole object for easy differentiation.
.. versionadded:: 18.1.0
.. versionchanged:: 20.1.0
Carriage returns are removed before hashing to give the same hashes
on Windows and UNIX-like operating systems.
"""
return hashlib.sha1( # noqa[S324]
self._pem_bytes.replace(b"\r", b"")
).hexdigest()
def as_bytes(self) -> bytes:
"""
Return the PEM-encoded content as :obj:`bytes`.
.. versionadded:: 16.1.0
"""
return self._pem_bytes
def as_text(self) -> str:
"""
Return the PEM-encoded content as text.
.. versionadded:: 18.1.0
"""
return self._pem_bytes.decode("utf-8")
@cached_property
def bytes_payload(self) -> bytes:
"""
The payload of the PEM-encoded content.
Possible PEM headers are removed.
.. versionadded:: 23.1.0
"""
return b"".join(
line
for line in self._pem_bytes.splitlines()[1:-1]
if b":" not in line # remove headers
)
@cached_property
def text_payload(self) -> str:
"""
The payload of the PEM-encoded content.
Possible PEM headers are removed.
.. versionadded:: 23.1.0
"""
return self.bytes_payload.decode("utf-8")
@cached_property
def decoded_payload(self) -> bytes:
"""
The base64-decoded payload of the PEM-encoded content.
Possible PEM headers are removed.
.. versionadded:: 23.1.0
"""
return b64decode(self.bytes_payload)
@cached_property
def meta_headers(self) -> dict[str, str]:
"""
Return a dictionary of payload headers.
If the value of a header is quoted, the quotes are removed.
.. versionadded:: 23.1.0
"""
expl = {}
for line in self._pem_bytes.decode().splitlines()[1:-1]:
if ":" not in line:
break
key, val = line.split(": ", 1)
# Strip quotes if they're only at the beginning and end.
if val.count('"') == 2 and val[0] == '"' and val[-1] == '"':
val = val[1:-1]
expl[key] = val
else:
# XXX: necessary for Coverage.py!? This can't happen with non-empty
# PEM objects.
pass # pragma: no cover
return expl
|
(pem_bytes: 'bytes | str')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.