Ninja
parser.cc
Go to the documentation of this file.
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 
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) !=
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 
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 }
Definition: lexer.h:27
static const char * TokenErrorHint(Token expected)
Return a human-readable token hint, used in error messages.
Definition: lexer.cc:96
bool Load(const std::string &filename, std::string *err, Lexer *parent=NULL)
Load and parse a file.
Definition: parser.cc:22
bool Error(const std::string &message, std::string *err)
Construct an error message with context.
Definition: lexer.cc:25
Token
Definition: lexer.h:32
#define METRIC_RECORD(name)
The primary interface to metrics.
Definition: metrics.h:84
static const char * TokenName(Token t)
Return a human-readable form of a token, used in error messages.
Definition: lexer.cc:75
bool ExpectToken(Lexer::Token expected, std::string *err)
If the next token is not expected, produce an error string saying "expected foo, got bar"...
Definition: parser.cc:44