summaryrefslogtreecommitdiff
path: root/tools/g-ir-scanner
blob: e4c1862d66753228099630f74c8987ba3b762e85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env python
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2008  Johan Dahlin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

import subprocess
import optparse
import os
import sys

# This only works on unix systems
currentdir = os.path.dirname(os.path.abspath(sys.argv[0]))
basedir = os.path.abspath(os.path.join(currentdir, '..'))
if (os.path.exists(os.path.join(basedir, '.svn')) or
    os.path.exists(os.path.join(basedir, '.git'))):
    path = basedir
else:
    path = os.path.join(basedir, 'lib', 'python%d.%d' % sys.version_info[:2],
                        'site-packages')
sys.path.insert(0, path)

from giscanner.glibtransformer import GLibTransformer
from giscanner.sourcescanner import SourceScanner
from giscanner.transformer import Transformer
from giscanner.ast import Include
from giscanner.minixpath import myxpath, xpath_assert


def _get_option_parser():
    parser = optparse.OptionParser('%prog [options] sources')
    parser.add_option("", "--format",
                      action="store", dest="format",
                      default="gir",
                      help="format to use, one of gidl, gir")
    parser.add_option("-i", "--include",
                      action="append", dest="includes", default=[],
                      help="include types for other gidls")
    parser.add_option("--add-include-path",
                      action="append", dest="include_paths", default=[],
                      help="include paths for other GIR files")
    parser.add_option("-l", "--library",
                      action="append", dest="libraries", default=[],
                      help="libraries of this unit")
    parser.add_option("-L", "--library-path",
                      action="append", dest="library_paths", default=[],
                      help="directories to search for libraries")
    parser.add_option("-n", "--namespace",
                      action="store", dest="namespace_name",
                      help="name of namespace for this unit, also used as --strip-prefix default")
    parser.add_option("", "--nsversion",
                      action="store", dest="namespace_version",
                      help="version of namespace for this unit")
    parser.add_option("", "--strip-prefix",
                      action="store", dest="strip_prefix", default=None,
                      help="remove this prefix from objects and functions")
    parser.add_option("-o", "--output",
                      action="store", dest="output",
                      help="output to writeout, defaults to stdout")
    parser.add_option("", "--pkg",
                      action="append", dest="packages", default=[],
                      help="pkg-config packages to get cflags from")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose",
                      help="be verbose")
    parser.add_option("", "--noclosure",
                      action="store_true", dest="noclosure",
                      help="do not delete unknown types")
    parser.add_option("", "--typelib-xml",
                      action="store_true", dest="typelib_xml",
                      help="Just convert GIR to typelib XML")
    parser.add_option("", "--inject",
                      action="store_true", dest="inject",
                      help="Inject additional components into GIR XML")
    parser.add_option("", "--xpath-assertions",
                      action="store", dest="xpath_assertions",
                      help="Use given file to create assertions on GIR content")

    group = optparse.OptionGroup(parser, "Preprocessor options")
    group.add_option("-I", help="Pre-processor include file",
                     action="append", dest="cpp_includes",
                     default=[])
    group.add_option("-D", help="Pre-processor define",
                     action="append", dest="cpp_defines",
                     default=[])
    group.add_option("-U", help="Pre-processor undefine",
                     action="append", dest="cpp_undefines",
                     default=[])
    group.add_option("-p", dest="", help="Ignored")
    parser.add_option_group(group)

    return parser


def _error(msg):
    raise SystemExit('ERROR: %s' % (msg, ))

def typelib_xml_strip(path):
    from giscanner.girparser import GIRParser
    from giscanner.girwriter import GIRWriter
    from giscanner.girparser import C_NS
    c_ns_key = '{%s}' % (C_NS, )

    parser = GIRParser(path, initial_parse=False)
    doc = parser.get_doc()
    for node in doc.getiterator():
        for attrib in list(node.attrib):
            if attrib.startswith(c_ns_key):
                del node.attrib[attrib]
    parser.parse()
    writer = GIRWriter(parser.get_namespace(),
                       parser.get_shared_libraries(),
                       parser.get_includes())
    sys.stdout.write(writer.get_xml())
    return 0

def inject(path, additions, outpath):
    from giscanner.girparser import GIRParser
    from giscanner.girwriter import GIRWriter
    from xml.etree.cElementTree import parse

    parser = GIRParser(path, initial_parse=False)
    root = parser.get_doc().getroot()
    injectDoc = parse(open(additions))
    for node in injectDoc.getroot():
        injectPath = node.attrib['path']
        target = myxpath(root, injectPath)
        if not target:
            raise ValueError("Couldn't find path %r" % (injectPath, ))
        for child in node:
            target.append(child)
    parser.parse()
    writer = GIRWriter(parser.get_namespace(),
                       parser.get_shared_libraries(),
                       parser.get_includes())
    outf = open(outpath, 'w')
    outf.write(writer.get_xml())
    outf.close()
    return 0

