fix generators after raise-from merge
[cython.git] / Cython / Compiler / CmdLine.py
1 #
2 #   Cython - Command Line Parsing
3 #
4
5 import os
6 import sys
7 import Options
8
9 usage = """\
10 Cython (http://cython.org) is a compiler for code written in the
11 Cython language.  Cython is based on Pyrex by Greg Ewing.
12
13 Usage: cython [options] sourcefile.{pyx,py} ...
14
15 Options:
16   -V, --version                  Display version number of cython compiler
17   -l, --create-listing           Write error messages to a listing file
18   -I, --include-dir <directory>  Search for include files in named directory
19                                  (multiple include directories are allowed).
20   -o, --output-file <filename>   Specify name of generated C file
21   -t, --timestamps               Only compile newer source files
22   -f, --force                    Compile all source files (overrides implied -t)
23   -q, --quiet                    Don't print module names in recursive mode
24   -v, --verbose                  Be verbose, print file names on multiple compilation
25   -p, --embed-positions          If specified, the positions in Cython files of each
26                                  function definition is embedded in its docstring.
27   --cleanup <level>              Release interned objects on python exit, for memory debugging.
28                                  Level indicates aggressiveness, default 0 releases nothing.
29   -w, --working <directory>      Sets the working directory for Cython (the directory modules
30                                  are searched from)
31   --gdb                          Output debug information for cygdb
32
33   -D, --no-docstrings            Strip docstrings from the compiled module.
34   -a, --annotate                 Produce a colorized HTML version of the source.
35   --line-directives              Produce #line directives pointing to the .pyx source
36   --cplus                        Output a C++ rather than C file.
37   --embed[=<method_name>]        Generate a main() function that embeds the Python interpreter.
38   -2                             Compile based on Python-2 syntax and code semantics.
39   -3                             Compile based on Python-3 syntax and code semantics.
40   --fast-fail                    Abort the compilation on the first error
41   --warning-error, -Werror       Make all warnings into errors
42   -X, --directive <name>=<value>[,<name=value,...] Overrides a compiler directive
43 """
44
45 # The following is broken http://trac.cython.org/cython_trac/ticket/379
46 #  -r, --recursive                Recursively find and compile dependencies (implies -t)
47
48
49 #The following experimental options are supported only on MacOSX:
50 #  -C, --compile    Compile generated .c file to .o file
51 #  --link           Link .o file to produce extension module (implies -C)
52 #  -+, --cplus      Use C++ compiler for compiling and linking
53 #  Additional .o files to link may be supplied when using -X."""
54
55 def bad_usage():
56     sys.stderr.write(usage)
57     sys.exit(1)
58
59 def parse_command_line(args):
60
61     from Cython.Compiler.Main import \
62         CompilationOptions, default_options
63
64     def pop_arg():
65         if args:
66             return args.pop(0)
67         else:
68             bad_usage()
69
70     def get_param(option):
71         tail = option[2:]
72         if tail:
73             return tail
74         else:
75             return pop_arg()
76
77     options = CompilationOptions(default_options)
78     sources = []
79     while args:
80         if args[0].startswith("-"):
81             option = pop_arg()
82             if option in ("-V", "--version"):
83                 options.show_version = 1
84             elif option in ("-l", "--create-listing"):
85                 options.use_listing_file = 1
86             elif option in ("-+", "--cplus"):
87                 options.cplus = 1
88             elif option.startswith("--embed"):
89                 ix = option.find('=')
90                 if ix == -1:
91                     Options.embed = "main"
92                 else:
93                     Options.embed = option[ix+1:]
94             elif option.startswith("-I"):
95                 options.include_path.append(get_param(option))
96             elif option == "--include-dir":
97                 options.include_path.append(pop_arg())
98             elif option in ("-w", "--working"):
99                 options.working_path = pop_arg()
100             elif option in ("-o", "--output-file"):
101                 options.output_file = pop_arg()
102             elif option in ("-r", "--recursive"):
103                 options.recursive = 1
104             elif option in ("-t", "--timestamps"):
105                 options.timestamps = 1
106             elif option in ("-f", "--force"):
107                 options.timestamps = 0
108             elif option in ("-v", "--verbose"):
109                 options.verbose += 1
110             elif option in ("-p", "--embed-positions"):
111                 Options.embed_pos_in_docstring = 1
112             elif option in ("-z", "--pre-import"):
113                 Options.pre_import = pop_arg()
114             elif option == "--cleanup":
115                 Options.generate_cleanup_code = int(pop_arg())
116             elif option in ("-D", "--no-docstrings"):
117                 Options.docstrings = False
118             elif option in ("-a", "--annotate"):
119                 Options.annotate = True
120             elif option == "--convert-range":
121                 Options.convert_range = True
122             elif option == "--line-directives":
123                 options.emit_linenums = True
124             elif option == "--no-c-in-traceback":
125                 options.c_line_in_traceback = False
126             elif option == "--gdb":
127                 options.gdb_debug = True
128                 options.output_dir = os.curdir
129             elif option == '-2':
130                 options.language_level = 2
131             elif option == '-3':
132                 options.language_level = 3
133             elif option == "--fast-fail":
134                 Options.fast_fail = True
135             elif option in ('-Werror', '--warning-errors'):
136                 Options.warning_errors = True
137             elif option == "--disable-function-redefinition":
138                 Options.disable_function_redefinition = True
139             elif option == "--directive" or option.startswith('-X'):
140                 if option.startswith('-X') and option[2:].strip():
141                     x_args = option[2:]
142                 else:
143                     x_args = pop_arg()
144                 try:
145                     options.compiler_directives = Options.parse_directive_list(
146                         x_args, relaxed_bool=True,
147                         current_settings=options.compiler_directives)
148                 except ValueError, e:
149                     sys.stderr.write("Error in compiler directive: %s\n" % e.args[0])
150                     sys.exit(1)
151             elif option.startswith('--debug'):
152                 option = option[2:].replace('-', '_')
153                 import DebugFlags
154                 if option in dir(DebugFlags):
155                     setattr(DebugFlags, option, True)
156                 else:
157                     sys.stderr.write("Unknown debug flag: %s\n" % option)
158                     bad_usage()
159             elif option in ('-h', '--help'):
160                 sys.stdout.write(usage)
161                 sys.exit(0)
162             else:
163                 sys.stderr.write("Unknown compiler flag: %s\n" % option)
164                 sys.exit(1)
165         else:
166             arg = pop_arg()
167             if arg.endswith(".pyx"):
168                 sources.append(arg)
169             elif arg.endswith(".py"):
170                 # maybe do some other stuff, but this should work for now
171                 sources.append(arg)
172             else:
173                 sys.stderr.write(
174                     "cython: %s: Unknown filename suffix\n" % arg)
175     if options.use_listing_file and len(sources) > 1:
176         sys.stderr.write(
177             "cython: Only one source file allowed when using -o\n")
178         sys.exit(1)
179     if len(sources) == 0 and not options.show_version:
180         bad_usage()
181     if Options.embed and len(sources) > 1:
182         sys.stderr.write(
183             "cython: Only one source file allowed when using -embed\n")
184         sys.exit(1)
185     return options, sources
186