Build self-consistent graphs for dupe edges with multiple outputs.
[platform/upstream/ninja.git] / src / manifest_parser.cc
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "manifest_parser.h"
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <vector>
20
21 #include "graph.h"
22 #include "metrics.h"
23 #include "state.h"
24 #include "util.h"
25 #include "version.h"
26
27 ManifestParser::ManifestParser(State* state, FileReader* file_reader)
28   : state_(state), file_reader_(file_reader) {
29   env_ = &state->bindings_;
30 }
31
32 bool ManifestParser::Load(const string& filename, string* err, Lexer* parent) {
33   METRIC_RECORD(".ninja parse");
34   string contents;
35   string read_err;
36   if (!file_reader_->ReadFile(filename, &contents, &read_err)) {
37     *err = "loading '" + filename + "': " + read_err;
38     if (parent)
39       parent->Error(string(*err), err);
40     return false;
41   }
42
43   // The lexer needs a nul byte at the end of its input, to know when it's done.
44   // It takes a StringPiece, and StringPiece's string constructor uses
45   // string::data().  data()'s return value isn't guaranteed to be
46   // null-terminated (although in practice - libc++, libstdc++, msvc's stl --
47   // it is, and C++11 demands that too), so add an explicit nul byte.
48   contents.resize(contents.size() + 1);
49
50   return Parse(filename, contents, err);
51 }
52
53 bool ManifestParser::Parse(const string& filename, const string& input,
54                            string* err) {
55   lexer_.Start(filename, input);
56
57   for (;;) {
58     Lexer::Token token = lexer_.ReadToken();
59     switch (token) {
60     case Lexer::POOL:
61       if (!ParsePool(err))
62         return false;
63       break;
64     case Lexer::BUILD:
65       if (!ParseEdge(err))
66         return false;
67       break;
68     case Lexer::RULE:
69       if (!ParseRule(err))
70         return false;
71       break;
72     case Lexer::DEFAULT:
73       if (!ParseDefault(err))
74         return false;
75       break;
76     case Lexer::IDENT: {
77       lexer_.UnreadToken();
78       string name;
79       EvalString let_value;
80       if (!ParseLet(&name, &let_value, err))
81         return false;
82       string value = let_value.Evaluate(env_);
83       // Check ninja_required_version immediately so we can exit
84       // before encountering any syntactic surprises.
85       if (name == "ninja_required_version")
86         CheckNinjaVersion(value);
87       env_->AddBinding(name, value);
88       break;
89     }
90     case Lexer::INCLUDE:
91       if (!ParseFileInclude(false, err))
92         return false;
93       break;
94     case Lexer::SUBNINJA:
95       if (!ParseFileInclude(true, err))
96         return false;
97       break;
98     case Lexer::ERROR: {
99       return lexer_.Error(lexer_.DescribeLastError(), err);
100     }
101     case Lexer::TEOF:
102       return true;
103     case Lexer::NEWLINE:
104       break;
105     default:
106       return lexer_.Error(string("unexpected ") + Lexer::TokenName(token),
107                           err);
108     }
109   }
110   return false;  // not reached
111 }
112
113
114 bool ManifestParser::ParsePool(string* err) {
115   string name;
116   if (!lexer_.ReadIdent(&name))
117     return lexer_.Error("expected pool name", err);
118
119   if (!ExpectToken(Lexer::NEWLINE, err))
120     return false;
121
122   if (state_->LookupPool(name) != NULL)
123     return lexer_.Error("duplicate pool '" + name + "'", err);
124
125   int depth = -1;
126
127   while (lexer_.PeekToken(Lexer::INDENT)) {
128     string key;
129     EvalString value;
130     if (!ParseLet(&key, &value, err))
131       return false;
132
133     if (key == "depth") {
134       string depth_string = value.Evaluate(env_);
135       depth = atol(depth_string.c_str());
136       if (depth < 0)
137         return lexer_.Error("invalid pool depth", err);
138     } else {
139       return lexer_.Error("unexpected variable '" + key + "'", err);
140     }
141   }
142
143   if (depth < 0)
144     return lexer_.Error("expected 'depth =' line", err);
145
146   state_->AddPool(new Pool(name, depth));
147   return true;
148 }
149
150
151 bool ManifestParser::ParseRule(string* err) {
152   string name;
153   if (!lexer_.ReadIdent(&name))
154     return lexer_.Error("expected rule name", err);
155
156   if (!ExpectToken(Lexer::NEWLINE, err))
157     return false;
158
159   if (env_->LookupRuleCurrentScope(name) != NULL)
160     return lexer_.Error("duplicate rule '" + name + "'", err);
161
162   Rule* rule = new Rule(name);  // XXX scoped_ptr
163
164   while (lexer_.PeekToken(Lexer::INDENT)) {
165     string key;
166     EvalString value;
167     if (!ParseLet(&key, &value, err))
168       return false;
169
170     if (Rule::IsReservedBinding(key)) {
171       rule->AddBinding(key, value);
172     } else {
173       // Die on other keyvals for now; revisit if we want to add a
174       // scope here.
175       return lexer_.Error("unexpected variable '" + key + "'", err);
176     }
177   }
178
179   if (rule->bindings_["rspfile"].empty() !=
180       rule->bindings_["rspfile_content"].empty()) {
181     return lexer_.Error("rspfile and rspfile_content need to be "
182                         "both specified", err);
183   }
184
185   if (rule->bindings_["command"].empty())
186     return lexer_.Error("expected 'command =' line", err);
187
188   env_->AddRule(rule);
189   return true;
190 }
191
192 bool ManifestParser::ParseLet(string* key, EvalString* value, string* err) {
193   if (!lexer_.ReadIdent(key))
194     return lexer_.Error("expected variable name", err);
195   if (!ExpectToken(Lexer::EQUALS, err))
196     return false;
197   if (!lexer_.ReadVarValue(value, err))
198     return false;
199   return true;
200 }
201
202 bool ManifestParser::ParseDefault(string* err) {
203   EvalString eval;
204   if (!lexer_.ReadPath(&eval, err))
205     return false;
206   if (eval.empty())
207     return lexer_.Error("expected target name", err);
208
209   do {
210     string path = eval.Evaluate(env_);
211     string path_err;
212     unsigned int slash_bits;  // Unused because this only does lookup.
213     if (!CanonicalizePath(&path, &slash_bits, &path_err))
214       return lexer_.Error(path_err, err);
215     if (!state_->AddDefault(path, &path_err))
216       return lexer_.Error(path_err, err);
217
218     eval.Clear();
219     if (!lexer_.ReadPath(&eval, err))
220       return false;
221   } while (!eval.empty());
222
223   if (!ExpectToken(Lexer::NEWLINE, err))
224     return false;
225
226   return true;
227 }
228
229 bool ManifestParser::ParseEdge(string* err) {
230   vector<EvalString> ins, outs;
231
232   {
233     EvalString out;
234     if (!lexer_.ReadPath(&out, err))
235       return false;
236     if (out.empty())
237       return lexer_.Error("expected path", err);
238
239     do {
240       outs.push_back(out);
241
242       out.Clear();
243       if (!lexer_.ReadPath(&out, err))
244         return false;
245     } while (!out.empty());
246   }
247
248   if (!ExpectToken(Lexer::COLON, err))
249     return false;
250
251   string rule_name;
252   if (!lexer_.ReadIdent(&rule_name))
253     return lexer_.Error("expected build command name", err);
254
255   const Rule* rule = env_->LookupRule(rule_name);
256   if (!rule)
257     return lexer_.Error("unknown build rule '" + rule_name + "'", err);
258
259   for (;;) {
260     // XXX should we require one path here?
261     EvalString in;
262     if (!lexer_.ReadPath(&in, err))
263       return false;
264     if (in.empty())
265       break;
266     ins.push_back(in);
267   }
268
269   // Add all implicit deps, counting how many as we go.
270   int implicit = 0;
271   if (lexer_.PeekToken(Lexer::PIPE)) {
272     for (;;) {
273       EvalString in;
274       if (!lexer_.ReadPath(&in, err))
275         return err;
276       if (in.empty())
277         break;
278       ins.push_back(in);
279       ++implicit;
280     }
281   }
282
283   // Add all order-only deps, counting how many as we go.
284   int order_only = 0;
285   if (lexer_.PeekToken(Lexer::PIPE2)) {
286     for (;;) {
287       EvalString in;
288       if (!lexer_.ReadPath(&in, err))
289         return false;
290       if (in.empty())
291         break;
292       ins.push_back(in);
293       ++order_only;
294     }
295   }
296
297   if (!ExpectToken(Lexer::NEWLINE, err))
298     return false;
299
300   // Bindings on edges are rare, so allocate per-edge envs only when needed.
301   bool has_indent_token = lexer_.PeekToken(Lexer::INDENT);
302   BindingEnv* env = has_indent_token ? new BindingEnv(env_) : env_;
303   while (has_indent_token) {
304     string key;
305     EvalString val;
306     if (!ParseLet(&key, &val, err))
307       return false;
308
309     env->AddBinding(key, val.Evaluate(env_));
310     has_indent_token = lexer_.PeekToken(Lexer::INDENT);
311   }
312
313   Edge* edge = state_->AddEdge(rule);
314   edge->env_ = env;
315
316   string pool_name = edge->GetBinding("pool");
317   if (!pool_name.empty()) {
318     Pool* pool = state_->LookupPool(pool_name);
319     if (pool == NULL)
320       return lexer_.Error("unknown pool name '" + pool_name + "'", err);
321     edge->pool_ = pool;
322   }
323
324   for (vector<EvalString>::iterator i = ins.begin(); i != ins.end(); ++i) {
325     string path = i->Evaluate(env);
326     string path_err;
327     unsigned int slash_bits;
328     if (!CanonicalizePath(&path, &slash_bits, &path_err))
329       return lexer_.Error(path_err, err);
330     state_->AddIn(edge, path, slash_bits);
331   }
332   for (vector<EvalString>::iterator i = outs.begin(); i != outs.end(); ++i) {
333     string path = i->Evaluate(env);
334     string path_err;
335     unsigned int slash_bits;
336     if (!CanonicalizePath(&path, &slash_bits, &path_err))
337       return lexer_.Error(path_err, err);
338     state_->AddOut(edge, path, slash_bits);
339   }
340   edge->implicit_deps_ = implicit;
341   edge->order_only_deps_ = order_only;
342
343   if (edge->outputs_.empty()) {
344     // All outputs of the edge are already created by other edges. Don't add
345     // this edge.
346     state_->edges_.pop_back();
347     delete edge;
348     return true;
349   }
350
351   // Multiple outputs aren't (yet?) supported with depslog.
352   string deps_type = edge->GetBinding("deps");
353   if (!deps_type.empty() && edge->outputs_.size() > 1) {
354     return lexer_.Error("multiple outputs aren't (yet?) supported by depslog; "
355                         "bring this up on the mailing list if it affects you",
356                         err);
357   }
358
359   return true;
360 }
361
362 bool ManifestParser::ParseFileInclude(bool new_scope, string* err) {
363   EvalString eval;
364   if (!lexer_.ReadPath(&eval, err))
365     return false;
366   string path = eval.Evaluate(env_);
367
368   ManifestParser subparser(state_, file_reader_);
369   if (new_scope) {
370     subparser.env_ = new BindingEnv(env_);
371   } else {
372     subparser.env_ = env_;
373   }
374
375   if (!subparser.Load(path, err, &lexer_))
376     return false;
377
378   if (!ExpectToken(Lexer::NEWLINE, err))
379     return false;
380
381   return true;
382 }
383
384 bool ManifestParser::ExpectToken(Lexer::Token expected, string* err) {
385   Lexer::Token token = lexer_.ReadToken();
386   if (token != expected) {
387     string message = string("expected ") + Lexer::TokenName(expected);
388     message += string(", got ") + Lexer::TokenName(token);
389     message += Lexer::TokenErrorHint(expected);
390     return lexer_.Error(message, err);
391   }
392   return true;
393 }