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
39
1.84M
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
contentful/contentful.py
contentful/client.py
Client._http_get
def _http_get(self, url, query): """ Performs the HTTP GET Request. """ if not self.authorization_as_header: query.update({'access_token': self.access_token}) response = None self._normalize_query(query) kwargs = { 'params': query, 'headers': self._request_headers() } if self._has_proxy(): kwargs['proxies'] = self._proxy_parameters() response = requests.get( self._url(url), **kwargs ) if response.status_code == 429: raise RateLimitExceededError(response) return response
python
def _http_get(self, url, query): if not self.authorization_as_header: query.update({'access_token': self.access_token}) response = None self._normalize_query(query) kwargs = { 'params': query, 'headers': self._request_headers() } if self._has_proxy(): kwargs['proxies'] = self._proxy_parameters() response = requests.get( self._url(url), **kwargs ) if response.status_code == 429: raise RateLimitExceededError(response) return response
[ "def", "_http_get", "(", "self", ",", "url", ",", "query", ")", ":", "if", "not", "self", ".", "authorization_as_header", ":", "query", ".", "update", "(", "{", "'access_token'", ":", "self", ".", "access_token", "}", ")", "response", "=", "None", "self", ".", "_normalize_query", "(", "query", ")", "kwargs", "=", "{", "'params'", ":", "query", ",", "'headers'", ":", "self", ".", "_request_headers", "(", ")", "}", "if", "self", ".", "_has_proxy", "(", ")", ":", "kwargs", "[", "'proxies'", "]", "=", "self", ".", "_proxy_parameters", "(", ")", "response", "=", "requests", ".", "get", "(", "self", ".", "_url", "(", "url", ")", ",", "*", "*", "kwargs", ")", "if", "response", ".", "status_code", "==", "429", ":", "raise", "RateLimitExceededError", "(", "response", ")", "return", "response" ]
Performs the HTTP GET Request.
[ "Performs", "the", "HTTP", "GET", "Request", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L518-L546
contentful/contentful.py
contentful/client.py
Client._get
def _get(self, url, query=None): """ Wrapper for the HTTP Request, Rate Limit Backoff is handled here, Responses are Processed with ResourceBuilder. """ if query is None: query = {} response = retry_request(self)(self._http_get)(url, query=query) if self.raw_mode: return response if response.status_code != 200: error = get_error(response) if self.raise_errors: raise error return error localized = query.get('locale', '') == '*' return ResourceBuilder( self.default_locale, localized, response.json(), max_depth=self.max_include_resolution_depth, reuse_entries=self.reuse_entries ).build()
python
def _get(self, url, query=None): if query is None: query = {} response = retry_request(self)(self._http_get)(url, query=query) if self.raw_mode: return response if response.status_code != 200: error = get_error(response) if self.raise_errors: raise error return error localized = query.get('locale', '') == '*' return ResourceBuilder( self.default_locale, localized, response.json(), max_depth=self.max_include_resolution_depth, reuse_entries=self.reuse_entries ).build()
[ "def", "_get", "(", "self", ",", "url", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "response", "=", "retry_request", "(", "self", ")", "(", "self", ".", "_http_get", ")", "(", "url", ",", "query", "=", "query", ")", "if", "self", ".", "raw_mode", ":", "return", "response", "if", "response", ".", "status_code", "!=", "200", ":", "error", "=", "get_error", "(", "response", ")", "if", "self", ".", "raise_errors", ":", "raise", "error", "return", "error", "localized", "=", "query", ".", "get", "(", "'locale'", ",", "''", ")", "==", "'*'", "return", "ResourceBuilder", "(", "self", ".", "default_locale", ",", "localized", ",", "response", ".", "json", "(", ")", ",", "max_depth", "=", "self", ".", "max_include_resolution_depth", ",", "reuse_entries", "=", "self", ".", "reuse_entries", ")", ".", "build", "(", ")" ]
Wrapper for the HTTP Request, Rate Limit Backoff is handled here, Responses are Processed with ResourceBuilder.
[ "Wrapper", "for", "the", "HTTP", "Request", "Rate", "Limit", "Backoff", "is", "handled", "here", "Responses", "are", "Processed", "with", "ResourceBuilder", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L548-L576
contentful/contentful.py
contentful/client.py
Client._proxy_parameters
def _proxy_parameters(self): """ Builds Proxy parameters Dict from client options. """ proxy_protocol = '' if self.proxy_host.startswith('https'): proxy_protocol = 'https' else: proxy_protocol = 'http' proxy = '{0}://'.format(proxy_protocol) if self.proxy_username and self.proxy_password: proxy += '{0}:{1}@'.format(self.proxy_username, self.proxy_password) proxy += sub(r'https?(://)?', '', self.proxy_host) if self.proxy_port: proxy += ':{0}'.format(self.proxy_port) return { 'http': proxy, 'https': proxy }
python
def _proxy_parameters(self): proxy_protocol = '' if self.proxy_host.startswith('https'): proxy_protocol = 'https' else: proxy_protocol = 'http' proxy = '{0}://'.format(proxy_protocol) if self.proxy_username and self.proxy_password: proxy += '{0}:{1}@'.format(self.proxy_username, self.proxy_password) proxy += sub(r'https?(://)?', '', self.proxy_host) if self.proxy_port: proxy += ':{0}'.format(self.proxy_port) return { 'http': proxy, 'https': proxy }
[ "def", "_proxy_parameters", "(", "self", ")", ":", "proxy_protocol", "=", "''", "if", "self", ".", "proxy_host", ".", "startswith", "(", "'https'", ")", ":", "proxy_protocol", "=", "'https'", "else", ":", "proxy_protocol", "=", "'http'", "proxy", "=", "'{0}://'", ".", "format", "(", "proxy_protocol", ")", "if", "self", ".", "proxy_username", "and", "self", ".", "proxy_password", ":", "proxy", "+=", "'{0}:{1}@'", ".", "format", "(", "self", ".", "proxy_username", ",", "self", ".", "proxy_password", ")", "proxy", "+=", "sub", "(", "r'https?(://)?'", ",", "''", ",", "self", ".", "proxy_host", ")", "if", "self", ".", "proxy_port", ":", "proxy", "+=", "':{0}'", ".", "format", "(", "self", ".", "proxy_port", ")", "return", "{", "'http'", ":", "proxy", ",", "'https'", ":", "proxy", "}" ]
Builds Proxy parameters Dict from client options.
[ "Builds", "Proxy", "parameters", "Dict", "from", "client", "options", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/client.py#L585-L609
contentful/contentful.py
contentful/asset.py
Asset.url
def url(self, **kwargs): """Returns a formatted URL for the Asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160" """ url = self.file['url'] args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) return url
python
def url(self, **kwargs): url = self.file['url'] args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) return url
[ "def", "url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "file", "[", "'url'", "]", "args", "=", "[", "'{0}={1}'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", "if", "args", ":", "url", "+=", "'?{0}'", ".", "format", "(", "'&'", ".", "join", "(", "args", ")", ")", "return", "url" ]
Returns a formatted URL for the Asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160"
[ "Returns", "a", "formatted", "URL", "for", "the", "Asset", "s", "File", "with", "serialized", "parameters", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/asset.py#L22-L39
contentful/contentful.py
contentful/resource.py
FieldsResource.fields
def fields(self, locale=None): """Get fields for a specific locale :param locale: (optional) Locale to fetch, defaults to default_locale. """ if locale is None: locale = self._locale() return self._fields.get(locale, {})
python
def fields(self, locale=None): if locale is None: locale = self._locale() return self._fields.get(locale, {})
[ "def", "fields", "(", "self", ",", "locale", "=", "None", ")", ":", "if", "locale", "is", "None", ":", "locale", "=", "self", ".", "_locale", "(", ")", "return", "self", ".", "_fields", ".", "get", "(", "locale", ",", "{", "}", ")" ]
Get fields for a specific locale :param locale: (optional) Locale to fetch, defaults to default_locale.
[ "Get", "fields", "for", "a", "specific", "locale" ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource.py#L152-L160
contentful/contentful.py
contentful/resource.py
Link.resolve
def resolve(self, client): """Resolves Link to a specific Resource""" resolve_method = getattr(client, snake_case(self.link_type)) if self.link_type == 'Space': return resolve_method() else: return resolve_method(self.id)
python
def resolve(self, client): resolve_method = getattr(client, snake_case(self.link_type)) if self.link_type == 'Space': return resolve_method() else: return resolve_method(self.id)
[ "def", "resolve", "(", "self", ",", "client", ")", ":", "resolve_method", "=", "getattr", "(", "client", ",", "snake_case", "(", "self", ".", "link_type", ")", ")", "if", "self", ".", "link_type", "==", "'Space'", ":", "return", "resolve_method", "(", ")", "else", ":", "return", "resolve_method", "(", "self", ".", "id", ")" ]
Resolves Link to a specific Resource
[ "Resolves", "Link", "to", "a", "specific", "Resource" ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/resource.py#L182-L189
contentful/contentful.py
contentful/utils.py
snake_case
def snake_case(a_string): """Returns a snake cased version of a string. :param a_string: any :class:`str` object. Usage: >>> snake_case('FooBar') "foo_bar" """ partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower()
python
def snake_case(a_string): partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower()
[ "def", "snake_case", "(", "a_string", ")", ":", "partial", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "a_string", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "partial", ")", ".", "lower", "(", ")" ]
Returns a snake cased version of a string. :param a_string: any :class:`str` object. Usage: >>> snake_case('FooBar') "foo_bar"
[ "Returns", "a", "snake", "cased", "version", "of", "a", "string", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L56-L67
contentful/contentful.py
contentful/utils.py
is_link_array
def is_link_array(value): """Checks if value is an array of links. :param value: any object. :return: Boolean :rtype: bool Usage: >>> is_link_array('foo') False >>> is_link_array([1, 2, 3]) False >>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}]) True """ if isinstance(value, list) and len(value) > 0: return is_link(value[0]) return False
python
def is_link_array(value): if isinstance(value, list) and len(value) > 0: return is_link(value[0]) return False
[ "def", "is_link_array", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", "and", "len", "(", "value", ")", ">", "0", ":", "return", "is_link", "(", "value", "[", "0", "]", ")", "return", "False" ]
Checks if value is an array of links. :param value: any object. :return: Boolean :rtype: bool Usage: >>> is_link_array('foo') False >>> is_link_array([1, 2, 3]) False >>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}]) True
[ "Checks", "if", "value", "is", "an", "array", "of", "links", "." ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L90-L108
contentful/contentful.py
contentful/utils.py
resource_for_link
def resource_for_link(link, includes, resources=None, locale=None): """Returns the resource that matches the link""" if resources is not None: cache_key = "{0}:{1}:{2}".format( link['sys']['linkType'], link['sys']['id'], locale ) if cache_key in resources: return resources[cache_key] for i in includes: if (i['sys']['id'] == link['sys']['id'] and i['sys']['type'] == link['sys']['linkType']): return i return None
python
def resource_for_link(link, includes, resources=None, locale=None): if resources is not None: cache_key = "{0}:{1}:{2}".format( link['sys']['linkType'], link['sys']['id'], locale ) if cache_key in resources: return resources[cache_key] for i in includes: if (i['sys']['id'] == link['sys']['id'] and i['sys']['type'] == link['sys']['linkType']): return i return None
[ "def", "resource_for_link", "(", "link", ",", "includes", ",", "resources", "=", "None", ",", "locale", "=", "None", ")", ":", "if", "resources", "is", "not", "None", ":", "cache_key", "=", "\"{0}:{1}:{2}\"", ".", "format", "(", "link", "[", "'sys'", "]", "[", "'linkType'", "]", ",", "link", "[", "'sys'", "]", "[", "'id'", "]", ",", "locale", ")", "if", "cache_key", "in", "resources", ":", "return", "resources", "[", "cache_key", "]", "for", "i", "in", "includes", ":", "if", "(", "i", "[", "'sys'", "]", "[", "'id'", "]", "==", "link", "[", "'sys'", "]", "[", "'id'", "]", "and", "i", "[", "'sys'", "]", "[", "'type'", "]", "==", "link", "[", "'sys'", "]", "[", "'linkType'", "]", ")", ":", "return", "i", "return", "None" ]
Returns the resource that matches the link
[ "Returns", "the", "resource", "that", "matches", "the", "link" ]
train
https://github.com/contentful/contentful.py/blob/73fe01d6ae5a1f8818880da65199107b584681dd/contentful/utils.py#L121-L137
phalt/swapi-python
swapi/utils.py
all_resource_urls
def all_resource_urls(query): ''' Get all the URLs for every resource ''' urls = [] next = True while next: response = requests.get(query) json_data = json.loads(response.content) for resource in json_data['results']: urls.append(resource['url']) if bool(json_data['next']): query = json_data['next'] else: next = False return urls
python
def all_resource_urls(query): urls = [] next = True while next: response = requests.get(query) json_data = json.loads(response.content) for resource in json_data['results']: urls.append(resource['url']) if bool(json_data['next']): query = json_data['next'] else: next = False return urls
[ "def", "all_resource_urls", "(", "query", ")", ":", "urls", "=", "[", "]", "next", "=", "True", "while", "next", ":", "response", "=", "requests", ".", "get", "(", "query", ")", "json_data", "=", "json", ".", "loads", "(", "response", ".", "content", ")", "for", "resource", "in", "json_data", "[", "'results'", "]", ":", "urls", ".", "append", "(", "resource", "[", "'url'", "]", ")", "if", "bool", "(", "json_data", "[", "'next'", "]", ")", ":", "query", "=", "json_data", "[", "'next'", "]", "else", ":", "next", "=", "False", "return", "urls" ]
Get all the URLs for every resource
[ "Get", "all", "the", "URLs", "for", "every", "resource" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/utils.py#L17-L30
phalt/swapi-python
swapi/swapi.py
_get
def _get(id, type): ''' Return a single person ''' result = query("{0}/{1}/{2}/".format( settings.BASE_URL, type, str(id)) ) return result
python
def _get(id, type): result = query("{0}/{1}/{2}/".format( settings.BASE_URL, type, str(id)) ) return result
[ "def", "_get", "(", "id", ",", "type", ")", ":", "result", "=", "query", "(", "\"{0}/{1}/{2}/\"", ".", "format", "(", "settings", ".", "BASE_URL", ",", "type", ",", "str", "(", "id", ")", ")", ")", "return", "result" ]
Return a single person
[ "Return", "a", "single", "person" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L36-L43
phalt/swapi-python
swapi/swapi.py
get_all
def get_all(resource): ''' Return all of a single resource ''' QUERYSETS = { settings.PEOPLE: PeopleQuerySet, settings.PLANETS: PlanetQuerySet, settings.STARSHIPS: StarshipQuerySet, settings.VEHICLES: VehicleQuerySet, settings.SPECIES: SpeciesQuerySet, settings.FILMS: FilmQuerySet } urls = all_resource_urls( "{0}/{1}/".format(settings.BASE_URL, resource) ) return QUERYSETS[resource](urls)
python
def get_all(resource): QUERYSETS = { settings.PEOPLE: PeopleQuerySet, settings.PLANETS: PlanetQuerySet, settings.STARSHIPS: StarshipQuerySet, settings.VEHICLES: VehicleQuerySet, settings.SPECIES: SpeciesQuerySet, settings.FILMS: FilmQuerySet } urls = all_resource_urls( "{0}/{1}/".format(settings.BASE_URL, resource) ) return QUERYSETS[resource](urls)
[ "def", "get_all", "(", "resource", ")", ":", "QUERYSETS", "=", "{", "settings", ".", "PEOPLE", ":", "PeopleQuerySet", ",", "settings", ".", "PLANETS", ":", "PlanetQuerySet", ",", "settings", ".", "STARSHIPS", ":", "StarshipQuerySet", ",", "settings", ".", "VEHICLES", ":", "VehicleQuerySet", ",", "settings", ".", "SPECIES", ":", "SpeciesQuerySet", ",", "settings", ".", "FILMS", ":", "FilmQuerySet", "}", "urls", "=", "all_resource_urls", "(", "\"{0}/{1}/\"", ".", "format", "(", "settings", ".", "BASE_URL", ",", "resource", ")", ")", "return", "QUERYSETS", "[", "resource", "]", "(", "urls", ")" ]
Return all of a single resource
[ "Return", "all", "of", "a", "single", "resource" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L46-L61
phalt/swapi-python
swapi/swapi.py
get_planet
def get_planet(planet_id): ''' Return a single planet ''' result = _get(planet_id, settings.PLANETS) return Planet(result.content)
python
def get_planet(planet_id): result = _get(planet_id, settings.PLANETS) return Planet(result.content)
[ "def", "get_planet", "(", "planet_id", ")", ":", "result", "=", "_get", "(", "planet_id", ",", "settings", ".", "PLANETS", ")", "return", "Planet", "(", "result", ".", "content", ")" ]
Return a single planet
[ "Return", "a", "single", "planet" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L64-L67
phalt/swapi-python
swapi/swapi.py
get_person
def get_person(people_id): ''' Return a single person ''' result = _get(people_id, settings.PEOPLE) return People(result.content)
python
def get_person(people_id): result = _get(people_id, settings.PEOPLE) return People(result.content)
[ "def", "get_person", "(", "people_id", ")", ":", "result", "=", "_get", "(", "people_id", ",", "settings", ".", "PEOPLE", ")", "return", "People", "(", "result", ".", "content", ")" ]
Return a single person
[ "Return", "a", "single", "person" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L70-L73
phalt/swapi-python
swapi/swapi.py
get_starship
def get_starship(starship_id): ''' Return a single starship ''' result = _get(starship_id, settings.STARSHIPS) return Starship(result.content)
python
def get_starship(starship_id): result = _get(starship_id, settings.STARSHIPS) return Starship(result.content)
[ "def", "get_starship", "(", "starship_id", ")", ":", "result", "=", "_get", "(", "starship_id", ",", "settings", ".", "STARSHIPS", ")", "return", "Starship", "(", "result", ".", "content", ")" ]
Return a single starship
[ "Return", "a", "single", "starship" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L76-L79
phalt/swapi-python
swapi/swapi.py
get_vehicle
def get_vehicle(vehicle_id): ''' Return a single vehicle ''' result = _get(vehicle_id, settings.VEHICLES) return Vehicle(result.content)
python
def get_vehicle(vehicle_id): result = _get(vehicle_id, settings.VEHICLES) return Vehicle(result.content)
[ "def", "get_vehicle", "(", "vehicle_id", ")", ":", "result", "=", "_get", "(", "vehicle_id", ",", "settings", ".", "VEHICLES", ")", "return", "Vehicle", "(", "result", ".", "content", ")" ]
Return a single vehicle
[ "Return", "a", "single", "vehicle" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L82-L85
phalt/swapi-python
swapi/swapi.py
get_species
def get_species(species_id): ''' Return a single species ''' result = _get(species_id, settings.SPECIES) return Species(result.content)
python
def get_species(species_id): result = _get(species_id, settings.SPECIES) return Species(result.content)
[ "def", "get_species", "(", "species_id", ")", ":", "result", "=", "_get", "(", "species_id", ",", "settings", ".", "SPECIES", ")", "return", "Species", "(", "result", ".", "content", ")" ]
Return a single species
[ "Return", "a", "single", "species" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L88-L91
phalt/swapi-python
swapi/swapi.py
get_film
def get_film(film_id): ''' Return a single film ''' result = _get(film_id, settings.FILMS) return Film(result.content)
python
def get_film(film_id): result = _get(film_id, settings.FILMS) return Film(result.content)
[ "def", "get_film", "(", "film_id", ")", ":", "result", "=", "_get", "(", "film_id", ",", "settings", ".", "FILMS", ")", "return", "Film", "(", "result", ".", "content", ")" ]
Return a single film
[ "Return", "a", "single", "film" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/swapi.py#L94-L97
phalt/swapi-python
swapi/models.py
BaseQuerySet.order_by
def order_by(self, order_attribute): ''' Return the list of items in a certain order ''' to_return = [] for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)): to_return.append(f) return to_return
python
def order_by(self, order_attribute): to_return = [] for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)): to_return.append(f) return to_return
[ "def", "order_by", "(", "self", ",", "order_attribute", ")", ":", "to_return", "=", "[", "]", "for", "f", "in", "sorted", "(", "self", ".", "items", ",", "key", "=", "lambda", "i", ":", "getattr", "(", "i", ",", "order_attribute", ")", ")", ":", "to_return", ".", "append", "(", "f", ")", "return", "to_return" ]
Return the list of items in a certain order
[ "Return", "the", "list", "of", "items", "in", "a", "certain", "order" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/models.py#L24-L29
phalt/swapi-python
swapi/models.py
Film.print_crawl
def print_crawl(self): ''' Print the opening crawl one line at a time ''' print("Star Wars") time.sleep(.5) print("Episode {0}".format(self.episode_id)) time.sleep(.5) print("") time.sleep(.5) print("{0}".format(self.title)) for line in self.gen_opening_crawl(): time.sleep(.5) print(line)
python
def print_crawl(self): print("Star Wars") time.sleep(.5) print("Episode {0}".format(self.episode_id)) time.sleep(.5) print("") time.sleep(.5) print("{0}".format(self.title)) for line in self.gen_opening_crawl(): time.sleep(.5) print(line)
[ "def", "print_crawl", "(", "self", ")", ":", "print", "(", "\"Star Wars\"", ")", "time", ".", "sleep", "(", ".5", ")", "print", "(", "\"Episode {0}\"", ".", "format", "(", "self", ".", "episode_id", ")", ")", "time", ".", "sleep", "(", ".5", ")", "print", "(", "\"\"", ")", "time", ".", "sleep", "(", ".5", ")", "print", "(", "\"{0}\"", ".", "format", "(", "self", ".", "title", ")", ")", "for", "line", "in", "self", ".", "gen_opening_crawl", "(", ")", ":", "time", ".", "sleep", "(", ".5", ")", "print", "(", "line", ")" ]
Print the opening crawl one line at a time
[ "Print", "the", "opening", "crawl", "one", "line", "at", "a", "time" ]
train
https://github.com/phalt/swapi-python/blob/cb9195fc498a1d1fc3b1998d485edc94b8408ca7/swapi/models.py#L135-L146
gccxml/pygccxml
pygccxml/utils/utils.py
is_str
def is_str(string): """ Python 2 and 3 compatible string checker. Args: string (str | basestring): the string to check Returns: bool: True or False """ if sys.version_info[:2] >= (3, 0): return isinstance(string, str) return isinstance(string, basestring)
python
def is_str(string): if sys.version_info[:2] >= (3, 0): return isinstance(string, str) return isinstance(string, basestring)
[ "def", "is_str", "(", "string", ")", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">=", "(", "3", ",", "0", ")", ":", "return", "isinstance", "(", "string", ",", "str", ")", "return", "isinstance", "(", "string", ",", "basestring", ")" ]
Python 2 and 3 compatible string checker. Args: string (str | basestring): the string to check Returns: bool: True or False
[ "Python", "2", "and", "3", "compatible", "string", "checker", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L18-L32
gccxml/pygccxml
pygccxml/utils/utils.py
find_xml_generator
def find_xml_generator(name="castxml"): """ Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. pygccxml does currently only support castxml as c++ parser. """ if sys.version_info[:2] >= (3, 3): path = _find_xml_generator_for_python_greater_equals_33(name) else: path = _find_xml_generator_for_legacy_python(name) if path == "" or path is None: raise Exception("No c++ parser found. Please install castxml.") return path.rstrip(), name
python
def find_xml_generator(name="castxml"): if sys.version_info[:2] >= (3, 3): path = _find_xml_generator_for_python_greater_equals_33(name) else: path = _find_xml_generator_for_legacy_python(name) if path == "" or path is None: raise Exception("No c++ parser found. Please install castxml.") return path.rstrip(), name
[ "def", "find_xml_generator", "(", "name", "=", "\"castxml\"", ")", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", ">=", "(", "3", ",", "3", ")", ":", "path", "=", "_find_xml_generator_for_python_greater_equals_33", "(", "name", ")", "else", ":", "path", "=", "_find_xml_generator_for_legacy_python", "(", "name", ")", "if", "path", "==", "\"\"", "or", "path", "is", "None", ":", "raise", "Exception", "(", "\"No c++ parser found. Please install castxml.\"", ")", "return", "path", ".", "rstrip", "(", ")", ",", "name" ]
Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. pygccxml does currently only support castxml as c++ parser.
[ "Try", "to", "find", "a", "c", "++", "parser", "(", "xml", "generator", ")" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L35-L58
gccxml/pygccxml
pygccxml/utils/utils.py
_create_logger_
def _create_logger_(name): """Implementation detail, creates a logger.""" logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
python
def _create_logger_(name): logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
[ "def", "_create_logger_", "(", "name", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(levelname)s %(message)s'", ")", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "return", "logger" ]
Implementation detail, creates a logger.
[ "Implementation", "detail", "creates", "a", "logger", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L79-L86
gccxml/pygccxml
pygccxml/utils/utils.py
remove_file_no_raise
def remove_file_no_raise(file_name, config): """Removes file from disk if exception is raised.""" # The removal can be disabled by the config for debugging purposes. if config.keep_xml: return True try: if os.path.exists(file_name): os.remove(file_name) except IOError as error: loggers.root.error( "Error occurred while removing temporary created file('%s'): %s", file_name, str(error))
python
def remove_file_no_raise(file_name, config): if config.keep_xml: return True try: if os.path.exists(file_name): os.remove(file_name) except IOError as error: loggers.root.error( "Error occurred while removing temporary created file('%s'): %s", file_name, str(error))
[ "def", "remove_file_no_raise", "(", "file_name", ",", "config", ")", ":", "# The removal can be disabled by the config for debugging purposes.", "if", "config", ".", "keep_xml", ":", "return", "True", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "os", ".", "remove", "(", "file_name", ")", "except", "IOError", "as", "error", ":", "loggers", ".", "root", ".", "error", "(", "\"Error occurred while removing temporary created file('%s'): %s\"", ",", "file_name", ",", "str", "(", "error", ")", ")" ]
Removes file from disk if exception is raised.
[ "Removes", "file", "from", "disk", "if", "exception", "is", "raised", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L150-L162
gccxml/pygccxml
pygccxml/utils/utils.py
create_temp_file_name
def create_temp_file_name(suffix, prefix=None, dir=None, directory=None): """ Small convenience function that creates temporary files. This function is a wrapper around the Python built-in function tempfile.mkstemp. """ if dir is not None: warnings.warn( "The dir argument is deprecated.\n" + "Please use the directory argument instead.", DeprecationWarning) # Deprecated since 1.9.0, will be removed in 2.0.0 directory = dir if not prefix: prefix = tempfile.gettempprefix() fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=directory) file_obj = os.fdopen(fd) file_obj.close() return name
python
def create_temp_file_name(suffix, prefix=None, dir=None, directory=None): if dir is not None: warnings.warn( "The dir argument is deprecated.\n" + "Please use the directory argument instead.", DeprecationWarning) directory = dir if not prefix: prefix = tempfile.gettempprefix() fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=directory) file_obj = os.fdopen(fd) file_obj.close() return name
[ "def", "create_temp_file_name", "(", "suffix", ",", "prefix", "=", "None", ",", "dir", "=", "None", ",", "directory", "=", "None", ")", ":", "if", "dir", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"The dir argument is deprecated.\\n\"", "+", "\"Please use the directory argument instead.\"", ",", "DeprecationWarning", ")", "# Deprecated since 1.9.0, will be removed in 2.0.0", "directory", "=", "dir", "if", "not", "prefix", ":", "prefix", "=", "tempfile", ".", "gettempprefix", "(", ")", "fd", ",", "name", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "directory", ")", "file_obj", "=", "os", ".", "fdopen", "(", "fd", ")", "file_obj", ".", "close", "(", ")", "return", "name" ]
Small convenience function that creates temporary files. This function is a wrapper around the Python built-in function tempfile.mkstemp.
[ "Small", "convenience", "function", "that", "creates", "temporary", "files", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L166-L186
gccxml/pygccxml
pygccxml/utils/utils.py
contains_parent_dir
def contains_parent_dir(fpath, dirs): """ Returns true if paths in dirs start with fpath. Precondition: dirs and fpath should be normalized before calling this function. """ # Note: this function is used nowhere in pygccxml but is used # at least by pypluplus; so it should stay here. return bool([x for x in dirs if _f(fpath, x)])
python
def contains_parent_dir(fpath, dirs): return bool([x for x in dirs if _f(fpath, x)])
[ "def", "contains_parent_dir", "(", "fpath", ",", "dirs", ")", ":", "# Note: this function is used nowhere in pygccxml but is used", "# at least by pypluplus; so it should stay here.", "return", "bool", "(", "[", "x", "for", "x", "in", "dirs", "if", "_f", "(", "fpath", ",", "x", ")", "]", ")" ]
Returns true if paths in dirs start with fpath. Precondition: dirs and fpath should be normalized before calling this function.
[ "Returns", "true", "if", "paths", "in", "dirs", "start", "with", "fpath", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/utils/utils.py#L194-L205
gccxml/pygccxml
pygccxml/declarations/cpptypes.py
free_function_type_t.create_decl_string
def create_decl_string( return_type, arguments_types, with_defaults=True): """ Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t` """ return free_function_type_t.NAME_TEMPLATE % { 'return_type': return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in arguments_types])}
python
def create_decl_string( return_type, arguments_types, with_defaults=True): return free_function_type_t.NAME_TEMPLATE % { 'return_type': return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in arguments_types])}
[ "def", "create_decl_string", "(", "return_type", ",", "arguments_types", ",", "with_defaults", "=", "True", ")", ":", "return", "free_function_type_t", ".", "NAME_TEMPLATE", "%", "{", "'return_type'", ":", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "arguments_types", "]", ")", "}" ]
Returns free function type :param return_type: function return type :type return_type: :class:`type_t` :param arguments_types: list of argument :class:`type <type_t>` :rtype: :class:`free_function_type_t`
[ "Returns", "free", "function", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L696-L711
gccxml/pygccxml
pygccxml/declarations/cpptypes.py
free_function_type_t.create_typedef
def create_typedef(self, typedef_name, unused=None, with_defaults=True): """returns string, that contains valid C++ code, that defines typedef to function type :param name: the desired name of typedef """ return free_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types])}
python
def create_typedef(self, typedef_name, unused=None, with_defaults=True): return free_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types])}
[ "def", "create_typedef", "(", "self", ",", "typedef_name", ",", "unused", "=", "None", ",", "with_defaults", "=", "True", ")", ":", "return", "free_function_type_t", ".", "TYPEDEF_NAME_TEMPLATE", "%", "{", "'typedef_name'", ":", "typedef_name", ",", "'return_type'", ":", "self", ".", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "self", ".", "arguments_types", "]", ")", "}" ]
returns string, that contains valid C++ code, that defines typedef to function type :param name: the desired name of typedef
[ "returns", "string", "that", "contains", "valid", "C", "++", "code", "that", "defines", "typedef", "to", "function", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L728-L739
gccxml/pygccxml
pygccxml/declarations/cpptypes.py
member_function_type_t.create_typedef
def create_typedef( self, typedef_name, class_alias=None, with_defaults=True): """creates typedef to the function type :param typedef_name: desired type name :rtype: string """ has_const_str = '' if self.has_const: has_const_str = 'const' if None is class_alias: if with_defaults: class_alias = self.class_inst.decl_string else: class_alias = self.class_inst.partial_decl_string return member_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'class': class_alias, 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types]), 'has_const': has_const_str}
python
def create_typedef( self, typedef_name, class_alias=None, with_defaults=True): has_const_str = '' if self.has_const: has_const_str = 'const' if None is class_alias: if with_defaults: class_alias = self.class_inst.decl_string else: class_alias = self.class_inst.partial_decl_string return member_function_type_t.TYPEDEF_NAME_TEMPLATE % { 'typedef_name': typedef_name, 'return_type': self.return_type.build_decl_string(with_defaults), 'class': class_alias, 'arguments': ','.join( [_f(x, with_defaults) for x in self.arguments_types]), 'has_const': has_const_str}
[ "def", "create_typedef", "(", "self", ",", "typedef_name", ",", "class_alias", "=", "None", ",", "with_defaults", "=", "True", ")", ":", "has_const_str", "=", "''", "if", "self", ".", "has_const", ":", "has_const_str", "=", "'const'", "if", "None", "is", "class_alias", ":", "if", "with_defaults", ":", "class_alias", "=", "self", ".", "class_inst", ".", "decl_string", "else", ":", "class_alias", "=", "self", ".", "class_inst", ".", "partial_decl_string", "return", "member_function_type_t", ".", "TYPEDEF_NAME_TEMPLATE", "%", "{", "'typedef_name'", ":", "typedef_name", ",", "'return_type'", ":", "self", ".", "return_type", ".", "build_decl_string", "(", "with_defaults", ")", ",", "'class'", ":", "class_alias", ",", "'arguments'", ":", "','", ".", "join", "(", "[", "_f", "(", "x", ",", "with_defaults", ")", "for", "x", "in", "self", ".", "arguments_types", "]", ")", ",", "'has_const'", ":", "has_const_str", "}" ]
creates typedef to the function type :param typedef_name: desired type name :rtype: string
[ "creates", "typedef", "to", "the", "function", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/cpptypes.py#L781-L806
gccxml/pygccxml
pygccxml/parser/__init__.py
parse
def parse( files, config=None, compilation_mode=COMPILATION_MODE.FILE_BY_FILE, cache=None): """ Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`parser.xml_generator_configuration_t` :param compilation_mode: Determines whether the files are parsed individually or as one single chunk :type compilation_mode: :class:`parser.COMPILATION_MODE` :param cache: Declaration cache (None=no cache) :type cache: :class:`parser.cache_base_t` or str :rtype: list of :class:`declarations.declaration_t` """ if not config: config = xml_generator_configuration_t() parser = project_reader_t(config=config, cache=cache) declarations = parser.read_files(files, compilation_mode) config.xml_generator_from_xml_file = parser.xml_generator_from_xml_file return declarations
python
def parse( files, config=None, compilation_mode=COMPILATION_MODE.FILE_BY_FILE, cache=None): if not config: config = xml_generator_configuration_t() parser = project_reader_t(config=config, cache=cache) declarations = parser.read_files(files, compilation_mode) config.xml_generator_from_xml_file = parser.xml_generator_from_xml_file return declarations
[ "def", "parse", "(", "files", ",", "config", "=", "None", ",", "compilation_mode", "=", "COMPILATION_MODE", ".", "FILE_BY_FILE", ",", "cache", "=", "None", ")", ":", "if", "not", "config", ":", "config", "=", "xml_generator_configuration_t", "(", ")", "parser", "=", "project_reader_t", "(", "config", "=", "config", ",", "cache", "=", "cache", ")", "declarations", "=", "parser", ".", "read_files", "(", "files", ",", "compilation_mode", ")", "config", ".", "xml_generator_from_xml_file", "=", "parser", ".", "xml_generator_from_xml_file", "return", "declarations" ]
Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`parser.xml_generator_configuration_t` :param compilation_mode: Determines whether the files are parsed individually or as one single chunk :type compilation_mode: :class:`parser.COMPILATION_MODE` :param cache: Declaration cache (None=no cache) :type cache: :class:`parser.cache_base_t` or str :rtype: list of :class:`declarations.declaration_t`
[ "Parse", "header", "files", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/__init__.py#L29-L53
gccxml/pygccxml
pygccxml/declarations/type_traits.py
__remove_alias
def __remove_alias(type_): """ Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type """ if isinstance(type_, cpptypes.declarated_t) and \ isinstance(type_.declaration, typedef.typedef_t): return __remove_alias(type_.declaration.decl_type) if isinstance(type_, cpptypes.compound_t): type_.base = __remove_alias(type_.base) return type_ return type_
python
def __remove_alias(type_): if isinstance(type_, cpptypes.declarated_t) and \ isinstance(type_.declaration, typedef.typedef_t): return __remove_alias(type_.declaration.decl_type) if isinstance(type_, cpptypes.compound_t): type_.base = __remove_alias(type_.base) return type_ return type_
[ "def", "__remove_alias", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "declarated_t", ")", "and", "isinstance", "(", "type_", ".", "declaration", ",", "typedef", ".", "typedef_t", ")", ":", "return", "__remove_alias", "(", "type_", ".", "declaration", ".", "decl_type", ")", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "compound_t", ")", ":", "type_", ".", "base", "=", "__remove_alias", "(", "type_", ".", "base", ")", "return", "type_", "return", "type_" ]
Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type
[ "Implementation", "detail", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L26-L42
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_alias
def remove_alias(type_): """ Returns `type_t` without typedef Args: type_ (type_t | declaration_t): type or declaration Returns: type_t: the type associated to the inputted declaration """ if isinstance(type_, cpptypes.type_t): type_ref = type_ elif isinstance(type_, typedef.typedef_t): type_ref = type_.decl_type else: # Not a valid input, just return it return type_ if type_ref.cache.remove_alias: return type_ref.cache.remove_alias no_alias = __remove_alias(type_ref.clone()) type_ref.cache.remove_alias = no_alias return no_alias
python
def remove_alias(type_): if isinstance(type_, cpptypes.type_t): type_ref = type_ elif isinstance(type_, typedef.typedef_t): type_ref = type_.decl_type else: return type_ if type_ref.cache.remove_alias: return type_ref.cache.remove_alias no_alias = __remove_alias(type_ref.clone()) type_ref.cache.remove_alias = no_alias return no_alias
[ "def", "remove_alias", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "type_t", ")", ":", "type_ref", "=", "type_", "elif", "isinstance", "(", "type_", ",", "typedef", ".", "typedef_t", ")", ":", "type_ref", "=", "type_", ".", "decl_type", "else", ":", "# Not a valid input, just return it", "return", "type_", "if", "type_ref", ".", "cache", ".", "remove_alias", ":", "return", "type_ref", ".", "cache", ".", "remove_alias", "no_alias", "=", "__remove_alias", "(", "type_ref", ".", "clone", "(", ")", ")", "type_ref", ".", "cache", ".", "remove_alias", "=", "no_alias", "return", "no_alias" ]
Returns `type_t` without typedef Args: type_ (type_t | declaration_t): type or declaration Returns: type_t: the type associated to the inputted declaration
[ "Returns", "type_t", "without", "typedef" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L45-L66
gccxml/pygccxml
pygccxml/declarations/type_traits.py
decompose_type
def decompose_type(tp): """ Implementation detail """ if isinstance(tp, cpptypes.compound_t): return [tp] + decompose_type(tp.base) elif isinstance(tp, typedef.typedef_t): return decompose_type(tp.decl_type) elif isinstance(tp, cpptypes.declarated_t) and \ isinstance(tp.declaration, typedef.typedef_t): return decompose_type(tp.declaration.decl_type) return [tp]
python
def decompose_type(tp): if isinstance(tp, cpptypes.compound_t): return [tp] + decompose_type(tp.base) elif isinstance(tp, typedef.typedef_t): return decompose_type(tp.decl_type) elif isinstance(tp, cpptypes.declarated_t) and \ isinstance(tp.declaration, typedef.typedef_t): return decompose_type(tp.declaration.decl_type) return [tp]
[ "def", "decompose_type", "(", "tp", ")", ":", "if", "isinstance", "(", "tp", ",", "cpptypes", ".", "compound_t", ")", ":", "return", "[", "tp", "]", "+", "decompose_type", "(", "tp", ".", "base", ")", "elif", "isinstance", "(", "tp", ",", "typedef", ".", "typedef_t", ")", ":", "return", "decompose_type", "(", "tp", ".", "decl_type", ")", "elif", "isinstance", "(", "tp", ",", "cpptypes", ".", "declarated_t", ")", "and", "isinstance", "(", "tp", ".", "declaration", ",", "typedef", ".", "typedef_t", ")", ":", "return", "decompose_type", "(", "tp", ".", "declaration", ".", "decl_type", ")", "return", "[", "tp", "]" ]
Implementation detail
[ "Implementation", "detail" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L69-L81
gccxml/pygccxml
pygccxml/declarations/type_traits.py
_create_cv_types
def _create_cv_types(base): """ Implementation detail. """ return ( [base, cpptypes.const_t(base), cpptypes.volatile_t(base), cpptypes.volatile_t(cpptypes.const_t(base))] )
python
def _create_cv_types(base): return ( [base, cpptypes.const_t(base), cpptypes.volatile_t(base), cpptypes.volatile_t(cpptypes.const_t(base))] )
[ "def", "_create_cv_types", "(", "base", ")", ":", "return", "(", "[", "base", ",", "cpptypes", ".", "const_t", "(", "base", ")", ",", "cpptypes", ".", "volatile_t", "(", "base", ")", ",", "cpptypes", ".", "volatile_t", "(", "cpptypes", ".", "const_t", "(", "base", ")", ")", "]", ")" ]
Implementation detail.
[ "Implementation", "detail", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L99-L109
gccxml/pygccxml
pygccxml/declarations/type_traits.py
does_match_definition
def does_match_definition(given, main, secondary): """implementation details""" assert isinstance(secondary, tuple) assert len(secondary) == 2 # general solution could be provided types = decompose_type(given) if isinstance(types[0], main): return True if len(types) >= 2: cond1 = isinstance(types[0], main) cond2 = isinstance(types[1], secondary) cond3 = isinstance(types[1], main) cond4 = isinstance(types[0], secondary) if (cond1 and cond2) or (cond3 and cond4): return True if len(types) >= 3: classes = set([tp.__class__ for tp in types[:3]]) desired = set([main] + list(secondary)) diff = classes.symmetric_difference(desired) if not diff: return True if len(diff) == 2: items = list(diff) return ( issubclass( items[0], items[1]) or issubclass(items[1], items[0])) return False else: return False
python
def does_match_definition(given, main, secondary): assert isinstance(secondary, tuple) assert len(secondary) == 2 types = decompose_type(given) if isinstance(types[0], main): return True if len(types) >= 2: cond1 = isinstance(types[0], main) cond2 = isinstance(types[1], secondary) cond3 = isinstance(types[1], main) cond4 = isinstance(types[0], secondary) if (cond1 and cond2) or (cond3 and cond4): return True if len(types) >= 3: classes = set([tp.__class__ for tp in types[:3]]) desired = set([main] + list(secondary)) diff = classes.symmetric_difference(desired) if not diff: return True if len(diff) == 2: items = list(diff) return ( issubclass( items[0], items[1]) or issubclass(items[1], items[0])) return False else: return False
[ "def", "does_match_definition", "(", "given", ",", "main", ",", "secondary", ")", ":", "assert", "isinstance", "(", "secondary", ",", "tuple", ")", "assert", "len", "(", "secondary", ")", "==", "2", "# general solution could be provided", "types", "=", "decompose_type", "(", "given", ")", "if", "isinstance", "(", "types", "[", "0", "]", ",", "main", ")", ":", "return", "True", "if", "len", "(", "types", ")", ">=", "2", ":", "cond1", "=", "isinstance", "(", "types", "[", "0", "]", ",", "main", ")", "cond2", "=", "isinstance", "(", "types", "[", "1", "]", ",", "secondary", ")", "cond3", "=", "isinstance", "(", "types", "[", "1", "]", ",", "main", ")", "cond4", "=", "isinstance", "(", "types", "[", "0", "]", ",", "secondary", ")", "if", "(", "cond1", "and", "cond2", ")", "or", "(", "cond3", "and", "cond4", ")", ":", "return", "True", "if", "len", "(", "types", ")", ">=", "3", ":", "classes", "=", "set", "(", "[", "tp", ".", "__class__", "for", "tp", "in", "types", "[", ":", "3", "]", "]", ")", "desired", "=", "set", "(", "[", "main", "]", "+", "list", "(", "secondary", ")", ")", "diff", "=", "classes", ".", "symmetric_difference", "(", "desired", ")", "if", "not", "diff", ":", "return", "True", "if", "len", "(", "diff", ")", "==", "2", ":", "items", "=", "list", "(", "diff", ")", "return", "(", "issubclass", "(", "items", "[", "0", "]", ",", "items", "[", "1", "]", ")", "or", "issubclass", "(", "items", "[", "1", "]", ",", "items", "[", "0", "]", ")", ")", "return", "False", "else", ":", "return", "False" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L139-L169
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_pointer
def is_pointer(type_): """returns True, if type represents C++ pointer type, False otherwise""" return does_match_definition(type_, cpptypes.pointer_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition(type_, cpptypes.pointer_t, (cpptypes.volatile_t, cpptypes.const_t))
python
def is_pointer(type_): return does_match_definition(type_, cpptypes.pointer_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition(type_, cpptypes.pointer_t, (cpptypes.volatile_t, cpptypes.const_t))
[ "def", "is_pointer", "(", "type_", ")", ":", "return", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "pointer_t", ",", "(", "cpptypes", ".", "const_t", ",", "cpptypes", ".", "volatile_t", ")", ")", "or", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "pointer_t", ",", "(", "cpptypes", ".", "volatile_t", ",", "cpptypes", ".", "const_t", ")", ")" ]
returns True, if type represents C++ pointer type, False otherwise
[ "returns", "True", "if", "type", "represents", "C", "++", "pointer", "type", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L229-L236
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_calldef_pointer
def is_calldef_pointer(type_): """returns True, if type represents pointer to free/member function, False otherwise""" if not is_pointer(type_): return False nake_type = remove_alias(type_) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.compound_t) \ and isinstance(nake_type.base, cpptypes.calldef_type_t)
python
def is_calldef_pointer(type_): if not is_pointer(type_): return False nake_type = remove_alias(type_) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.compound_t) \ and isinstance(nake_type.base, cpptypes.calldef_type_t)
[ "def", "is_calldef_pointer", "(", "type_", ")", ":", "if", "not", "is_pointer", "(", "type_", ")", ":", "return", "False", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "compound_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "calldef_type_t", ")" ]
returns True, if type represents pointer to free/member function, False otherwise
[ "returns", "True", "if", "type", "represents", "pointer", "to", "free", "/", "member", "function", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L239-L247
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_pointer
def remove_pointer(type_): """removes pointer from the type definition If type is not pointer type, it will be returned as is. """ nake_type = remove_alias(type_) if not is_pointer(nake_type): return type_ elif isinstance(nake_type, cpptypes.volatile_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.volatile_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.const_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.const_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.volatile_t) \ and isinstance(nake_type.base, cpptypes.const_t) \ and isinstance(nake_type.base.base, cpptypes.pointer_t): return ( cpptypes.volatile_t(cpptypes.const_t(nake_type.base.base.base)) ) return nake_type.base
python
def remove_pointer(type_): nake_type = remove_alias(type_) if not is_pointer(nake_type): return type_ elif isinstance(nake_type, cpptypes.volatile_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.volatile_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.const_t) and \ isinstance(nake_type.base, cpptypes.pointer_t): return cpptypes.const_t(nake_type.base.base) elif isinstance(nake_type, cpptypes.volatile_t) \ and isinstance(nake_type.base, cpptypes.const_t) \ and isinstance(nake_type.base.base, cpptypes.pointer_t): return ( cpptypes.volatile_t(cpptypes.const_t(nake_type.base.base.base)) ) return nake_type.base
[ "def", "remove_pointer", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_pointer", "(", "nake_type", ")", ":", "return", "type_", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "cpptypes", ".", "volatile_t", "(", "nake_type", ".", "base", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "cpptypes", ".", "const_t", "(", "nake_type", ".", "base", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ",", "cpptypes", ".", "const_t", ")", "and", "isinstance", "(", "nake_type", ".", "base", ".", "base", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "(", "cpptypes", ".", "volatile_t", "(", "cpptypes", ".", "const_t", "(", "nake_type", ".", "base", ".", "base", ".", "base", ")", ")", ")", "return", "nake_type", ".", "base" ]
removes pointer from the type definition If type is not pointer type, it will be returned as is.
[ "removes", "pointer", "from", "the", "type", "definition" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L250-L271
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_array
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
python
def is_array(type_): nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
[ "def", "is_array", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_reference", "(", "nake_type", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "return", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")" ]
returns True, if type represents C++ array type, False otherwise
[ "returns", "True", "if", "type", "represents", "C", "++", "array", "type", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L280-L285
gccxml/pygccxml
pygccxml/declarations/type_traits.py
array_size
def array_size(type_): """returns array size""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) assert isinstance(nake_type, cpptypes.array_t) return nake_type.size
python
def array_size(type_): nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) assert isinstance(nake_type, cpptypes.array_t) return nake_type.size
[ "def", "array_size", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "nake_type", "=", "remove_reference", "(", "nake_type", ")", "nake_type", "=", "remove_cv", "(", "nake_type", ")", "assert", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", "return", "nake_type", ".", "size" ]
returns array size
[ "returns", "array", "size" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L288-L294
gccxml/pygccxml
pygccxml/declarations/type_traits.py
array_item_type
def array_item_type(type_): """returns array item type""" if is_array(type_): type_ = remove_alias(type_) type_ = remove_cv(type_) return type_.base elif is_pointer(type_): return remove_pointer(type_) else: raise RuntimeError( "array_item_type functions takes as argument array or pointer " + "types")
python
def array_item_type(type_): if is_array(type_): type_ = remove_alias(type_) type_ = remove_cv(type_) return type_.base elif is_pointer(type_): return remove_pointer(type_) else: raise RuntimeError( "array_item_type functions takes as argument array or pointer " + "types")
[ "def", "array_item_type", "(", "type_", ")", ":", "if", "is_array", "(", "type_", ")", ":", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "base", "elif", "is_pointer", "(", "type_", ")", ":", "return", "remove_pointer", "(", "type_", ")", "else", ":", "raise", "RuntimeError", "(", "\"array_item_type functions takes as argument array or pointer \"", "+", "\"types\"", ")" ]
returns array item type
[ "returns", "array", "item", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L297-L308
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_reference
def remove_reference(type_): """removes reference from the type definition If type is not reference type, it will be returned as is. """ nake_type = remove_alias(type_) if not is_reference(nake_type): return type_ return nake_type.base
python
def remove_reference(type_): nake_type = remove_alias(type_) if not is_reference(nake_type): return type_ return nake_type.base
[ "def", "remove_reference", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_reference", "(", "nake_type", ")", ":", "return", "type_", "return", "nake_type", ".", "base" ]
removes reference from the type definition If type is not reference type, it will be returned as is.
[ "removes", "reference", "from", "the", "type", "definition" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L311-L320
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_const
def remove_const(type_): """removes const from the type definition If type is not const type, it will be returned as is """ nake_type = remove_alias(type_) if not is_const(nake_type): return type_ else: # Handling for const and volatile qualified types. There is a # difference in behavior between GCCXML and CastXML for cv-qual arrays. # GCCXML produces the following nesting of types: # -> volatile_t(const_t(array_t)) # while CastXML produces the following nesting: # -> array_t(volatile_t(const_t)) # For both cases, we must unwrap the types, remove const_t, and add # back the outer layers if isinstance(nake_type, cpptypes.array_t): is_v = is_volatile(nake_type) if is_v: result_type = nake_type.base.base.base else: result_type = nake_type.base.base if is_v: result_type = cpptypes.volatile_t(result_type) return cpptypes.array_t(result_type, nake_type.size) elif isinstance(nake_type, cpptypes.volatile_t): return cpptypes.volatile_t(nake_type.base.base) return nake_type.base
python
def remove_const(type_): nake_type = remove_alias(type_) if not is_const(nake_type): return type_ else: if isinstance(nake_type, cpptypes.array_t): is_v = is_volatile(nake_type) if is_v: result_type = nake_type.base.base.base else: result_type = nake_type.base.base if is_v: result_type = cpptypes.volatile_t(result_type) return cpptypes.array_t(result_type, nake_type.size) elif isinstance(nake_type, cpptypes.volatile_t): return cpptypes.volatile_t(nake_type.base.base) return nake_type.base
[ "def", "remove_const", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_const", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "# Handling for const and volatile qualified types. There is a", "# difference in behavior between GCCXML and CastXML for cv-qual arrays.", "# GCCXML produces the following nesting of types:", "# -> volatile_t(const_t(array_t))", "# while CastXML produces the following nesting:", "# -> array_t(volatile_t(const_t))", "# For both cases, we must unwrap the types, remove const_t, and add", "# back the outer layers", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "is_v", "=", "is_volatile", "(", "nake_type", ")", "if", "is_v", ":", "result_type", "=", "nake_type", ".", "base", ".", "base", ".", "base", "else", ":", "result_type", "=", "nake_type", ".", "base", ".", "base", "if", "is_v", ":", "result_type", "=", "cpptypes", ".", "volatile_t", "(", "result_type", ")", "return", "cpptypes", ".", "array_t", "(", "result_type", ",", "nake_type", ".", "size", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "cpptypes", ".", "volatile_t", "(", "nake_type", ".", "base", ".", "base", ")", "return", "nake_type", ".", "base" ]
removes const from the type definition If type is not const type, it will be returned as is
[ "removes", "const", "from", "the", "type", "definition" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L335-L366
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_declarated
def remove_declarated(type_): """removes type-declaration class-binder :class:`declarated_t` from the `type_` If `type_` is not :class:`declarated_t`, it will be returned as is """ type_ = remove_alias(type_) if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base if isinstance(type_, cpptypes.declarated_t): type_ = type_.declaration return type_
python
def remove_declarated(type_): type_ = remove_alias(type_) if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base if isinstance(type_, cpptypes.declarated_t): type_ = type_.declaration return type_
[ "def", "remove_declarated", "(", "type_", ")", ":", "type_", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "elaborated_t", ")", ":", "type_", "=", "type_", ".", "base", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "declarated_t", ")", ":", "type_", "=", "type_", ".", "declaration", "return", "type_" ]
removes type-declaration class-binder :class:`declarated_t` from the `type_` If `type_` is not :class:`declarated_t`, it will be returned as is
[ "removes", "type", "-", "declaration", "class", "-", "binder", ":", "class", ":", "declarated_t", "from", "the", "type_" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L369-L380
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_same
def is_same(type1, type2): """returns True, if type1 and type2 are same types""" nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
python
def is_same(type1, type2): nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
[ "def", "is_same", "(", "type1", ",", "type2", ")", ":", "nake_type1", "=", "remove_declarated", "(", "type1", ")", "nake_type2", "=", "remove_declarated", "(", "type2", ")", "return", "nake_type1", "==", "nake_type2" ]
returns True, if type1 and type2 are same types
[ "returns", "True", "if", "type1", "and", "type2", "are", "same", "types" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L383-L387
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_elaborated
def is_elaborated(type_): """returns True, if type represents C++ elaborated type, False otherwise""" nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.elaborated_t): return True elif isinstance(nake_type, cpptypes.reference_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.pointer_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.volatile_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.const_t): return is_elaborated(nake_type.base) return False
python
def is_elaborated(type_): nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.elaborated_t): return True elif isinstance(nake_type, cpptypes.reference_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.pointer_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.volatile_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.const_t): return is_elaborated(nake_type.base) return False
[ "def", "is_elaborated", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "elaborated_t", ")", ":", "return", "True", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "reference_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "pointer_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", ":", "return", "is_elaborated", "(", "nake_type", ".", "base", ")", "return", "False" ]
returns True, if type represents C++ elaborated type, False otherwise
[ "returns", "True", "if", "type", "represents", "C", "++", "elaborated", "type", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L390-L403
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_elaborated
def remove_elaborated(type_): """removes type-declaration class-binder :class:`elaborated_t` from the `type_` If `type_` is not :class:`elaborated_t`, it will be returned as is """ nake_type = remove_alias(type_) if not is_elaborated(nake_type): return type_ else: if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base return type_
python
def remove_elaborated(type_): nake_type = remove_alias(type_) if not is_elaborated(nake_type): return type_ else: if isinstance(type_, cpptypes.elaborated_t): type_ = type_.base return type_
[ "def", "remove_elaborated", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_elaborated", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "elaborated_t", ")", ":", "type_", "=", "type_", ".", "base", "return", "type_" ]
removes type-declaration class-binder :class:`elaborated_t` from the `type_` If `type_` is not :class:`elaborated_t`, it will be returned as is
[ "removes", "type", "-", "declaration", "class", "-", "binder", ":", "class", ":", "elaborated_t", "from", "the", "type_" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L406-L418
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_volatile
def is_volatile(type_): """returns True, if type represents C++ volatile type, False otherwise""" nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.volatile_t): return True elif isinstance(nake_type, cpptypes.const_t): return is_volatile(nake_type.base) elif isinstance(nake_type, cpptypes.array_t): return is_volatile(nake_type.base) return False
python
def is_volatile(type_): nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.volatile_t): return True elif isinstance(nake_type, cpptypes.const_t): return is_volatile(nake_type.base) elif isinstance(nake_type, cpptypes.array_t): return is_volatile(nake_type.base) return False
[ "def", "is_volatile", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "volatile_t", ")", ":", "return", "True", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "const_t", ")", ":", "return", "is_volatile", "(", "nake_type", ".", "base", ")", "elif", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "return", "is_volatile", "(", "nake_type", ".", "base", ")", "return", "False" ]
returns True, if type represents C++ volatile type, False otherwise
[ "returns", "True", "if", "type", "represents", "C", "++", "volatile", "type", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L421-L430
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_volatile
def remove_volatile(type_): """removes volatile from the type definition If type is not volatile type, it will be returned as is """ nake_type = remove_alias(type_) if not is_volatile(nake_type): return type_ else: if isinstance(nake_type, cpptypes.array_t): is_c = is_const(nake_type) if is_c: base_type_ = nake_type.base.base.base else: base_type_ = nake_type.base.base result_type = base_type_ if is_c: result_type = cpptypes.const_t(result_type) return cpptypes.array_t(result_type, nake_type.size) return nake_type.base
python
def remove_volatile(type_): nake_type = remove_alias(type_) if not is_volatile(nake_type): return type_ else: if isinstance(nake_type, cpptypes.array_t): is_c = is_const(nake_type) if is_c: base_type_ = nake_type.base.base.base else: base_type_ = nake_type.base.base result_type = base_type_ if is_c: result_type = cpptypes.const_t(result_type) return cpptypes.array_t(result_type, nake_type.size) return nake_type.base
[ "def", "remove_volatile", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_volatile", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "if", "isinstance", "(", "nake_type", ",", "cpptypes", ".", "array_t", ")", ":", "is_c", "=", "is_const", "(", "nake_type", ")", "if", "is_c", ":", "base_type_", "=", "nake_type", ".", "base", ".", "base", ".", "base", "else", ":", "base_type_", "=", "nake_type", ".", "base", ".", "base", "result_type", "=", "base_type_", "if", "is_c", ":", "result_type", "=", "cpptypes", ".", "const_t", "(", "result_type", ")", "return", "cpptypes", ".", "array_t", "(", "result_type", ",", "nake_type", ".", "size", ")", "return", "nake_type", ".", "base" ]
removes volatile from the type definition If type is not volatile type, it will be returned as is
[ "removes", "volatile", "from", "the", "type", "definition" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L433-L452
gccxml/pygccxml
pygccxml/declarations/type_traits.py
remove_cv
def remove_cv(type_): """removes const and volatile from the type definition""" nake_type = remove_alias(type_) if not is_const(nake_type) and not is_volatile(nake_type): return type_ result = nake_type if is_const(result): result = remove_const(result) if is_volatile(result): result = remove_volatile(result) if is_const(result): result = remove_const(result) return result
python
def remove_cv(type_): nake_type = remove_alias(type_) if not is_const(nake_type) and not is_volatile(nake_type): return type_ result = nake_type if is_const(result): result = remove_const(result) if is_volatile(result): result = remove_volatile(result) if is_const(result): result = remove_const(result) return result
[ "def", "remove_cv", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_const", "(", "nake_type", ")", "and", "not", "is_volatile", "(", "nake_type", ")", ":", "return", "type_", "result", "=", "nake_type", "if", "is_const", "(", "result", ")", ":", "result", "=", "remove_const", "(", "result", ")", "if", "is_volatile", "(", "result", ")", ":", "result", "=", "remove_volatile", "(", "result", ")", "if", "is_const", "(", "result", ")", ":", "result", "=", "remove_const", "(", "result", ")", "return", "result" ]
removes const and volatile from the type definition
[ "removes", "const", "and", "volatile", "from", "the", "type", "definition" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L455-L468
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_fundamental
def is_fundamental(type_): """returns True, if type represents C++ fundamental type""" return does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.volatile_t, cpptypes.const_t))
python
def is_fundamental(type_): return does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.volatile_t, cpptypes.const_t))
[ "def", "is_fundamental", "(", "type_", ")", ":", "return", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "fundamental_t", ",", "(", "cpptypes", ".", "const_t", ",", "cpptypes", ".", "volatile_t", ")", ")", "or", "does_match_definition", "(", "type_", ",", "cpptypes", ".", "fundamental_t", ",", "(", "cpptypes", ".", "volatile_t", ",", "cpptypes", ".", "const_t", ")", ")" ]
returns True, if type represents C++ fundamental type
[ "returns", "True", "if", "type", "represents", "C", "++", "fundamental", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L471-L480
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_std_string
def is_std_string(type_): """ Returns True, if type represents C++ `std::string`, False otherwise. """ if utils.is_str(type_): return type_ in string_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in string_equivalences
python
def is_std_string(type_): if utils.is_str(type_): return type_ in string_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in string_equivalences
[ "def", "is_std_string", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "string_equivalences", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "string_equivalences" ]
Returns True, if type represents C++ `std::string`, False otherwise.
[ "Returns", "True", "if", "type", "represents", "C", "++", "std", "::", "string", "False", "otherwise", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L512-L524
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_std_wstring
def is_std_wstring(type_): """ Returns True, if type represents C++ `std::wstring`, False otherwise. """ if utils.is_str(type_): return type_ in wstring_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wstring_equivalences
python
def is_std_wstring(type_): if utils.is_str(type_): return type_ in wstring_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wstring_equivalences
[ "def", "is_std_wstring", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "wstring_equivalences", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "wstring_equivalences" ]
Returns True, if type represents C++ `std::wstring`, False otherwise.
[ "Returns", "True", "if", "type", "represents", "C", "++", "std", "::", "wstring", "False", "otherwise", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L527-L539
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_std_ostream
def is_std_ostream(type_): """ Returns True, if type represents C++ std::ostream, False otherwise. """ if utils.is_str(type_): return type_ in ostream_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in ostream_equivalences
python
def is_std_ostream(type_): if utils.is_str(type_): return type_ in ostream_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in ostream_equivalences
[ "def", "is_std_ostream", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "ostream_equivalences", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "ostream_equivalences" ]
Returns True, if type represents C++ std::ostream, False otherwise.
[ "Returns", "True", "if", "type", "represents", "C", "++", "std", "::", "ostream", "False", "otherwise", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L542-L554
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_std_wostream
def is_std_wostream(type_): """ Returns True, if type represents C++ std::wostream, False otherwise. """ if utils.is_str(type_): return type_ in wostream_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wostream_equivalences
python
def is_std_wostream(type_): if utils.is_str(type_): return type_ in wostream_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in wostream_equivalences
[ "def", "is_std_wostream", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "wostream_equivalences", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", "type_", "=", "remove_cv", "(", "type_", ")", "return", "type_", ".", "decl_string", "in", "wostream_equivalences" ]
Returns True, if type represents C++ std::wostream, False otherwise.
[ "Returns", "True", "if", "type", "represents", "C", "++", "std", "::", "wostream", "False", "otherwise", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L557-L569
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.has_pattern
def has_pattern(self, decl_string): """ Implementation detail """ if self.__begin == "<": # Cleanup parentheses blocks before checking for the pattern # See also the args() method (in this file) for more explanations. decl_string = re.sub("\\s\\(.*?\\)", "", decl_string).strip() last_part = decl_string.split('::')[-1] return ( decl_string.find(self.__begin) != -1 and last_part.find(self.__end) != -1 )
python
def has_pattern(self, decl_string): if self.__begin == "<": decl_string = re.sub("\\s\\(.*?\\)", "", decl_string).strip() last_part = decl_string.split('::')[-1] return ( decl_string.find(self.__begin) != -1 and last_part.find(self.__end) != -1 )
[ "def", "has_pattern", "(", "self", ",", "decl_string", ")", ":", "if", "self", ".", "__begin", "==", "\"<\"", ":", "# Cleanup parentheses blocks before checking for the pattern", "# See also the args() method (in this file) for more explanations.", "decl_string", "=", "re", ".", "sub", "(", "\"\\\\s\\\\(.*?\\\\)\"", ",", "\"\"", ",", "decl_string", ")", ".", "strip", "(", ")", "last_part", "=", "decl_string", ".", "split", "(", "'::'", ")", "[", "-", "1", "]", "return", "(", "decl_string", ".", "find", "(", "self", ".", "__begin", ")", "!=", "-", "1", "and", "last_part", ".", "find", "(", "self", ".", "__end", ")", "!=", "-", "1", ")" ]
Implementation detail
[ "Implementation", "detail" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L32-L46
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.name
def name(self, decl_string): """implementation details""" if not self.has_pattern(decl_string): return decl_string args_begin = decl_string.find(self.__begin) return decl_string[0: args_begin].strip()
python
def name(self, decl_string): if not self.has_pattern(decl_string): return decl_string args_begin = decl_string.find(self.__begin) return decl_string[0: args_begin].strip()
[ "def", "name", "(", "self", ",", "decl_string", ")", ":", "if", "not", "self", ".", "has_pattern", "(", "decl_string", ")", ":", "return", "decl_string", "args_begin", "=", "decl_string", ".", "find", "(", "self", ".", "__begin", ")", "return", "decl_string", "[", "0", ":", "args_begin", "]", ".", "strip", "(", ")" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L48-L53
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.__find_args_separator
def __find_args_separator(self, decl_string, start_pos): """implementation details""" bracket_depth = 0 for index, ch in enumerate(decl_string[start_pos:]): if ch not in (self.__begin, self.__end, self.__separator): continue # I am interested only in < and > elif self.__separator == ch: if not bracket_depth: return index + start_pos elif self.__begin == ch: bracket_depth += 1 elif not bracket_depth: return index + start_pos else: bracket_depth -= 1 return -1
python
def __find_args_separator(self, decl_string, start_pos): bracket_depth = 0 for index, ch in enumerate(decl_string[start_pos:]): if ch not in (self.__begin, self.__end, self.__separator): continue elif self.__separator == ch: if not bracket_depth: return index + start_pos elif self.__begin == ch: bracket_depth += 1 elif not bracket_depth: return index + start_pos else: bracket_depth -= 1 return -1
[ "def", "__find_args_separator", "(", "self", ",", "decl_string", ",", "start_pos", ")", ":", "bracket_depth", "=", "0", "for", "index", ",", "ch", "in", "enumerate", "(", "decl_string", "[", "start_pos", ":", "]", ")", ":", "if", "ch", "not", "in", "(", "self", ".", "__begin", ",", "self", ".", "__end", ",", "self", ".", "__separator", ")", ":", "continue", "# I am interested only in < and >", "elif", "self", ".", "__separator", "==", "ch", ":", "if", "not", "bracket_depth", ":", "return", "index", "+", "start_pos", "elif", "self", ".", "__begin", "==", "ch", ":", "bracket_depth", "+=", "1", "elif", "not", "bracket_depth", ":", "return", "index", "+", "start_pos", "else", ":", "bracket_depth", "-=", "1", "return", "-", "1" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L55-L70
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.args
def args(self, decl_string): """ Extracts a list of arguments from the provided declaration string. Implementation detail. Example usages: Input: myClass<std::vector<int>, std::vector<double>> Output: [std::vector<int>, std::vector<double>] Args: decl_string (str): the full declaration string Returns: list: list of arguments as strings """ args_begin = decl_string.find(self.__begin) args_end = decl_string.rfind(self.__end) if -1 in (args_begin, args_end) or args_begin == args_end: raise RuntimeError( "%s doesn't validate template instantiation string" % decl_string) args_only = decl_string[args_begin + 1: args_end].strip() # The list of arguments to be returned args = [] parentheses_blocks = [] prev_span = 0 if self.__begin == "<": # In case where we are splitting template names, there # can be parentheses blocks (for arguments) that need to be taken # care of. # Build a regex matching a space (\s) # + something inside parentheses regex = re.compile("\\s\\(.*?\\)") for m in regex.finditer(args_only): # Store the position and the content parentheses_blocks.append([m.start() - prev_span, m.group()]) prev_span = m.end() - m.start() # Cleanup the args_only string by removing the parentheses and # their content. args_only = args_only.replace(m.group(), "") # Now we are trying to split the args_only string in multiple arguments previous_found, found = 0, 0 while True: found = self.__find_args_separator(args_only, previous_found) if found == -1: args.append(args_only[previous_found:].strip()) # This is the last argument. Break out of the loop. break else: args.append(args_only[previous_found: found].strip()) previous_found = found + 1 # skip found separator # Get the size and position for each argument absolute_pos_list = [] absolute_pos = 0 for arg in args: absolute_pos += len(arg) absolute_pos_list.append(absolute_pos) for item in parentheses_blocks: # In case where there are parentheses blocks we add them back # to the right argument parentheses_block_absolute_pos = item[0] parentheses_block_string = item[1] current_arg_absolute_pos = 0 for arg_index, arg_absolute_pos in enumerate(absolute_pos_list): current_arg_absolute_pos += arg_absolute_pos if current_arg_absolute_pos >= parentheses_block_absolute_pos: # Add the parentheses block back and break out of the loop. args[arg_index] += parentheses_block_string break return args
python
def args(self, decl_string): args_begin = decl_string.find(self.__begin) args_end = decl_string.rfind(self.__end) if -1 in (args_begin, args_end) or args_begin == args_end: raise RuntimeError( "%s doesn't validate template instantiation string" % decl_string) args_only = decl_string[args_begin + 1: args_end].strip() args = [] parentheses_blocks = [] prev_span = 0 if self.__begin == "<": regex = re.compile("\\s\\(.*?\\)") for m in regex.finditer(args_only): parentheses_blocks.append([m.start() - prev_span, m.group()]) prev_span = m.end() - m.start() args_only = args_only.replace(m.group(), "") previous_found, found = 0, 0 while True: found = self.__find_args_separator(args_only, previous_found) if found == -1: args.append(args_only[previous_found:].strip()) break else: args.append(args_only[previous_found: found].strip()) previous_found = found + 1 absolute_pos_list = [] absolute_pos = 0 for arg in args: absolute_pos += len(arg) absolute_pos_list.append(absolute_pos) for item in parentheses_blocks: parentheses_block_absolute_pos = item[0] parentheses_block_string = item[1] current_arg_absolute_pos = 0 for arg_index, arg_absolute_pos in enumerate(absolute_pos_list): current_arg_absolute_pos += arg_absolute_pos if current_arg_absolute_pos >= parentheses_block_absolute_pos: args[arg_index] += parentheses_block_string break return args
[ "def", "args", "(", "self", ",", "decl_string", ")", ":", "args_begin", "=", "decl_string", ".", "find", "(", "self", ".", "__begin", ")", "args_end", "=", "decl_string", ".", "rfind", "(", "self", ".", "__end", ")", "if", "-", "1", "in", "(", "args_begin", ",", "args_end", ")", "or", "args_begin", "==", "args_end", ":", "raise", "RuntimeError", "(", "\"%s doesn't validate template instantiation string\"", "%", "decl_string", ")", "args_only", "=", "decl_string", "[", "args_begin", "+", "1", ":", "args_end", "]", ".", "strip", "(", ")", "# The list of arguments to be returned", "args", "=", "[", "]", "parentheses_blocks", "=", "[", "]", "prev_span", "=", "0", "if", "self", ".", "__begin", "==", "\"<\"", ":", "# In case where we are splitting template names, there", "# can be parentheses blocks (for arguments) that need to be taken", "# care of.", "# Build a regex matching a space (\\s)", "# + something inside parentheses", "regex", "=", "re", ".", "compile", "(", "\"\\\\s\\\\(.*?\\\\)\"", ")", "for", "m", "in", "regex", ".", "finditer", "(", "args_only", ")", ":", "# Store the position and the content", "parentheses_blocks", ".", "append", "(", "[", "m", ".", "start", "(", ")", "-", "prev_span", ",", "m", ".", "group", "(", ")", "]", ")", "prev_span", "=", "m", ".", "end", "(", ")", "-", "m", ".", "start", "(", ")", "# Cleanup the args_only string by removing the parentheses and", "# their content.", "args_only", "=", "args_only", ".", "replace", "(", "m", ".", "group", "(", ")", ",", "\"\"", ")", "# Now we are trying to split the args_only string in multiple arguments", "previous_found", ",", "found", "=", "0", ",", "0", "while", "True", ":", "found", "=", "self", ".", "__find_args_separator", "(", "args_only", ",", "previous_found", ")", "if", "found", "==", "-", "1", ":", "args", ".", "append", "(", "args_only", "[", "previous_found", ":", "]", ".", "strip", "(", ")", ")", "# This is the last argument. Break out of the loop.", "break", "else", ":", "args", ".", "append", "(", "args_only", "[", "previous_found", ":", "found", "]", ".", "strip", "(", ")", ")", "previous_found", "=", "found", "+", "1", "# skip found separator", "# Get the size and position for each argument", "absolute_pos_list", "=", "[", "]", "absolute_pos", "=", "0", "for", "arg", "in", "args", ":", "absolute_pos", "+=", "len", "(", "arg", ")", "absolute_pos_list", ".", "append", "(", "absolute_pos", ")", "for", "item", "in", "parentheses_blocks", ":", "# In case where there are parentheses blocks we add them back", "# to the right argument", "parentheses_block_absolute_pos", "=", "item", "[", "0", "]", "parentheses_block_string", "=", "item", "[", "1", "]", "current_arg_absolute_pos", "=", "0", "for", "arg_index", ",", "arg_absolute_pos", "in", "enumerate", "(", "absolute_pos_list", ")", ":", "current_arg_absolute_pos", "+=", "arg_absolute_pos", "if", "current_arg_absolute_pos", ">=", "parentheses_block_absolute_pos", ":", "# Add the parentheses block back and break out of the loop.", "args", "[", "arg_index", "]", "+=", "parentheses_block_string", "break", "return", "args" ]
Extracts a list of arguments from the provided declaration string. Implementation detail. Example usages: Input: myClass<std::vector<int>, std::vector<double>> Output: [std::vector<int>, std::vector<double>] Args: decl_string (str): the full declaration string Returns: list: list of arguments as strings
[ "Extracts", "a", "list", "of", "arguments", "from", "the", "provided", "declaration", "string", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L72-L150
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.find_args
def find_args(self, text, start=None): """implementation details""" if start is None: start = 0 first_occurance = text.find(self.__begin, start) if first_occurance == -1: return self.NOT_FOUND previous_found, found = first_occurance + 1, 0 while True: found = self.__find_args_separator(text, previous_found) if found == -1: return self.NOT_FOUND elif text[found] == self.__end: return first_occurance, found else: previous_found = found + 1
python
def find_args(self, text, start=None): if start is None: start = 0 first_occurance = text.find(self.__begin, start) if first_occurance == -1: return self.NOT_FOUND previous_found, found = first_occurance + 1, 0 while True: found = self.__find_args_separator(text, previous_found) if found == -1: return self.NOT_FOUND elif text[found] == self.__end: return first_occurance, found else: previous_found = found + 1
[ "def", "find_args", "(", "self", ",", "text", ",", "start", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "0", "first_occurance", "=", "text", ".", "find", "(", "self", ".", "__begin", ",", "start", ")", "if", "first_occurance", "==", "-", "1", ":", "return", "self", ".", "NOT_FOUND", "previous_found", ",", "found", "=", "first_occurance", "+", "1", ",", "0", "while", "True", ":", "found", "=", "self", ".", "__find_args_separator", "(", "text", ",", "previous_found", ")", "if", "found", "==", "-", "1", ":", "return", "self", ".", "NOT_FOUND", "elif", "text", "[", "found", "]", "==", "self", ".", "__end", ":", "return", "first_occurance", ",", "found", "else", ":", "previous_found", "=", "found", "+", "1" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L155-L170
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.split
def split(self, decl_string): """implementation details""" assert self.has_pattern(decl_string) return self.name(decl_string), self.args(decl_string)
python
def split(self, decl_string): assert self.has_pattern(decl_string) return self.name(decl_string), self.args(decl_string)
[ "def", "split", "(", "self", ",", "decl_string", ")", ":", "assert", "self", ".", "has_pattern", "(", "decl_string", ")", "return", "self", ".", "name", "(", "decl_string", ")", ",", "self", ".", "args", "(", "decl_string", ")" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L172-L175
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.split_recursive
def split_recursive(self, decl_string): """implementation details""" assert self.has_pattern(decl_string) to_go = [decl_string] while to_go: name, args = self.split(to_go.pop()) for arg in args: if self.has_pattern(arg): to_go.append(arg) yield name, args
python
def split_recursive(self, decl_string): assert self.has_pattern(decl_string) to_go = [decl_string] while to_go: name, args = self.split(to_go.pop()) for arg in args: if self.has_pattern(arg): to_go.append(arg) yield name, args
[ "def", "split_recursive", "(", "self", ",", "decl_string", ")", ":", "assert", "self", ".", "has_pattern", "(", "decl_string", ")", "to_go", "=", "[", "decl_string", "]", "while", "to_go", ":", "name", ",", "args", "=", "self", ".", "split", "(", "to_go", ".", "pop", "(", ")", ")", "for", "arg", "in", "args", ":", "if", "self", ".", "has_pattern", "(", "arg", ")", ":", "to_go", ".", "append", "(", "arg", ")", "yield", "name", ",", "args" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L177-L186
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.join
def join(self, name, args, arg_separator=None): """implementation details""" if None is arg_separator: arg_separator = ', ' args = [_f for _f in args if _f] if not args: args_str = ' ' elif len(args) == 1: args_str = ' ' + args[0] + ' ' else: args_str = ' ' + arg_separator.join(args) + ' ' return ''.join([name, self.__begin, args_str, self.__end])
python
def join(self, name, args, arg_separator=None): if None is arg_separator: arg_separator = ', ' args = [_f for _f in args if _f] if not args: args_str = ' ' elif len(args) == 1: args_str = ' ' + args[0] + ' ' else: args_str = ' ' + arg_separator.join(args) + ' ' return ''.join([name, self.__begin, args_str, self.__end])
[ "def", "join", "(", "self", ",", "name", ",", "args", ",", "arg_separator", "=", "None", ")", ":", "if", "None", "is", "arg_separator", ":", "arg_separator", "=", "', '", "args", "=", "[", "_f", "for", "_f", "in", "args", "if", "_f", "]", "if", "not", "args", ":", "args_str", "=", "' '", "elif", "len", "(", "args", ")", "==", "1", ":", "args_str", "=", "' '", "+", "args", "[", "0", "]", "+", "' '", "else", ":", "args_str", "=", "' '", "+", "arg_separator", ".", "join", "(", "args", ")", "+", "' '", "return", "''", ".", "join", "(", "[", "name", ",", "self", ".", "__begin", ",", "args_str", ",", "self", ".", "__end", "]", ")" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L188-L201
gccxml/pygccxml
pygccxml/declarations/pattern_parser.py
parser_t.normalize
def normalize(self, decl_string, arg_separator=None): """implementation details""" if not self.has_pattern(decl_string): return decl_string name, args = self.split(decl_string) for i, arg in enumerate(args): args[i] = self.normalize(arg) return self.join(name, args, arg_separator)
python
def normalize(self, decl_string, arg_separator=None): if not self.has_pattern(decl_string): return decl_string name, args = self.split(decl_string) for i, arg in enumerate(args): args[i] = self.normalize(arg) return self.join(name, args, arg_separator)
[ "def", "normalize", "(", "self", ",", "decl_string", ",", "arg_separator", "=", "None", ")", ":", "if", "not", "self", ".", "has_pattern", "(", "decl_string", ")", ":", "return", "decl_string", "name", ",", "args", "=", "self", ".", "split", "(", "decl_string", ")", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "args", "[", "i", "]", "=", "self", ".", "normalize", "(", "arg", ")", "return", "self", ".", "join", "(", "name", ",", "args", ",", "arg_separator", ")" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pattern_parser.py#L203-L210
gccxml/pygccxml
pygccxml/declarations/has_operator_matcher.py
has_public_binary_operator
def has_public_binary_operator(type_, operator_symbol): """returns True, if `type_` has public binary operator, otherwise False""" type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) type_ = type_traits.remove_declarated(type_) assert isinstance(type_, class_declaration.class_t) if type_traits.is_std_string(type_) or type_traits.is_std_wstring(type_): # In some case compare operators of std::basic_string are not # instantiated return True operators = type_.member_operators( function=matchers.custom_matcher_t( lambda decl: not decl.is_artificial) & matchers.access_type_matcher_t('public'), symbol=operator_symbol, allow_empty=True, recursive=False) if operators: return True declarated = cpptypes.declarated_t(type_) const = cpptypes.const_t(declarated) reference = cpptypes.reference_t(const) operators = type_.top_parent.operators( function=lambda decl: not decl.is_artificial, arg_types=[reference, None], symbol=operator_symbol, allow_empty=True, recursive=True) if operators: return True for bi in type_.recursive_bases: assert isinstance(bi, class_declaration.hierarchy_info_t) if bi.access_type != class_declaration.ACCESS_TYPES.PUBLIC: continue operators = bi.related_class.member_operators( function=matchers.custom_matcher_t( lambda decl: not decl.is_artificial) & matchers.access_type_matcher_t('public'), symbol=operator_symbol, allow_empty=True, recursive=False) if operators: return True return False
python
def has_public_binary_operator(type_, operator_symbol): type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) type_ = type_traits.remove_declarated(type_) assert isinstance(type_, class_declaration.class_t) if type_traits.is_std_string(type_) or type_traits.is_std_wstring(type_): return True operators = type_.member_operators( function=matchers.custom_matcher_t( lambda decl: not decl.is_artificial) & matchers.access_type_matcher_t('public'), symbol=operator_symbol, allow_empty=True, recursive=False) if operators: return True declarated = cpptypes.declarated_t(type_) const = cpptypes.const_t(declarated) reference = cpptypes.reference_t(const) operators = type_.top_parent.operators( function=lambda decl: not decl.is_artificial, arg_types=[reference, None], symbol=operator_symbol, allow_empty=True, recursive=True) if operators: return True for bi in type_.recursive_bases: assert isinstance(bi, class_declaration.hierarchy_info_t) if bi.access_type != class_declaration.ACCESS_TYPES.PUBLIC: continue operators = bi.related_class.member_operators( function=matchers.custom_matcher_t( lambda decl: not decl.is_artificial) & matchers.access_type_matcher_t('public'), symbol=operator_symbol, allow_empty=True, recursive=False) if operators: return True return False
[ "def", "has_public_binary_operator", "(", "type_", ",", "operator_symbol", ")", ":", "type_", "=", "type_traits", ".", "remove_alias", "(", "type_", ")", "type_", "=", "type_traits", ".", "remove_cv", "(", "type_", ")", "type_", "=", "type_traits", ".", "remove_declarated", "(", "type_", ")", "assert", "isinstance", "(", "type_", ",", "class_declaration", ".", "class_t", ")", "if", "type_traits", ".", "is_std_string", "(", "type_", ")", "or", "type_traits", ".", "is_std_wstring", "(", "type_", ")", ":", "# In some case compare operators of std::basic_string are not", "# instantiated", "return", "True", "operators", "=", "type_", ".", "member_operators", "(", "function", "=", "matchers", ".", "custom_matcher_t", "(", "lambda", "decl", ":", "not", "decl", ".", "is_artificial", ")", "&", "matchers", ".", "access_type_matcher_t", "(", "'public'", ")", ",", "symbol", "=", "operator_symbol", ",", "allow_empty", "=", "True", ",", "recursive", "=", "False", ")", "if", "operators", ":", "return", "True", "declarated", "=", "cpptypes", ".", "declarated_t", "(", "type_", ")", "const", "=", "cpptypes", ".", "const_t", "(", "declarated", ")", "reference", "=", "cpptypes", ".", "reference_t", "(", "const", ")", "operators", "=", "type_", ".", "top_parent", ".", "operators", "(", "function", "=", "lambda", "decl", ":", "not", "decl", ".", "is_artificial", ",", "arg_types", "=", "[", "reference", ",", "None", "]", ",", "symbol", "=", "operator_symbol", ",", "allow_empty", "=", "True", ",", "recursive", "=", "True", ")", "if", "operators", ":", "return", "True", "for", "bi", "in", "type_", ".", "recursive_bases", ":", "assert", "isinstance", "(", "bi", ",", "class_declaration", ".", "hierarchy_info_t", ")", "if", "bi", ".", "access_type", "!=", "class_declaration", ".", "ACCESS_TYPES", ".", "PUBLIC", ":", "continue", "operators", "=", "bi", ".", "related_class", ".", "member_operators", "(", "function", "=", "matchers", ".", "custom_matcher_t", "(", "lambda", "decl", ":", "not", "decl", ".", "is_artificial", ")", "&", "matchers", ".", "access_type_matcher_t", "(", "'public'", ")", ",", "symbol", "=", "operator_symbol", ",", "allow_empty", "=", "True", ",", "recursive", "=", "False", ")", "if", "operators", ":", "return", "True", "return", "False" ]
returns True, if `type_` has public binary operator, otherwise False
[ "returns", "True", "if", "type_", "has", "public", "binary", "operator", "otherwise", "False" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/has_operator_matcher.py#L7-L49
gccxml/pygccxml
pygccxml/declarations/pointer_traits.py
_search_in_bases
def _search_in_bases(type_): """Implementation detail.""" found = False for base_type in type_.declaration.bases: try: found = internal_type_traits.get_by_name( base_type.related_class, "element_type") except runtime_errors.declaration_not_found_t: pass if found: return found raise RuntimeError( ("Unable to find 'element_type' declaration '%s'" "in type '%s'.") % type_.decl_string)
python
def _search_in_bases(type_): found = False for base_type in type_.declaration.bases: try: found = internal_type_traits.get_by_name( base_type.related_class, "element_type") except runtime_errors.declaration_not_found_t: pass if found: return found raise RuntimeError( ("Unable to find 'element_type' declaration '%s'" "in type '%s'.") % type_.decl_string)
[ "def", "_search_in_bases", "(", "type_", ")", ":", "found", "=", "False", "for", "base_type", "in", "type_", ".", "declaration", ".", "bases", ":", "try", ":", "found", "=", "internal_type_traits", ".", "get_by_name", "(", "base_type", ".", "related_class", ",", "\"element_type\"", ")", "except", "runtime_errors", ".", "declaration_not_found_t", ":", "pass", "if", "found", ":", "return", "found", "raise", "RuntimeError", "(", "(", "\"Unable to find 'element_type' declaration '%s'\"", "\"in type '%s'.\"", ")", "%", "type_", ".", "decl_string", ")" ]
Implementation detail.
[ "Implementation", "detail", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pointer_traits.py#L116-L129
gccxml/pygccxml
pygccxml/declarations/pointer_traits.py
smart_pointer_traits.is_smart_pointer
def is_smart_pointer(type_): """returns True, if type represents instantiation of `boost::shared_ptr` or `std::shared_ptr`, False otherwise""" type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) type_ = type_traits.remove_declarated(type_) if not isinstance(type_, (class_declaration.class_declaration_t, class_declaration.class_t)): return False if not ( traits_impl_details.impl_details.is_defined_in_xxx( 'boost', type_) or traits_impl_details.impl_details.is_defined_in_xxx( 'std', type_)): return False return type_.decl_string.startswith('::boost::shared_ptr<') or \ type_.decl_string.startswith('::std::shared_ptr<')
python
def is_smart_pointer(type_): type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) type_ = type_traits.remove_declarated(type_) if not isinstance(type_, (class_declaration.class_declaration_t, class_declaration.class_t)): return False if not ( traits_impl_details.impl_details.is_defined_in_xxx( 'boost', type_) or traits_impl_details.impl_details.is_defined_in_xxx( 'std', type_)): return False return type_.decl_string.startswith('::boost::shared_ptr<') or \ type_.decl_string.startswith('::std::shared_ptr<')
[ "def", "is_smart_pointer", "(", "type_", ")", ":", "type_", "=", "type_traits", ".", "remove_alias", "(", "type_", ")", "type_", "=", "type_traits", ".", "remove_cv", "(", "type_", ")", "type_", "=", "type_traits", ".", "remove_declarated", "(", "type_", ")", "if", "not", "isinstance", "(", "type_", ",", "(", "class_declaration", ".", "class_declaration_t", ",", "class_declaration", ".", "class_t", ")", ")", ":", "return", "False", "if", "not", "(", "traits_impl_details", ".", "impl_details", ".", "is_defined_in_xxx", "(", "'boost'", ",", "type_", ")", "or", "traits_impl_details", ".", "impl_details", ".", "is_defined_in_xxx", "(", "'std'", ",", "type_", ")", ")", ":", "return", "False", "return", "type_", ".", "decl_string", ".", "startswith", "(", "'::boost::shared_ptr<'", ")", "or", "type_", ".", "decl_string", ".", "startswith", "(", "'::std::shared_ptr<'", ")" ]
returns True, if type represents instantiation of `boost::shared_ptr` or `std::shared_ptr`, False otherwise
[ "returns", "True", "if", "type", "represents", "instantiation", "of", "boost", "::", "shared_ptr", "or", "std", "::", "shared_ptr", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pointer_traits.py#L48-L65
gccxml/pygccxml
pygccxml/declarations/pointer_traits.py
smart_pointer_traits.value_type
def value_type(type_): """returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type""" if not smart_pointer_traits.is_smart_pointer(type_): raise TypeError( 'Type "%s" is not an instantiation of \ boost::shared_ptr or std::shared_ptr' % type_.decl_string) try: return internal_type_traits.get_by_name(type_, "element_type") except runtime_errors.declaration_not_found_t: return _search_in_bases(type_)
python
def value_type(type_): if not smart_pointer_traits.is_smart_pointer(type_): raise TypeError( 'Type "%s" is not an instantiation of \ boost::shared_ptr or std::shared_ptr' % type_.decl_string) try: return internal_type_traits.get_by_name(type_, "element_type") except runtime_errors.declaration_not_found_t: return _search_in_bases(type_)
[ "def", "value_type", "(", "type_", ")", ":", "if", "not", "smart_pointer_traits", ".", "is_smart_pointer", "(", "type_", ")", ":", "raise", "TypeError", "(", "'Type \"%s\" is not an instantiation of \\\n boost::shared_ptr or std::shared_ptr'", "%", "type_", ".", "decl_string", ")", "try", ":", "return", "internal_type_traits", ".", "get_by_name", "(", "type_", ",", "\"element_type\"", ")", "except", "runtime_errors", ".", "declaration_not_found_t", ":", "return", "_search_in_bases", "(", "type_", ")" ]
returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type
[ "returns", "reference", "to", "boost", "::", "shared_ptr", "\\", "or", "std", "::", "shared_ptr", "value", "type" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pointer_traits.py#L68-L79
gccxml/pygccxml
pygccxml/declarations/traits_impl_details.py
impl_details.is_defined_in_xxx
def is_defined_in_xxx(xxx, cls): """ Small helper method that checks whether the class `cls` is defined under `::xxx` namespace """ if not cls.parent: return False if not isinstance(cls.parent, namespace.namespace_t): return False if xxx != cls.parent.name: return False xxx_ns = cls.parent if not xxx_ns.parent: return False if not isinstance(xxx_ns.parent, namespace.namespace_t): return False if xxx_ns.parent.name != '::': return False global_ns = xxx_ns.parent return None is global_ns.parent
python
def is_defined_in_xxx(xxx, cls): if not cls.parent: return False if not isinstance(cls.parent, namespace.namespace_t): return False if xxx != cls.parent.name: return False xxx_ns = cls.parent if not xxx_ns.parent: return False if not isinstance(xxx_ns.parent, namespace.namespace_t): return False if xxx_ns.parent.name != '::': return False global_ns = xxx_ns.parent return None is global_ns.parent
[ "def", "is_defined_in_xxx", "(", "xxx", ",", "cls", ")", ":", "if", "not", "cls", ".", "parent", ":", "return", "False", "if", "not", "isinstance", "(", "cls", ".", "parent", ",", "namespace", ".", "namespace_t", ")", ":", "return", "False", "if", "xxx", "!=", "cls", ".", "parent", ".", "name", ":", "return", "False", "xxx_ns", "=", "cls", ".", "parent", "if", "not", "xxx_ns", ".", "parent", ":", "return", "False", "if", "not", "isinstance", "(", "xxx_ns", ".", "parent", ",", "namespace", ".", "namespace_t", ")", ":", "return", "False", "if", "xxx_ns", ".", "parent", ".", "name", "!=", "'::'", ":", "return", "False", "global_ns", "=", "xxx_ns", ".", "parent", "return", "None", "is", "global_ns", ".", "parent" ]
Small helper method that checks whether the class `cls` is defined under `::xxx` namespace
[ "Small", "helper", "method", "that", "checks", "whether", "the", "class", "cls", "is", "defined", "under", "::", "xxx", "namespace" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/traits_impl_details.py#L17-L42
gccxml/pygccxml
pygccxml/declarations/traits_impl_details.py
impl_details.find_value_type
def find_value_type(global_ns, value_type_str): """implementation details""" if not value_type_str.startswith('::'): value_type_str = '::' + value_type_str found = global_ns.decls( name=value_type_str, function=lambda decl: not isinstance(decl, calldef.calldef_t), allow_empty=True) if not found: no_global_ns_value_type_str = value_type_str[2:] if no_global_ns_value_type_str in cpptypes.FUNDAMENTAL_TYPES: return cpptypes.FUNDAMENTAL_TYPES[no_global_ns_value_type_str] elif type_traits.is_std_string(value_type_str): string_ = global_ns.typedef('::std::string') return type_traits.remove_declarated(string_) elif type_traits.is_std_wstring(value_type_str): string_ = global_ns.typedef('::std::wstring') return type_traits.remove_declarated(string_) else: value_type_str = no_global_ns_value_type_str has_const = value_type_str.startswith('const ') if has_const: value_type_str = value_type_str[len('const '):] has_pointer = value_type_str.endswith('*') if has_pointer: value_type_str = value_type_str[:-1] found = None if has_const or has_pointer: found = impl_details.find_value_type( global_ns, value_type_str) if not found: return None else: if isinstance(found, class_declaration.class_types): return cpptypes.declarated_t(found) if has_const: return cpptypes.const_t(found) if has_pointer: return cpptypes.pointer_t(found) if len(found) == 1: return found[0] return None
python
def find_value_type(global_ns, value_type_str): if not value_type_str.startswith('::'): value_type_str = '::' + value_type_str found = global_ns.decls( name=value_type_str, function=lambda decl: not isinstance(decl, calldef.calldef_t), allow_empty=True) if not found: no_global_ns_value_type_str = value_type_str[2:] if no_global_ns_value_type_str in cpptypes.FUNDAMENTAL_TYPES: return cpptypes.FUNDAMENTAL_TYPES[no_global_ns_value_type_str] elif type_traits.is_std_string(value_type_str): string_ = global_ns.typedef('::std::string') return type_traits.remove_declarated(string_) elif type_traits.is_std_wstring(value_type_str): string_ = global_ns.typedef('::std::wstring') return type_traits.remove_declarated(string_) else: value_type_str = no_global_ns_value_type_str has_const = value_type_str.startswith('const ') if has_const: value_type_str = value_type_str[len('const '):] has_pointer = value_type_str.endswith('*') if has_pointer: value_type_str = value_type_str[:-1] found = None if has_const or has_pointer: found = impl_details.find_value_type( global_ns, value_type_str) if not found: return None else: if isinstance(found, class_declaration.class_types): return cpptypes.declarated_t(found) if has_const: return cpptypes.const_t(found) if has_pointer: return cpptypes.pointer_t(found) if len(found) == 1: return found[0] return None
[ "def", "find_value_type", "(", "global_ns", ",", "value_type_str", ")", ":", "if", "not", "value_type_str", ".", "startswith", "(", "'::'", ")", ":", "value_type_str", "=", "'::'", "+", "value_type_str", "found", "=", "global_ns", ".", "decls", "(", "name", "=", "value_type_str", ",", "function", "=", "lambda", "decl", ":", "not", "isinstance", "(", "decl", ",", "calldef", ".", "calldef_t", ")", ",", "allow_empty", "=", "True", ")", "if", "not", "found", ":", "no_global_ns_value_type_str", "=", "value_type_str", "[", "2", ":", "]", "if", "no_global_ns_value_type_str", "in", "cpptypes", ".", "FUNDAMENTAL_TYPES", ":", "return", "cpptypes", ".", "FUNDAMENTAL_TYPES", "[", "no_global_ns_value_type_str", "]", "elif", "type_traits", ".", "is_std_string", "(", "value_type_str", ")", ":", "string_", "=", "global_ns", ".", "typedef", "(", "'::std::string'", ")", "return", "type_traits", ".", "remove_declarated", "(", "string_", ")", "elif", "type_traits", ".", "is_std_wstring", "(", "value_type_str", ")", ":", "string_", "=", "global_ns", ".", "typedef", "(", "'::std::wstring'", ")", "return", "type_traits", ".", "remove_declarated", "(", "string_", ")", "else", ":", "value_type_str", "=", "no_global_ns_value_type_str", "has_const", "=", "value_type_str", ".", "startswith", "(", "'const '", ")", "if", "has_const", ":", "value_type_str", "=", "value_type_str", "[", "len", "(", "'const '", ")", ":", "]", "has_pointer", "=", "value_type_str", ".", "endswith", "(", "'*'", ")", "if", "has_pointer", ":", "value_type_str", "=", "value_type_str", "[", ":", "-", "1", "]", "found", "=", "None", "if", "has_const", "or", "has_pointer", ":", "found", "=", "impl_details", ".", "find_value_type", "(", "global_ns", ",", "value_type_str", ")", "if", "not", "found", ":", "return", "None", "else", ":", "if", "isinstance", "(", "found", ",", "class_declaration", ".", "class_types", ")", ":", "return", "cpptypes", ".", "declarated_t", "(", "found", ")", "if", "has_const", ":", "return", "cpptypes", ".", "const_t", "(", "found", ")", "if", "has_pointer", ":", "return", "cpptypes", ".", "pointer_t", "(", "found", ")", "if", "len", "(", "found", ")", "==", "1", ":", "return", "found", "[", "0", "]", "return", "None" ]
implementation details
[ "implementation", "details" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/traits_impl_details.py#L45-L88
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t.update
def update(self, source_file, configuration, declarations, included_files): """Replace a cache entry by a new value. :param source_file: a C++ source file name. :type source_file: str :param configuration: configuration object. :type configuration: :class:`xml_generator_configuration_t` :param declarations: declarations contained in the `source_file` :type declarations: pickable object :param included_files: included files :type included_files: list of str """ # Normlize all paths... source_file = os.path.normpath(source_file) included_files = [os.path.normpath(p) for p in included_files] # Create the list of dependent files. This is the included_files list # + the source file. Duplicate names are removed. dependent_files = {} for name in [source_file] + included_files: dependent_files[name] = 1 key = self._create_cache_key(source_file) # Remove an existing entry (if there is one) # After calling this method, it is guaranteed that __index[key] # does not exist anymore. self._remove_entry(source_file, key) # Create a new entry... # Create the sigs of all dependent files... filesigs = [] for filename in list(dependent_files.keys()): id_, sig = self.__filename_rep.acquire_filename(filename) filesigs.append((id_, sig)) configsig = self._create_config_signature(configuration) entry = index_entry_t(filesigs, configsig) self.__index[key] = entry self.__modified_flag = True # Write the declarations into the cache file... cachefilename = self._create_cache_filename(source_file) self._write_file(cachefilename, declarations)
python
def update(self, source_file, configuration, declarations, included_files): source_file = os.path.normpath(source_file) included_files = [os.path.normpath(p) for p in included_files] dependent_files = {} for name in [source_file] + included_files: dependent_files[name] = 1 key = self._create_cache_key(source_file) self._remove_entry(source_file, key) filesigs = [] for filename in list(dependent_files.keys()): id_, sig = self.__filename_rep.acquire_filename(filename) filesigs.append((id_, sig)) configsig = self._create_config_signature(configuration) entry = index_entry_t(filesigs, configsig) self.__index[key] = entry self.__modified_flag = True cachefilename = self._create_cache_filename(source_file) self._write_file(cachefilename, declarations)
[ "def", "update", "(", "self", ",", "source_file", ",", "configuration", ",", "declarations", ",", "included_files", ")", ":", "# Normlize all paths...", "source_file", "=", "os", ".", "path", ".", "normpath", "(", "source_file", ")", "included_files", "=", "[", "os", ".", "path", ".", "normpath", "(", "p", ")", "for", "p", "in", "included_files", "]", "# Create the list of dependent files. This is the included_files list", "# + the source file. Duplicate names are removed.", "dependent_files", "=", "{", "}", "for", "name", "in", "[", "source_file", "]", "+", "included_files", ":", "dependent_files", "[", "name", "]", "=", "1", "key", "=", "self", ".", "_create_cache_key", "(", "source_file", ")", "# Remove an existing entry (if there is one)", "# After calling this method, it is guaranteed that __index[key]", "# does not exist anymore.", "self", ".", "_remove_entry", "(", "source_file", ",", "key", ")", "# Create a new entry...", "# Create the sigs of all dependent files...", "filesigs", "=", "[", "]", "for", "filename", "in", "list", "(", "dependent_files", ".", "keys", "(", ")", ")", ":", "id_", ",", "sig", "=", "self", ".", "__filename_rep", ".", "acquire_filename", "(", "filename", ")", "filesigs", ".", "append", "(", "(", "id_", ",", "sig", ")", ")", "configsig", "=", "self", ".", "_create_config_signature", "(", "configuration", ")", "entry", "=", "index_entry_t", "(", "filesigs", ",", "configsig", ")", "self", ".", "__index", "[", "key", "]", "=", "entry", "self", ".", "__modified_flag", "=", "True", "# Write the declarations into the cache file...", "cachefilename", "=", "self", ".", "_create_cache_filename", "(", "source_file", ")", "self", ".", "_write_file", "(", "cachefilename", ",", "declarations", ")" ]
Replace a cache entry by a new value. :param source_file: a C++ source file name. :type source_file: str :param configuration: configuration object. :type configuration: :class:`xml_generator_configuration_t` :param declarations: declarations contained in the `source_file` :type declarations: pickable object :param included_files: included files :type included_files: list of str
[ "Replace", "a", "cache", "entry", "by", "a", "new", "value", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L127-L171
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t.cached_value
def cached_value(self, source_file, configuration): """Return the cached declarations or None. :param source_file: Header file name :type source_file: str :param configuration: Configuration object :type configuration: :class:`parser.xml_generator_configuration_t` :rtype: Cached declarations or None """ # Check if the cache contains an entry for source_file key = self._create_cache_key(source_file) entry = self.__index.get(key) if entry is None: # print "CACHE: %s: Not cached"%source_file return None # Check if the entry is still valid. It is not valid if: # - the source_file has been updated # - the configuration object has changed (i.e. the header is parsed # by gccxml with different settings which may influence the # declarations) # - the included files have been updated # (this list is part of the cache entry as it cannot be known # by the caller when cached_value() is called. It was instead # passed to update()) # Check if the config is different... configsig = self._create_config_signature(configuration) if configsig != entry.configsig: # print "CACHE: %s: Config mismatch"%source_file return None # Check if any of the dependent files has been modified... for id_, sig in entry.filesigs: if self.__filename_rep.is_file_modified(id_, sig): # print "CACHE: %s: Entry not up to date"%source_file return None # Load and return the cached declarations cachefilename = self._create_cache_filename(source_file) decls = self._read_file(cachefilename) # print "CACHE: Using cached decls for",source_file return decls
python
def cached_value(self, source_file, configuration): key = self._create_cache_key(source_file) entry = self.__index.get(key) if entry is None: return None configsig = self._create_config_signature(configuration) if configsig != entry.configsig: return None for id_, sig in entry.filesigs: if self.__filename_rep.is_file_modified(id_, sig): return None cachefilename = self._create_cache_filename(source_file) decls = self._read_file(cachefilename) return decls
[ "def", "cached_value", "(", "self", ",", "source_file", ",", "configuration", ")", ":", "# Check if the cache contains an entry for source_file", "key", "=", "self", ".", "_create_cache_key", "(", "source_file", ")", "entry", "=", "self", ".", "__index", ".", "get", "(", "key", ")", "if", "entry", "is", "None", ":", "# print \"CACHE: %s: Not cached\"%source_file", "return", "None", "# Check if the entry is still valid. It is not valid if:", "# - the source_file has been updated", "# - the configuration object has changed (i.e. the header is parsed", "# by gccxml with different settings which may influence the", "# declarations)", "# - the included files have been updated", "# (this list is part of the cache entry as it cannot be known", "# by the caller when cached_value() is called. It was instead", "# passed to update())", "# Check if the config is different...", "configsig", "=", "self", ".", "_create_config_signature", "(", "configuration", ")", "if", "configsig", "!=", "entry", ".", "configsig", ":", "# print \"CACHE: %s: Config mismatch\"%source_file", "return", "None", "# Check if any of the dependent files has been modified...", "for", "id_", ",", "sig", "in", "entry", ".", "filesigs", ":", "if", "self", ".", "__filename_rep", ".", "is_file_modified", "(", "id_", ",", "sig", ")", ":", "# print \"CACHE: %s: Entry not up to date\"%source_file", "return", "None", "# Load and return the cached declarations", "cachefilename", "=", "self", ".", "_create_cache_filename", "(", "source_file", ")", "decls", "=", "self", ".", "_read_file", "(", "cachefilename", ")", "# print \"CACHE: Using cached decls for\",source_file", "return", "decls" ]
Return the cached declarations or None. :param source_file: Header file name :type source_file: str :param configuration: Configuration object :type configuration: :class:`parser.xml_generator_configuration_t` :rtype: Cached declarations or None
[ "Return", "the", "cached", "declarations", "or", "None", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L173-L217
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._load
def _load(self): """Load the cache. Loads the `index.dat` file, which contains the index table and the file name repository. This method is called by the :meth:`__init__` """ indexfilename = os.path.join(self.__dir, "index.dat") if os.path.exists(indexfilename): data = self._read_file(indexfilename) self.__index = data[0] self.__filename_rep = data[1] if self.__filename_rep._sha1_sigs != self.__sha1_sigs: print(( "CACHE: Warning: sha1_sigs stored in the cache is set " + "to %s.") % self.__filename_rep._sha1_sigs) print("Please remove the cache to change this setting.") self.__sha1_sigs = self.__filename_rep._sha1_sigs else: self.__index = {} self.__filename_rep = filename_repository_t(self.__sha1_sigs) self.__modified_flag = False
python
def _load(self): indexfilename = os.path.join(self.__dir, "index.dat") if os.path.exists(indexfilename): data = self._read_file(indexfilename) self.__index = data[0] self.__filename_rep = data[1] if self.__filename_rep._sha1_sigs != self.__sha1_sigs: print(( "CACHE: Warning: sha1_sigs stored in the cache is set " + "to %s.") % self.__filename_rep._sha1_sigs) print("Please remove the cache to change this setting.") self.__sha1_sigs = self.__filename_rep._sha1_sigs else: self.__index = {} self.__filename_rep = filename_repository_t(self.__sha1_sigs) self.__modified_flag = False
[ "def", "_load", "(", "self", ")", ":", "indexfilename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "\"index.dat\"", ")", "if", "os", ".", "path", ".", "exists", "(", "indexfilename", ")", ":", "data", "=", "self", ".", "_read_file", "(", "indexfilename", ")", "self", ".", "__index", "=", "data", "[", "0", "]", "self", ".", "__filename_rep", "=", "data", "[", "1", "]", "if", "self", ".", "__filename_rep", ".", "_sha1_sigs", "!=", "self", ".", "__sha1_sigs", ":", "print", "(", "(", "\"CACHE: Warning: sha1_sigs stored in the cache is set \"", "+", "\"to %s.\"", ")", "%", "self", ".", "__filename_rep", ".", "_sha1_sigs", ")", "print", "(", "\"Please remove the cache to change this setting.\"", ")", "self", ".", "__sha1_sigs", "=", "self", ".", "__filename_rep", ".", "_sha1_sigs", "else", ":", "self", ".", "__index", "=", "{", "}", "self", ".", "__filename_rep", "=", "filename_repository_t", "(", "self", ".", "__sha1_sigs", ")", "self", ".", "__modified_flag", "=", "False" ]
Load the cache. Loads the `index.dat` file, which contains the index table and the file name repository. This method is called by the :meth:`__init__`
[ "Load", "the", "cache", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L219-L243
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._save
def _save(self): """ save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat` """ if self.__modified_flag: self.__filename_rep.update_id_counter() indexfilename = os.path.join(self.__dir, "index.dat") self._write_file( indexfilename, (self.__index, self.__filename_rep)) self.__modified_flag = False
python
def _save(self): if self.__modified_flag: self.__filename_rep.update_id_counter() indexfilename = os.path.join(self.__dir, "index.dat") self._write_file( indexfilename, (self.__index, self.__filename_rep)) self.__modified_flag = False
[ "def", "_save", "(", "self", ")", ":", "if", "self", ".", "__modified_flag", ":", "self", ".", "__filename_rep", ".", "update_id_counter", "(", ")", "indexfilename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "\"index.dat\"", ")", "self", ".", "_write_file", "(", "indexfilename", ",", "(", "self", ".", "__index", ",", "self", ".", "__filename_rep", ")", ")", "self", ".", "__modified_flag", "=", "False" ]
save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat`
[ "save", "the", "cache", "index", "in", "case", "it", "was", "modified", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L245-L261
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._read_file
def _read_file(self, filename): """ read a Python object from a cache file. Reads a pickled object from disk and returns it. :param filename: Name of the file that should be read. :type filename: str :rtype: object """ if self.__compression: f = gzip.GzipFile(filename, "rb") else: f = open(filename, "rb") res = pickle.load(f) f.close() return res
python
def _read_file(self, filename): if self.__compression: f = gzip.GzipFile(filename, "rb") else: f = open(filename, "rb") res = pickle.load(f) f.close() return res
[ "def", "_read_file", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "__compression", ":", "f", "=", "gzip", ".", "GzipFile", "(", "filename", ",", "\"rb\"", ")", "else", ":", "f", "=", "open", "(", "filename", ",", "\"rb\"", ")", "res", "=", "pickle", ".", "load", "(", "f", ")", "f", ".", "close", "(", ")", "return", "res" ]
read a Python object from a cache file. Reads a pickled object from disk and returns it. :param filename: Name of the file that should be read. :type filename: str :rtype: object
[ "read", "a", "Python", "object", "from", "a", "cache", "file", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L263-L280
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._write_file
def _write_file(self, filename, data): """Write a data item into a file. The data object is written to a file using the pickle mechanism. :param filename: Output file name :type filename: str :param data: A Python object that will be pickled """ if self.__compression: f = gzip.GzipFile(filename, "wb") else: f = open(filename, "wb") pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) f.close()
python
def _write_file(self, filename, data): if self.__compression: f = gzip.GzipFile(filename, "wb") else: f = open(filename, "wb") pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) f.close()
[ "def", "_write_file", "(", "self", ",", "filename", ",", "data", ")", ":", "if", "self", ".", "__compression", ":", "f", "=", "gzip", ".", "GzipFile", "(", "filename", ",", "\"wb\"", ")", "else", ":", "f", "=", "open", "(", "filename", ",", "\"wb\"", ")", "pickle", ".", "dump", "(", "data", ",", "f", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "f", ".", "close", "(", ")" ]
Write a data item into a file. The data object is written to a file using the pickle mechanism. :param filename: Output file name :type filename: str :param data: A Python object that will be pickled
[ "Write", "a", "data", "item", "into", "a", "file", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L282-L297
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._remove_entry
def _remove_entry(self, source_file, key): """Remove an entry from the cache. source_file is the name of the header and key is its corresponding cache key (obtained by a call to :meth:_create_cache_key ). The entry is removed from the index table, any referenced file name is released and the cache file is deleted. If key references a non-existing entry, the method returns immediately. :param source_file: Header file name :type source_file: str :param key: Key value for the specified header file :type key: hash table object """ entry = self.__index.get(key) if entry is None: return # Release the referenced files... for id_, _ in entry.filesigs: self.__filename_rep.release_filename(id_) # Remove the cache entry... del self.__index[key] self.__modified_flag = True # Delete the corresponding cache file... cachefilename = self._create_cache_filename(source_file) try: os.remove(cachefilename) except OSError as e: print("Could not remove cache file (%s)" % e)
python
def _remove_entry(self, source_file, key): entry = self.__index.get(key) if entry is None: return for id_, _ in entry.filesigs: self.__filename_rep.release_filename(id_) del self.__index[key] self.__modified_flag = True cachefilename = self._create_cache_filename(source_file) try: os.remove(cachefilename) except OSError as e: print("Could not remove cache file (%s)" % e)
[ "def", "_remove_entry", "(", "self", ",", "source_file", ",", "key", ")", ":", "entry", "=", "self", ".", "__index", ".", "get", "(", "key", ")", "if", "entry", "is", "None", ":", "return", "# Release the referenced files...", "for", "id_", ",", "_", "in", "entry", ".", "filesigs", ":", "self", ".", "__filename_rep", ".", "release_filename", "(", "id_", ")", "# Remove the cache entry...", "del", "self", ".", "__index", "[", "key", "]", "self", ".", "__modified_flag", "=", "True", "# Delete the corresponding cache file...", "cachefilename", "=", "self", ".", "_create_cache_filename", "(", "source_file", ")", "try", ":", "os", ".", "remove", "(", "cachefilename", ")", "except", "OSError", "as", "e", ":", "print", "(", "\"Could not remove cache file (%s)\"", "%", "e", ")" ]
Remove an entry from the cache. source_file is the name of the header and key is its corresponding cache key (obtained by a call to :meth:_create_cache_key ). The entry is removed from the index table, any referenced file name is released and the cache file is deleted. If key references a non-existing entry, the method returns immediately. :param source_file: Header file name :type source_file: str :param key: Key value for the specified header file :type key: hash table object
[ "Remove", "an", "entry", "from", "the", "cache", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L299-L333
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._create_cache_key
def _create_cache_key(source_file): """ return the cache key for a header file. :param source_file: Header file name :type source_file: str :rtype: str """ path, name = os.path.split(source_file) return name + str(hash(path))
python
def _create_cache_key(source_file): path, name = os.path.split(source_file) return name + str(hash(path))
[ "def", "_create_cache_key", "(", "source_file", ")", ":", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "source_file", ")", "return", "name", "+", "str", "(", "hash", "(", "path", ")", ")" ]
return the cache key for a header file. :param source_file: Header file name :type source_file: str :rtype: str
[ "return", "the", "cache", "key", "for", "a", "header", "file", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L336-L345
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._create_cache_filename
def _create_cache_filename(self, source_file): """ return the cache file name for a header file. :param source_file: Header file name :type source_file: str :rtype: str """ res = self._create_cache_key(source_file) + ".cache" return os.path.join(self.__dir, res)
python
def _create_cache_filename(self, source_file): res = self._create_cache_key(source_file) + ".cache" return os.path.join(self.__dir, res)
[ "def", "_create_cache_filename", "(", "self", ",", "source_file", ")", ":", "res", "=", "self", ".", "_create_cache_key", "(", "source_file", ")", "+", "\".cache\"", "return", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "res", ")" ]
return the cache file name for a header file. :param source_file: Header file name :type source_file: str :rtype: str
[ "return", "the", "cache", "file", "name", "for", "a", "header", "file", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L347-L356
gccxml/pygccxml
pygccxml/parser/directory_cache.py
directory_cache_t._create_config_signature
def _create_config_signature(config): """ return the signature for a config object. The signature is computed as sha1 digest of the contents of working_directory, include_paths, define_symbols and undefine_symbols. :param config: Configuration object :type config: :class:`parser.xml_generator_configuration_t` :rtype: str """ m = hashlib.sha1() m.update(config.working_directory.encode("utf-8")) for p in config.include_paths: m.update(p.encode("utf-8")) for p in config.define_symbols: m.update(p.encode("utf-8")) for p in config.undefine_symbols: m.update(p.encode("utf-8")) for p in config.cflags: m.update(p.encode("utf-8")) return m.digest()
python
def _create_config_signature(config): m = hashlib.sha1() m.update(config.working_directory.encode("utf-8")) for p in config.include_paths: m.update(p.encode("utf-8")) for p in config.define_symbols: m.update(p.encode("utf-8")) for p in config.undefine_symbols: m.update(p.encode("utf-8")) for p in config.cflags: m.update(p.encode("utf-8")) return m.digest()
[ "def", "_create_config_signature", "(", "config", ")", ":", "m", "=", "hashlib", ".", "sha1", "(", ")", "m", ".", "update", "(", "config", ".", "working_directory", ".", "encode", "(", "\"utf-8\"", ")", ")", "for", "p", "in", "config", ".", "include_paths", ":", "m", ".", "update", "(", "p", ".", "encode", "(", "\"utf-8\"", ")", ")", "for", "p", "in", "config", ".", "define_symbols", ":", "m", ".", "update", "(", "p", ".", "encode", "(", "\"utf-8\"", ")", ")", "for", "p", "in", "config", ".", "undefine_symbols", ":", "m", ".", "update", "(", "p", ".", "encode", "(", "\"utf-8\"", ")", ")", "for", "p", "in", "config", ".", "cflags", ":", "m", ".", "update", "(", "p", ".", "encode", "(", "\"utf-8\"", ")", ")", "return", "m", ".", "digest", "(", ")" ]
return the signature for a config object. The signature is computed as sha1 digest of the contents of working_directory, include_paths, define_symbols and undefine_symbols. :param config: Configuration object :type config: :class:`parser.xml_generator_configuration_t` :rtype: str
[ "return", "the", "signature", "for", "a", "config", "object", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L359-L381
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t.acquire_filename
def acquire_filename(self, name): """Acquire a file name and return its id and its signature. """ id_ = self.__id_lut.get(name) # Is this a new entry? if id_ is None: # then create one... id_ = self.__next_id self.__next_id += 1 self.__id_lut[name] = id_ entry = filename_entry_t(name) self.__entries[id_] = entry else: # otherwise obtain the entry... entry = self.__entries[id_] entry.inc_ref_count() return id_, self._get_signature(entry)
python
def acquire_filename(self, name): id_ = self.__id_lut.get(name) if id_ is None: id_ = self.__next_id self.__next_id += 1 self.__id_lut[name] = id_ entry = filename_entry_t(name) self.__entries[id_] = entry else: entry = self.__entries[id_] entry.inc_ref_count() return id_, self._get_signature(entry)
[ "def", "acquire_filename", "(", "self", ",", "name", ")", ":", "id_", "=", "self", ".", "__id_lut", ".", "get", "(", "name", ")", "# Is this a new entry?", "if", "id_", "is", "None", ":", "# then create one...", "id_", "=", "self", ".", "__next_id", "self", ".", "__next_id", "+=", "1", "self", ".", "__id_lut", "[", "name", "]", "=", "id_", "entry", "=", "filename_entry_t", "(", "name", ")", "self", ".", "__entries", "[", "id_", "]", "=", "entry", "else", ":", "# otherwise obtain the entry...", "entry", "=", "self", ".", "__entries", "[", "id_", "]", "entry", ".", "inc_ref_count", "(", ")", "return", "id_", ",", "self", ".", "_get_signature", "(", "entry", ")" ]
Acquire a file name and return its id and its signature.
[ "Acquire", "a", "file", "name", "and", "return", "its", "id", "and", "its", "signature", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L466-L484
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t.release_filename
def release_filename(self, id_): """Release a file name. """ entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id (%d)" % id_) # Decrease reference count and check if the entry has to be removed... if entry.dec_ref_count() == 0: del self.__entries[id_] del self.__id_lut[entry.filename]
python
def release_filename(self, id_): entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id (%d)" % id_) if entry.dec_ref_count() == 0: del self.__entries[id_] del self.__id_lut[entry.filename]
[ "def", "release_filename", "(", "self", ",", "id_", ")", ":", "entry", "=", "self", ".", "__entries", ".", "get", "(", "id_", ")", "if", "entry", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid filename id (%d)\"", "%", "id_", ")", "# Decrease reference count and check if the entry has to be removed...", "if", "entry", ".", "dec_ref_count", "(", ")", "==", "0", ":", "del", "self", ".", "__entries", "[", "id_", "]", "del", "self", ".", "__id_lut", "[", "entry", ".", "filename", "]" ]
Release a file name.
[ "Release", "a", "file", "name", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L486-L497
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t.is_file_modified
def is_file_modified(self, id_, signature): """Check if the file referred to by `id_` has been modified. """ entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id_ (%d)" % id_) # Is the signature already known? if entry.sig_valid: # use the cached signature filesig = entry.signature else: # compute the signature and store it filesig = self._get_signature(entry) entry.signature = filesig entry.sig_valid = True return filesig != signature
python
def is_file_modified(self, id_, signature): entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id_ (%d)" % id_) if entry.sig_valid: filesig = entry.signature else: filesig = self._get_signature(entry) entry.signature = filesig entry.sig_valid = True return filesig != signature
[ "def", "is_file_modified", "(", "self", ",", "id_", ",", "signature", ")", ":", "entry", "=", "self", ".", "__entries", ".", "get", "(", "id_", ")", "if", "entry", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid filename id_ (%d)\"", "%", "id_", ")", "# Is the signature already known?", "if", "entry", ".", "sig_valid", ":", "# use the cached signature", "filesig", "=", "entry", ".", "signature", "else", ":", "# compute the signature and store it", "filesig", "=", "self", ".", "_get_signature", "(", "entry", ")", "entry", ".", "signature", "=", "filesig", "entry", ".", "sig_valid", "=", "True", "return", "filesig", "!=", "signature" ]
Check if the file referred to by `id_` has been modified.
[ "Check", "if", "the", "file", "referred", "to", "by", "id_", "has", "been", "modified", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L499-L517
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t.update_id_counter
def update_id_counter(self): """Update the `id_` counter so that it doesn't grow forever. """ if not self.__entries: self.__next_id = 1 else: self.__next_id = max(self.__entries.keys()) + 1
python
def update_id_counter(self): if not self.__entries: self.__next_id = 1 else: self.__next_id = max(self.__entries.keys()) + 1
[ "def", "update_id_counter", "(", "self", ")", ":", "if", "not", "self", ".", "__entries", ":", "self", ".", "__next_id", "=", "1", "else", ":", "self", ".", "__next_id", "=", "max", "(", "self", ".", "__entries", ".", "keys", "(", ")", ")", "+", "1" ]
Update the `id_` counter so that it doesn't grow forever.
[ "Update", "the", "id_", "counter", "so", "that", "it", "doesn", "t", "grow", "forever", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L519-L526
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t._get_signature
def _get_signature(self, entry): """Return the signature of the file stored in entry. """ if self._sha1_sigs: # return sha1 digest of the file content... if not os.path.exists(entry.filename): return None try: with open(entry.filename, "r") as f: data = f.read() return hashlib.sha1(data.encode("utf-8")).digest() except IOError as e: print("Cannot determine sha1 digest:", e) return None else: # return file modification date... try: return os.path.getmtime(entry.filename) except OSError: return None
python
def _get_signature(self, entry): if self._sha1_sigs: if not os.path.exists(entry.filename): return None try: with open(entry.filename, "r") as f: data = f.read() return hashlib.sha1(data.encode("utf-8")).digest() except IOError as e: print("Cannot determine sha1 digest:", e) return None else: try: return os.path.getmtime(entry.filename) except OSError: return None
[ "def", "_get_signature", "(", "self", ",", "entry", ")", ":", "if", "self", ".", "_sha1_sigs", ":", "# return sha1 digest of the file content...", "if", "not", "os", ".", "path", ".", "exists", "(", "entry", ".", "filename", ")", ":", "return", "None", "try", ":", "with", "open", "(", "entry", ".", "filename", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "return", "hashlib", ".", "sha1", "(", "data", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "digest", "(", ")", "except", "IOError", "as", "e", ":", "print", "(", "\"Cannot determine sha1 digest:\"", ",", "e", ")", "return", "None", "else", ":", "# return file modification date...", "try", ":", "return", "os", ".", "path", ".", "getmtime", "(", "entry", ".", "filename", ")", "except", "OSError", ":", "return", "None" ]
Return the signature of the file stored in entry.
[ "Return", "the", "signature", "of", "the", "file", "stored", "in", "entry", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L528-L548
gccxml/pygccxml
pygccxml/parser/directory_cache.py
filename_repository_t._dump
def _dump(self): # pragma: no cover """ Dump contents for debugging/testing. """ print(70 * "-") print("ID lookup table:") for name in self.__id_lut: id_ = self.__id_lut[name] print(" %s -> %d" % (name, id_)) print(70 * "-") print("%-4s %-60s %s" % ("ID", "Filename", "Refcount")) print(70 * "-") for id_ in self.__entries: entry = self.__entries[id_] print("%04d %-60s %d" % (id_, entry.filename, entry.refcount))
python
def _dump(self): print(70 * "-") print("ID lookup table:") for name in self.__id_lut: id_ = self.__id_lut[name] print(" %s -> %d" % (name, id_)) print(70 * "-") print("%-4s %-60s %s" % ("ID", "Filename", "Refcount")) print(70 * "-") for id_ in self.__entries: entry = self.__entries[id_] print("%04d %-60s %d" % (id_, entry.filename, entry.refcount))
[ "def", "_dump", "(", "self", ")", ":", "# pragma: no cover", "print", "(", "70", "*", "\"-\"", ")", "print", "(", "\"ID lookup table:\"", ")", "for", "name", "in", "self", ".", "__id_lut", ":", "id_", "=", "self", ".", "__id_lut", "[", "name", "]", "print", "(", "\" %s -> %d\"", "%", "(", "name", ",", "id_", ")", ")", "print", "(", "70", "*", "\"-\"", ")", "print", "(", "\"%-4s %-60s %s\"", "%", "(", "\"ID\"", ",", "\"Filename\"", ",", "\"Refcount\"", ")", ")", "print", "(", "70", "*", "\"-\"", ")", "for", "id_", "in", "self", ".", "__entries", ":", "entry", "=", "self", ".", "__entries", "[", "id_", "]", "print", "(", "\"%04d %-60s %d\"", "%", "(", "id_", ",", "entry", ".", "filename", ",", "entry", ".", "refcount", ")", ")" ]
Dump contents for debugging/testing.
[ "Dump", "contents", "for", "debugging", "/", "testing", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/directory_cache.py#L550-L566
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
is_union
def is_union(declaration): """ Returns True if declaration represents a C++ union Args: declaration (declaration_t): the declaration to be checked. Returns: bool: True if declaration represents a C++ union """ if not is_class(declaration): return False decl = class_traits.get_declaration(declaration) return decl.class_type == class_declaration.CLASS_TYPES.UNION
python
def is_union(declaration): if not is_class(declaration): return False decl = class_traits.get_declaration(declaration) return decl.class_type == class_declaration.CLASS_TYPES.UNION
[ "def", "is_union", "(", "declaration", ")", ":", "if", "not", "is_class", "(", "declaration", ")", ":", "return", "False", "decl", "=", "class_traits", ".", "get_declaration", "(", "declaration", ")", "return", "decl", ".", "class_type", "==", "class_declaration", ".", "CLASS_TYPES", ".", "UNION" ]
Returns True if declaration represents a C++ union Args: declaration (declaration_t): the declaration to be checked. Returns: bool: True if declaration represents a C++ union
[ "Returns", "True", "if", "declaration", "represents", "a", "C", "++", "union" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L18-L31
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
is_struct
def is_struct(declaration): """ Returns True if declaration represents a C++ struct Args: declaration (declaration_t): the declaration to be checked. Returns: bool: True if declaration represents a C++ struct """ if not is_class(declaration): return False decl = class_traits.get_declaration(declaration) return decl.class_type == class_declaration.CLASS_TYPES.STRUCT
python
def is_struct(declaration): if not is_class(declaration): return False decl = class_traits.get_declaration(declaration) return decl.class_type == class_declaration.CLASS_TYPES.STRUCT
[ "def", "is_struct", "(", "declaration", ")", ":", "if", "not", "is_class", "(", "declaration", ")", ":", "return", "False", "decl", "=", "class_traits", ".", "get_declaration", "(", "declaration", ")", "return", "decl", ".", "class_type", "==", "class_declaration", ".", "CLASS_TYPES", ".", "STRUCT" ]
Returns True if declaration represents a C++ struct Args: declaration (declaration_t): the declaration to be checked. Returns: bool: True if declaration represents a C++ struct
[ "Returns", "True", "if", "declaration", "represents", "a", "C", "++", "struct" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L34-L47
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
find_trivial_constructor
def find_trivial_constructor(type_): """ Returns reference to trivial constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the trivial constructor """ assert isinstance(type_, class_declaration.class_t) trivial = type_.constructors( lambda x: is_trivial_constructor(x), recursive=False, allow_empty=True) if trivial: return trivial[0] return None
python
def find_trivial_constructor(type_): assert isinstance(type_, class_declaration.class_t) trivial = type_.constructors( lambda x: is_trivial_constructor(x), recursive=False, allow_empty=True) if trivial: return trivial[0] return None
[ "def", "find_trivial_constructor", "(", "type_", ")", ":", "assert", "isinstance", "(", "type_", ",", "class_declaration", ".", "class_t", ")", "trivial", "=", "type_", ".", "constructors", "(", "lambda", "x", ":", "is_trivial_constructor", "(", "x", ")", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "if", "trivial", ":", "return", "trivial", "[", "0", "]", "return", "None" ]
Returns reference to trivial constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the trivial constructor
[ "Returns", "reference", "to", "trivial", "constructor", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L111-L131
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
find_copy_constructor
def find_copy_constructor(type_): """ Returns reference to copy constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the copy constructor """ copy_ = type_.constructors( lambda x: is_copy_constructor(x), recursive=False, allow_empty=True) if copy_: return copy_[0] return None
python
def find_copy_constructor(type_): copy_ = type_.constructors( lambda x: is_copy_constructor(x), recursive=False, allow_empty=True) if copy_: return copy_[0] return None
[ "def", "find_copy_constructor", "(", "type_", ")", ":", "copy_", "=", "type_", ".", "constructors", "(", "lambda", "x", ":", "is_copy_constructor", "(", "x", ")", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "if", "copy_", ":", "return", "copy_", "[", "0", "]", "return", "None" ]
Returns reference to copy constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the copy constructor
[ "Returns", "reference", "to", "copy", "constructor", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L134-L152
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
find_noncopyable_vars
def find_noncopyable_vars(class_type, already_visited_cls_vars=None): """ Returns list of all `noncopyable` variables. If an already_visited_cls_vars list is provided as argument, the returned list will not contain these variables. This list will be extended with whatever variables pointing to classes have been found. Args: class_type (declarations.class_t): the class to be searched. already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. Returns: list: list of all `noncopyable` variables. """ assert isinstance(class_type, class_declaration.class_t) logger = utils.loggers.cxx_parser mvars = class_type.variables( lambda v: not v.type_qualifiers.has_static, recursive=False, allow_empty=True) noncopyable_vars = [] if already_visited_cls_vars is None: already_visited_cls_vars = [] message = ( "__contains_noncopyable_mem_var - %s - TRUE - " + "contains const member variable") for mvar in mvars: var_type = type_traits.remove_reference(mvar.decl_type) if type_traits.is_const(var_type): no_const = type_traits.remove_const(var_type) if type_traits.is_fundamental(no_const) or is_enum(no_const): logger.debug( (message + "- fundamental or enum"), var_type.decl_string) noncopyable_vars.append(mvar) if is_class(no_const): logger.debug((message + " - class"), var_type.decl_string) noncopyable_vars.append(mvar) if type_traits.is_array(no_const): logger.debug((message + " - array"), var_type.decl_string) noncopyable_vars.append(mvar) if type_traits.is_pointer(var_type): continue if class_traits.is_my_case(var_type): cls = class_traits.get_declaration(var_type) # Exclude classes that have already been visited. if cls in already_visited_cls_vars: continue already_visited_cls_vars.append(cls) if is_noncopyable(cls, already_visited_cls_vars): logger.debug( (message + " - class that is not copyable"), var_type.decl_string) noncopyable_vars.append(mvar) logger.debug(( "__contains_noncopyable_mem_var - %s - FALSE - doesn't " + "contain noncopyable members"), class_type.decl_string) return noncopyable_vars
python
def find_noncopyable_vars(class_type, already_visited_cls_vars=None): assert isinstance(class_type, class_declaration.class_t) logger = utils.loggers.cxx_parser mvars = class_type.variables( lambda v: not v.type_qualifiers.has_static, recursive=False, allow_empty=True) noncopyable_vars = [] if already_visited_cls_vars is None: already_visited_cls_vars = [] message = ( "__contains_noncopyable_mem_var - %s - TRUE - " + "contains const member variable") for mvar in mvars: var_type = type_traits.remove_reference(mvar.decl_type) if type_traits.is_const(var_type): no_const = type_traits.remove_const(var_type) if type_traits.is_fundamental(no_const) or is_enum(no_const): logger.debug( (message + "- fundamental or enum"), var_type.decl_string) noncopyable_vars.append(mvar) if is_class(no_const): logger.debug((message + " - class"), var_type.decl_string) noncopyable_vars.append(mvar) if type_traits.is_array(no_const): logger.debug((message + " - array"), var_type.decl_string) noncopyable_vars.append(mvar) if type_traits.is_pointer(var_type): continue if class_traits.is_my_case(var_type): cls = class_traits.get_declaration(var_type) if cls in already_visited_cls_vars: continue already_visited_cls_vars.append(cls) if is_noncopyable(cls, already_visited_cls_vars): logger.debug( (message + " - class that is not copyable"), var_type.decl_string) noncopyable_vars.append(mvar) logger.debug(( "__contains_noncopyable_mem_var - %s - FALSE - doesn't " + "contain noncopyable members"), class_type.decl_string) return noncopyable_vars
[ "def", "find_noncopyable_vars", "(", "class_type", ",", "already_visited_cls_vars", "=", "None", ")", ":", "assert", "isinstance", "(", "class_type", ",", "class_declaration", ".", "class_t", ")", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "mvars", "=", "class_type", ".", "variables", "(", "lambda", "v", ":", "not", "v", ".", "type_qualifiers", ".", "has_static", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "noncopyable_vars", "=", "[", "]", "if", "already_visited_cls_vars", "is", "None", ":", "already_visited_cls_vars", "=", "[", "]", "message", "=", "(", "\"__contains_noncopyable_mem_var - %s - TRUE - \"", "+", "\"contains const member variable\"", ")", "for", "mvar", "in", "mvars", ":", "var_type", "=", "type_traits", ".", "remove_reference", "(", "mvar", ".", "decl_type", ")", "if", "type_traits", ".", "is_const", "(", "var_type", ")", ":", "no_const", "=", "type_traits", ".", "remove_const", "(", "var_type", ")", "if", "type_traits", ".", "is_fundamental", "(", "no_const", ")", "or", "is_enum", "(", "no_const", ")", ":", "logger", ".", "debug", "(", "(", "message", "+", "\"- fundamental or enum\"", ")", ",", "var_type", ".", "decl_string", ")", "noncopyable_vars", ".", "append", "(", "mvar", ")", "if", "is_class", "(", "no_const", ")", ":", "logger", ".", "debug", "(", "(", "message", "+", "\" - class\"", ")", ",", "var_type", ".", "decl_string", ")", "noncopyable_vars", ".", "append", "(", "mvar", ")", "if", "type_traits", ".", "is_array", "(", "no_const", ")", ":", "logger", ".", "debug", "(", "(", "message", "+", "\" - array\"", ")", ",", "var_type", ".", "decl_string", ")", "noncopyable_vars", ".", "append", "(", "mvar", ")", "if", "type_traits", ".", "is_pointer", "(", "var_type", ")", ":", "continue", "if", "class_traits", ".", "is_my_case", "(", "var_type", ")", ":", "cls", "=", "class_traits", ".", "get_declaration", "(", "var_type", ")", "# Exclude classes that have already been visited.", "if", "cls", "in", "already_visited_cls_vars", ":", "continue", "already_visited_cls_vars", ".", "append", "(", "cls", ")", "if", "is_noncopyable", "(", "cls", ",", "already_visited_cls_vars", ")", ":", "logger", ".", "debug", "(", "(", "message", "+", "\" - class that is not copyable\"", ")", ",", "var_type", ".", "decl_string", ")", "noncopyable_vars", ".", "append", "(", "mvar", ")", "logger", ".", "debug", "(", "(", "\"__contains_noncopyable_mem_var - %s - FALSE - doesn't \"", "+", "\"contain noncopyable members\"", ")", ",", "class_type", ".", "decl_string", ")", "return", "noncopyable_vars" ]
Returns list of all `noncopyable` variables. If an already_visited_cls_vars list is provided as argument, the returned list will not contain these variables. This list will be extended with whatever variables pointing to classes have been found. Args: class_type (declarations.class_t): the class to be searched. already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. Returns: list: list of all `noncopyable` variables.
[ "Returns", "list", "of", "all", "noncopyable", "variables", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L155-L228
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_trivial_constructor
def has_trivial_constructor(class_): """if class has public trivial constructor, this function will return reference to it, None otherwise""" class_ = class_traits.get_declaration(class_) trivial = find_trivial_constructor(class_) if trivial and trivial.access_type == 'public': return trivial
python
def has_trivial_constructor(class_): class_ = class_traits.get_declaration(class_) trivial = find_trivial_constructor(class_) if trivial and trivial.access_type == 'public': return trivial
[ "def", "has_trivial_constructor", "(", "class_", ")", ":", "class_", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "trivial", "=", "find_trivial_constructor", "(", "class_", ")", "if", "trivial", "and", "trivial", ".", "access_type", "==", "'public'", ":", "return", "trivial" ]
if class has public trivial constructor, this function will return reference to it, None otherwise
[ "if", "class", "has", "public", "trivial", "constructor", "this", "function", "will", "return", "reference", "to", "it", "None", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L231-L237
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_copy_constructor
def has_copy_constructor(class_): """if class has public copy constructor, this function will return reference to it, None otherwise""" class_ = class_traits.get_declaration(class_) copy_constructor = find_copy_constructor(class_) if copy_constructor and copy_constructor.access_type == 'public': return copy_constructor
python
def has_copy_constructor(class_): class_ = class_traits.get_declaration(class_) copy_constructor = find_copy_constructor(class_) if copy_constructor and copy_constructor.access_type == 'public': return copy_constructor
[ "def", "has_copy_constructor", "(", "class_", ")", ":", "class_", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "copy_constructor", "=", "find_copy_constructor", "(", "class_", ")", "if", "copy_constructor", "and", "copy_constructor", ".", "access_type", "==", "'public'", ":", "return", "copy_constructor" ]
if class has public copy constructor, this function will return reference to it, None otherwise
[ "if", "class", "has", "public", "copy", "constructor", "this", "function", "will", "return", "reference", "to", "it", "None", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L240-L246
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_destructor
def has_destructor(class_): """if class has destructor, this function will return reference to it, None otherwise""" class_ = class_traits.get_declaration(class_) destructor = class_.decls( decl_type=calldef_members.destructor_t, recursive=False, allow_empty=True) if destructor: return destructor[0]
python
def has_destructor(class_): class_ = class_traits.get_declaration(class_) destructor = class_.decls( decl_type=calldef_members.destructor_t, recursive=False, allow_empty=True) if destructor: return destructor[0]
[ "def", "has_destructor", "(", "class_", ")", ":", "class_", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "destructor", "=", "class_", ".", "decls", "(", "decl_type", "=", "calldef_members", ".", "destructor_t", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "if", "destructor", ":", "return", "destructor", "[", "0", "]" ]
if class has destructor, this function will return reference to it, None otherwise
[ "if", "class", "has", "destructor", "this", "function", "will", "return", "reference", "to", "it", "None", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L249-L258
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_public_constructor
def has_public_constructor(class_): """if class has any public constructor, this function will return list of them, otherwise None""" class_ = class_traits.get_declaration(class_) decls = class_.constructors( lambda c: not is_copy_constructor(c) and c.access_type == 'public', recursive=False, allow_empty=True) if decls: return decls
python
def has_public_constructor(class_): class_ = class_traits.get_declaration(class_) decls = class_.constructors( lambda c: not is_copy_constructor(c) and c.access_type == 'public', recursive=False, allow_empty=True) if decls: return decls
[ "def", "has_public_constructor", "(", "class_", ")", ":", "class_", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "decls", "=", "class_", ".", "constructors", "(", "lambda", "c", ":", "not", "is_copy_constructor", "(", "c", ")", "and", "c", ".", "access_type", "==", "'public'", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "if", "decls", ":", "return", "decls" ]
if class has any public constructor, this function will return list of them, otherwise None
[ "if", "class", "has", "any", "public", "constructor", "this", "function", "will", "return", "list", "of", "them", "otherwise", "None" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L261-L270
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_public_assign
def has_public_assign(class_): """returns True, if class has public assign operator, False otherwise""" class_ = class_traits.get_declaration(class_) decls = class_.member_operators( lambda o: o.symbol == '=' and o.access_type == 'public', recursive=False, allow_empty=True) return bool(decls)
python
def has_public_assign(class_): class_ = class_traits.get_declaration(class_) decls = class_.member_operators( lambda o: o.symbol == '=' and o.access_type == 'public', recursive=False, allow_empty=True) return bool(decls)
[ "def", "has_public_assign", "(", "class_", ")", ":", "class_", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "decls", "=", "class_", ".", "member_operators", "(", "lambda", "o", ":", "o", ".", "symbol", "==", "'='", "and", "o", ".", "access_type", "==", "'public'", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", "return", "bool", "(", "decls", ")" ]
returns True, if class has public assign operator, False otherwise
[ "returns", "True", "if", "class", "has", "public", "assign", "operator", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L273-L280
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
has_vtable
def has_vtable(decl_type): """True, if class has virtual table, False otherwise""" assert isinstance(decl_type, class_declaration.class_t) return bool( decl_type.calldefs( lambda f: isinstance(f, calldef_members.member_function_t) and f.virtuality != calldef_types.VIRTUALITY_TYPES.NOT_VIRTUAL, recursive=False, allow_empty=True))
python
def has_vtable(decl_type): assert isinstance(decl_type, class_declaration.class_t) return bool( decl_type.calldefs( lambda f: isinstance(f, calldef_members.member_function_t) and f.virtuality != calldef_types.VIRTUALITY_TYPES.NOT_VIRTUAL, recursive=False, allow_empty=True))
[ "def", "has_vtable", "(", "decl_type", ")", ":", "assert", "isinstance", "(", "decl_type", ",", "class_declaration", ".", "class_t", ")", "return", "bool", "(", "decl_type", ".", "calldefs", "(", "lambda", "f", ":", "isinstance", "(", "f", ",", "calldef_members", ".", "member_function_t", ")", "and", "f", ".", "virtuality", "!=", "calldef_types", ".", "VIRTUALITY_TYPES", ".", "NOT_VIRTUAL", ",", "recursive", "=", "False", ",", "allow_empty", "=", "True", ")", ")" ]
True, if class has virtual table, False otherwise
[ "True", "if", "class", "has", "virtual", "table", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L289-L297
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
is_base_and_derived
def is_base_and_derived(based, derived): """returns True, if there is "base and derived" relationship between classes, False otherwise""" assert isinstance(based, class_declaration.class_t) assert isinstance(derived, (class_declaration.class_t, tuple)) if isinstance(derived, class_declaration.class_t): all_derived = ([derived]) else: # tuple all_derived = derived for derived_cls in all_derived: for base_desc in derived_cls.recursive_bases: if base_desc.related_class == based: return True return False
python
def is_base_and_derived(based, derived): assert isinstance(based, class_declaration.class_t) assert isinstance(derived, (class_declaration.class_t, tuple)) if isinstance(derived, class_declaration.class_t): all_derived = ([derived]) else: all_derived = derived for derived_cls in all_derived: for base_desc in derived_cls.recursive_bases: if base_desc.related_class == based: return True return False
[ "def", "is_base_and_derived", "(", "based", ",", "derived", ")", ":", "assert", "isinstance", "(", "based", ",", "class_declaration", ".", "class_t", ")", "assert", "isinstance", "(", "derived", ",", "(", "class_declaration", ".", "class_t", ",", "tuple", ")", ")", "if", "isinstance", "(", "derived", ",", "class_declaration", ".", "class_t", ")", ":", "all_derived", "=", "(", "[", "derived", "]", ")", "else", ":", "# tuple", "all_derived", "=", "derived", "for", "derived_cls", "in", "all_derived", ":", "for", "base_desc", "in", "derived_cls", ".", "recursive_bases", ":", "if", "base_desc", ".", "related_class", "==", "based", ":", "return", "True", "return", "False" ]
returns True, if there is "base and derived" relationship between classes, False otherwise
[ "returns", "True", "if", "there", "is", "base", "and", "derived", "relationship", "between", "classes", "False", "otherwise" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L300-L315
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
__is_noncopyable_single
def __is_noncopyable_single(class_, already_visited_cls_vars=None): """ Implementation detail. Checks if the class is non copyable, without considering the base classes. Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. Returns: bool: if the class is non copyable """ # It is not enough to check base classes, we should also to check # member variables. logger = utils.loggers.cxx_parser if has_copy_constructor(class_) \ and has_public_constructor(class_) \ and has_public_assign(class_) \ and has_public_destructor(class_): msg = os.linesep.join([ "__is_noncopyable_single - %s - COPYABLE:" % class_.decl_string, " trivial copy constructor: yes", " public constructor: yes", " public assign: yes", " public destructor: yes"]) logger.debug(msg) return False if already_visited_cls_vars is None: already_visited_cls_vars = [] if find_noncopyable_vars(class_, already_visited_cls_vars): logger.debug( ("__is_noncopyable_single(TRUE) - %s - contains noncopyable " + "members"), class_.decl_string) return True logger.debug(( "__is_noncopyable_single(FALSE) - %s - COPYABLE, because is " + "doesn't contains noncopyable members"), class_.decl_string) return False
python
def __is_noncopyable_single(class_, already_visited_cls_vars=None): logger = utils.loggers.cxx_parser if has_copy_constructor(class_) \ and has_public_constructor(class_) \ and has_public_assign(class_) \ and has_public_destructor(class_): msg = os.linesep.join([ "__is_noncopyable_single - %s - COPYABLE:" % class_.decl_string, " trivial copy constructor: yes", " public constructor: yes", " public assign: yes", " public destructor: yes"]) logger.debug(msg) return False if already_visited_cls_vars is None: already_visited_cls_vars = [] if find_noncopyable_vars(class_, already_visited_cls_vars): logger.debug( ("__is_noncopyable_single(TRUE) - %s - contains noncopyable " + "members"), class_.decl_string) return True logger.debug(( "__is_noncopyable_single(FALSE) - %s - COPYABLE, because is " + "doesn't contains noncopyable members"), class_.decl_string) return False
[ "def", "__is_noncopyable_single", "(", "class_", ",", "already_visited_cls_vars", "=", "None", ")", ":", "# It is not enough to check base classes, we should also to check", "# member variables.", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "if", "has_copy_constructor", "(", "class_", ")", "and", "has_public_constructor", "(", "class_", ")", "and", "has_public_assign", "(", "class_", ")", "and", "has_public_destructor", "(", "class_", ")", ":", "msg", "=", "os", ".", "linesep", ".", "join", "(", "[", "\"__is_noncopyable_single - %s - COPYABLE:\"", "%", "class_", ".", "decl_string", ",", "\" trivial copy constructor: yes\"", ",", "\" public constructor: yes\"", ",", "\" public assign: yes\"", ",", "\" public destructor: yes\"", "]", ")", "logger", ".", "debug", "(", "msg", ")", "return", "False", "if", "already_visited_cls_vars", "is", "None", ":", "already_visited_cls_vars", "=", "[", "]", "if", "find_noncopyable_vars", "(", "class_", ",", "already_visited_cls_vars", ")", ":", "logger", ".", "debug", "(", "(", "\"__is_noncopyable_single(TRUE) - %s - contains noncopyable \"", "+", "\"members\"", ")", ",", "class_", ".", "decl_string", ")", "return", "True", "logger", ".", "debug", "(", "(", "\"__is_noncopyable_single(FALSE) - %s - COPYABLE, because is \"", "+", "\"doesn't contains noncopyable members\"", ")", ",", "class_", ".", "decl_string", ")", "return", "False" ]
Implementation detail. Checks if the class is non copyable, without considering the base classes. Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. Returns: bool: if the class is non copyable
[ "Implementation", "detail", "." ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L662-L705
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
is_noncopyable
def is_noncopyable(class_, already_visited_cls_vars=None): """ Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable """ logger = utils.loggers.cxx_parser class_decl = class_traits.get_declaration(class_) true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string if is_union(class_): return False if class_decl.is_abstract: logger.debug(true_header + "abstract client") return True # if class has public, user defined copy constructor, than this class is # copyable copy_ = find_copy_constructor(class_decl) if copy_ and copy_.access_type == 'public' and not copy_.is_artificial: return False if already_visited_cls_vars is None: already_visited_cls_vars = [] for base_desc in class_decl.recursive_bases: assert isinstance(base_desc, class_declaration.hierarchy_info_t) if base_desc.related_class.decl_string in \ ('::boost::noncopyable', '::boost::noncopyable_::noncopyable'): logger.debug(true_header + "derives from boost::noncopyable") return True if not has_copy_constructor(base_desc.related_class): base_copy_ = find_copy_constructor(base_desc.related_class) if base_copy_ and base_copy_.access_type == 'private': logger.debug( true_header + "there is private copy constructor") return True elif __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if not has_copy_constructor(class_decl): logger.debug(true_header + "does not have trivial copy constructor") return True elif not has_public_constructor(class_decl): logger.debug(true_header + "does not have a public constructor") return True elif has_destructor(class_decl) and not has_public_destructor(class_decl): logger.debug(true_header + "has private destructor") return True return __is_noncopyable_single(class_decl, already_visited_cls_vars)
python
def is_noncopyable(class_, already_visited_cls_vars=None): logger = utils.loggers.cxx_parser class_decl = class_traits.get_declaration(class_) true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string if is_union(class_): return False if class_decl.is_abstract: logger.debug(true_header + "abstract client") return True copy_ = find_copy_constructor(class_decl) if copy_ and copy_.access_type == 'public' and not copy_.is_artificial: return False if already_visited_cls_vars is None: already_visited_cls_vars = [] for base_desc in class_decl.recursive_bases: assert isinstance(base_desc, class_declaration.hierarchy_info_t) if base_desc.related_class.decl_string in \ ('::boost::noncopyable', '::boost::noncopyable_::noncopyable'): logger.debug(true_header + "derives from boost::noncopyable") return True if not has_copy_constructor(base_desc.related_class): base_copy_ = find_copy_constructor(base_desc.related_class) if base_copy_ and base_copy_.access_type == 'private': logger.debug( true_header + "there is private copy constructor") return True elif __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if not has_copy_constructor(class_decl): logger.debug(true_header + "does not have trivial copy constructor") return True elif not has_public_constructor(class_decl): logger.debug(true_header + "does not have a public constructor") return True elif has_destructor(class_decl) and not has_public_destructor(class_decl): logger.debug(true_header + "has private destructor") return True return __is_noncopyable_single(class_decl, already_visited_cls_vars)
[ "def", "is_noncopyable", "(", "class_", ",", "already_visited_cls_vars", "=", "None", ")", ":", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "class_decl", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "true_header", "=", "\"is_noncopyable(TRUE) - %s - \"", "%", "class_", ".", "decl_string", "if", "is_union", "(", "class_", ")", ":", "return", "False", "if", "class_decl", ".", "is_abstract", ":", "logger", ".", "debug", "(", "true_header", "+", "\"abstract client\"", ")", "return", "True", "# if class has public, user defined copy constructor, than this class is", "# copyable", "copy_", "=", "find_copy_constructor", "(", "class_decl", ")", "if", "copy_", "and", "copy_", ".", "access_type", "==", "'public'", "and", "not", "copy_", ".", "is_artificial", ":", "return", "False", "if", "already_visited_cls_vars", "is", "None", ":", "already_visited_cls_vars", "=", "[", "]", "for", "base_desc", "in", "class_decl", ".", "recursive_bases", ":", "assert", "isinstance", "(", "base_desc", ",", "class_declaration", ".", "hierarchy_info_t", ")", "if", "base_desc", ".", "related_class", ".", "decl_string", "in", "(", "'::boost::noncopyable'", ",", "'::boost::noncopyable_::noncopyable'", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"derives from boost::noncopyable\"", ")", "return", "True", "if", "not", "has_copy_constructor", "(", "base_desc", ".", "related_class", ")", ":", "base_copy_", "=", "find_copy_constructor", "(", "base_desc", ".", "related_class", ")", "if", "base_copy_", "and", "base_copy_", ".", "access_type", "==", "'private'", ":", "logger", ".", "debug", "(", "true_header", "+", "\"there is private copy constructor\"", ")", "return", "True", "elif", "__is_noncopyable_single", "(", "base_desc", ".", "related_class", ",", "already_visited_cls_vars", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"__is_noncopyable_single returned True\"", ")", "return", "True", "if", "__is_noncopyable_single", "(", "base_desc", ".", "related_class", ",", "already_visited_cls_vars", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"__is_noncopyable_single returned True\"", ")", "return", "True", "if", "not", "has_copy_constructor", "(", "class_decl", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"does not have trivial copy constructor\"", ")", "return", "True", "elif", "not", "has_public_constructor", "(", "class_decl", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"does not have a public constructor\"", ")", "return", "True", "elif", "has_destructor", "(", "class_decl", ")", "and", "not", "has_public_destructor", "(", "class_decl", ")", ":", "logger", ".", "debug", "(", "true_header", "+", "\"has private destructor\"", ")", "return", "True", "return", "__is_noncopyable_single", "(", "class_decl", ",", "already_visited_cls_vars", ")" ]
Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable
[ "Checks", "if", "class", "is", "non", "copyable" ]
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L708-L785