forked from tensorflow/minigo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsgf.cc
More file actions
366 lines (325 loc) · 9.61 KB
/
Copy pathsgf.cc
File metadata and controls
366 lines (325 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "cc/sgf.h"
#include <cctype>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "cc/constants.h"
#include "cc/logging.h"
namespace minigo {
namespace sgf {
namespace {
class Parser {
public:
Parser(absl::string_view contents, std::string* error)
: original_contents_(contents), contents_(contents), error_(error) {}
bool Parse(Collection* collection) {
*error_ = "";
while (SkipWhitespace()) {
collection->trees.push_back(absl::make_unique<Tree>());
if (!ParseTree(collection->trees.back().get())) {
return false;
}
}
return done();
}
bool done() const { return contents_.empty(); }
char peek() const { return contents_[0]; }
private:
bool ParseTree(Tree* tree) {
if (!Read('(')) {
return false;
}
if (!ParseSequence(tree)) {
return false;
}
for (;;) {
if (!SkipWhitespace()) {
return Error("reached EOF when parsing tree");
}
if (peek() == '(') {
tree->sub_trees.push_back(absl::make_unique<Tree>());
if (!ParseTree(tree->sub_trees.back().get())) {
return false;
}
} else {
return Read(')');
}
}
}
bool ParseSequence(Tree* tree) {
for (;;) {
if (!SkipWhitespace()) {
return Error("reached EOF when parsing sequence");
}
if (peek() != ';') {
break;
}
tree->nodes.push_back(absl::make_unique<Node>());
if (!ParseNode(tree->nodes.back().get())) {
return false;
}
}
if (tree->nodes.empty()) {
return Error("tree has no nodes");
}
return true;
}
bool ParseNode(Node* node) {
MG_CHECK(Read(';'));
for (;;) {
if (!SkipWhitespace()) {
return Error("reached EOF when parsing node");
}
if (!absl::ascii_isupper(peek())) {
return true;
}
Property prop;
if (!ParseProperty(&prop)) {
return false;
}
if (prop.id == "B" || prop.id == "W") {
if (node->move.color != Color::kEmpty) {
return Error("node already has a move");
}
node->move.color = prop.id == "B" ? Color::kBlack : Color::kWhite;
if (prop.values.size() != 1) {
return Error("expected exactly one property value, got \"",
prop.ToString(), "\"");
}
node->move.c = Coord::FromSgf(prop.values[0], true);
if (node->move.c == Coord::kInvalid) {
return Error(prop.values[0], " is not a valid SGF coordinate");
}
} else {
node->properties.push_back(std::move(prop));
}
}
}
bool ParseProperty(Property* prop) {
if (!ReadTo('[', &prop->id)) {
return false;
}
if (prop->id.empty()) {
return Error("property has an empty ID");
}
if (!SkipWhitespace()) {
return Error("reached EOF when parsing property ", prop->id);
}
for (;;) {
prop->values.emplace_back();
if (!ParseValue(&prop->values.back())) {
return false;
}
SkipWhitespace();
if (peek() != '[') {
break;
}
}
return true;
}
bool ParseValue(std::string* value) {
return Read('[') && ReadTo(']', value) && Read(']');
}
bool Read(char c) {
if (done()) {
return Error("expected '", absl::string_view(&c, 1), "', got EOF");
}
if (contents_[0] != c) {
return Error("expected '", absl::string_view(&c, 1), "', got '",
contents_.substr(0, 1), "'");
}
contents_ = contents_.substr(1);
return true;
}
bool ReadTo(char c, std::string* result) {
result->clear();
bool read_escape = false;
for (size_t i = 0; i < contents_.size(); ++i) {
char x = contents_[i];
if (!read_escape) {
read_escape = x == '\\';
if (read_escape) {
continue;
}
}
// Don't check the we're done reading if the current character is an
// escaped \].
if ((!read_escape || x != ']') && x == c) {
contents_ = contents_.substr(i);
return true;
}
absl::StrAppend(result, absl::string_view(&x, 1));
read_escape = false;
}
return Error("reached EOF before finding '", absl::string_view(&c, 1), "'");
}
// Skip over whitespace.
// Updates contents_ and returns true if there are non-whitespace characters
// remaining. Leaves contents_ alone and returns false if only whitespace
// characters remain.
bool SkipWhitespace() {
contents_ = absl::StripLeadingAsciiWhitespace(contents_);
return !contents_.empty();
}
template <typename... Args>
bool Error(Args&&... args) {
// Find the line & column number the error occured at.
int line = 1;
int col = 1;
for (auto* c = original_contents_.data(); c != contents_.data(); ++c) {
if (*c == '\n') {
++line;
col = 1;
} else {
++col;
}
}
*error_ = absl::StrCat("ERROR at line:", line, " col:", col, ": ", args...);
return false;
}
absl::string_view original_contents_;
absl::string_view contents_;
std::string* error_;
};
} // namespace
std::string Property::ToString() const {
return absl::StrCat(id, "[", absl::StrJoin(values, "]["), "]");
}
std::string Node::ToString() const {
std::string str = ";";
if (move.color != Color::kEmpty) {
absl::StrAppend(&str, ColorToCode(move.color), "[", move.c.ToSgf(), "]");
}
for (const auto& prop : properties) {
absl::StrAppend(&str, prop.ToString());
}
return str;
}
const Property* Node::FindProperty(absl::string_view id) const {
for (const auto& prop : properties) {
if (prop.id == id) {
return ∝
}
}
return nullptr;
}
const std::string& Node::GetComment() const {
static const std::string empty;
const auto* prop = FindProperty("C");
return prop != nullptr ? prop->values[0] : empty;
}
std::string Node::GetCommentAndProperties() const {
std::vector<std::string> comments;
std::vector<std::string> prop_strs;
for (const auto& prop : properties) {
if (prop.id == "GC") {
// The game comment goes first.
comments.insert(comments.begin(), prop.values[0]);
} else if (prop.id == "C") {
// The node comment goes after the game comment.
comments.push_back(prop.values[0]);
} else {
prop_strs.push_back(prop.ToString());
}
}
// If we have both comments and properties, insert a blank line to separate
// them.
if (!comments.empty() && !prop_strs.empty()) {
comments.push_back("");
}
comments.insert(comments.end(), prop_strs.begin(), prop_strs.end());
return absl::StrJoin(comments, "\n");
}
std::string Tree::ToString() const {
std::vector<std::string> lines;
for (const auto& node : nodes) {
lines.push_back(node->ToString());
}
for (const auto& sub_tree : sub_trees) {
lines.push_back(sub_tree->ToString());
}
return absl::StrCat("(", absl::StrJoin(lines, "\n"), ")");
}
std::vector<Move> Tree::ExtractMainLine() const {
std::vector<Move> result;
const auto* tree = this;
for (;;) {
for (const auto& node : tree->nodes) {
if (node->move.c != Coord::kInvalid) {
result.push_back(node->move);
}
}
if (tree->sub_trees.empty()) {
break;
}
tree = tree->sub_trees[0].get();
}
return result;
}
std::string Collection::ToString() const {
std::vector<std::string> parts;
for (const auto& tree : trees) {
parts.push_back(tree->ToString());
}
return absl::StrJoin(parts, "\n");
}
bool Parse(absl::string_view contents, Collection* collection,
std::string* error) {
*collection = {};
*error = "";
return Parser(contents, error).Parse(collection);
}
std::string CreateSgfString(absl::Span<const MoveWithComment> moves,
const CreateSgfOptions& options) {
auto str = absl::StrFormat(
"(;GM[1]FF[4]CA[UTF-8]AP[Minigo_sgfgenerator]RU[%s]\n"
"SZ[%d]KM[%g]PW[%s]PB[%s]RE[%s]\n",
options.ruleset, kN, options.komi, options.white_name, options.black_name,
options.result);
if (!options.game_comment.empty()) {
absl::StrAppend(&str, "C[", options.game_comment, "]\n");
}
for (const auto& move_with_comment : moves) {
Move move = move_with_comment.move;
MG_CHECK(move.color == Color::kBlack || move.color == Color::kWhite);
absl::StrAppendFormat(&str, ";%s[%s]", ColorToCode(move.color),
move.c.ToSgf());
if (!move_with_comment.comment.empty()) {
absl::StrAppend(&str, "C[", move_with_comment.comment, "]");
}
}
absl::StrAppend(&str, ")\n");
return str;
}
std::ostream& operator<<(std::ostream& os, const MoveWithComment& move) {
MG_CHECK(move.move.color == Color::kBlack ||
move.move.color == Color::kWhite);
if (move.move.color == Color::kBlack) {
os << "B";
} else {
os << "W";
}
os << "[" << move.move.c.ToSgf() << "]";
if (!move.comment.empty()) {
os << "C[" << move.comment << "]";
}
return os;
}
} // namespace sgf
} // namespace minigo