Add support for implicit outputs in ninja_syntax.py.
[platform/upstream/ninja.git] / misc / ninja_syntax.py
1 #!/usr/bin/python
2
3 """Python module for generating .ninja files.
4
5 Note that this is emphatically not a required piece of Ninja; it's
6 just a helpful utility for build-file-generation systems that already
7 use Python.
8 """
9
10 import re
11 import textwrap
12
13 def escape_path(word):
14     return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
15
16 class Writer(object):
17     def __init__(self, output, width=78):
18         self.output = output
19         self.width = width
20
21     def newline(self):
22         self.output.write('\n')
23
24     def comment(self, text, has_path=False):
25         for line in textwrap.wrap(text, self.width - 2, break_long_words=False,
26                                   break_on_hyphens=False):
27             self.output.write('# ' + line + '\n')
28
29     def variable(self, key, value, indent=0):
30         if value is None:
31             return
32         if isinstance(value, list):
33             value = ' '.join(filter(None, value))  # Filter out empty strings.
34         self._line('%s = %s' % (key, value), indent)
35
36     def pool(self, name, depth):
37         self._line('pool %s' % name)
38         self.variable('depth', depth, indent=1)
39
40     def rule(self, name, command, description=None, depfile=None,
41              generator=False, pool=None, restat=False, rspfile=None,
42              rspfile_content=None, deps=None):
43         self._line('rule %s' % name)
44         self.variable('command', command, indent=1)
45         if description:
46             self.variable('description', description, indent=1)
47         if depfile:
48             self.variable('depfile', depfile, indent=1)
49         if generator:
50             self.variable('generator', '1', indent=1)
51         if pool:
52             self.variable('pool', pool, indent=1)
53         if restat:
54             self.variable('restat', '1', indent=1)
55         if rspfile:
56             self.variable('rspfile', rspfile, indent=1)
57         if rspfile_content:
58             self.variable('rspfile_content', rspfile_content, indent=1)
59         if deps:
60             self.variable('deps', deps, indent=1)
61
62     def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
63               variables=None, implicit_outputs=None):
64         outputs = as_list(outputs)
65         out_outputs = [escape_path(x) for x in outputs]
66         all_inputs = [escape_path(x) for x in as_list(inputs)]
67
68         if implicit:
69             implicit = [escape_path(x) for x in as_list(implicit)]
70             all_inputs.append('|')
71             all_inputs.extend(implicit)
72         if order_only:
73             order_only = [escape_path(x) for x in as_list(order_only)]
74             all_inputs.append('||')
75             all_inputs.extend(order_only)
76         if implicit_outputs:
77             implicit_outputs = [escape_path(x)
78                                 for x in as_list(implicit_outputs)]
79             out_outputs.append('|')
80             out_outputs.extend(implicit_outputs)
81
82         self._line('build %s: %s' % (' '.join(out_outputs),
83                                      ' '.join([rule] + all_inputs)))
84
85         if variables:
86             if isinstance(variables, dict):
87                 iterator = iter(variables.items())
88             else:
89                 iterator = iter(variables)
90
91             for key, val in iterator:
92                 self.variable(key, val, indent=1)
93
94         return outputs
95
96     def include(self, path):
97         self._line('include %s' % path)
98
99     def subninja(self, path):
100         self._line('subninja %s' % path)
101
102     def default(self, paths):
103         self._line('default %s' % ' '.join(as_list(paths)))
104
105     def _count_dollars_before_index(self, s, i):
106         """Returns the number of '$' characters right in front of s[i]."""
107         dollar_count = 0
108         dollar_index = i - 1
109         while dollar_index > 0 and s[dollar_index] == '$':
110             dollar_count += 1
111             dollar_index -= 1
112         return dollar_count
113
114     def _line(self, text, indent=0):
115         """Write 'text' word-wrapped at self.width characters."""
116         leading_space = '  ' * indent
117         while len(leading_space) + len(text) > self.width:
118             # The text is too wide; wrap if possible.
119
120             # Find the rightmost space that would obey our width constraint and
121             # that's not an escaped space.
122             available_space = self.width - len(leading_space) - len(' $')
123             space = available_space
124             while True:
125                 space = text.rfind(' ', 0, space)
126                 if (space < 0 or
127                     self._count_dollars_before_index(text, space) % 2 == 0):
128                     break
129
130             if space < 0:
131                 # No such space; just use the first unescaped space we can find.
132                 space = available_space - 1
133                 while True:
134                     space = text.find(' ', space + 1)
135                     if (space < 0 or
136                         self._count_dollars_before_index(text, space) % 2 == 0):
137                         break
138             if space < 0:
139                 # Give up on breaking.
140                 break
141
142             self.output.write(leading_space + text[0:space] + ' $\n')
143             text = text[space+1:]
144
145             # Subsequent lines are continuations, so indent them.
146             leading_space = '  ' * (indent+2)
147
148         self.output.write(leading_space + text + '\n')
149
150     def close(self):
151         self.output.close()
152
153
154 def as_list(input):
155     if input is None:
156         return []
157     if isinstance(input, list):
158         return input
159     return [input]
160
161
162 def escape(string):
163     """Escape a string such that it can be embedded into a Ninja file without
164     further interpretation."""
165     assert '\n' not in string, 'Ninja syntax does not allow newlines'
166     # We only have one special metacharacter: '$'.
167     return string.replace('$', '$$')
168
169
170 def expand(string, vars, local_vars={}):
171     """Expand a string containing $vars as Ninja would.
172
173     Note: doesn't handle the full Ninja variable syntax, but it's enough
174     to make configure.py's use of it work.
175     """
176     def exp(m):
177         var = m.group(1)
178         if var == '$':
179             return '$'
180         return local_vars.get(var, vars.get(var, ''))
181     return re.sub(r'\$(\$|\w*)', exp, string)