def validate(assertions, path):
    from xml.etree.cElementTree import parse
    doc = parse(open(path))
    root = doc.getroot()
    f = open(assertions)
    assertions_list = f.readlines()
    print "=== CHECKING %s (%d assertions) ===" % (assertions,
                                                   len(assertions_list))
    for assertion in assertions_list:
        assertion = assertion.strip()
        xpath_assert(root, assertion)
    f.close()
    print "=== PASSED %s ===" % (assertions, )
    return 0

def main(args):
    parser = _get_option_parser()
    (options, args) = parser.parse_args(args)

    if len(args) <= 1:
        _error('Need at least one filename')

    if options.typelib_xml:
        return typelib_xml_strip(args[1])

    if options.inject:
        if len(args) != 4:
            _error('Need three filenames; e.g. g-ir-scanner --inject Source.gir Additions.xml SourceOut.gir')
        return inject(*args[1:4])

    if options.xpath_assertions:
        return validate(options.xpath_assertions, args[1])

    if not options.namespace_name:
        _error('Namespace name missing')

    if options.format == 'gir':
        from giscanner.girwriter import GIRWriter as Writer
    else:
        _error("Unknown format: %s" % (options.format, ))

    if not options.libraries:
        _error("Must specify --library at least one primary library")
    libraries = options.libraries

    for package in options.packages:
        output = subprocess.Popen(['pkg-config', '--cflags', package],
                                  stdout=subprocess.PIPE).communicate()[0]
        # Some pkg-config files on Windows have options we don't understand,
        # so we explicitly filter to only the ones we need.
        options_whitelist = ['-I', '-D', '-U', '-l', '-L']
        def filter_option(opt):
            for optstart in options_whitelist:
                if opt.startswith(optstart):
                    return True
            return False
        output = output.split()
        filtered_output = filter(filter_option, output)
        pkg_options, unused = parser.parse_args(filtered_output)
        options.cpp_includes.extend(pkg_options.cpp_includes)
        options.cpp_defines.extend(pkg_options.cpp_defines)
        options.cpp_undefines.extend(pkg_options.cpp_undefines)

        output = subprocess.Popen(['pkg-config', '--libs-only-L', package],
                                  stdout=subprocess.PIPE).communicate()[0]
        output = output.split()
        filtered_output = filter(filter_option, output)
        pkg_options, unused = parser.parse_args(filtered_output)
        options.library_paths.extend(pkg_options.library_paths)

    # FIXME: using LPATH is definitely not portable enough. Using Python's
    # find_library for finding our shared libraries is not a portable enough
    # anyway as it behaves differently depending on the OS
    lpath = os.environ.get('LPATH')
    library_path = ':'.join(options.library_paths)

    ld_library_path = os.environ.get('LD_LIBRARY_PATH')
    if ld_library_path:
        library_path = ':'.join([ld_library_path, library_path])

    if lpath:
        os.environ['LPATH'] = ':'.join([lpath, library_path])
    else:
        os.environ['LPATH'] = library_path

    filenames = []
    for arg in args:
        if (arg.endswith('.c') or
            arg.endswith('.h')):
            if not os.path.exists(arg):
                _error('%s: no such a file or directory' % (arg, ))
            filenames.append(arg)

    # Run the preprocessor, tokenize and construct simple
    # objects representing the raw C symbols
    ss = SourceScanner()
    ss.set_cpp_options(options.cpp_includes,
                       options.cpp_defines,
                       options.cpp_undefines)
    ss.parse_files(filenames)
    ss.parse_macros(filenames)

    # Transform the C symbols into AST nodes
    transformer = Transformer(ss, options.namespace_name, options.namespace_version)
    if options.strip_prefix:
        transformer.set_strip_prefix(options.strip_prefix)
    else:
        transformer.set_strip_prefix(options.namespace_name)
    transformer.set_include_paths(options.include_paths)
    shown_include_warning = False
    for include in options.includes:
        if os.sep in include:
            raise ValueError("Invalid include path %r" % (include, ))
        include_obj = Include.from_string(include)
        transformer.register_include(include_obj)

    # Transform the C AST nodes into higher level
    # GLib/GObject nodes
    glibtransformer = GLibTransformer(transformer, noclosure=options.noclosure)
    if options.libraries:
        for library in options.libraries:
            glibtransformer.add_library(library)

    namespace = glibtransformer.parse()

    # Write out AST
    writer = Writer(namespace, libraries, transformer.get_includes())
    data = writer.get_xml()
    if options.output:
        fd = open(options.output, "w")
        fd.write(data)
    else:
        print data

    return 0

sys.exit(main(sys.argv))