1 // Copyright 2018 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 "parser.h"
16
17 #include "disk_interface.h"
18 #include "metrics.h"
19
20 using namespace std;
21
Load(const string & filename,string * err,Lexer * parent)22 bool Parser::Load(const string& filename, string* err, Lexer* parent) {
23 METRIC_RECORD(".ninja parse");
24 string contents;
25 string read_err;
26 if (file_reader_->ReadFile(filename, &contents, &read_err) !=
27 FileReader::Okay) {
28 *err = "loading '" + filename + "': " + read_err;
29 if (parent)
30 parent->Error(string(*err), err);
31 return false;
32 }
33
34 // The lexer needs a nul byte at the end of its input, to know when it's done.
35 // It takes a StringPiece, and StringPiece's string constructor uses
36 // string::data(). data()'s return value isn't guaranteed to be
37 // null-terminated (although in practice - libc++, libstdc++, msvc's stl --
38 // it is, and C++11 demands that too), so add an explicit nul byte.
39 contents.resize(contents.size() + 1);
40
41 return Parse(filename, contents, err);
42 }
43
ExpectToken(Lexer::Token expected,string * err)44 bool Parser::ExpectToken(Lexer::Token expected, string* err) {
45 Lexer::Token token = lexer_.ReadToken();
46 if (token != expected) {
47 string message = string("expected ") + Lexer::TokenName(expected);
48 message += string(", got ") + Lexer::TokenName(token);
49 message += Lexer::TokenErrorHint(expected);
50 return lexer_.Error(message, err);
51 }
52 return true;
53 }
54