Remove trailing whitespace.
[cython.git] / Cython / Compiler / Options.py
1 #
2 #  Cython - Compilation-wide options and pragma declarations
3 #
4
5 cache_builtins = 1  #  Perform lookups on builtin names only once
6
7 embed_pos_in_docstring = 0
8 gcc_branch_hints = 1
9
10 pre_import = None
11 docstrings = True
12
13 # Decref global variables in this module on exit for garbage collection.
14 # 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects
15 # Mostly for reducing noise for Valgrind, only executes at process exit
16 # (when all memory will be reclaimed anyways).
17 generate_cleanup_code = 0
18
19 annotate = 0
20
21 # This will abort the compilation on the first error occured rather than trying
22 # to keep going and printing further error messages.
23 fast_fail = False
24
25 # This will convert statements of the form "for i in range(...)"
26 # to "for i from ..." when i is a cdef'd integer type, and the direction
27 # (i.e. sign of step) can be determined.
28 # WARNING: This may change the semantics if the range causes assignment to
29 # i to overflow. Specifically, if this option is set, an error will be
30 # raised before the loop is entered, wheras without this option the loop
31 # will execute until an overflowing value is encountered.
32 convert_range = 1
33
34 # Enable this to allow one to write your_module.foo = ... to overwrite the
35 # definition if the cpdef function foo, at the cost of an extra dictionary
36 # lookup on every call.
37 # If this is 0 it simply creates a wrapper.
38 lookup_module_cpdef = 0
39
40 # This will set local variables to None rather than NULL which may cause
41 # surpress what would be an UnboundLocalError in pure Python but eliminates
42 # checking for NULL on every use, and can decref rather than xdecref at the end.
43 # WARNING: This is a work in progress, may currently segfault.
44 init_local_none = 1
45
46 # Append the c file and line number to the traceback for exceptions.
47 c_line_in_traceback = 1
48
49 # Whether or not to embed the Python interpreter, for use in making a
50 # standalone executable. This will provide a main() method which simply
51 # executes the body of this module.
52 embed = False
53
54
55 # Declare compiler directives
56 directive_defaults = {
57     'boundscheck' : True,
58     'nonecheck' : False,
59     'embedsignature' : False,
60     'locals' : {},
61     'auto_cpdef': False,
62     'cdivision': False, # was True before 0.12
63     'cdivision_warnings': False,
64     'always_allow_keywords': False,
65     'allow_none_for_extension_args': True,
66     'wraparound' : True,
67     'ccomplex' : False, # use C99/C++ for complex types and arith
68     'callspec' : "",
69     'final' : False,
70     'internal' : False,
71     'profile': False,
72     'infer_types': None,
73     'infer_types.verbose': False,
74     'autotestdict': True,
75     'autotestdict.cdef': False,
76     'autotestdict.all': False,
77     'language_level': 2,
78     'fast_getattr': False, # Undocumented until we come up with a better way to handle this everywhere.
79
80     'warn': None,
81     'warn.undeclared': False,
82
83 # test support
84     'test_assert_path_exists' : [],
85     'test_fail_if_path_exists' : [],
86
87 # experimental, subject to change
88     'binding': False,
89 }
90
91 # Override types possibilities above, if needed
92 directive_types = {
93     'final' : bool,  # final cdef classes and methods
94     'internal' : bool,  # cdef class visibility in the module dict
95     'infer_types' : bool, # values can be True/None/False
96     }
97
98 for key, val in directive_defaults.items():
99     if key not in directive_types:
100         directive_types[key] = type(val)
101
102 directive_scopes = { # defaults to available everywhere
103     # 'module', 'function', 'class', 'with statement'
104     'final' : ('cclass',),   # add 'method' in the future
105     'internal' : ('cclass',),
106     'autotestdict' : ('module',),
107     'autotestdict.all' : ('module',),
108     'autotestdict.cdef' : ('module',),
109     'test_assert_path_exists' : ('function', 'class', 'cclass'),
110     'test_fail_if_path_exists' : ('function', 'class', 'cclass'),
111 }
112
113 def parse_directive_value(name, value, relaxed_bool=False):
114     """
115     Parses value as an option value for the given name and returns
116     the interpreted value. None is returned if the option does not exist.
117
118     >>> print parse_directive_value('nonexisting', 'asdf asdfd')
119     None
120     >>> parse_directive_value('boundscheck', 'True')
121     True
122     >>> parse_directive_value('boundscheck', 'true')
123     Traceback (most recent call last):
124        ...
125     ValueError: boundscheck directive must be set to True or False, got 'true'
126
127     """
128     type = directive_types.get(name)
129     if not type: return None
130     orig_value = value
131     if type is bool:
132         value = str(value)
133         if value == 'True': return True
134         if value == 'False': return False
135         if relaxed_bool:
136             value = value.lower()
137             if value in ("true", "yes"): return True
138             elif value in ("false", "no"): return False
139         raise ValueError("%s directive must be set to True or False, got '%s'" % (
140             name, orig_value))
141     elif type is int:
142         try:
143             return int(value)
144         except ValueError:
145             raise ValueError("%s directive must be set to an integer, got '%s'" % (
146                 name, orig_value))
147     elif type is str:
148         return str(value)
149     else:
150         assert False
151
152 def parse_directive_list(s, relaxed_bool=False, ignore_unknown=False,
153                          current_settings=None):
154     """
155     Parses a comma-separated list of pragma options. Whitespace
156     is not considered.
157
158     >>> parse_directive_list('      ')
159     {}
160     >>> (parse_directive_list('boundscheck=True') ==
161     ... {'boundscheck': True})
162     True
163     >>> parse_directive_list('  asdf')
164     Traceback (most recent call last):
165        ...
166     ValueError: Expected "=" in option "asdf"
167     >>> parse_directive_list('boundscheck=hey')
168     Traceback (most recent call last):
169        ...
170     ValueError: boundscheck directive must be set to True or False, got 'hey'
171     >>> parse_directive_list('unknown=True')
172     Traceback (most recent call last):
173        ...
174     ValueError: Unknown option: "unknown"
175     """
176     if current_settings is None:
177         result = {}
178     else:
179         result = current_settings
180     for item in s.split(','):
181         item = item.strip()
182         if not item: continue
183         if not '=' in item: raise ValueError('Expected "=" in option "%s"' % item)
184         name, value = [ s.strip() for s in item.strip().split('=', 1) ]
185         parsed_value = parse_directive_value(name, value, relaxed_bool=relaxed_bool)
186         if parsed_value is None:
187             if not ignore_unknown:
188                 raise ValueError('Unknown option: "%s"' % name)
189         else:
190             result[name] = parsed_value
191     return result