diff options
Diffstat (limited to 'giscanner')
-rw-r--r-- | giscanner/annotationmain.py | 1 | ||||
-rw-r--r-- | giscanner/annotationparser.py | 65 | ||||
-rw-r--r-- | giscanner/ast.py | 88 | ||||
-rw-r--r-- | giscanner/cachestore.py | 5 | ||||
-rw-r--r-- | giscanner/codegen.py | 12 | ||||
-rw-r--r-- | giscanner/docmain.py | 1 | ||||
-rw-r--r-- | giscanner/docwriter.py | 23 | ||||
-rw-r--r-- | giscanner/dumper.py | 13 | ||||
-rw-r--r-- | giscanner/gdumpparser.py | 9 | ||||
-rw-r--r-- | giscanner/girparser.py | 54 | ||||
-rw-r--r-- | giscanner/girwriter.py | 21 | ||||
-rw-r--r-- | giscanner/introspectablepass.py | 44 | ||||
-rw-r--r-- | giscanner/maintransformer.py | 61 | ||||
-rw-r--r-- | giscanner/message.py | 18 | ||||
-rwxr-xr-x | giscanner/scannermain.py | 30 | ||||
-rw-r--r-- | giscanner/sectionparser.py | 4 | ||||
-rw-r--r-- | giscanner/shlibs.py | 4 | ||||
-rw-r--r-- | giscanner/sourcescanner.py | 8 | ||||
-rw-r--r-- | giscanner/testcodegen.py | 3 | ||||
-rw-r--r-- | giscanner/transformer.py | 45 | ||||
-rw-r--r-- | giscanner/utils.py | 9 | ||||
-rwxr-xr-x | giscanner/xmlwriter.py | 18 |
22 files changed, 296 insertions, 240 deletions
diff --git a/giscanner/annotationmain.py b/giscanner/annotationmain.py index 4df6e831..304f5a32 100644 --- a/giscanner/annotationmain.py +++ b/giscanner/annotationmain.py @@ -26,6 +26,7 @@ from giscanner.scannermain import (get_preprocessor_option_group, create_source_scanner, process_packages) + def annotation_main(args): parser = optparse.OptionParser('%prog [options] sources') diff --git a/giscanner/annotationparser.py b/giscanner/annotationparser.py index c0b439a1..a0657dc4 100644 --- a/giscanner/annotationparser.py +++ b/giscanner/annotationparser.py @@ -141,7 +141,8 @@ OPT_TRANSFER_FLOATING = 'floating' # Program matching the start of a comment block. # # Results in 0 symbolic groups. -COMMENT_START_RE = re.compile(r''' +COMMENT_START_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters / # 1 forward slash character @@ -157,7 +158,8 @@ COMMENT_START_RE = re.compile(r''' # # Results in 1 symbolic group: # - group 1 = description -COMMENT_END_RE = re.compile(r''' +COMMENT_END_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<description>.*?) # description text @@ -173,7 +175,8 @@ COMMENT_END_RE = re.compile(r''' # line inside a comment block. # # Results in 0 symbolic groups. -COMMENT_ASTERISK_RE = re.compile(r''' +COMMENT_ASTERISK_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters \* # 1 asterisk character @@ -189,7 +192,8 @@ COMMENT_ASTERISK_RE = re.compile(r''' # # Results in 1 symbolic group: # - group 1 = indentation -COMMENT_INDENTATION_RE = re.compile(r''' +COMMENT_INDENTATION_RE = re.compile( + r''' ^ (?P<indentation>[^\S\n\r]*) # 0 or more whitespace characters .* @@ -200,7 +204,8 @@ COMMENT_INDENTATION_RE = re.compile(r''' # Program matching an empty line. # # Results in 0 symbolic groups. -EMPTY_LINE_RE = re.compile(r''' +EMPTY_LINE_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters $ # end @@ -212,7 +217,8 @@ EMPTY_LINE_RE = re.compile(r''' # Results in 2 symbolic groups: # - group 1 = colon # - group 2 = section_name -SECTION_RE = re.compile(r''' +SECTION_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters SECTION # SECTION @@ -231,7 +237,8 @@ SECTION_RE = re.compile(r''' # - group 1 = symbol_name # - group 2 = colon # - group 3 = annotations -SYMBOL_RE = re.compile(r''' +SYMBOL_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<symbol_name>[\w-]*\w) # symbol name @@ -251,7 +258,8 @@ SYMBOL_RE = re.compile(r''' # - group 2 = property_name # - group 3 = colon # - group 4 = annotations -PROPERTY_RE = re.compile(r''' +PROPERTY_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<class_name>[\w]+) # class name @@ -275,7 +283,8 @@ PROPERTY_RE = re.compile(r''' # - group 2 = signal_name # - group 3 = colon # - group 4 = annotations -SIGNAL_RE = re.compile(r''' +SIGNAL_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<class_name>[\w]+) # class name @@ -299,7 +308,8 @@ SIGNAL_RE = re.compile(r''' # - group 2 = annotations # - group 3 = colon # - group 4 = description -PARAMETER_RE = re.compile(r''' +PARAMETER_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters @ # @ character @@ -324,7 +334,8 @@ PARAMETER_RE = re.compile(r''' # - group 3 = colon # - group 4 = description _all_tags = '|'.join(_ALL_TAGS).replace(' ', '\\ ') -TAG_RE = re.compile(r''' +TAG_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<tag_name>''' + _all_tags + r''') # tag name @@ -348,7 +359,8 @@ TAG_RE = re.compile(r''' # - group 2 = annotations # - group 3 = colon # - group 4 = description -MULTILINE_ANNOTATION_CONTINUATION_RE = re.compile(r''' +MULTILINE_ANNOTATION_CONTINUATION_RE = re.compile( + r''' ^ # start [^\S\n\r]* # 0 or more whitespace characters (?P<annotations>(?:\(.*?\)[^\S\n\r]*)*) # annotations @@ -444,8 +456,8 @@ class DocTag(object): s = 'one value' else: s = '%d values' % (n_params, ) - if ((n_params > 0 and (value is None or value.length() != n_params)) or - n_params == 0 and value is not None): + if ((n_params > 0 and (value is None or value.length() != n_params)) + or n_params == 0 and value is not None): if value is None: length = 0 else: @@ -814,7 +826,7 @@ class AnnotationParser(object): if description: comment_lines[-1] = (line_offset, description) position = message.Position(filename, lineno + line_offset) - marker = ' '*result.end('description') + '^' + marker = ' ' * result.end('description') + '^' message.warn("Comments should end with */ on a new line:\n%s\n%s" % (line, marker), position) @@ -922,7 +934,7 @@ class AnnotationParser(object): if 'colon' in result.groupdict() and result.group('colon') != ':': colon_start = result.start('colon') colon_column = column_offset + colon_start - marker = ' '*colon_column + '^' + marker = ' ' * colon_column + '^' message.warn("missing ':' at column %s:\n%s\n%s" % (colon_column + 1, original_line, marker), position) @@ -942,7 +954,7 @@ class AnnotationParser(object): # right thing to do because sooner or later some long # descriptions will contain something matching an identifier # pattern by accident. - marker = ' '*column_offset + '^' + marker = ' ' * column_offset + '^' message.warn('ignoring unrecognized GTK-Doc comment block, identifier not ' 'found:\n%s\n%s' % (original_line, marker), position) @@ -965,7 +977,7 @@ class AnnotationParser(object): if in_part != PART_PARAMETERS: column = result.start('parameter_name') + column_offset - marker = ' '*column + '^' + marker = ' ' * column + '^' message.warn("'@%s' parameter unexpected at this location:\n%s\n%s" % (param_name, original_line, marker), position) @@ -983,7 +995,7 @@ class AnnotationParser(object): position) elif param_name in comment_block.params.keys(): column = result.start('parameter_name') + column_offset - marker = ' '*column + '^' + marker = ' ' * column + '^' message.warn("multiple '@%s' parameters for identifier '%s':\n%s\n%s" % (param_name, comment_block.name, original_line, marker), position) @@ -1007,8 +1019,7 @@ class AnnotationParser(object): # identifier (when there are no parameters) and encounter an empty # line, we must be parsing the comment block description. #################################################################### - if (EMPTY_LINE_RE.match(line) - and in_part in [PART_IDENTIFIER, PART_PARAMETERS]): + if (EMPTY_LINE_RE.match(line) and in_part in [PART_IDENTIFIER, PART_PARAMETERS]): in_part = PART_DESCRIPTION part_indent = line_indent continue @@ -1022,7 +1033,7 @@ class AnnotationParser(object): tag_annotations = result.group('annotations') tag_description = result.group('description') - marker = ' '*(result.start('tag_name') + column_offset) + '^' + marker = ' ' * (result.start('tag_name') + column_offset) + '^' # Deprecated GTK-Doc Description: tag if tag_name.lower() == TAG_DESCRIPTION: @@ -1047,7 +1058,7 @@ class AnnotationParser(object): if in_part != PART_TAGS: column = result.start('tag_name') + column_offset - marker = ' '*column + '^' + marker = ' ' * column + '^' message.warn("'%s:' tag unexpected at this location:\n%s\n%s" % (tag_name, original_line, marker), position) @@ -1071,7 +1082,7 @@ class AnnotationParser(object): else: if tag_name.lower() in comment_block.tags.keys(): column = result.start('tag_name') + column_offset - marker = ' '*column + '^' + marker = ' ' * column + '^' message.warn("multiple '%s:' tags for identifier '%s':\n%s\n%s" % (tag_name, comment_block.name, original_line, marker), position) @@ -1149,7 +1160,7 @@ class AnnotationParser(object): part.value = '' def _validate_multiline_annotation_continuation(self, line, original_line, - column_offset, position): + column_offset, position): ''' Validate parameters and tags (except the first line) and generate warnings about invalid annotations spanning multiple lines. @@ -1163,7 +1174,7 @@ class AnnotationParser(object): result = MULTILINE_ANNOTATION_CONTINUATION_RE.match(line) if result: column = result.start('annotations') + column_offset - marker = ' '*column + '^' + marker = ' ' * column + '^' message.warn('ignoring invalid multiline annotation continuation:\n' '%s\n%s' % (original_line, marker), position) @@ -1179,7 +1190,7 @@ class AnnotationParser(object): for i, c in enumerate(value): if c == '(' and opened == -1: - opened = i+1 + opened = i + 1 if c == ')' and opened != -1: segment = value[opened:i] parts = segment.split(' ', 1) diff --git a/giscanner/ast.py b/giscanner/ast.py index 25184886..4c54b548 100644 --- a/giscanner/ast.py +++ b/giscanner/ast.py @@ -28,15 +28,17 @@ from .collections import OrderedDict from .message import Position from .utils import to_underscores + class Type(object): - """A Type can be either: -* A reference to a node (target_giname) -* A reference to a "fundamental" type like 'utf8' -* A "foreign" type - this can be any string." -If none are specified, then it's in an "unresolved" state. An -unresolved type can have two data sources; a "ctype" which comes -from a C type string, or a gtype_name (from g_type_name()). -""" # ''' + """ + A Type can be either: + * A reference to a node (target_giname) + * A reference to a "fundamental" type like 'utf8' + * A "foreign" type - this can be any string." + If none are specified, then it's in an "unresolved" state. An + unresolved type can have two data sources; a "ctype" which comes + from a C type string, or a gtype_name (from g_type_name()). + """ def __init__(self, ctype=None, @@ -125,11 +127,12 @@ in contrast to the other create_type() functions.""" def __cmp__(self, other): if self.target_fundamental: return cmp(self.target_fundamental, other.target_fundamental) - if self.target_giname: + elif self.target_giname: return cmp(self.target_giname, other.target_giname) - if self.target_foreign: + elif self.target_foreign: return cmp(self.target_foreign, other.target_foreign) - return cmp(self.ctype, other.ctype) + else: + return cmp(self.ctype, other.ctype) def is_equiv(self, typeval): """Return True if the specified types are compatible at @@ -170,6 +173,7 @@ in contrast to the other create_type() functions.""" data = '' return '%s(%sctype=%s)' % (self.__class__.__name__, data, self.ctype) + class TypeUnknown(Type): def __init__(self): Type.__init__(self, _target_unknown=True) @@ -351,9 +355,7 @@ SIGNAL_MUST_COLLECT = 'must-collect' class Namespace(object): - def __init__(self, name, version, - identifier_prefixes=None, - symbol_prefixes=None): + def __init__(self, name, version, identifier_prefixes=None, symbol_prefixes=None): self.name = name self.version = version if identifier_prefixes is not None: @@ -367,15 +369,15 @@ class Namespace(object): self.symbol_prefixes = [to_underscores(p).lower() for p in ps] # cache upper-cased versions self._ucase_symbol_prefixes = [p.upper() for p in self.symbol_prefixes] - self.names = OrderedDict() # Maps from GIName -> node - self.aliases = {} # Maps from GIName -> GIName - self.type_names = {} # Maps from GTName -> node - self.ctypes = {} # Maps from CType -> node - self.symbols = {} # Maps from function symbols -> Function - self.includes = set() # Include - self.shared_libraries = [] # str - self.c_includes = [] # str - self.exported_packages = [] # str + self.names = OrderedDict() # Maps from GIName -> node + self.aliases = {} # Maps from GIName -> GIName + self.type_names = {} # Maps from GTName -> node + self.ctypes = {} # Maps from CType -> node + self.symbols = {} # Maps from function symbols -> Function + self.includes = set() # Include + self.shared_libraries = [] # str + self.c_includes = [] # str + self.exported_packages = [] # str def type_from_name(self, name, ctype=None): """Backwards compatibility method for older .gir files, which @@ -416,7 +418,7 @@ but adds it to things like ctypes, symbols, and type_names. if isinstance(node, (Class, Interface)): for m in chain(node.signals, node.properties): m.namespace = self - if isinstance(node, Enum) or isinstance(node, Bitfield): + if isinstance(node, (Enum, Bitfield)): for fn in node.static_methods: if not isinstance(fn, Function): continue @@ -482,6 +484,7 @@ functions via get_by_symbol().""" for node in self.itervalues(): node.walk(callback, []) + class Include(object): def __init__(self, name, version): @@ -504,6 +507,7 @@ class Include(object): def __str__(self): return '%s-%s' % (self.name, self.version) + class Annotated(object): """An object which has a few generic metadata properties.""" @@ -511,12 +515,13 @@ properties.""" self.version = None self.skip = False self.introspectable = True - self.attributes = [] # (key, value)* + self.attributes = [] # (key, value)* self.stability = None self.deprecated = None self.deprecated_version = None self.doc = None + class Node(Annotated): """A node is a type of object which is uniquely identified by its (namespace, name) pair. When combined with a ., this is called a @@ -527,7 +532,7 @@ GIName. It's possible for nodes to contain or point to other nodes.""" def __init__(self, name=None): Annotated.__init__(self) - self.namespace = None # Should be set later by Namespace.append() + self.namespace = None # Should be set later by Namespace.append() self.name = name self.foreign = False self.file_positions = set() @@ -596,8 +601,8 @@ class Callable(Node): self.retval = retval self.parameters = parameters self.throws = not not throws - self.instance_parameter = None # Parameter - self.parent = None # A Class or Interface + self.instance_parameter = None # Parameter + self.parent = None # A Class or Interface # Returns all parameters, including the instance parameter @property @@ -627,10 +632,10 @@ class Function(Callable): self.symbol = symbol self.is_method = False self.is_constructor = False - self.shadowed_by = None # C symbol string - self.shadows = None # C symbol string - self.moved_to = None # namespaced function name string - self.internal_skipped = False # if True, this func will not be written to GIR + self.shadowed_by = None # C symbol string + self.shadows = None # C symbol string + self.moved_to = None # namespaced function name string + self.internal_skipped = False # if True, this func will not be written to GIR def clone(self): clone = copy.copy(self) @@ -641,8 +646,7 @@ class Function(Callable): def is_type_meta_function(self): # Named correctly - if not (self.name.endswith('_get_type') or - self.name.endswith('_get_gtype')): + if not (self.name.endswith('_get_type') or self.name.endswith('_get_gtype')): return False # Doesn't have any parameters @@ -651,14 +655,13 @@ class Function(Callable): # Returns GType rettype = self.retval.type - if (not rettype.is_equiv(TYPE_GTYPE) and - rettype.target_giname != 'Gtk.Type'): - message.warn("function '%s' returns '%r', not a GType" % - (self.name, rettype)) + if (not rettype.is_equiv(TYPE_GTYPE) and rettype.target_giname != 'Gtk.Type'): + message.warn("function '%s' returns '%r', not a GType" % (self.name, rettype)) return False return True + class ErrorQuarkFunction(Function): def __init__(self, name, retval, parameters, throws, symbol, error_domain): @@ -679,7 +682,6 @@ class VFunction(Callable): return obj - class Varargs(Type): def __init__(self): @@ -715,6 +717,7 @@ class Array(Type): arr.size = self.size return arr + class List(Type): def __init__(self, name, element_type, **kwargs): @@ -727,6 +730,7 @@ class List(Type): def clone(self): return List(self.name, self.element_type) + class Map(Type): def __init__(self, key_type, value_type, **kwargs): @@ -739,6 +743,7 @@ class Map(Type): def clone(self): return Map(self.key_type, self.value_type) + class Alias(Node): def __init__(self, name, target, ctype=None): @@ -881,6 +886,7 @@ class Compound(Node, Registered): if field.anonymous_node is not None: field.anonymous_node.walk(callback, chain) + class Field(Annotated): def __init__(self, name, typenode, readable, writable, bits=None, @@ -894,7 +900,7 @@ class Field(Annotated): self.bits = bits self.anonymous_node = anonymous_node self.private = False - self.parent = None # a compound + self.parent = None # a compound def __cmp__(self, other): return cmp(self.name, other.name) @@ -1090,7 +1096,7 @@ class Property(Node): self.transfer = PARAM_TRANSFER_NONE else: self.transfer = transfer - self.parent = None # A Class or Interface + self.parent = None # A Class or Interface class Callback(Callable): diff --git a/giscanner/cachestore.py b/giscanner/cachestore.py index 5f66b66a..ad4c7a36 100644 --- a/giscanner/cachestore.py +++ b/giscanner/cachestore.py @@ -31,6 +31,7 @@ import giscanner _CACHE_VERSION_FILENAME = '.cache-version' + def _get_versionhash(): toplevel = os.path.dirname(giscanner.__file__) # Use pyc instead of py to avoid extra IO @@ -40,6 +41,7 @@ def _get_versionhash(): mtimes = (str(os.stat(source).st_mtime) for source in sources) return hashlib.sha1(''.join(mtimes)).hexdigest() + def _get_cachedir(): if 'GI_SCANNER_DISABLE_CACHE' in os.environ: return None @@ -150,8 +152,7 @@ class CacheStore(object): if store_filename is None: return - if (os.path.exists(store_filename) and - self._cache_is_valid(store_filename, filename)): + if (os.path.exists(store_filename) and self._cache_is_valid(store_filename, filename)): return None tmp_fd, tmp_filename = tempfile.mkstemp(prefix='g-ir-scanner-cache-') diff --git a/giscanner/codegen.py b/giscanner/codegen.py index b73a7da3..e9ed9415 100644 --- a/giscanner/codegen.py +++ b/giscanner/codegen.py @@ -24,6 +24,7 @@ from contextlib import contextmanager from . import ast + class CCodeGenerator(object): def __init__(self, namespace, out_h_filename, out_c_filename): self.out_h_filename = out_h_filename @@ -36,15 +37,16 @@ class CCodeGenerator(object): return '%s_%s' % (self.namespace.symbol_prefixes[0], name) def _typecontainer_to_ctype(self, param): - if (isinstance(param, ast.Parameter) and - param.direction in (ast.PARAM_DIRECTION_OUT, - ast.PARAM_DIRECTION_INOUT)): + if (isinstance(param, ast.Parameter) + and param.direction in (ast.PARAM_DIRECTION_OUT, ast.PARAM_DIRECTION_INOUT)): suffix = '*' else: suffix = '' - if (param.type.is_equiv((ast.TYPE_STRING, ast.TYPE_FILENAME)) and - param.transfer == ast.PARAM_TRANSFER_NONE): + + if (param.type.is_equiv((ast.TYPE_STRING, ast.TYPE_FILENAME)) + and param.transfer == ast.PARAM_TRANSFER_NONE): return "const gchar*" + suffix + return param.type.ctype + suffix def _write_prelude(self, out, func): diff --git a/giscanner/docmain.py b/giscanner/docmain.py index afd509ff..3287dcc6 100644 --- a/giscanner/docmain.py +++ b/giscanner/docmain.py @@ -24,6 +24,7 @@ import optparse from .docwriter import DocWriter from .transformer import Transformer + def doc_main(args): parser = optparse.OptionParser('%prog [options] GIR-file') diff --git a/giscanner/docwriter.py b/giscanner/docwriter.py index b3716ec6..982ab37c 100644 --- a/giscanner/docwriter.py +++ b/giscanner/docwriter.py @@ -31,6 +31,7 @@ from mako.lookup import TemplateLookup from . import ast, xmlwriter from .utils import to_underscores + def make_page_id(node, recursive=False): if isinstance(node, ast.Namespace): if recursive: @@ -51,6 +52,7 @@ def make_page_id(node, recursive=False): else: return '%s.%s' % (make_page_id(parent, recursive=True), node.name) + def get_node_kind(node): if isinstance(node, ast.Namespace): node_kind = 'namespace' @@ -78,6 +80,7 @@ def get_node_kind(node): return node_kind + class TemplatedScanner(object): def __init__(self, specs): self.specs = self.unmangle_specs(specs) @@ -141,6 +144,7 @@ class TemplatedScanner(object): if pos < len(text): yield ('other', text[pos:], None) + class DocstringScanner(TemplatedScanner): def __init__(self): specs = [ @@ -156,6 +160,7 @@ class DocstringScanner(TemplatedScanner): super(DocstringScanner, self).__init__(specs) + class DocFormatter(object): def __init__(self, transformer): self._transformer = transformer @@ -358,6 +363,7 @@ class DocFormatter(object): parent_chain.reverse() return parent_chain + class DocFormatterC(DocFormatter): language = "C" mime_type = "text/x-csrc" @@ -380,7 +386,7 @@ class DocFormatterC(DocFormatter): return getattr(node, 'ctype') def format_function_name(self, func): - if isinstance(func, (ast.Function)): + if isinstance(func, ast.Function): return func.symbol else: return func.name @@ -388,6 +394,7 @@ class DocFormatterC(DocFormatter): def get_parameters(self, node): return node.all_parameters + class DocFormatterIntrospectableBase(DocFormatter): def should_render_node(self, node): if isinstance(node, ast.Record) and node.is_gtype_struct_for is not None: @@ -398,6 +405,7 @@ class DocFormatterIntrospectableBase(DocFormatter): return super(DocFormatterIntrospectableBase, self).should_render_node(node) + class DocFormatterPython(DocFormatterIntrospectableBase): language = "Python" mime_type = "text/python" @@ -418,7 +426,7 @@ class DocFormatterPython(DocFormatterIntrospectableBase): if getattr(node, "is_method", False): return True - if isinstance(node, (ast.VFunction)): + if isinstance(node, ast.VFunction): return True return False @@ -451,8 +459,7 @@ class DocFormatterPython(DocFormatterIntrospectableBase): "GParam": "GLib.Param", "PyObject": "object", "GStrv": "[str]", - "GVariant": "GLib.Variant", - } + "GVariant": "GLib.Variant"} return fundamental_types.get(name, name) @@ -476,6 +483,7 @@ class DocFormatterPython(DocFormatterIntrospectableBase): def get_parameters(self, node): return node.all_parameters + class DocFormatterGjs(DocFormatterIntrospectableBase): language = "Gjs" mime_type = "text/x-gjs" @@ -490,7 +498,7 @@ class DocFormatterGjs(DocFormatterIntrospectableBase): if getattr(node, "is_method", False): return True - if isinstance(node, (ast.VFunction)): + if isinstance(node, ast.VFunction): return True return False @@ -514,8 +522,7 @@ class DocFormatterGjs(DocFormatterIntrospectableBase): "GParam": "GLib.Param", "PyObject": "Object", "GStrv": "[String]", - "GVariant": "GLib.Variant", - } + "GVariant": "GLib.Variant"} return fundamental_types.get(name, name) @@ -558,12 +565,14 @@ class DocFormatterGjs(DocFormatterIntrospectableBase): params.append(param) return params + LANGUAGES = { "c": DocFormatterC, "python": DocFormatterPython, "gjs": DocFormatterGjs, } + class DocWriter(object): def __init__(self, transformer, language): self._transformer = transformer diff --git a/giscanner/dumper.py b/giscanner/dumper.py index b9f529ea..157b24da 100644 --- a/giscanner/dumper.py +++ b/giscanner/dumper.py @@ -223,7 +223,7 @@ class DumpCompiler(object): # The Microsoft compiler uses different option flags for # compilation result output if self._pkgconfig_msvc_flags: - args.extend(['-c', '-Fe'+output, '-Fo'+output]) + args.extend(['-c', '-Fe' + output, '-Fo' + output]) else: args.extend(['-c', '-o', output]) for source in sources: @@ -254,7 +254,7 @@ class DumpCompiler(object): # We can use -o for the Microsoft compiler/linker, # but it is considered deprecated usage with that if self._pkgconfig_msvc_flags: - args.extend(['-Fe'+output]) + args.extend(['-Fe' + output]) else: args.extend(['-o', output]) if libtool: @@ -313,9 +313,9 @@ class DumpCompiler(object): if self._options.namespace_version: args.append(str.lower(self._options.namespace_name) + '-' + - self._options.namespace_version+'.lib') + self._options.namespace_version + '.lib') else: - args.append(str.lower(self._options.namespace_name)+'.lib') + args.append(str.lower(self._options.namespace_name) + '.lib') else: args.append('-Wl,-rpath=.') @@ -329,7 +329,7 @@ class DumpCompiler(object): # to .lib files, not the .dll as the --library option specifies the # .dll(s) the .gir file refers to if self._pkgconfig_msvc_flags == '': - if library.endswith(".la"): # explicitly specified libtool library + if library.endswith(".la"): # explicitly specified libtool library args.append(library) else: args.append('-l' + library) @@ -358,11 +358,12 @@ class DumpCompiler(object): # The --library option on Windows pass in the .dll file(s) the # .gir files refer to, so don't link to them on Visual C++ if self._pkgconfig_msvc_flags == '': - if library.endswith(".la"): # explicitly specified libtool library + if library.endswith(".la"): # explicitly specified libtool library args.append(library) else: args.append('-l' + library) + def compile_introspection_binary(options, get_type_functions, error_quark_functions): dc = DumpCompiler(options, get_type_functions, error_quark_functions) diff --git a/giscanner/gdumpparser.py b/giscanner/gdumpparser.py index 79525030..568777bd 100644 --- a/giscanner/gdumpparser.py +++ b/giscanner/gdumpparser.py @@ -203,8 +203,7 @@ blob containing data gleaned from GObject's primitive introspection.""" def _initparse_gobject_record(self, record): if (record.name.startswith('ParamSpec') - and not record.name in ('ParamSpecPool', 'ParamSpecClass', - 'ParamSpecTypeInfo')): + and not record.name in ('ParamSpecPool', 'ParamSpecClass', 'ParamSpecTypeInfo')): parent = None if record.name != 'ParamSpec': parent = ast.Type(target_giname='GObject.ParamSpec') @@ -280,7 +279,6 @@ blob containing data gleaned from GObject's primitive introspection.""" member.attrib['name'], member.attrib['nick'])) - if xmlnode.tag == 'flags': klass = ast.Bitfield else: @@ -437,7 +435,7 @@ different --identifier-prefix.""" % (xmlnode.attrib['name'], self._namespace.ide if i == 0: argname = 'object' else: - argname = 'p%s' % (i-1, ) + argname = 'p%s' % (i - 1, ) pctype = parameter.attrib['type'] ptype = ast.Type.create_from_gtype_name(pctype) param = ast.Parameter(argname, ptype) @@ -526,8 +524,7 @@ different --identifier-prefix.""" % (xmlnode.attrib['name'], self._namespace.ide return False def _strip_class_suffix(self, name): - if (name.endswith('Class') or - name.endswith('Iface')): + if (name.endswith('Class') or name.endswith('Iface')): return name[:-5] elif name.endswith('Interface'): return name[:-9] diff --git a/giscanner/girparser.py b/giscanner/girparser.py index 63a3fd02..2538036a 100644 --- a/giscanner/girparser.py +++ b/giscanner/girparser.py @@ -101,9 +101,8 @@ class GIRParser(object): assert root.tag == _corens('repository') version = root.attrib['version'] if version != COMPATIBLE_GIR_VERSION: - raise SystemExit("%s: Incompatible version %s (supported: %s)" \ - % (self._get_current_file(), - version, COMPATIBLE_GIR_VERSION)) + raise SystemExit("%s: Incompatible version %s (supported: %s)" % + (self._get_current_file(), version, COMPATIBLE_GIR_VERSION)) for node in root.getchildren(): if node.tag == _corens('include'): @@ -122,9 +121,9 @@ class GIRParser(object): if symbol_prefixes: symbol_prefixes = symbol_prefixes.split(',') self._namespace = ast.Namespace(ns.attrib['name'], - ns.attrib['version'], - identifier_prefixes=identifier_prefixes, - symbol_prefixes=symbol_prefixes) + ns.attrib['version'], + identifier_prefixes=identifier_prefixes, + symbol_prefixes=symbol_prefixes) if 'shared-library' in ns.attrib: self._namespace.shared_libraries = ns.attrib['shared-library'].split(',') self._namespace.includes = self._includes @@ -140,8 +139,7 @@ class GIRParser(object): _corens('interface'): self._parse_object_interface, _corens('record'): self._parse_record, _corens('union'): self._parse_union, - _glibns('boxed'): self._parse_boxed, - } + _glibns('boxed'): self._parse_boxed} if not self._types_only: parser_methods[_corens('constant')] = self._parse_constant @@ -153,8 +151,7 @@ class GIRParser(object): method(node) def _parse_include(self, node): - include = ast.Include(node.attrib['name'], - node.attrib['version']) + include = ast.Include(node.attrib['name'], node.attrib['version']) self._includes.add(include) def _parse_pkgconfig_package(self, node): @@ -165,9 +162,7 @@ class GIRParser(object): def _parse_alias(self, node): typeval = self._parse_type(node) - alias = ast.Alias(node.attrib['name'], - typeval, - node.attrib.get(_cns('type'))) + alias = ast.Alias(node.attrib['name'], typeval, node.attrib.get(_cns('type'))) self._parse_generic_attribs(node, alias) self._namespace.append(alias) @@ -427,7 +422,8 @@ class GIRParser(object): return ast.Type(ctype=ctype) elif name in ['GLib.List', 'GLib.SList']: subchild = self._find_first_child(typenode, - map(_corens, ('callback', 'array', 'varargs', 'type'))) + map(_corens, ('callback', 'array', + 'varargs', 'type'))) if subchild is not None: element_type = self._parse_type(typenode) else: @@ -438,9 +434,7 @@ class GIRParser(object): subchildren_types = map(self._parse_type_simple, subchildren) while len(subchildren_types) < 2: subchildren_types.append(ast.TYPE_ANY) - return ast.Map(subchildren_types[0], - subchildren_types[1], - ctype=ctype) + return ast.Map(subchildren_types[0], subchildren_types[1], ctype=ctype) else: return self._namespace.type_from_name(name, ctype) else: @@ -462,8 +456,8 @@ class GIRParser(object): lenidx = typenode.attrib.get('length') if lenidx is not None: idx = int(lenidx) - assert idx < len(parent.parameters), "%r %d >= %d" \ - % (parent, idx, len(parent.parameters)) + assert idx < len(parent.parameters), "%r %d >= %d" % (parent, idx, + len(parent.parameters)) typeval.length_param_name = parent.parameters[idx].argname def _parse_boxed(self, node): @@ -509,11 +503,11 @@ class GIRParser(object): assert node.tag == _corens('field'), node.tag type_node = self._parse_type(node) field = ast.Field(node.attrib.get('name'), - type_node, - node.attrib.get('readable') != '0', - node.attrib.get('writable') == '1', - node.attrib.get('bits'), - anonymous_node=anonymous_node) + type_node, + node.attrib.get('readable') != '0', + node.attrib.get('writable') == '1', + node.attrib.get('bits'), + anonymous_node=anonymous_node) field.private = node.attrib.get('private') == '1' field.parent = parent self._parse_generic_attribs(node, field) @@ -521,12 +515,12 @@ class GIRParser(object): def _parse_property(self, node, parent): prop = ast.Property(node.attrib['name'], - self._parse_type(node), - node.attrib.get('readable') != '0', - node.attrib.get('writable') == '1', - node.attrib.get('construct') == '1', - node.attrib.get('construct-only') == '1', - node.attrib.get('transfer-ownership')) + self._parse_type(node), + node.attrib.get('readable') != '0', + node.attrib.get('writable') == '1', + node.attrib.get('construct') == '1', + node.attrib.get('construct-only') == '1', + node.attrib.get('transfer-ownership')) self._parse_generic_attribs(node, prop) prop.parent = parent return prop diff --git a/giscanner/girwriter.py b/giscanner/girwriter.py index 2578a331..e7af2533 100644 --- a/giscanner/girwriter.py +++ b/giscanner/girwriter.py @@ -28,14 +28,15 @@ from .xmlwriter import XMLWriter # Compatible changes we just make inline COMPATIBLE_GIR_VERSION = '1.2' + class GIRWriter(XMLWriter): def __init__(self, namespace): super(GIRWriter, self).__init__() self.write_comment( -'''This file was automatically generated from C sources - DO NOT EDIT! -To affect the contents of this file, edit the original C definitions, -and/or use gtk-doc annotations. ''') + 'This file was automatically generated from C sources - DO NOT EDIT!\n' + 'To affect the contents of this file, edit the original C definitions,\n' + 'and/or use gtk-doc annotations. ') self._write_repository(namespace) def _write_repository(self, namespace): @@ -43,8 +44,7 @@ and/or use gtk-doc annotations. ''') ('version', COMPATIBLE_GIR_VERSION), ('xmlns', 'http://www.gtk.org/introspection/core/1.0'), ('xmlns:c', 'http://www.gtk.org/introspection/c/1.0'), - ('xmlns:glib', 'http://www.gtk.org/introspection/glib/1.0'), - ] + ('xmlns:glib', 'http://www.gtk.org/introspection/glib/1.0')] with self.tagcontext('repository', attrs): for include in sorted(namespace.includes): self._write_include(include) @@ -292,8 +292,8 @@ and/or use gtk-doc annotations. ''') attrs.append(('fixed-size', '%d' % (ntype.size, ))) if ntype.length_param_name is not None: assert function - attrs.insert(0, ('length', '%d' - % (function.get_parameter_index(ntype.length_param_name, )))) + length = function.get_parameter_index(ntype.length_param_name) + attrs.insert(0, ('length', '%d' % (length, ))) with self.tagcontext('array', attrs): self._write_type(ntype.element_type) @@ -482,7 +482,7 @@ and/or use gtk-doc annotations. ''') attrs = list(extra_attrs) if record.name is not None: attrs.append(('name', record.name)) - if record.ctype is not None: # the record might be anonymous + if record.ctype is not None: # the record might be anonymous attrs.append(('c:type', record.ctype)) if record.disguised: attrs.append(('disguised', '1')) @@ -513,7 +513,7 @@ and/or use gtk-doc annotations. ''') attrs = [] if union.name is not None: attrs.append(('name', union.name)) - if union.ctype is not None: # the union might be anonymous + if union.ctype is not None: # the union might be anonymous attrs.append(('c:type', union.ctype)) self._append_version(union, attrs) self._append_node_generic(union, attrs) @@ -544,8 +544,7 @@ and/or use gtk-doc annotations. ''') elif isinstance(field.anonymous_node, ast.Union): self._write_union(field.anonymous_node) else: - raise AssertionError("Unknown field anonymous: %r" \ - % (field.anonymous_node, )) + raise AssertionError("Unknown field anonymous: %r" % (field.anonymous_node, )) else: attrs = [('name', field.name)] self._append_node_generic(field, attrs) diff --git a/giscanner/introspectablepass.py b/giscanner/introspectablepass.py index 3e295391..3d67c73e 100644 --- a/giscanner/introspectablepass.py +++ b/giscanner/introspectablepass.py @@ -21,6 +21,7 @@ from . import ast from . import message from .annotationparser import TAG_RETURNS + class IntrospectablePass(object): def __init__(self, transformer, blocks): @@ -79,7 +80,7 @@ class IntrospectablePass(object): if not node.type.resolved: self._parameter_warning(parent, node, -"Unresolved type: %r" % (node.type.unresolved_string, )) + "Unresolved type: %r" % (node.type.unresolved_string, )) parent.introspectable = False return @@ -88,22 +89,23 @@ class IntrospectablePass(object): return if (isinstance(node.type, (ast.List, ast.Array)) - and node.type.element_type == ast.TYPE_ANY): + and node.type.element_type == ast.TYPE_ANY): self._parameter_warning(parent, node, "Missing (element-type) annotation") parent.introspectable = False return if (is_parameter - and isinstance(target, ast.Callback) - and not node.type.target_giname in ('GLib.DestroyNotify', - 'Gio.AsyncReadyCallback') - and node.scope is None): - self._parameter_warning(parent, node, - ("Missing (scope) annotation for callback" + - " without GDestroyNotify (valid: %s, %s)") - % (ast.PARAM_SCOPE_CALL, ast.PARAM_SCOPE_ASYNC)) - parent.introspectable = False - return + and isinstance(target, ast.Callback) + and not node.type.target_giname in ('GLib.DestroyNotify', 'Gio.AsyncReadyCallback') + and node.scope is None): + self._parameter_warning( + parent, + node, + "Missing (scope) annotation for callback without " + "GDestroyNotify (valid: %s, %s)" % (ast.PARAM_SCOPE_CALL, ast.PARAM_SCOPE_ASYNC)) + + parent.introspectable = False + return if is_return and isinstance(target, ast.Callback): self._parameter_warning(parent, node, "Callbacks cannot be return values; use (skip)") @@ -111,12 +113,14 @@ class IntrospectablePass(object): return if (is_return - and isinstance(target, (ast.Record, ast.Union)) - and target.get_type is None - and not target.foreign): + and isinstance(target, (ast.Record, ast.Union)) + and target.get_type is None + and not target.foreign): if node.transfer != ast.PARAM_TRANSFER_NONE: - self._parameter_warning(parent, node, -"Invalid non-constant return of bare structure or union; register as boxed type or (skip)") + self._parameter_warning( + parent, node, + "Invalid non-constant return of bare structure or union; " + "register as boxed type or (skip)") parent.introspectable = False return @@ -143,10 +147,10 @@ class IntrospectablePass(object): # These are not introspectable pending us adding # larger type tags to the typelib (in theory these could # be 128 bit or larger) - if typeval.is_equiv((ast.TYPE_LONG_LONG, ast.TYPE_LONG_ULONG, - ast.TYPE_LONG_DOUBLE)): + elif typeval.is_equiv((ast.TYPE_LONG_LONG, ast.TYPE_LONG_ULONG, ast.TYPE_LONG_DOUBLE)): return False - return True + else: + return True target = self._transformer.lookup_typenode(typeval) if not target: return False diff --git a/giscanner/maintransformer.py b/giscanner/maintransformer.py index 8292f8eb..6acc5947 100644 --- a/giscanner/maintransformer.py +++ b/giscanner/maintransformer.py @@ -37,6 +37,7 @@ from .annotationparser import (OPT_ALLOW_NONE, OPT_ARRAY, OPT_ATTRIBUTE, OPT_TRANSFER_NONE, OPT_TRANSFER_FLOATING) from .utils import to_underscores_noprefix + class MainTransformer(object): def __init__(self, transformer, blocks): @@ -105,7 +106,7 @@ class MainTransformer(object): def _pass_fixup_hidden_fields(self, node, chain): """Hide all callbacks starting with _; the typical -usage is void (*_gtk_reserved1)(void);""" + usage is void (*_gtk_reserved1)(void);""" if isinstance(node, (ast.Class, ast.Interface, ast.Record, ast.Union)): for field in node.fields: if (field @@ -204,7 +205,7 @@ usage is void (*_gtk_reserved1)(void);""" if isinstance(node, ast.Function): self._apply_annotations_function(node, chain) if isinstance(node, ast.Callback): - self._apply_annotations_callable(node, chain, block = self._get_block(node)) + self._apply_annotations_callable(node, chain, block=self._get_block(node)) if isinstance(node, (ast.Class, ast.Interface, ast.Union, ast.Enum, ast.Bitfield, ast.Callback)): self._apply_annotations_annotated(node, self._get_block(node)) @@ -257,7 +258,7 @@ usage is void (*_gtk_reserved1)(void);""" Use resolver() on each identifier, and combiner() on the parts of each complete type. (top_combiner is used on the top-most type.)""" bits = re.split(r'([,<>()])', type_str, 1) - first, sep, rest = [bits[0], '', ''] if (len(bits)==1) else bits + first, sep, rest = [bits[0], '', ''] if (len(bits) == 1) else bits args = [resolver(first)] if sep == '<' or sep == '(': lastsep = '>' if (sep == '<') else ')' @@ -268,9 +269,11 @@ usage is void (*_gtk_reserved1)(void);""" else: rest = sep + rest return top_combiner(*args), rest + def resolver(ident): res = self._transformer.create_type_from_user_string(ident) return res + def combiner(base, *rest): if not rest: return base @@ -281,6 +284,7 @@ usage is void (*_gtk_reserved1)(void);""" message.warn( "Too many parameters in type specification %r" % (type_str, )) return base + def top_combiner(base, *rest): if type_node is not None and isinstance(type_node, ast.Type): base.is_const = type_node.is_const @@ -327,24 +331,23 @@ usage is void (*_gtk_reserved1)(void);""" return block.position def _check_array_element_type(self, array, options): + array_type = array.array_type + element_type = array.element_type + # GPtrArrays are allowed to contain non basic types # (except enums and flags) or basic types that are # as big as a gpointer - if array.array_type == ast.Array.GLIB_PTRARRAY and \ - ((array.element_type in ast.BASIC_GIR_TYPES - and not array.element_type in ast.POINTER_TYPES) or - isinstance(array.element_type, ast.Enum) or - isinstance(array.element_type, ast.Bitfield)): - message.warn("invalid (element-type) for a GPtrArray, " - "must be a pointer", options.position) + if array_type == ast.Array.GLIB_PTRARRAY: + if ((element_type in ast.BASIC_GIR_TYPES and not element_type in ast.POINTER_TYPES) + or isinstance(element_type, (ast.Enum, ast.Bitfield))): + message.warn("invalid (element-type) for a GPtrArray, " + "must be a pointer", options.position) # GByteArrays have (element-type) guint8 by default - if array.array_type == ast.Array.GLIB_BYTEARRAY: - if array.element_type == ast.TYPE_ANY: + if array_type == ast.Array.GLIB_BYTEARRAY: + if element_type == ast.TYPE_ANY: array.element_type = ast.TYPE_UINT8 - elif not array.element_type in [ast.TYPE_UINT8, - ast.TYPE_INT8, - ast.TYPE_CHAR]: + elif not element_type in [ast.TYPE_UINT8, ast.TYPE_INT8, ast.TYPE_CHAR]: message.warn("invalid (element-type) for a GByteArray, " "must be one of guint8, gint8 or gchar", options.position) @@ -454,8 +457,8 @@ usage is void (*_gtk_reserved1)(void);""" def _get_transfer_default_returntype_basic(self, typeval): if (typeval.is_equiv(ast.BASIC_GIR_TYPES) - or typeval.is_const - or typeval.is_equiv(ast.TYPE_NONE)): + or typeval.is_const + or typeval.is_equiv(ast.TYPE_NONE)): return ast.PARAM_TRANSFER_NONE elif typeval.is_equiv(ast.TYPE_STRING): # Non-const strings default to FULL @@ -535,8 +538,7 @@ usage is void (*_gtk_reserved1)(void);""" caller_allocates = False annotated_direction = None - if (OPT_INOUT in options or - OPT_INOUT_ALT in options): + if (OPT_INOUT in options or OPT_INOUT_ALT in options): annotated_direction = ast.PARAM_DIRECTION_INOUT elif OPT_OUT in options: subtype = options[OPT_OUT] @@ -574,9 +576,9 @@ usage is void (*_gtk_reserved1)(void);""" self._adjust_container_type(parent, node, options) - if (OPT_ALLOW_NONE in options or - node.type.target_giname == 'Gio.AsyncReadyCallback' or - node.type.target_giname == 'Gio.Cancellable'): + if (OPT_ALLOW_NONE in options + or node.type.target_giname == 'Gio.AsyncReadyCallback' + or node.type.target_giname == 'Gio.Cancellable'): node.allow_none = True if tag is not None and tag.comment is not None: @@ -605,7 +607,7 @@ usage is void (*_gtk_reserved1)(void);""" if ': ' in value: colon = value.find(': ') version = value[:colon] - desc = value[colon+2:] + desc = value[colon + 2:] else: desc = value version = None @@ -718,8 +720,7 @@ usage is void (*_gtk_reserved1)(void);""" (param, ) = unused text = ', should be %r' % (param, ) else: - text = ', should be one of %s' % ( - ', '.join(repr(p) for p in unused), ) + text = ', should be one of %s' % (', '.join(repr(p) for p in unused), ) tag = block.params.get(doc_name) message.warn( @@ -795,14 +796,14 @@ usage is void (*_gtk_reserved1)(void);""" # Resolve real parameter names early, so that in later # phase we can refer to them while resolving annotations. for i, param in enumerate(signal.parameters): - param.argname, tag = names[i+1] + param.argname, tag = names[i + 1] else: message.warn("incorrect number of parameters in comment block, " "parameter annotations will be ignored.", block.position) for i, param in enumerate(signal.parameters): if names: - name, tag = names[i+1] + name, tag = names[i + 1] options = getattr(tag, 'options', {}) param_type = options.get(OPT_TYPE) if param_type: @@ -1164,9 +1165,9 @@ method or constructor of some type.""" origin_node = self._get_constructor_class(func, subsymbol) if origin_node is None: if func.is_constructor: - message.warn_node(func, - "Can't find matching type for constructor; symbol=%r" \ - % (func.symbol, )) + message.warn_node( + func, + "Can't find matching type for constructor; symbol=%r" % (func.symbol, )) return False # Some sanity checks; only objects and boxeds can have ctors diff --git a/giscanner/message.py b/giscanner/message.py index 8a948cd3..3a330afe 100644 --- a/giscanner/message.py +++ b/giscanner/message.py @@ -61,7 +61,7 @@ class Position(object): return '%s:' % (filename, ) def offset(self, offset): - return Position(self.filename, self.line+offset, self.column) + return Position(self.filename, self.line + offset, self.column) class MessageLogger(object): @@ -119,16 +119,14 @@ If the warning is related to a ast.Node type, see log_node().""" elif log_type == FATAL: error_type = "Fatal" if prefix: - text = ( -'''%s: %s: %s: %s: %s\n''' % (last_position, error_type, self._namespace.name, - prefix, text)) + text = ('%s: %s: %s: %s: %s\n' % (last_position, error_type, + self._namespace.name, prefix, text)) else: if self._namespace: - text = ( -'''%s: %s: %s: %s\n''' % (last_position, error_type, self._namespace.name, text)) + text = ('%s: %s: %s: %s\n' % (last_position, error_type, + self._namespace.name, text)) else: - text = ( -'''%s: %s: %s\n''' % (last_position, error_type, text)) + text = ('%s: %s: %s\n' % (last_position, error_type, text)) self._output.write(text) if log_type == FATAL: @@ -169,17 +167,21 @@ def log_node(log_type, node, text, context=None, positions=None): ml = MessageLogger.get() ml.log_node(log_type, node, text, context=context, positions=positions) + def warn(text, positions=None, prefix=None): ml = MessageLogger.get() ml.log(WARNING, text, positions, prefix) + def warn_node(node, text, context=None, positions=None): log_node(WARNING, node, text, context=context, positions=positions) + def warn_symbol(symbol, text): ml = MessageLogger.get() ml.log_symbol(WARNING, symbol, text) + def fatal(text, positions=None, prefix=None): ml = MessageLogger.get() ml.log(FATAL, text, positions, prefix) diff --git a/giscanner/scannermain.py b/giscanner/scannermain.py index 8ccd1f09..00dc30d6 100755 --- a/giscanner/scannermain.py +++ b/giscanner/scannermain.py @@ -42,14 +42,17 @@ from giscanner.sourcescanner import SourceScanner, ALL_EXTS from giscanner.transformer import Transformer from . import utils + def process_cflags_begin(option, opt, value, parser): cflags = getattr(parser.values, option.dest) while len(parser.rargs) > 0 and parser.rargs[0] != '--cflags-end': cflags.append(parser.rargs.pop(0)) + def process_cflags_end(option, opt, value, parser): pass + def get_preprocessor_option_group(parser): group = optparse.OptionGroup(parser, "Preprocessor options") group.add_option("", "--cflags-begin", @@ -71,6 +74,7 @@ def get_preprocessor_option_group(parser): group.add_option("-p", dest="", help="Ignored") return group + def get_windows_option_group(parser): group = optparse.OptionGroup(parser, "Machine Dependent Options") group.add_option("-m", help="some machine dependent option", @@ -79,13 +83,13 @@ def get_windows_option_group(parser): return group + def _get_option_parser(): parser = optparse.OptionParser('%prog [options] sources') parser.add_option('', "--quiet", action="store_true", dest="quiet", default=False, - help="If passed, do not print details of normal" \ - + " operation") + help="If passed, do not print details of normal operation") parser.add_option("", "--format", action="store", dest="format", default="gir", @@ -204,6 +208,7 @@ match the namespace prefix.""") def _error(msg): raise SystemExit('ERROR: %s' % (msg, )) + def passthrough_gir(path, f): parser = GIRParser() parser.parse(path) @@ -211,6 +216,7 @@ def passthrough_gir(path, f): writer = GIRWriter(parser.get_namespace()) f.write(writer.get_xml()) + def test_codegen(optstring): (namespace, out_h_filename, out_c_filename) = optstring.split(',') if namespace == 'Everything': @@ -221,6 +227,7 @@ def test_codegen(optstring): _error("Invaild namespace %r" % (namespace, )) return 0 + def process_options(output, allowed_flags): for option in output.split(): for flag in allowed_flags: @@ -229,6 +236,7 @@ def process_options(output, allowed_flags): yield option break + def process_packages(options, packages): args = ['pkg-config', '--cflags'] args.extend(packages) @@ -248,6 +256,7 @@ def process_packages(options, packages): options.cpp_defines.extend(pkg_options.cpp_defines) options.cpp_undefines.extend(pkg_options.cpp_undefines) + def extract_filenames(args): filenames = [] for arg in args: @@ -261,6 +270,7 @@ def extract_filenames(args): filenames.append(os.path.abspath(arg)) return filenames + def extract_filelist(options): filenames = [] if not os.path.exists(options.filelist): @@ -271,10 +281,10 @@ def extract_filelist(options): # We don't support real C++ parsing yet, but we should be able # to understand C API implemented in C++ files. filename = line.strip() - if (filename.endswith('.c') or filename.endswith('.cpp') or - filename.endswith('.cc') or filename.endswith('.cxx') or - filename.endswith('.h') or filename.endswith('.hpp') or - filename.endswith('.hxx')): + if (filename.endswith('.c') or filename.endswith('.cpp') + or filename.endswith('.cc') or filename.endswith('.cxx') + or filename.endswith('.h') or filename.endswith('.hpp') + or filename.endswith('.hxx')): if not os.path.exists(filename): _error('%s: Invalid filelist entry-no such file or directory' % (line, )) # Make absolute, because we do comparisons inside scannerparser.c @@ -282,6 +292,7 @@ def extract_filelist(options): filenames.append(os.path.abspath(filename)) return filenames + def create_namespace(options): if options.strip_prefix: print """g-ir-scanner: warning: Option --strip-prefix has been deprecated; @@ -310,6 +321,7 @@ see --identifier-prefix and --symbol-prefix.""" identifier_prefixes=identifier_prefixes, symbol_prefixes=symbol_prefixes) + def create_transformer(namespace, options): transformer = Transformer(namespace, accept_unprefixed=options.accept_unprefixed) @@ -331,6 +343,7 @@ def create_transformer(namespace, options): return transformer + def create_binary(transformer, options, args): # Transform the C AST nodes into higher level # GLib/GObject nodes @@ -341,7 +354,7 @@ def create_binary(transformer, options, args): gdump_parser.init_parse() if options.program: - args=[options.program] + args = [options.program] args.extend(options.program_args) binary = IntrospectionBinary(args) else: @@ -354,6 +367,7 @@ def create_binary(transformer, options, args): gdump_parser.parse() return shlibs + def create_source_scanner(options, args): if hasattr(options, 'filelist') and options.filelist: filenames = extract_filelist(options) @@ -371,6 +385,7 @@ def create_source_scanner(options, args): ss.parse_macros(filenames) return ss + def write_output(data, options): if options.output == "-": output = sys.stdout @@ -407,6 +422,7 @@ def write_output(data, options): except IOError as e: _error("while writing output: %s" % (e.strerror, )) + def scanner_main(args): parser = _get_option_parser() (options, args) = parser.parse_args(args) diff --git a/giscanner/sectionparser.py b/giscanner/sectionparser.py index 0b013be1..61763e45 100644 --- a/giscanner/sectionparser.py +++ b/giscanner/sectionparser.py @@ -19,10 +19,12 @@ import re + class SectionsFile(object): def __init__(self, sections): self.sections = sections + class Section(object): def __init__(self): self.file = None @@ -30,11 +32,13 @@ class Section(object): self.includes = None self.subsections = [] + class Subsection(object): def __init__(self, name): self.name = name self.symbols = [] + def parse_sections_file(lines): sections = [] current_section = None diff --git a/giscanner/shlibs.py b/giscanner/shlibs.py index 4f622db3..1241827d 100644 --- a/giscanner/shlibs.py +++ b/giscanner/shlibs.py @@ -26,6 +26,7 @@ import subprocess from .utils import get_libtool_command, extract_libtool_shlib + # For .la files, the situation is easy. def _resolve_libtool(options, binary, libraries): shlibs = [] @@ -36,6 +37,7 @@ def _resolve_libtool(options, binary, libraries): return shlibs + # Assume ldd output is something vaguely like # # libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0x006c1000) @@ -51,6 +53,7 @@ def _ldd_library_pattern(library_name): return re.compile("(?<![A-Za-z0-9_-])(lib*%s[^A-Za-z0-9_-][^\s\(\)]*)" % re.escape(library_name)) + # This is a what we do for non-la files. We assume that we are on an # ELF-like system where ldd exists and the soname extracted with ldd is # a filename that can be opened with dlopen(). @@ -118,6 +121,7 @@ def _resolve_non_libtool(options, binary, libraries): return shlibs + # We want to resolve a set of library names (the <foo> of -l<foo>) # against a library to find the shared library name. The shared # library name is suppose to be what you pass to dlopen() (or diff --git a/giscanner/sourcescanner.py b/giscanner/sourcescanner.py index 736ddbd4..d5c43926 100644 --- a/giscanner/sourcescanner.py +++ b/giscanner/sourcescanner.py @@ -93,8 +93,7 @@ def symbol_type_name(symbol_type): CSYMBOL_TYPE_UNION: 'union', CSYMBOL_TYPE_ENUM: 'enum', CSYMBOL_TYPE_TYPEDEF: 'typedef', - CSYMBOL_TYPE_MEMBER: 'member', - }.get(symbol_type) + CSYMBOL_TYPE_MEMBER: 'member'}.get(symbol_type) def ctype_name(ctype): @@ -108,8 +107,7 @@ def ctype_name(ctype): CTYPE_ENUM: 'enum', CTYPE_POINTER: 'pointer', CTYPE_ARRAY: 'array', - CTYPE_FUNCTION: 'function', - }.get(ctype) + CTYPE_FUNCTION: 'function'}.get(ctype) class SourceType(object): @@ -266,7 +264,7 @@ class SourceScanner(object): return self._scanner.get_comments() def dump(self): - print '-'*30 + print '-' * 30 for symbol in self._scanner.get_symbols(): print symbol.ident, symbol.base_type.name, symbol.type diff --git a/giscanner/testcodegen.py b/giscanner/testcodegen.py index f304dc7a..1ed247c7 100644 --- a/giscanner/testcodegen.py +++ b/giscanner/testcodegen.py @@ -27,12 +27,14 @@ DEFAULT_C_VALUES = {ast.TYPE_ANY: 'NULL', ast.TYPE_FILENAME: '""', ast.TYPE_GTYPE: 'g_object_get_type ()'} + def get_default_for_typeval(typeval): default = DEFAULT_C_VALUES.get(typeval) if default: return default return "0" + def uscore_from_type(typeval): if typeval.target_fundamental: return typeval.target_fundamental.replace(' ', '_') @@ -41,6 +43,7 @@ def uscore_from_type(typeval): else: assert False, typeval + class EverythingCodeGenerator(object): def __init__(self, out_h_filename, out_c_filename): diff --git a/giscanner/transformer.py b/giscanner/transformer.py index f1aa165d..f70d756a 100644 --- a/giscanner/transformer.py +++ b/giscanner/transformer.py @@ -34,6 +34,7 @@ from .sourcescanner import ( CSYMBOL_TYPE_MEMBER, CSYMBOL_TYPE_ELLIPSIS, CSYMBOL_TYPE_CONST, TYPE_QUALIFIER_CONST, TYPE_QUALIFIER_VOLATILE) + class TransformerException(Exception): pass @@ -54,7 +55,7 @@ class Transformer(object): self._namespace = namespace self._pkg_config_packages = set() self._typedefs_ns = {} - self._parsed_includes = {} # <string namespace -> Namespace> + self._parsed_includes = {} # <string namespace -> Namespace> self._includepaths = [] self._passthrough_mode = False @@ -104,7 +105,7 @@ class Transformer(object): if not ns_compound: ns_compound = self._namespace.get('_' + compound.name) if (not ns_compound and isinstance(compound, (ast.Record, ast.Union)) - and len(compound.fields) == 0): + and len(compound.fields) == 0): disguised = ast.Record(compound.name, typedef, disguised=True) self._namespace.append(disguised) elif not ns_compound: @@ -126,8 +127,8 @@ class Transformer(object): def register_include_uninstalled(self, include_path): basename = os.path.basename(include_path) if not basename.endswith('.gir'): - raise SystemExit( -"Include path %r must be a filename path ending in .gir" % (include_path, )) + raise SystemExit("Include path %r must be a filename path " + "ending in .gir" % (include_path, )) girname = basename[:-4] include = ast.Include.from_string(girname) if include in self._namespace.includes: @@ -175,8 +176,7 @@ None.""" path = os.path.join(d, girname) if os.path.exists(path): return path - sys.stderr.write("Couldn't find include %r (search path: %r)\n"\ - % (girname, searchdirs)) + sys.stderr.write("Couldn't find include %r (search path: %r)\n" % (girname, searchdirs)) sys.exit(1) @classmethod @@ -228,7 +228,7 @@ currently-scanned namespace is first.""" def _split_c_string_for_namespace_matches(self, name, is_identifier=False): matches = [] # Namespaces which might contain this name - unprefixed_namespaces = [] # Namespaces with no prefix, last resort + unprefixed_namespaces = [] # Namespaces with no prefix, last resort for ns in self._iter_namespaces(): if is_identifier: prefixes = ns.identifier_prefixes @@ -502,8 +502,8 @@ raise ValueError.""" def _create_member(self, symbol, parent_symbol=None): source_type = symbol.base_type - if (source_type.type == CTYPE_POINTER and - symbol.base_type.base_type.type == CTYPE_FUNCTION): + if (source_type.type == CTYPE_POINTER + and symbol.base_type.base_type.type == CTYPE_FUNCTION): node = self._create_callback(symbol, member=True) elif source_type.type == CTYPE_STRUCT and source_type.name is None: node = self._create_struct(symbol, anonymous=True) @@ -519,8 +519,8 @@ raise ValueError.""" # to be able to properly calculate the size of the compound # type (e.g. GValue) that contains this array, see # <https://bugzilla.gnome.org/show_bug.cgi?id=657040>. - if (source_type.base_type.type == CTYPE_UNION and - source_type.base_type.name is None): + if (source_type.base_type.type == CTYPE_UNION + and source_type.base_type.name is None): synthesized_type = self._synthesize_union_type(symbol, parent_symbol) ftype = ast.Array(None, synthesized_type, complete_ctype=complete_ctype) else: @@ -558,11 +558,9 @@ raise ValueError.""" def _create_typedef(self, symbol): ctype = symbol.base_type.type - if (ctype == CTYPE_POINTER and - symbol.base_type.base_type.type == CTYPE_FUNCTION): + if (ctype == CTYPE_POINTER and symbol.base_type.base_type.type == CTYPE_FUNCTION): node = self._create_typedef_callback(symbol) - elif (ctype == CTYPE_POINTER and - symbol.base_type.base_type.type == CTYPE_STRUCT): + elif (ctype == CTYPE_POINTER and symbol.base_type.base_type.type == CTYPE_STRUCT): node = self._create_typedef_struct(symbol, disguised=True) elif ctype == CTYPE_STRUCT: node = self._create_typedef_struct(symbol) @@ -627,8 +625,7 @@ raise ValueError.""" derefed_typename = canonical.replace('*', '') # Preserve "pointerness" of struct/union members - if (is_member and canonical.endswith('*') and - derefed_typename in ast.basic_type_names): + if (is_member and canonical.endswith('*') and derefed_typename in ast.basic_type_names): return 'gpointer' else: return derefed_typename @@ -714,8 +711,7 @@ raise ValueError.""" # Don't create constants for non-public things # http://bugzilla.gnome.org/show_bug.cgi?id=572790 - if (symbol.source_filename is None or - not symbol.source_filename.endswith('.h')): + if (symbol.source_filename is None or not symbol.source_filename.endswith('.h')): return None try: name = self._strip_symbol(symbol) @@ -738,13 +734,13 @@ raise ValueError.""" if isinstance(target, ast.Type): unaliased = target if unaliased == ast.TYPE_UINT64: - value = str(symbol.const_int % 2**64) + value = str(symbol.const_int % 2 ** 64) elif unaliased == ast.TYPE_UINT32: - value = str(symbol.const_int % 2**32) + value = str(symbol.const_int % 2 ** 32) elif unaliased == ast.TYPE_UINT16: - value = str(symbol.const_int % 2**16) + value = str(symbol.const_int % 2 ** 16) elif unaliased == ast.TYPE_UINT8: - value = str(symbol.const_int % 2**16) + value = str(symbol.const_int % 2 ** 16) else: value = str(symbol.const_int) elif symbol.const_double is not None: @@ -842,8 +838,7 @@ raise ValueError.""" # Mark the 'user_data' arguments for i, param in enumerate(parameters): - if (param.type.target_fundamental == 'gpointer' and - param.argname == 'user_data'): + if (param.type.target_fundamental == 'gpointer' and param.argname == 'user_data'): param.closure_name = param.argname if member: diff --git a/giscanner/utils.py b/giscanner/utils.py index 9adf6d93..77d05b9e 100644 --- a/giscanner/utils.py +++ b/giscanner/utils.py @@ -22,7 +22,10 @@ import re import os import subprocess + _debugflags = None + + def have_debug_flag(flag): """Check for whether a specific debugging feature is enabled. Well-known flags: @@ -38,6 +41,7 @@ Well-known flags: _debugflags.remove('') return flag in _debugflags + def break_on_debug_flag(flag): if have_debug_flag(flag): import pdb @@ -69,8 +73,10 @@ def to_underscores_noprefix(name): name = _upperstr_pat2.sub(r'\1_\2', name) return name + _libtool_pat = re.compile("dlname='([A-z0-9\.\-\+]+)'\n") + def _extract_dlname_field(la_file): f = open(la_file) data = f.read() @@ -81,6 +87,7 @@ def _extract_dlname_field(la_file): else: return None + # Returns the name that we would pass to dlopen() the library # corresponding to this .la file def extract_libtool_shlib(la_file): @@ -92,6 +99,7 @@ def extract_libtool_shlib(la_file): # a path rather than the raw dlname return os.path.basename(dlname) + def extract_libtool(la_file): dlname = _extract_dlname_field(la_file) if dlname is None: @@ -104,6 +112,7 @@ def extract_libtool(la_file): libname = libname.replace('.libs/.libs', '.libs') return libname + # Returns arguments for invoking libtool, if applicable, otherwise None def get_libtool_command(options): libtool_infection = not options.nolibtool diff --git a/giscanner/xmlwriter.py b/giscanner/xmlwriter.py index 4a1dc9fb..6efe684d 100755 --- a/giscanner/xmlwriter.py +++ b/giscanner/xmlwriter.py @@ -44,8 +44,7 @@ def _calc_attrs_length(attributes, indent, self_indent): return attr_length + indent + self_indent -def collect_attributes(tag_name, attributes, self_indent, - self_indent_char, indent=-1): +def collect_attributes(tag_name, attributes, self_indent, self_indent_char, indent=-1): if not attributes: return '' if _calc_attrs_length(attributes, indent, self_indent) > 79: @@ -68,6 +67,7 @@ def collect_attributes(tag_name, attributes, self_indent, first = False return attr_value + def build_xml_tag(tag_name, attributes=None, data=None, self_indent=0, self_indent_char=' '): if attributes is None: @@ -86,6 +86,7 @@ def build_xml_tag(tag_name, attributes=None, data=None, self_indent=0, len(prefix) + len(suffix)) return prefix + attrs + suffix + with LibtoolImporter(None, None): if 'UNINSTALLED_INTROSPECTION_SRCDIR' in os.environ: from _giscanner import collect_attributes @@ -108,10 +109,8 @@ class XMLWriter(object): def _open_tag(self, tag_name, attributes=None): if attributes is None: attributes = [] - attrs = collect_attributes( - tag_name, attributes, self._indent, - self._indent_char, - len(tag_name) + 2) + attrs = collect_attributes(tag_name, attributes, + self._indent, self._indent_char, len(tag_name) + 2) self.write_line(u'<%s%s>' % (tag_name, attrs)) def _close_tag(self, tag_name): @@ -137,10 +136,9 @@ class XMLWriter(object): if do_escape: line = escape(line) if indent: - self._data.write('%s%s%s' % ( - self._indent_char * self._indent, - line.encode('utf-8'), - self._newline_char)) + self._data.write('%s%s%s' % (self._indent_char * self._indent, + line.encode('utf-8'), + self._newline_char)) else: self._data.write('%s%s' % (line.encode('utf-8'), self._newline_char)) |