giscanner: unbreak g-ir-annotationtool...
[platform/upstream/gobject-introspection.git] / giscanner / scannermain.py
1 #!/usr/bin/env python
2 # -*- Mode: Python -*-
3 # GObject-Introspection - a framework for introspecting GObject libraries
4 # Copyright (C) 2008-2010 Johan Dahlin
5 # Copyright (C) 2009 Red Hat, Inc.
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 # 02110-1301, USA.
21 #
22
23 import errno
24 import optparse
25 import os
26 import shutil
27 import subprocess
28 import sys
29 import tempfile
30
31 from giscanner import message
32 from giscanner.annotationparser import AnnotationParser
33 from giscanner.ast import Include, Namespace
34 from giscanner.dumper import compile_introspection_binary
35 from giscanner.gdumpparser import GDumpParser, IntrospectionBinary
36 from giscanner.introspectablepass import IntrospectablePass
37 from giscanner.girparser import GIRParser
38 from giscanner.girwriter import GIRWriter
39 from giscanner.maintransformer import MainTransformer
40 from giscanner.shlibs import resolve_shlibs
41 from giscanner.sourcescanner import SourceScanner
42 from giscanner.transformer import Transformer
43 from . import utils
44
45 def get_preprocessor_option_group(parser):
46     group = optparse.OptionGroup(parser, "Preprocessor options")
47     group.add_option("-I", help="Pre-processor include file",
48                      action="append", dest="cpp_includes",
49                      default=[])
50     group.add_option("-D", help="Pre-processor define",
51                      action="append", dest="cpp_defines",
52                      default=[])
53     group.add_option("-U", help="Pre-processor undefine",
54                      action="append", dest="cpp_undefines",
55                      default=[])
56     group.add_option("-p", dest="", help="Ignored")
57     return group
58
59 def get_windows_option_group(parser):
60     group = optparse.OptionGroup(parser, "Machine Dependent Options")
61     group.add_option("-m", help="some machine dependent option",
62                      action="append", dest='m_option',
63                      default=[])
64
65     return group
66
67 def _get_option_parser():
68     parser = optparse.OptionParser('%prog [options] sources')
69     parser.add_option('', "--quiet",
70                       action="store_true", dest="quiet",
71                       default=False,
72                       help="If passed, do not print details of normal" \
73                           + " operation")
74     parser.add_option("", "--format",
75                       action="store", dest="format",
76                       default="gir",
77                       help="format to use, one of gidl, gir")
78     parser.add_option("-i", "--include",
79                       action="append", dest="includes", default=[],
80                       help="Add specified gir file as dependency")
81     parser.add_option("", "--include-uninstalled",
82                       action="append", dest="includes_uninstalled", default=[],
83                       help=("""A file path to a dependency; only use this "
84                             "when building multiple .gir files inside a "
85                             "single module."""))
86     parser.add_option("", "--add-include-path",
87                       action="append", dest="include_paths", default=[],
88                       help="include paths for other GIR files")
89     parser.add_option("", "--program",
90                       action="store", dest="program", default=None,
91                       help="program to execute")
92     parser.add_option("", "--program-arg",
93                       action="append", dest="program_args", default=[],
94                       help="extra arguments to program")
95     parser.add_option("", "--libtool",
96                       action="store", dest="libtool_path", default=None,
97                       help="full path to libtool")
98     parser.add_option("", "--no-libtool",
99                       action="store_true", dest="nolibtool", default=False,
100                       help="do not use libtool")
101     parser.add_option("", "--external-library",
102                       action="store_true", dest="external_library", default=False,
103                       help=("""If true, the library is located on the system,""" +
104                             """not in the current directory"""))
105     parser.add_option("-l", "--library",
106                       action="append", dest="libraries", default=[],
107                       help="libraries of this unit")
108     parser.add_option("-L", "--library-path",
109                       action="append", dest="library_paths", default=[],
110                       help="directories to search for libraries")
111     parser.add_option("", "--header-only",
112                       action="store_true", dest="header_only", default=[],
113                       help="If specified, just generate a GIR for the given header files")
114     parser.add_option("-n", "--namespace",
115                       action="store", dest="namespace_name",
116                       help=("name of namespace for this unit, also "
117                             "used to compute --identifier-prefix and --symbol-prefix"))
118     parser.add_option("", "--nsversion",
119                       action="store", dest="namespace_version",
120                       help="version of namespace for this unit")
121     parser.add_option("", "--strip-prefix",
122                       action="store", dest="strip_prefix",
123                       help="""Option --strip-prefix is deprecated, please see --identifier-prefix
124 and --symbol-prefix.""")
125     parser.add_option("", "--identifier-prefix",
126                       action="append", dest="identifier_prefixes", default=[],
127                       help="""Remove this prefix from C identifiers (structure typedefs, etc.).
128 May be specified multiple times.  This is also used as the default for --symbol-prefix if
129 the latter is not specified.""")
130     parser.add_option("", "--symbol-prefix",
131                       action="append", dest="symbol_prefixes", default=[],
132                       help="Remove this prefix from C symbols (function names)")
133     parser.add_option("", "--accept-unprefixed",
134                       action="store_true", dest="accept_unprefixed", default=False,
135                       help="""If specified, accept symbols and identifiers that do not
136 match the namespace prefix.""")
137     parser.add_option("", "--add-init-section",
138                       action="append", dest="init_sections", default=[],
139             help="add extra initialization code in the introspection program")
140     parser.add_option("-o", "--output",
141                       action="store", dest="output", default="-",
142                       help="output filename to write to, defaults to - (stdout)")
143     parser.add_option("", "--pkg",
144                       action="append", dest="packages", default=[],
145                       help="pkg-config packages to get cflags from")
146     parser.add_option("", "--pkg-export",
147                       action="append", dest="packages_export", default=[],
148                       help="Associated pkg-config packages for this library")
149     parser.add_option('', "--warn-all",
150                       action="store_true", dest="warn_all", default=False,
151                       help="If true, enable all warnings for introspection")
152     parser.add_option('', "--warn-error",
153                       action="store_true", dest="warn_fatal",
154                       help="Turn warnings into fatal errors")
155     parser.add_option("-v", "--verbose",
156                       action="store_true", dest="verbose",
157                       help="be verbose")
158     parser.add_option("", "--c-include",
159                       action="append", dest="c_includes", default=[],
160                       help="headers which should be included in C programs")
161     parser.add_option("", "--filelist",
162                       action="store", dest="filelist", default=[],
163                       help="file containing headers and sources to be scanned")
164
165     group = get_preprocessor_option_group(parser)
166     parser.add_option_group(group)
167
168     if os.environ.get('MSYSTEM') == 'MINGW32':
169         group = get_windows_option_group(parser)
170         parser.add_option_group(group)
171
172     # Private options
173     parser.add_option('', "--generate-typelib-tests",
174                       action="store", dest="test_codegen", default=None,
175                       help=optparse.SUPPRESS_HELP)
176     parser.add_option('', "--passthrough-gir",
177                       action="store", dest="passthrough_gir", default=None,
178                       help=optparse.SUPPRESS_HELP)
179     parser.add_option('', "--reparse-validate",
180                       action="store_true", dest="reparse_validate_gir", default=False,
181                       help=optparse.SUPPRESS_HELP)
182     parser.add_option("", "--typelib-xml",
183                       action="store_true", dest="typelib_xml",
184                       help=optparse.SUPPRESS_HELP)
185
186     return parser
187
188
189 def _error(msg):
190     raise SystemExit('ERROR: %s' % (msg, ))
191
192 def passthrough_gir(path, f):
193     parser = GIRParser()
194     parser.parse(path)
195
196     writer = GIRWriter(parser.get_namespace(),
197                        parser.get_shared_libraries(),
198                        parser.get_includes(),
199                        parser.get_pkgconfig_packages(),
200                        parser.get_c_includes())
201     f.write(writer.get_xml())
202
203 def test_codegen(optstring):
204     (namespace, out_h_filename, out_c_filename) = optstring.split(',')
205     if namespace == 'Everything':
206         from .testcodegen import EverythingCodeGenerator
207         gen = EverythingCodeGenerator(out_h_filename, out_c_filename)
208         gen.write()
209     else:
210         _error("Invaild namespace %r" % (namespace, ))
211     return 0
212
213 def process_options(output, allowed_flags):
214     for option in output.split():
215         for flag in allowed_flags:
216             if not option.startswith(flag):
217                 continue
218             yield option
219             break
220
221 def process_packages(options, packages):
222     args = ['pkg-config', '--cflags']
223     args.extend(packages)
224     output = subprocess.Popen(args,
225                               stdout=subprocess.PIPE).communicate()[0]
226     if output is None:
227         # the error output should have already appeared on our stderr,
228         # so we just exit
229         return 1
230     # Some pkg-config files on Windows have options we don't understand,
231     # so we explicitly filter to only the ones we need.
232     options_whitelist = ['-I', '-D', '-U', '-l', '-L']
233     filtered_output = list(process_options(output, options_whitelist))
234     parser = _get_option_parser()
235     pkg_options, unused = parser.parse_args(filtered_output)
236     options.cpp_includes.extend(pkg_options.cpp_includes)
237     options.cpp_defines.extend(pkg_options.cpp_defines)
238     options.cpp_undefines.extend(pkg_options.cpp_undefines)
239
240 def extract_filenames(args):
241     filenames = []
242     for arg in args:
243         # We don't support real C++ parsing yet, but we should be able
244         # to understand C API implemented in C++ files.
245         if (arg.endswith('.c') or arg.endswith('.cpp') or
246             arg.endswith('.cc') or arg.endswith('.cxx') or
247             arg.endswith('.h') or arg.endswith('.hpp') or
248             arg.endswith('.hxx')):
249             if not os.path.exists(arg):
250                 _error('%s: no such a file or directory' % (arg, ))
251             # Make absolute, because we do comparisons inside scannerparser.c
252             # against the absolute path that cpp will give us
253             filenames.append(os.path.abspath(arg))
254     return filenames
255
256 def extract_filelist(options):
257     filenames = []
258     if not os.path.exists(options.filelist):
259         _error('%s: no such filelist file' % (options.filelist, ))
260     filelist_file = open(options.filelist, "r")
261     lines = filelist_file.readlines()
262     for line in lines:
263         # We don't support real C++ parsing yet, but we should be able
264         # to understand C API implemented in C++ files.
265         filename = line.strip()
266         if (filename.endswith('.c') or filename.endswith('.cpp') or
267             filename.endswith('.cc') or filename.endswith('.cxx') or
268             filename.endswith('.h') or filename.endswith('.hpp') or
269             filename.endswith('.hxx')):
270             if not os.path.exists(filename):
271                 _error('%s: Invalid filelist entry-no such file or directory' % (line, ))
272             # Make absolute, because we do comparisons inside scannerparser.c
273             # against the absolute path that cpp will give us
274             filenames.append(os.path.abspath(filename))
275     return filenames
276
277 def create_namespace(options):
278     if options.strip_prefix:
279         print """g-ir-scanner: warning: Option --strip-prefix has been deprecated;
280 see --identifier-prefix and --symbol-prefix."""
281         options.identifier_prefixes.append(options.strip_prefix)
282
283     # We do this dance because the empty list has different semantics from
284     # None; if the user didn't specify the options, we want to use None so
285     # the Namespace constructor picks the defaults.
286     if options.identifier_prefixes:
287         identifier_prefixes = options.identifier_prefixes
288     else:
289         identifier_prefixes = None
290     if options.symbol_prefixes:
291         for prefix in options.symbol_prefixes:
292             # See Transformer._split_c_string_for_namespace_matches() for
293             # why this check is needed
294             if prefix.lower() != prefix:
295                 _error("Values for --symbol-prefix must be entirely lowercase")
296         symbol_prefixes = options.symbol_prefixes
297     else:
298         symbol_prefixes = None
299
300     return Namespace(options.namespace_name,
301                      options.namespace_version,
302                      identifier_prefixes=identifier_prefixes,
303                      symbol_prefixes=symbol_prefixes)
304
305 def create_transformer(namespace, options):
306     transformer = Transformer(namespace,
307                               accept_unprefixed=options.accept_unprefixed)
308     transformer.set_include_paths(options.include_paths)
309     if options.passthrough_gir:
310         transformer.disable_cache()
311         transformer.set_passthrough_mode()
312
313     shown_include_warning = False
314     for include in options.includes:
315         if os.sep in include:
316             _error("Invalid include path %r" % (include, ))
317         try:
318             include_obj = Include.from_string(include)
319         except:
320             _error("Malformed include %r\n" % (include, ))
321         transformer.register_include(include_obj)
322     for include_path in options.includes_uninstalled:
323         transformer.register_include_uninstalled(include_path)
324
325     return transformer
326
327 def create_binary(transformer, options, args):
328     # Transform the C AST nodes into higher level
329     # GLib/GObject nodes
330     gdump_parser = GDumpParser(transformer)
331
332     # Do enough parsing that we have the get_type() functions to reference
333     # when creating the introspection binary
334     gdump_parser.init_parse()
335
336     if options.program:
337         args=[options.program]
338         args.extend(options.program_args)
339         binary = IntrospectionBinary(args)
340     else:
341         binary = compile_introspection_binary(options,
342                                               gdump_parser.get_get_type_functions(),
343                                               gdump_parser.get_error_quark_functions())
344
345     shlibs = resolve_shlibs(options, binary, options.libraries)
346     gdump_parser.set_introspection_binary(binary)
347     gdump_parser.parse()
348     return shlibs
349
350 def create_source_scanner(options, args):
351     if hasattr(options, 'filelist') and options.filelist:
352         filenames = extract_filelist(options)
353     else:
354         filenames = extract_filenames(args)
355
356     # Run the preprocessor, tokenize and construct simple
357     # objects representing the raw C symbols
358     ss = SourceScanner()
359     ss.set_cpp_options(options.cpp_includes,
360                        options.cpp_defines,
361                        options.cpp_undefines)
362     ss.parse_files(filenames)
363     ss.parse_macros(filenames)
364     return ss
365
366 def write_output(data, options):
367     if options.output == "-":
368         output = sys.stdout
369     elif options.reparse_validate_gir:
370         main_f, main_f_name = tempfile.mkstemp(suffix='.gir')
371         main_f = os.fdopen(main_f, 'w')
372         main_f.write(data)
373         main_f.close()
374
375         temp_f, temp_f_name = tempfile.mkstemp(suffix='.gir')
376         temp_f = os.fdopen(temp_f, 'w')
377         passthrough_gir(main_f_name, temp_f)
378         temp_f.close()
379         if not utils.files_are_identical(main_f_name, temp_f_name):
380             _error("Failed to re-parse gir file; scanned=%r passthrough=%r" % (
381                 main_f_name, temp_f_name))
382         os.unlink(temp_f_name)
383         try:
384             shutil.move(main_f_name, options.output)
385         except OSError, e:
386             if e.errno == errno.EPERM:
387                 os.unlink(main_f_name)
388                 return 0
389             raise
390         return 0
391     else:
392         try:
393             output = open(options.output, "w")
394         except IOError, e:
395             _error("opening output for writing: %s" % (e.strerror, ))
396
397     try:
398         output.write(data)
399     except IOError, e:
400         _error("while writing output: %s" % (e.strerror, ))
401
402 def scanner_main(args):
403     parser = _get_option_parser()
404     (options, args) = parser.parse_args(args)
405
406     if options.passthrough_gir:
407         passthrough_gir(options.passthrough_gir, sys.stdout)
408     if options.test_codegen:
409         return test_codegen(options.test_codegen)
410
411     if hasattr(options, 'filelist') and not options.filelist:
412         if len(args) <= 1:
413             _error('Need at least one filename')
414
415     if not options.namespace_name:
416         _error('Namespace name missing')
417
418     if options.format == 'gir':
419         from giscanner.girwriter import GIRWriter as Writer
420     else:
421         _error("Unknown format: %s" % (options.format, ))
422
423     if not (options.libraries
424             or options.program
425             or options.header_only):
426         _error("Must specify --program or --library")
427
428     namespace = create_namespace(options)
429     logger = message.MessageLogger.get(namespace=namespace)
430     if options.warn_all:
431         logger.enable_warnings(True)
432     transformer = create_transformer(namespace, options)
433
434     packages = set(options.packages)
435     packages.update(transformer.get_pkgconfig_packages())
436     if packages:
437         exit_code = process_packages(options, packages)
438         if exit_code:
439             return exit_code
440
441     ss = create_source_scanner(options, args)
442
443     ap = AnnotationParser()
444     blocks = ap.parse(ss.get_comments())
445
446     # Transform the C symbols into AST nodes
447     transformer.set_annotations(blocks)
448     transformer.parse(ss.get_symbols())
449
450     if not options.header_only:
451         shlibs = create_binary(transformer, options, args)
452     else:
453         shlibs = []
454
455     main = MainTransformer(transformer, blocks)
456     main.transform()
457
458     utils.break_on_debug_flag('tree')
459
460     final = IntrospectablePass(transformer, blocks)
461     final.validate()
462
463     warning_count = logger.get_warning_count()
464     if options.warn_fatal and warning_count > 0:
465         message.fatal("warnings configured as fatal")
466         return 1
467     elif warning_count > 0 and options.warn_all is False:
468         print ("g-ir-scanner: %s: warning: %d warnings suppressed (use --warn-all to see them)"
469                % (transformer.namespace.name, warning_count, ))
470
471     # Write out AST
472     if options.packages_export:
473         exported_packages = options.packages_export
474     else:
475         exported_packages = options.packages
476
477     writer = Writer(transformer.namespace, shlibs, transformer.get_includes(),
478                     exported_packages, options.c_includes)
479     data = writer.get_xml()
480
481     write_output(data, options)
482
483     return 0