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
|
/* DataNode.cpp
Copyright (c) 2014 by Michael Zahniser
Endless Sky is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "DataNode.h"
#include "DataWriter.h"
#include "Logger.h"
#include <algorithm>
#include <cctype>
#include <cmath>
using namespace std;
// Construct a DataNode and remember what its parent is.
DataNode::DataNode(const DataNode *parent) noexcept(false)
: parent(parent)
{
// To avoid a lot of memory reallocation, have every node start out with
// capacity for four tokens. This makes file loading slightly faster, at the
// cost of DataFiles taking up a bit more memory.
tokens.reserve(4);
}
// Copy constructor.
DataNode::DataNode(const DataNode &other)
: children(other.children), tokens(other.tokens), lineNumber(std::move(other.lineNumber))
{
Reparent();
}
// Copy assignment operator.
DataNode &DataNode::operator=(const DataNode &other)
{
children = other.children;
tokens = other.tokens;
lineNumber = std::move(other.lineNumber);
Reparent();
return *this;
}
DataNode::DataNode(DataNode &&other) noexcept
: children(std::move(other.children)), tokens(std::move(other.tokens)), lineNumber(other.lineNumber)
{
Reparent();
}
DataNode &DataNode::operator=(DataNode &&other) noexcept
{
children.swap(other.children);
tokens.swap(other.tokens);
lineNumber = other.lineNumber;
Reparent();
return *this;
}
// Get the number of tokens in this line of the data file.
int DataNode::Size() const noexcept
{
return tokens.size();
}
// Get all tokens.
const vector<string> &DataNode::Tokens() const noexcept
{
return tokens;
}
// Add tokens to the node.
void DataNode::AddToken(const std::string &token)
{
tokens.emplace_back(token);
}
// Get the token with the given index. No bounds checking is done.
// DataFile loading guarantees index 0 always exists.
const string &DataNode::Token(int index) const
{
return tokens[index];
}
// Convert the token with the given index to a numerical value.
double DataNode::Value(int index) const
{
// Check for empty strings and out-of-bounds indices.
if(static_cast<size_t>(index) >= tokens.size() || tokens[index].empty())
PrintTrace("Error: Requested token index (" + to_string(index) + ") is out of bounds:");
else if(!IsNumber(tokens[index]))
PrintTrace("Error: Cannot convert value \"" + tokens[index] + "\" to a number:");
else
return Value(tokens[index]);
return 0.;
}
// Static helper function for any class which needs to parse string -> number.
double DataNode::Value(const string &token)
{
// Allowed format: "[+-]?[0-9]*[.]?[0-9]*([eE][+-]?[0-9]*)?".
if(!IsNumber(token))
{
Logger::LogError("Cannot convert value \"" + token + "\" to a number.");
return 0.;
}
const char *it = token.c_str();
// Check for leading sign.
double sign = (*it == '-') ? -1. : 1.;
it += (*it == '-' || *it == '+');
// Digits before the decimal point.
int64_t value = 0;
while(*it >= '0' && *it <= '9')
value = (value * 10) + (*it++ - '0');
// Digits after the decimal point (if any).
int64_t power = 0;
if(*it == '.')
{
++it;
while(*it >= '0' && *it <= '9')
{
value = (value * 10) + (*it++ - '0');
--power;
}
}
// Exponent.
if(*it == 'e' || *it == 'E')
{
++it;
int64_t sign = (*it == '-') ? -1 : 1;
it += (*it == '-' || *it == '+');
int64_t exponent = 0;
while(*it >= '0' && *it <= '9')
exponent = (exponent * 10) + (*it++ - '0');
power += sign * exponent;
}
// Compose the return value.
return copysign(value * pow(10., power), sign);
}
// Check if the token at the given index is a number in a format that this
// class is able to parse.
bool DataNode::IsNumber(int index) const
{
// Make sure this token exists and is not empty.
if(static_cast<size_t>(index) >= tokens.size() || tokens[index].empty())
return false;
return IsNumber(tokens[index]);
}
bool DataNode::IsNumber(const string &token)
{
bool hasDecimalPoint = false;
bool hasExponent = false;
bool isLeading = true;
for(const char *it = token.c_str(); *it; ++it)
{
// If this is the start of the number or the exponent, it is allowed to
// be a '-' or '+' sign.
if(isLeading)
{
isLeading = false;
if(*it == '-' || *it == '+')
continue;
}
// If this is a decimal, it may or may not be allowed.
if(*it == '.')
{
if(hasDecimalPoint || hasExponent)
return false;
hasDecimalPoint = true;
}
else if(*it == 'e' || *it == 'E')
{
if(hasExponent)
return false;
hasExponent = true;
// At the start of an exponent, a '-' or '+' is allowed.
isLeading = true;
}
else if(*it < '0' || *it > '9')
return false;
}
return true;
}
// Convert the token at the given index to a boolean. This returns false
// and prints an error if the index is out of range or the token cannot
// be interpreted as a number.
bool DataNode::BoolValue(int index) const
{
// Check for empty strings and out-of-bounds indices.
if(static_cast<size_t>(index) >= tokens.size() || tokens[index].empty())
PrintTrace("Error: Requested token index (" + to_string(index) + ") is out of bounds:");
else if(!IsBool(tokens[index]))
PrintTrace("Error: Cannot convert value \"" + tokens[index] + "\" to a boolean:");
else
{
const string &token = tokens[index];
return token == "true" || token == "1";
}
return false;
}
// Check if the token at the given index is a boolean, i.e. "true"/"1" or "false"/"0"
// as a string.
bool DataNode::IsBool(int index) const
{
// Make sure this token exists and is not empty.
if(static_cast<size_t>(index) >= tokens.size() || tokens[index].empty())
return false;
return IsBool(tokens[index]);
}
bool DataNode::IsBool(const string &token)
{
return token == "true" || token == "1" || token == "false" || token == "0";
}
bool DataNode::IsConditionName(const string &token)
{
// For now check if condition names start with an alphabetic character, and that is all we check for now.
// Token "'" is required for backwards compatibility (used for illegal tokens).
// Boolean keywords are not valid conditionNames, so we also check for that.
return
!token.empty() &&
!IsBool(token) &&
(
(token == "'") ||
(token[0] >= 'a' && token[0] <= 'z') ||
(token[0] >= 'A' && token[0] <= 'Z')
);
}
// Add a new child. The child's parent must be this node.
void DataNode::AddChild(const DataNode &child)
{
children.emplace_back(child);
}
// Check if this node has any children.
bool DataNode::HasChildren() const noexcept
{
return !children.empty();
}
// Iterator to the beginning of the list of children.
list<DataNode>::const_iterator DataNode::begin() const noexcept
{
return children.begin();
}
// Iterator to the end of the list of children.
list<DataNode>::const_iterator DataNode::end() const noexcept
{
return children.end();
}
// Print a message followed by a "trace" of this node and its parents.
int DataNode::PrintTrace(const string &message) const
{
if(!message.empty())
Logger::LogError(message);
// Recursively print all the parents of this node, so that the user can
// trace it back to the right point in the file.
size_t indent = 0;
if(parent)
indent = parent->PrintTrace() + 2;
if(tokens.empty())
return indent;
// Convert this node back to tokenized text, with quotes used as necessary.
string line = !parent ? "" : "L" + to_string(lineNumber) + ": ";
line.append(string(indent, ' '));
for(const string &token : tokens)
{
if(&token != &tokens.front())
line += ' ';
line += DataWriter::Quote(token);
}
Logger::LogError(line);
// Put an empty line in the log between each error message.
if(!message.empty())
Logger::LogError("");
// Tell the caller what indentation level we're at now.
return indent;
}
// Adjust the parent pointers when a copy is made of a DataNode.
void DataNode::Reparent() noexcept
{
for(DataNode &child : children)
{
child.parent = this;
child.Reparent();
}
}
|