1 //===-- runtime/edit-input.cpp --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "edit-input.h" 10 #include "namelist.h" 11 #include "flang/Common/real.h" 12 #include "flang/Common/uint128.h" 13 #include <algorithm> 14 15 namespace Fortran::runtime::io { 16 17 static bool EditBOZInput(IoStatementState &io, const DataEdit &edit, void *n, 18 int base, int totalBitSize) { 19 std::optional<int> remaining; 20 std::optional<char32_t> next{io.PrepareInput(edit, remaining)}; 21 common::UnsignedInt128 value{0}; 22 for (; next; next = io.NextInField(remaining, edit)) { 23 char32_t ch{*next}; 24 if (ch == ' ' || ch == '\t') { 25 continue; 26 } 27 int digit{0}; 28 if (ch >= '0' && ch <= '1') { 29 digit = ch - '0'; 30 } else if (base >= 8 && ch >= '2' && ch <= '7') { 31 digit = ch - '0'; 32 } else if (base >= 10 && ch >= '8' && ch <= '9') { 33 digit = ch - '0'; 34 } else if (base == 16 && ch >= 'A' && ch <= 'Z') { 35 digit = ch + 10 - 'A'; 36 } else if (base == 16 && ch >= 'a' && ch <= 'z') { 37 digit = ch + 10 - 'a'; 38 } else { 39 io.GetIoErrorHandler().SignalError( 40 "Bad character '%lc' in B/O/Z input field", ch); 41 return false; 42 } 43 value *= base; 44 value += digit; 45 } 46 // TODO: check for overflow 47 std::memcpy(n, &value, totalBitSize >> 3); 48 return true; 49 } 50 51 static inline char32_t GetDecimalPoint(const DataEdit &edit) { 52 return edit.modes.editingFlags & decimalComma ? char32_t{','} : char32_t{'.'}; 53 } 54 55 // Prepares input from a field, and consumes the sign, if any. 56 // Returns true if there's a '-' sign. 57 static bool ScanNumericPrefix(IoStatementState &io, const DataEdit &edit, 58 std::optional<char32_t> &next, std::optional<int> &remaining) { 59 next = io.PrepareInput(edit, remaining); 60 bool negative{false}; 61 if (next) { 62 negative = *next == '-'; 63 if (negative || *next == '+') { 64 io.GotChar(); 65 io.SkipSpaces(remaining); 66 next = io.NextInField(remaining, edit); 67 } 68 } 69 return negative; 70 } 71 72 bool EditIntegerInput( 73 IoStatementState &io, const DataEdit &edit, void *n, int kind) { 74 RUNTIME_CHECK(io.GetIoErrorHandler(), kind >= 1 && !(kind & (kind - 1))); 75 switch (edit.descriptor) { 76 case DataEdit::ListDirected: 77 if (IsNamelistName(io)) { 78 return false; 79 } 80 break; 81 case 'G': 82 case 'I': 83 break; 84 case 'B': 85 return EditBOZInput(io, edit, n, 2, kind << 3); 86 case 'O': 87 return EditBOZInput(io, edit, n, 8, kind << 3); 88 case 'Z': 89 return EditBOZInput(io, edit, n, 16, kind << 3); 90 case 'A': // legacy extension 91 return EditDefaultCharacterInput( 92 io, edit, reinterpret_cast<char *>(n), kind); 93 default: 94 io.GetIoErrorHandler().SignalError(IostatErrorInFormat, 95 "Data edit descriptor '%c' may not be used with an INTEGER data item", 96 edit.descriptor); 97 return false; 98 } 99 std::optional<int> remaining; 100 std::optional<char32_t> next; 101 bool negate{ScanNumericPrefix(io, edit, next, remaining)}; 102 common::UnsignedInt128 value{0}; 103 bool any{negate}; 104 for (; next; next = io.NextInField(remaining, edit)) { 105 char32_t ch{*next}; 106 if (ch == ' ' || ch == '\t') { 107 if (edit.modes.editingFlags & blankZero) { 108 ch = '0'; // BZ mode - treat blank as if it were zero 109 } else { 110 continue; 111 } 112 } 113 int digit{0}; 114 if (ch >= '0' && ch <= '9') { 115 digit = ch - '0'; 116 } else { 117 io.GetIoErrorHandler().SignalError( 118 "Bad character '%lc' in INTEGER input field", ch); 119 return false; 120 } 121 value *= 10; 122 value += digit; 123 any = true; 124 } 125 if (negate) { 126 value = -value; 127 } 128 if (any || !io.GetConnectionState().IsAtEOF()) { 129 std::memcpy(n, &value, kind); // a blank field means zero 130 } 131 return any; 132 } 133 134 // Parses a REAL input number from the input source as a normalized 135 // fraction into a supplied buffer -- there's an optional '-', a 136 // decimal point, and at least one digit. The adjusted exponent value 137 // is returned in a reference argument. The returned value is the number 138 // of characters that (should) have been written to the buffer -- this can 139 // be larger than the buffer size and can indicate overflow. Replaces 140 // blanks with zeroes if appropriate. 141 static int ScanRealInput(char *buffer, int bufferSize, IoStatementState &io, 142 const DataEdit &edit, int &exponent) { 143 std::optional<int> remaining; 144 std::optional<char32_t> next; 145 int got{0}; 146 std::optional<int> decimalPoint; 147 auto Put{[&](char ch) -> void { 148 if (got < bufferSize) { 149 buffer[got] = ch; 150 } 151 ++got; 152 }}; 153 if (ScanNumericPrefix(io, edit, next, remaining)) { 154 Put('-'); 155 } 156 if (next.value_or(' ') == ' ') { // empty/blank field means zero 157 remaining.reset(); 158 if (!io.GetConnectionState().IsAtEOF()) { 159 Put('0'); 160 } 161 return got; 162 } 163 char32_t decimal{GetDecimalPoint(edit)}; 164 char32_t first{*next >= 'a' && *next <= 'z' ? *next + 'A' - 'a' : *next}; 165 if (first == 'N' || first == 'I') { 166 // NaN or infinity - convert to upper case 167 // Subtle: a blank field of digits could be followed by 'E' or 'D', 168 for (; next && 169 ((*next >= 'a' && *next <= 'z') || (*next >= 'A' && *next <= 'Z')); 170 next = io.NextInField(remaining, edit)) { 171 if (*next >= 'a' && *next <= 'z') { 172 Put(*next - 'a' + 'A'); 173 } else { 174 Put(*next); 175 } 176 } 177 if (next && *next == '(') { // NaN(...) 178 while (next && *next != ')') { 179 next = io.NextInField(remaining, edit); 180 } 181 } 182 exponent = 0; 183 } else if (first == decimal || (first >= '0' && first <= '9') || 184 first == 'E' || first == 'D' || first == 'Q') { 185 Put('.'); // input field is normalized to a fraction 186 auto start{got}; 187 bool bzMode{(edit.modes.editingFlags & blankZero) != 0}; 188 for (; next; next = io.NextInField(remaining, edit)) { 189 char32_t ch{*next}; 190 if (ch == ' ' || ch == '\t') { 191 if (bzMode) { 192 ch = '0'; // BZ mode - treat blank as if it were zero 193 } else { 194 continue; 195 } 196 } 197 if (ch == '0' && got == start && !decimalPoint) { 198 // omit leading zeroes before the decimal 199 } else if (ch >= '0' && ch <= '9') { 200 Put(ch); 201 } else if (ch == decimal && !decimalPoint) { 202 // the decimal point is *not* copied to the buffer 203 decimalPoint = got - start; // # of digits before the decimal point 204 } else { 205 break; 206 } 207 } 208 if (got == start) { 209 Put('0'); // emit at least one digit 210 } 211 if (next && 212 (*next == 'e' || *next == 'E' || *next == 'd' || *next == 'D' || 213 *next == 'q' || *next == 'Q')) { 214 // Optional exponent letter. Blanks are allowed between the 215 // optional exponent letter and the exponent value. 216 io.SkipSpaces(remaining); 217 next = io.NextInField(remaining, edit); 218 } 219 // The default exponent is -kP, but the scale factor doesn't affect 220 // an explicit exponent. 221 exponent = -edit.modes.scale; 222 if (next && 223 (*next == '-' || *next == '+' || (*next >= '0' && *next <= '9') || 224 (bzMode && (*next == ' ' || *next == '\t')))) { 225 bool negExpo{*next == '-'}; 226 if (negExpo || *next == '+') { 227 next = io.NextInField(remaining, edit); 228 } 229 for (exponent = 0; next; next = io.NextInField(remaining, edit)) { 230 if (*next >= '0' && *next <= '9') { 231 exponent = 10 * exponent + *next - '0'; 232 } else if (bzMode && (*next == ' ' || *next == '\t')) { 233 exponent = 10 * exponent; 234 } else { 235 break; 236 } 237 } 238 if (negExpo) { 239 exponent = -exponent; 240 } 241 } 242 if (decimalPoint) { 243 exponent += *decimalPoint; 244 } else { 245 // When no decimal point (or comma) appears in the value, the 'd' 246 // part of the edit descriptor must be interpreted as the number of 247 // digits in the value to be interpreted as being to the *right* of 248 // the assumed decimal point (13.7.2.3.2) 249 exponent += got - start - edit.digits.value_or(0); 250 } 251 } else { 252 // TODO: hex FP input 253 exponent = 0; 254 return 0; 255 } 256 // Consume the trailing ')' of a list-directed or NAMELIST complex 257 // input value. 258 if (edit.descriptor == DataEdit::ListDirectedImaginaryPart) { 259 if (next && (*next == ' ' || *next == '\t')) { 260 next = io.NextInField(remaining, edit); 261 } 262 if (!next) { // NextInField fails on separators like ')' 263 next = io.GetCurrentChar(); 264 if (next && *next == ')') { 265 io.HandleRelativePosition(1); 266 } 267 } 268 } else if (remaining) { 269 while (next && (*next == ' ' || *next == '\t')) { 270 next = io.NextInField(remaining, edit); 271 } 272 if (next) { 273 return 0; // error: unused nonblank character in fixed-width field 274 } 275 } 276 return got; 277 } 278 279 // If no special modes are in effect and the form of the input value 280 // that's present in the input stream is acceptable to the decimal->binary 281 // converter without modification, this fast path for real input 282 // saves time by avoiding memory copies and reformatting of the exponent. 283 template <int PRECISION> 284 static bool TryFastPathRealInput( 285 IoStatementState &io, const DataEdit &edit, void *n) { 286 if (edit.modes.editingFlags & (blankZero | decimalComma)) { 287 return false; 288 } 289 if (edit.modes.scale != 0) { 290 return false; 291 } 292 const char *str{nullptr}; 293 std::size_t got{io.GetNextInputBytes(str)}; 294 if (got == 0 || str == nullptr || 295 !io.GetConnectionState().recordLength.has_value()) { 296 return false; // could not access reliably-terminated input stream 297 } 298 const char *p{str}; 299 std::int64_t maxConsume{ 300 std::min<std::int64_t>(got, edit.width.value_or(got))}; 301 const char *limit{str + maxConsume}; 302 decimal::ConversionToBinaryResult<PRECISION> converted{ 303 decimal::ConvertToBinary<PRECISION>(p, edit.modes.round, limit)}; 304 if (converted.flags & decimal::Invalid) { 305 return false; 306 } 307 if (edit.digits.value_or(0) != 0 && 308 std::memchr(str, '.', p - str) == nullptr) { 309 // No explicit decimal point, and edit descriptor is Fw.d (or other) 310 // with d != 0, which implies scaling. 311 return false; 312 } 313 for (; p < limit && (*p == ' ' || *p == '\t'); ++p) { 314 } 315 if (edit.descriptor == DataEdit::ListDirectedImaginaryPart) { 316 // Need to consume a trailing ')' and any white space after 317 if (p >= limit || *p != ')') { 318 return false; 319 } 320 for (++p; p < limit && (*p == ' ' || *p == '\t'); ++p) { 321 } 322 } 323 if (edit.width && p < str + *edit.width) { 324 return false; // unconverted characters remain in fixed width field 325 } 326 // Success on the fast path! 327 // TODO: raise converted.flags as exceptions? 328 *reinterpret_cast<decimal::BinaryFloatingPointNumber<PRECISION> *>(n) = 329 converted.binary; 330 io.HandleRelativePosition(p - str); 331 return true; 332 } 333 334 template <int KIND> 335 bool EditCommonRealInput(IoStatementState &io, const DataEdit &edit, void *n) { 336 constexpr int binaryPrecision{common::PrecisionOfRealKind(KIND)}; 337 if (TryFastPathRealInput<binaryPrecision>(io, edit, n)) { 338 return true; 339 } 340 // Fast path wasn't available or didn't work; go the more general route 341 static constexpr int maxDigits{ 342 common::MaxDecimalConversionDigits(binaryPrecision)}; 343 static constexpr int bufferSize{maxDigits + 18}; 344 char buffer[bufferSize]; 345 int exponent{0}; 346 int got{ScanRealInput(buffer, maxDigits + 2, io, edit, exponent)}; 347 if (got >= maxDigits + 2) { 348 io.GetIoErrorHandler().Crash("EditCommonRealInput: buffer was too small"); 349 return false; 350 } 351 if (got == 0) { 352 io.GetIoErrorHandler().SignalError("Bad REAL input value"); 353 return false; 354 } 355 bool hadExtra{got > maxDigits}; 356 if (exponent != 0) { 357 buffer[got++] = 'e'; 358 if (exponent < 0) { 359 buffer[got++] = '-'; 360 exponent = -exponent; 361 } 362 if (exponent > 9999) { 363 exponent = 9999; // will convert to +/-Inf 364 } 365 if (exponent > 999) { 366 int dig{exponent / 1000}; 367 buffer[got++] = '0' + dig; 368 int rest{exponent - 1000 * dig}; 369 dig = rest / 100; 370 buffer[got++] = '0' + dig; 371 rest -= 100 * dig; 372 dig = rest / 10; 373 buffer[got++] = '0' + dig; 374 buffer[got++] = '0' + (rest - 10 * dig); 375 } else if (exponent > 99) { 376 int dig{exponent / 100}; 377 buffer[got++] = '0' + dig; 378 int rest{exponent - 100 * dig}; 379 dig = rest / 10; 380 buffer[got++] = '0' + dig; 381 buffer[got++] = '0' + (rest - 10 * dig); 382 } else if (exponent > 9) { 383 int dig{exponent / 10}; 384 buffer[got++] = '0' + dig; 385 buffer[got++] = '0' + (exponent - 10 * dig); 386 } else { 387 buffer[got++] = '0' + exponent; 388 } 389 } 390 buffer[got] = '\0'; 391 const char *p{buffer}; 392 decimal::ConversionToBinaryResult<binaryPrecision> converted{ 393 decimal::ConvertToBinary<binaryPrecision>(p, edit.modes.round)}; 394 if (hadExtra) { 395 converted.flags = static_cast<enum decimal::ConversionResultFlags>( 396 converted.flags | decimal::Inexact); 397 } 398 // TODO: raise converted.flags as exceptions? 399 *reinterpret_cast<decimal::BinaryFloatingPointNumber<binaryPrecision> *>(n) = 400 converted.binary; 401 return true; 402 } 403 404 template <int KIND> 405 bool EditRealInput(IoStatementState &io, const DataEdit &edit, void *n) { 406 constexpr int binaryPrecision{common::PrecisionOfRealKind(KIND)}; 407 switch (edit.descriptor) { 408 case DataEdit::ListDirected: 409 if (IsNamelistName(io)) { 410 return false; 411 } 412 return EditCommonRealInput<KIND>(io, edit, n); 413 case DataEdit::ListDirectedRealPart: 414 case DataEdit::ListDirectedImaginaryPart: 415 case 'F': 416 case 'E': // incl. EN, ES, & EX 417 case 'D': 418 case 'G': 419 return EditCommonRealInput<KIND>(io, edit, n); 420 case 'B': 421 return EditBOZInput( 422 io, edit, n, 2, common::BitsForBinaryPrecision(binaryPrecision)); 423 case 'O': 424 return EditBOZInput( 425 io, edit, n, 8, common::BitsForBinaryPrecision(binaryPrecision)); 426 case 'Z': 427 return EditBOZInput( 428 io, edit, n, 16, common::BitsForBinaryPrecision(binaryPrecision)); 429 case 'A': // legacy extension 430 return EditDefaultCharacterInput( 431 io, edit, reinterpret_cast<char *>(n), KIND); 432 default: 433 io.GetIoErrorHandler().SignalError(IostatErrorInFormat, 434 "Data edit descriptor '%c' may not be used for REAL input", 435 edit.descriptor); 436 return false; 437 } 438 } 439 440 // 13.7.3 in Fortran 2018 441 bool EditLogicalInput(IoStatementState &io, const DataEdit &edit, bool &x) { 442 switch (edit.descriptor) { 443 case DataEdit::ListDirected: 444 if (IsNamelistName(io)) { 445 return false; 446 } 447 break; 448 case 'L': 449 case 'G': 450 break; 451 default: 452 io.GetIoErrorHandler().SignalError(IostatErrorInFormat, 453 "Data edit descriptor '%c' may not be used for LOGICAL input", 454 edit.descriptor); 455 return false; 456 } 457 std::optional<int> remaining; 458 std::optional<char32_t> next{io.PrepareInput(edit, remaining)}; 459 if (next && *next == '.') { // skip optional period 460 next = io.NextInField(remaining, edit); 461 } 462 if (!next) { 463 io.GetIoErrorHandler().SignalError("Empty LOGICAL input field"); 464 return false; 465 } 466 switch (*next) { 467 case 'T': 468 case 't': 469 x = true; 470 break; 471 case 'F': 472 case 'f': 473 x = false; 474 break; 475 default: 476 io.GetIoErrorHandler().SignalError( 477 "Bad character '%lc' in LOGICAL input field", *next); 478 return false; 479 } 480 if (remaining) { // ignore the rest of the field 481 io.HandleRelativePosition(*remaining); 482 } else if (edit.descriptor == DataEdit::ListDirected) { 483 while (io.NextInField(remaining, edit)) { // discard rest of field 484 } 485 } 486 return true; 487 } 488 489 // See 13.10.3.1 paragraphs 7-9 in Fortran 2018 490 static bool EditDelimitedCharacterInput( 491 IoStatementState &io, char *x, std::size_t length, char32_t delimiter) { 492 bool result{true}; 493 while (true) { 494 auto ch{io.GetCurrentChar()}; 495 if (!ch) { 496 if (io.AdvanceRecord()) { 497 continue; 498 } else { 499 result = false; // EOF in character value 500 break; 501 } 502 } 503 io.HandleRelativePosition(1); 504 if (*ch == delimiter) { 505 auto next{io.GetCurrentChar()}; 506 if (next && *next == delimiter) { 507 // Repeated delimiter: use as character value 508 io.HandleRelativePosition(1); 509 } else { 510 break; // closing delimiter 511 } 512 } 513 if (length > 0) { 514 *x++ = *ch; 515 --length; 516 } 517 } 518 std::fill_n(x, length, ' '); 519 return result; 520 } 521 522 static bool EditListDirectedDefaultCharacterInput( 523 IoStatementState &io, char *x, std::size_t length, const DataEdit &edit) { 524 auto ch{io.GetCurrentChar()}; 525 if (ch && (*ch == '\'' || *ch == '"')) { 526 io.HandleRelativePosition(1); 527 return EditDelimitedCharacterInput(io, x, length, *ch); 528 } 529 if (IsNamelistName(io) || io.GetConnectionState().IsAtEOF()) { 530 return false; 531 } 532 // Undelimited list-directed character input: stop at a value separator 533 // or the end of the current record. 534 std::optional<int> remaining{length}; 535 while (std::optional<char32_t> next{io.NextInField(remaining, edit)}) { 536 switch (*next) { 537 case ' ': 538 case '\t': 539 case ',': 540 case ';': 541 case '/': 542 remaining = 0; // value separator: stop 543 break; 544 default: 545 *x++ = *next; 546 --length; 547 } 548 } 549 std::fill_n(x, length, ' '); 550 return true; 551 } 552 553 bool EditDefaultCharacterInput( 554 IoStatementState &io, const DataEdit &edit, char *x, std::size_t length) { 555 switch (edit.descriptor) { 556 case DataEdit::ListDirected: 557 return EditListDirectedDefaultCharacterInput(io, x, length, edit); 558 case 'A': 559 case 'G': 560 break; 561 default: 562 io.GetIoErrorHandler().SignalError(IostatErrorInFormat, 563 "Data edit descriptor '%c' may not be used with a CHARACTER data item", 564 edit.descriptor); 565 return false; 566 } 567 if (io.GetConnectionState().IsAtEOF()) { 568 return false; 569 } 570 std::size_t remaining{length}; 571 if (edit.width && *edit.width > 0) { 572 remaining = *edit.width; 573 } 574 // When the field is wider than the variable, we drop the leading 575 // characters. When the variable is wider than the field, there's 576 // trailing padding. 577 const char *input{nullptr}; 578 std::size_t ready{0}; 579 bool hitEnd{false}; 580 if (remaining > length) { 581 // Discard leading bytes. 582 // These bytes don't count towards INQUIRE(IOLENGTH=). 583 std::size_t skip{remaining - length}; 584 do { 585 if (ready == 0) { 586 ready = io.GetNextInputBytes(input); 587 if (ready == 0) { 588 hitEnd = true; 589 break; 590 } 591 } 592 std::size_t chunk{std::min<std::size_t>(skip, ready)}; 593 io.HandleRelativePosition(chunk); 594 ready -= chunk; 595 input += chunk; 596 skip -= chunk; 597 } while (skip > 0); 598 remaining = length; 599 } 600 // Transfer payload bytes; these do count. 601 while (remaining > 0) { 602 if (ready == 0) { 603 ready = io.GetNextInputBytes(input); 604 if (ready == 0) { 605 hitEnd = true; 606 break; 607 } 608 } 609 std::size_t chunk{std::min<std::size_t>(remaining, ready)}; 610 std::memcpy(x, input, chunk); 611 x += chunk; 612 input += chunk; 613 io.GotChar(chunk); 614 io.HandleRelativePosition(chunk); 615 ready -= chunk; 616 remaining -= chunk; 617 length -= chunk; 618 } 619 // Pad the remainder of the input variable, if any. 620 std::memset(x, ' ', length); 621 if (hitEnd) { 622 io.CheckForEndOfRecord(); // signal any needed error 623 } 624 return true; 625 } 626 627 template bool EditRealInput<2>(IoStatementState &, const DataEdit &, void *); 628 template bool EditRealInput<3>(IoStatementState &, const DataEdit &, void *); 629 template bool EditRealInput<4>(IoStatementState &, const DataEdit &, void *); 630 template bool EditRealInput<8>(IoStatementState &, const DataEdit &, void *); 631 template bool EditRealInput<10>(IoStatementState &, const DataEdit &, void *); 632 // TODO: double/double 633 template bool EditRealInput<16>(IoStatementState &, const DataEdit &, void *); 634 } // namespace Fortran::runtime::io 635