summaryrefslogtreecommitdiff
path: root/giscanner/scannermain.py
blob: 630acb6fdb947070a7adf002148fd244dcd078dc (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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2008-2010 Johan Dahlin
# Copyright (C) 2009 Red Hat, Inc.
#
# 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 errno
import optparse
import os
import shutil
import subprocess
import sys
import tempfile

from giscanner import message
from giscanner.annotationparser import AnnotationParser
from giscanner.ast import Include, Namespace
from giscanner.dumper import compile_introspection_binary
from giscanner.gdumpparser import GDumpParser, IntrospectionBinary
from giscanner.introspectablepass import IntrospectablePass
from giscanner.girparser import GIRParser
from giscanner.girwriter import GIRWriter
from giscanner.maintransformer import MainTransformer
from giscanner.shlibs import resolve_shlibs
from giscanner.sourcescanner import SourceScanner
from giscanner.transformer import Transformer
from . import utils

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")
    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="Add specified gir file as dependency")
    parser.add_option("", "--include-uninstalled",
                      action="append", dest="includes_uninstalled", default=[],
                      help=("""A file path to a dependency; only use this "
                            "when building multiple .gir files inside a "
                            "single module."""))
    parser.add_option("", "--add-include-path",
                      action="append", dest="include_paths", default=[],
                      help="include paths for other GIR files")
    parser.add_option("", "--program",
                      action="store", dest="program", default=None,
                      help="program to execute")
    parser.add_option("", "--program-arg",
                      action="append", dest="program_args", default=[],
                      help="extra arguments to program")
    parser.add_option("", "--libtool",
                      action="store", dest="libtool_path", default=None,
                      help="full path to libtool")
    parser.add_option("", "--no-libtool",
                      action="store_true", dest="nolibtool", default=False,
                      help="do not use libtool")
    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 to compute --identifier-prefix and --symbol-prefix"))
    parser.add_option("", "--nsversion",
                      action="store", dest="namespace_version",
                      help="version of namespace for this unit")
    parser.add_option("", "--identifier-prefix",
                      action="append", dest="identifier_prefixes", default=[],
                      help="""Remove this prefix from C identifiers (structure typedefs, etc.).
May be specified multiple times.  This is also used as the default for --symbol-prefix if
the latter is not specified.""")
    parser.add_option("", "--symbol-prefix",
                      action="append", dest="symbol_prefixes", default=[],
                      help="Remove this prefix from C symbols (function names)")
    parser.add_option("", "--accept-unprefixed",
                      action="store_true", dest="accept_unprefixed", default=False,
                      help="""If specified, accept symbols and identifiers that do not
match the namespace prefix.""")
    parser.add_option("", "--add-init-section",
                      action="append", dest="init_sections", default=[],
            help="add extra initialization code in the introspection program")
    parser.add_option("-o", "--output",
                      action="store", dest="output", default="-",
                      help="output filename to write to, defaults to - (stdout)")
    parser.add_option("", "--pkg",
                      action="append", dest="packages", default=[],
                      help="pkg-config packages to get cflags from")
    parser.add_option("", "--pkg-export",
                      action="append", dest="packages_export", default=[],
                      help="Associated pkg-config packages for this library")
    parser.add_option('', "--warn-all",
                      action="store_true", dest="warn_all", default=False,
                      help="If true, enable all warnings for introspection")
    parser.add_option('', "--warn-error",
                      action="store_true", dest="warn_fatal",
                      help="Turn warnings into fatal errors")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose",
                      help="be verbose")
    parser.add_option("", "--c-include",
                      action="append", dest="c_includes", default=[],
                      help="headers which should be included in C programs")

    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)

    # Private options
    parser.add_option('', "--generate-typelib-tests",
                      action="store", dest="test_codegen", default=None,
                      help=optparse.SUPPRESS_HELP)
    parser.add_option('', "--passthrough-gir",
                      action="store", dest="passthrough_gir", default=None,
                      help=optparse.SUPPRESS_HELP)
    parser.add_option('', "--reparse-validate",
                      action="store_true", dest="reparse_validate_gir", default=False,
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("", "--typelib-xml",
                      action="store_true", dest="typelib_xml",
                      help=optparse.SUPPRESS_HELP)

    return parser


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

def passthrough_gir(path, f):
    parser = GIRParser()
    parser.parse(path)

    writer = GIRWriter(parser.get_namespace(),
                       parser.get_shared_libraries(),
                       parser.get_includes(),
                       parser.get_pkgconfig_packages(),
                       parser.get_c_includes())
    f.write(writer.get_xml())

def test_codegen(optstring):
    (namespace, out_h_filename, out_c_filename) = optstring.split(',')
    if namespace == 'Everything':
        from .testcodegen import EverythingCodeGenerator
        gen = EverythingCodeGenerator(out_h_filename, out_c_filename)
        gen.write()
    else:
        _error("Invaild namespace %r" % (namespace, ))
    return 0

def process_options(output, allowed_flags):
    for option in output.split():
        for flag in allowed_flags:
            if not option.startswith(flag):
                continue
            yield option
            break

def process_packages(options, packages):
    args = ['pkg-config', '--cflags']
    args.extend(packages)
    output = subprocess.Popen(args,
                              stdout=subprocess.PIPE).communicate()[0]
    if output is None:
        # the error output should have already appeared on our stderr,
        # so we just exit
        return 1
    # 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']
    filtered_output = list(process_options(output, options_whitelist))
    parser = _get_option_parser()
    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)

    args = ['pkg-config', '--libs-only-L']
    args.extend(packages)
    output = subprocess.Popen(args,
                              stdout=subprocess.PIPE).communicate()[0]
    if output is None:
        return 1
    filtered_output = list(process_options(output, options_whitelist))
    pkg_options, unused = parser.parse_args(filtered_output)
    options.library_paths.extend(pkg_options.library_paths)

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

    if options.passthrough_gir:
        passthrough_gir(options.passthrough_gir, sys.stdout)
    if options.test_codegen:
        return test_codegen(options.test_codegen)

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

    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 or options.program):
        _error("Must specify --program or --library")
    libraries = options.libraries

    filenames = []
    for arg in args:
        # We don't support real C++ parsing yet, but we should be able
        # to understand C API implemented in C++ files.
        if (arg.endswith('.c') or arg.endswith('.cpp') or
            arg.endswith('.cc') or arg.endswith('.cxx') or
            arg.endswith('.h') or arg.endswith('.hpp') or
            arg.endswith('.hxx')):
            if not os.path.exists(arg):
                _error('%s: no such a file or directory' % (arg, ))
            # Make absolute, because we do comparisons inside scannerparser.c
            # against the absolute path that cpp will give us
            filenames.append(os.path.abspath(arg))

    # We do this dance because the empty list has different semantics from
    # None; if the user didn't specify the options, we want to use None so
    # the Namespace constructor picks the defaults.
    if options.identifier_prefixes:
        identifier_prefixes = options.identifier_prefixes
    else:
        identifier_prefixes = None
    if options.symbol_prefixes:
        symbol_prefixes = options.symbol_prefixes
    else:
        symbol_prefixes = None

    namespace = Namespace(options.namespace_name,
                          options.namespace_version,
                          identifier_prefixes=identifier_prefixes,
                          symbol_prefixes=symbol_prefixes)
    logger = message.MessageLogger.get(namespace=namespace)
    if options.warn_all:
        logger.enable_warnings(True)
    transformer = Transformer(namespace,
                              accept_unprefixed=options.accept_unprefixed)
    transformer.set_include_paths(options.include_paths)
    shown_include_warning = False
    for include in options.includes:
        if os.sep in include:
            _error("Invalid include path %r" % (include, ))
        try:
            include_obj = Include.from_string(include)
        except:
            _error("Malformed include %r\n" % (include, ))
        transformer.register_include(include_obj)
    for include_path in options.includes_uninstalled:
        transformer.register_include_uninstalled(include_path)

    packages = set(options.packages)
    packages.update(transformer.get_pkgconfig_packages())
    exit_code = process_packages(options, packages)
    if exit_code:
        return exit_code

    # 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.parse(ss.get_symbols())

    # Transform the C AST nodes into higher level
    # GLib/GObject nodes
    gdump_parser = GDumpParser(transformer)

    # Do enough parsing that we have the get_type() functions to reference
    # when creating the introspection binary
    gdump_parser.init_parse()

    if options.program:
        args=[options.program]
        args.extend(options.program_args)
        binary = IntrospectionBinary(args)
    else:
        binary = compile_introspection_binary(options,
                            gdump_parser.get_get_type_functions())

    shlibs = resolve_shlibs(options, binary, libraries)

    gdump_parser.set_introspection_binary(binary)
    gdump_parser.parse()

    ap = AnnotationParser()
    blocks = ap.parse(ss.get_comments())

    main = MainTransformer(transformer, blocks)
    main.transform()

    utils.break_on_debug_flag('tree')

    final = IntrospectablePass(transformer)
    final.validate()

    if options.warn_fatal and logger.did_warn():
        message.fatal("warnings configured as fatal")
        return 1

    # Write out AST
    if options.packages_export:
        exported_packages = options.packages_export
    else:
        exported_packages = options.packages
    writer = Writer(transformer.namespace, shlibs, transformer.get_includes(),
                    exported_packages, options.c_includes)
    data = writer.get_xml()

    if options.output == "-":
        output = sys.stdout
    elif options.reparse_validate_gir:
        main_f, main_f_name = tempfile.mkstemp(suffix='.gir')
        main_f = os.fdopen(main_f, 'w')
        main_f.write(data)
        main_f.close()

        temp_f, temp_f_name = tempfile.mkstemp(suffix='.gir')
        temp_f = os.fdopen(temp_f, 'w')
        passthrough_gir(main_f_name, temp_f)
        temp_f.close()
        if not utils.files_are_identical(main_f_name, temp_f_name):
            _error("Failed to re-parse gir file; scanned=%r passthrough=%r" % (
                main_f_name, temp_f_name))
        os.unlink(temp_f_name)
        try:
            shutil.move(main_f_name, options.output)
        except OSError, e:
            if e.errno == errno.EPERM:
                os.unlink(main_f_name)
                return 0
            raise
        return 0
    else:
        try:
            output = open(options.output, "w")
        except IOError, e:
            _error("opening output for writing: %s" % (e.strerror, ))

    try:
        output.write(data)
    except IOError, e:
        _error("while writing output: %s" % (e.strerror, ))

    return 0