io-stmt.cpp
20 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//===-- runtime/io-stmt.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "io-stmt.h"
#include "connection.h"
#include "format.h"
#include "memory.h"
#include "tools.h"
#include "unit.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <limits>
namespace Fortran::runtime::io {
int IoStatementBase::EndIoStatement() { return GetIoStat(); }
std::optional<DataEdit> IoStatementBase::GetNextDataEdit(
IoStatementState &, int) {
return std::nullopt;
}
template <Direction DIR, typename CHAR>
InternalIoStatementState<DIR, CHAR>::InternalIoStatementState(
Buffer scalar, std::size_t length, const char *sourceFile, int sourceLine)
: IoStatementBase{sourceFile, sourceLine}, unit_{scalar, length} {}
template <Direction DIR, typename CHAR>
InternalIoStatementState<DIR, CHAR>::InternalIoStatementState(
const Descriptor &d, const char *sourceFile, int sourceLine)
: IoStatementBase{sourceFile, sourceLine}, unit_{d, *this} {}
template <Direction DIR, typename CHAR>
bool InternalIoStatementState<DIR, CHAR>::Emit(
const CharType *data, std::size_t chars) {
if constexpr (DIR == Direction::Input) {
Crash("InternalIoStatementState<Direction::Input>::Emit() called");
return false;
}
return unit_.Emit(data, chars, *this);
}
template <Direction DIR, typename CHAR>
std::optional<char32_t> InternalIoStatementState<DIR, CHAR>::GetCurrentChar() {
if constexpr (DIR == Direction::Output) {
Crash(
"InternalIoStatementState<Direction::Output>::GetCurrentChar() called");
return std::nullopt;
}
return unit_.GetCurrentChar(*this);
}
template <Direction DIR, typename CHAR>
bool InternalIoStatementState<DIR, CHAR>::AdvanceRecord(int n) {
while (n-- > 0) {
if (!unit_.AdvanceRecord(*this)) {
return false;
}
}
return true;
}
template <Direction DIR, typename CHAR>
void InternalIoStatementState<DIR, CHAR>::BackspaceRecord() {
unit_.BackspaceRecord(*this);
}
template <Direction DIR, typename CHAR>
int InternalIoStatementState<DIR, CHAR>::EndIoStatement() {
if constexpr (DIR == Direction::Output) {
unit_.EndIoStatement(); // fill
}
auto result{IoStatementBase::EndIoStatement()};
if (free_) {
FreeMemory(this);
}
return result;
}
template <Direction DIR, typename CHAR>
void InternalIoStatementState<DIR, CHAR>::HandleAbsolutePosition(
std::int64_t n) {
return unit_.HandleAbsolutePosition(n);
}
template <Direction DIR, typename CHAR>
void InternalIoStatementState<DIR, CHAR>::HandleRelativePosition(
std::int64_t n) {
return unit_.HandleRelativePosition(n);
}
template <Direction DIR, typename CHAR>
InternalFormattedIoStatementState<DIR, CHAR>::InternalFormattedIoStatementState(
Buffer buffer, std::size_t length, const CHAR *format,
std::size_t formatLength, const char *sourceFile, int sourceLine)
: InternalIoStatementState<DIR, CHAR>{buffer, length, sourceFile,
sourceLine},
ioStatementState_{*this}, format_{*this, format, formatLength} {}
template <Direction DIR, typename CHAR>
InternalFormattedIoStatementState<DIR, CHAR>::InternalFormattedIoStatementState(
const Descriptor &d, const CHAR *format, std::size_t formatLength,
const char *sourceFile, int sourceLine)
: InternalIoStatementState<DIR, CHAR>{d, sourceFile, sourceLine},
ioStatementState_{*this}, format_{*this, format, formatLength} {}
template <Direction DIR, typename CHAR>
int InternalFormattedIoStatementState<DIR, CHAR>::EndIoStatement() {
if constexpr (DIR == Direction::Output) {
format_.Finish(*this); // ignore any remaining input positioning actions
}
return InternalIoStatementState<DIR, CHAR>::EndIoStatement();
}
template <Direction DIR, typename CHAR>
InternalListIoStatementState<DIR, CHAR>::InternalListIoStatementState(
Buffer buffer, std::size_t length, const char *sourceFile, int sourceLine)
: InternalIoStatementState<DIR, CharType>{buffer, length, sourceFile,
sourceLine},
ioStatementState_{*this} {}
template <Direction DIR, typename CHAR>
InternalListIoStatementState<DIR, CHAR>::InternalListIoStatementState(
const Descriptor &d, const char *sourceFile, int sourceLine)
: InternalIoStatementState<DIR, CharType>{d, sourceFile, sourceLine},
ioStatementState_{*this} {}
ExternalIoStatementBase::ExternalIoStatementBase(
ExternalFileUnit &unit, const char *sourceFile, int sourceLine)
: IoStatementBase{sourceFile, sourceLine}, unit_{unit} {}
MutableModes &ExternalIoStatementBase::mutableModes() { return unit_.modes; }
ConnectionState &ExternalIoStatementBase::GetConnectionState() { return unit_; }
int ExternalIoStatementBase::EndIoStatement() {
if (unit_.nonAdvancing) {
unit_.leftTabLimit = unit_.furthestPositionInRecord;
unit_.nonAdvancing = false;
} else {
unit_.leftTabLimit.reset();
}
auto result{IoStatementBase::EndIoStatement()};
unit_.EndIoStatement(); // annihilates *this in unit_.u_
return result;
}
void OpenStatementState::set_path(
const char *path, std::size_t length, int kind) {
if (kind != 1) { // TODO
Crash("OPEN: FILE= with unimplemented: CHARACTER(KIND=%d)", kind);
}
std::size_t bytes{length * kind}; // TODO: UTF-8 encoding of Unicode path
path_ = SaveDefaultCharacter(path, bytes, *this);
pathLength_ = length;
}
int OpenStatementState::EndIoStatement() {
if (wasExtant_ && status_ != OpenStatus::Old) {
SignalError("OPEN statement for connected unit must have STATUS='OLD'");
}
unit().OpenUnit(status_, position_, std::move(path_), pathLength_, *this);
return ExternalIoStatementBase::EndIoStatement();
}
int CloseStatementState::EndIoStatement() {
int result{ExternalIoStatementBase::EndIoStatement()};
unit().CloseUnit(status_, *this);
unit().DestroyClosed();
return result;
}
int NoopCloseStatementState::EndIoStatement() {
auto result{IoStatementBase::EndIoStatement()};
FreeMemory(this);
return result;
}
template <Direction DIR> int ExternalIoStatementState<DIR>::EndIoStatement() {
if (!unit().nonAdvancing) {
unit().AdvanceRecord(*this);
}
if constexpr (DIR == Direction::Output) {
unit().FlushIfTerminal(*this);
}
return ExternalIoStatementBase::EndIoStatement();
}
template <Direction DIR>
bool ExternalIoStatementState<DIR>::Emit(const char *data, std::size_t chars) {
if constexpr (DIR == Direction::Input) {
Crash("ExternalIoStatementState::Emit(char) called for input statement");
}
return unit().Emit(data, chars * sizeof(*data), *this);
}
template <Direction DIR>
bool ExternalIoStatementState<DIR>::Emit(
const char16_t *data, std::size_t chars) {
if constexpr (DIR == Direction::Input) {
Crash(
"ExternalIoStatementState::Emit(char16_t) called for input statement");
}
// TODO: UTF-8 encoding
return unit().Emit(
reinterpret_cast<const char *>(data), chars * sizeof(*data), *this);
}
template <Direction DIR>
bool ExternalIoStatementState<DIR>::Emit(
const char32_t *data, std::size_t chars) {
if constexpr (DIR == Direction::Input) {
Crash(
"ExternalIoStatementState::Emit(char32_t) called for input statement");
}
// TODO: UTF-8 encoding
return unit().Emit(
reinterpret_cast<const char *>(data), chars * sizeof(*data), *this);
}
template <Direction DIR>
std::optional<char32_t> ExternalIoStatementState<DIR>::GetCurrentChar() {
if constexpr (DIR == Direction::Output) {
Crash(
"ExternalIoStatementState<Direction::Output>::GetCurrentChar() called");
}
return unit().GetCurrentChar(*this);
}
template <Direction DIR>
bool ExternalIoStatementState<DIR>::AdvanceRecord(int n) {
while (n-- > 0) {
if (!unit().AdvanceRecord(*this)) {
return false;
}
}
return true;
}
template <Direction DIR> void ExternalIoStatementState<DIR>::BackspaceRecord() {
unit().BackspaceRecord(*this);
}
template <Direction DIR>
void ExternalIoStatementState<DIR>::HandleAbsolutePosition(std::int64_t n) {
return unit().HandleAbsolutePosition(n);
}
template <Direction DIR>
void ExternalIoStatementState<DIR>::HandleRelativePosition(std::int64_t n) {
return unit().HandleRelativePosition(n);
}
template <Direction DIR, typename CHAR>
ExternalFormattedIoStatementState<DIR, CHAR>::ExternalFormattedIoStatementState(
ExternalFileUnit &unit, const CHAR *format, std::size_t formatLength,
const char *sourceFile, int sourceLine)
: ExternalIoStatementState<DIR>{unit, sourceFile, sourceLine},
mutableModes_{unit.modes}, format_{*this, format, formatLength} {}
template <Direction DIR, typename CHAR>
int ExternalFormattedIoStatementState<DIR, CHAR>::EndIoStatement() {
format_.Finish(*this);
return ExternalIoStatementState<DIR>::EndIoStatement();
}
std::optional<DataEdit> IoStatementState::GetNextDataEdit(int n) {
return std::visit(
[&](auto &x) { return x.get().GetNextDataEdit(*this, n); }, u_);
}
bool IoStatementState::Emit(const char *data, std::size_t n) {
return std::visit([=](auto &x) { return x.get().Emit(data, n); }, u_);
}
std::optional<char32_t> IoStatementState::GetCurrentChar() {
return std::visit([&](auto &x) { return x.get().GetCurrentChar(); }, u_);
}
bool IoStatementState::AdvanceRecord(int n) {
return std::visit([=](auto &x) { return x.get().AdvanceRecord(n); }, u_);
}
void IoStatementState::BackspaceRecord() {
std::visit([](auto &x) { x.get().BackspaceRecord(); }, u_);
}
void IoStatementState::HandleRelativePosition(std::int64_t n) {
std::visit([=](auto &x) { x.get().HandleRelativePosition(n); }, u_);
}
int IoStatementState::EndIoStatement() {
return std::visit([](auto &x) { return x.get().EndIoStatement(); }, u_);
}
ConnectionState &IoStatementState::GetConnectionState() {
return std::visit(
[](auto &x) -> ConnectionState & { return x.get().GetConnectionState(); },
u_);
}
MutableModes &IoStatementState::mutableModes() {
return std::visit(
[](auto &x) -> MutableModes & { return x.get().mutableModes(); }, u_);
}
IoErrorHandler &IoStatementState::GetIoErrorHandler() const {
return std::visit(
[](auto &x) -> IoErrorHandler & {
return static_cast<IoErrorHandler &>(x.get());
},
u_);
}
ExternalFileUnit *IoStatementState::GetExternalFileUnit() const {
return std::visit([](auto &x) { return x.get().GetExternalFileUnit(); }, u_);
}
bool IoStatementState::EmitRepeated(char ch, std::size_t n) {
return std::visit(
[=](auto &x) {
for (std::size_t j{0}; j < n; ++j) {
if (!x.get().Emit(&ch, 1)) {
return false;
}
}
return true;
},
u_);
}
bool IoStatementState::EmitField(
const char *p, std::size_t length, std::size_t width) {
if (width <= 0) {
width = static_cast<int>(length);
}
if (length > static_cast<std::size_t>(width)) {
return EmitRepeated('*', width);
} else {
return EmitRepeated(' ', static_cast<int>(width - length)) &&
Emit(p, length);
}
}
std::optional<char32_t> IoStatementState::SkipSpaces(
std::optional<int> &remaining) {
while (!remaining || *remaining > 0) {
if (auto ch{GetCurrentChar()}) {
if (*ch != ' ') {
return ch;
}
HandleRelativePosition(1);
if (remaining) {
--*remaining;
}
} else {
break;
}
}
return std::nullopt;
}
std::optional<char32_t> IoStatementState::NextInField(
std::optional<int> &remaining) {
if (!remaining) { // list-directed or namelist: check for separators
if (auto next{GetCurrentChar()}) {
switch (*next) {
case ' ':
case ',':
case ';':
case '/':
case '(':
case ')':
case '\'':
case '"':
case '*':
case '\n': // for stream access
break;
default:
HandleRelativePosition(1);
return next;
}
}
} else if (*remaining > 0) {
if (auto next{GetCurrentChar()}) {
--*remaining;
HandleRelativePosition(1);
return next;
}
const ConnectionState &connection{GetConnectionState()};
if (!connection.IsAtEOF() && connection.isFixedRecordLength &&
connection.recordLength &&
connection.positionInRecord >= *connection.recordLength) {
if (connection.modes.pad) { // PAD='YES'
--*remaining;
return std::optional<char32_t>{' '};
}
IoErrorHandler &handler{GetIoErrorHandler()};
if (connection.nonAdvancing) {
handler.SignalEor();
} else {
handler.SignalError(IostatRecordReadOverrun);
}
}
}
return std::nullopt;
}
std::optional<char32_t> IoStatementState::GetNextNonBlank() {
auto ch{GetCurrentChar()};
while (ch.value_or(' ') == ' ') {
if (ch) {
HandleRelativePosition(1);
} else if (!AdvanceRecord()) {
return std::nullopt;
}
ch = GetCurrentChar();
}
return ch;
}
bool ListDirectedStatementState<Direction::Output>::NeedAdvance(
const ConnectionState &connection, std::size_t width) const {
return connection.positionInRecord > 0 &&
width > connection.RemainingSpaceInRecord();
}
bool ListDirectedStatementState<Direction::Output>::EmitLeadingSpaceOrAdvance(
IoStatementState &io, std::size_t length, bool isCharacter) {
if (length == 0) {
return true;
}
const ConnectionState &connection{io.GetConnectionState()};
int space{connection.positionInRecord == 0 ||
!(isCharacter && lastWasUndelimitedCharacter)};
lastWasUndelimitedCharacter = false;
if (NeedAdvance(connection, space + length)) {
return io.AdvanceRecord();
}
if (space) {
return io.Emit(" ", 1);
}
return true;
}
std::optional<DataEdit>
ListDirectedStatementState<Direction::Output>::GetNextDataEdit(
IoStatementState &io, int maxRepeat) {
DataEdit edit;
edit.descriptor = DataEdit::ListDirected;
edit.repeat = maxRepeat;
edit.modes = io.mutableModes();
return edit;
}
std::optional<DataEdit>
ListDirectedStatementState<Direction::Input>::GetNextDataEdit(
IoStatementState &io, int maxRepeat) {
// N.B. list-directed transfers cannot be nonadvancing (C1221)
ConnectionState &connection{io.GetConnectionState()};
DataEdit edit;
edit.descriptor = DataEdit::ListDirected;
edit.repeat = 1; // may be overridden below
edit.modes = connection.modes;
if (hitSlash_) { // everything after '/' is nullified
edit.descriptor = DataEdit::ListDirectedNullValue;
return edit;
}
char32_t comma{','};
if (io.mutableModes().editingFlags & decimalComma) {
comma = ';';
}
if (remaining_ > 0 && !realPart_) { // "r*c" repetition in progress
while (connection.currentRecordNumber > initialRecordNumber_) {
io.BackspaceRecord();
}
connection.HandleAbsolutePosition(initialPositionInRecord_);
if (!imaginaryPart_) {
edit.repeat = std::min<int>(remaining_, maxRepeat);
auto ch{io.GetNextNonBlank()};
if (!ch || *ch == ' ' || *ch == comma) { // "r*" repeated null
edit.descriptor = DataEdit::ListDirectedNullValue;
}
}
remaining_ -= edit.repeat;
return edit;
}
// Skip separators, handle a "r*c" repeat count; see 13.10.2 in Fortran 2018
auto ch{io.GetNextNonBlank()};
if (imaginaryPart_) {
imaginaryPart_ = false;
if (ch && *ch == ')') {
io.HandleRelativePosition(1);
ch = io.GetNextNonBlank();
}
} else if (realPart_) {
realPart_ = false;
imaginaryPart_ = true;
}
if (!ch) {
return std::nullopt;
}
if (*ch == '/') {
hitSlash_ = true;
edit.descriptor = DataEdit::ListDirectedNullValue;
return edit;
}
bool isFirstItem{isFirstItem_};
isFirstItem_ = false;
if (*ch == comma) {
if (isFirstItem) {
edit.descriptor = DataEdit::ListDirectedNullValue;
return edit;
}
// Consume comma & whitespace after previous item.
io.HandleRelativePosition(1);
ch = io.GetNextNonBlank();
if (!ch) {
return std::nullopt;
}
if (*ch == comma || *ch == '/') {
edit.descriptor = DataEdit::ListDirectedNullValue;
return edit;
}
}
if (imaginaryPart_) { // can't repeat components
return edit;
}
if (*ch >= '0' && *ch <= '9') { // look for "r*" repetition count
auto start{connection.positionInRecord};
int r{0};
do {
static auto constexpr clamp{(std::numeric_limits<int>::max() - '9') / 10};
if (r >= clamp) {
r = 0;
break;
}
r = 10 * r + (*ch - '0');
io.HandleRelativePosition(1);
ch = io.GetCurrentChar();
} while (ch && *ch >= '0' && *ch <= '9');
if (r > 0 && ch && *ch == '*') { // subtle: r must be nonzero
io.HandleRelativePosition(1);
ch = io.GetCurrentChar();
if (ch && *ch == '/') { // r*/
hitSlash_ = true;
edit.descriptor = DataEdit::ListDirectedNullValue;
return edit;
}
if (!ch || *ch == ' ' || *ch == comma) { // "r*" null
edit.descriptor = DataEdit::ListDirectedNullValue;
}
edit.repeat = std::min<int>(r, maxRepeat);
remaining_ = r - edit.repeat;
initialRecordNumber_ = connection.currentRecordNumber;
initialPositionInRecord_ = connection.positionInRecord;
} else { // not a repetition count, just an integer value; rewind
connection.positionInRecord = start;
}
}
if (!imaginaryPart_ && ch && *ch == '(') {
realPart_ = true;
io.HandleRelativePosition(1);
}
return edit;
}
template <Direction DIR>
bool UnformattedIoStatementState<DIR>::Receive(char *data, std::size_t bytes) {
if constexpr (DIR == Direction::Output) {
this->Crash(
"UnformattedIoStatementState::Receive() called for output statement");
}
return this->unit().Receive(data, bytes, *this);
}
template <Direction DIR>
int UnformattedIoStatementState<DIR>::EndIoStatement() {
ExternalFileUnit &unit{this->unit()};
if constexpr (DIR == Direction::Output) {
if (unit.access == Access::Sequential && !unit.isFixedRecordLength) {
// Append the length of a sequential unformatted variable-length record
// as its footer, then overwrite the reserved first four bytes of the
// record with its length as its header. These four bytes were skipped
// over in BeginUnformattedOutput().
// TODO: Break very large records up into subrecords with negative
// headers &/or footers
union {
std::uint32_t u;
char c[sizeof u];
} u;
u.u = unit.furthestPositionInRecord - sizeof u;
// TODO: Convert record length to little-endian on big-endian host?
if (!(this->Emit(u.c, sizeof u) &&
(this->HandleAbsolutePosition(0), this->Emit(u.c, sizeof u)))) {
return false;
}
}
}
return ExternalIoStatementState<DIR>::EndIoStatement();
}
template class InternalIoStatementState<Direction::Output>;
template class InternalIoStatementState<Direction::Input>;
template class InternalFormattedIoStatementState<Direction::Output>;
template class InternalFormattedIoStatementState<Direction::Input>;
template class InternalListIoStatementState<Direction::Output>;
template class InternalListIoStatementState<Direction::Input>;
template class ExternalIoStatementState<Direction::Output>;
template class ExternalIoStatementState<Direction::Input>;
template class ExternalFormattedIoStatementState<Direction::Output>;
template class ExternalFormattedIoStatementState<Direction::Input>;
template class ExternalListIoStatementState<Direction::Output>;
template class ExternalListIoStatementState<Direction::Input>;
template class UnformattedIoStatementState<Direction::Output>;
template class UnformattedIoStatementState<Direction::Input>;
int ExternalMiscIoStatementState::EndIoStatement() {
ExternalFileUnit &ext{unit()};
switch (which_) {
case Flush:
ext.Flush(*this);
std::fflush(nullptr); // flushes C stdio output streams (12.9(2))
break;
case Backspace:
ext.BackspaceRecord(*this);
break;
case Endfile:
ext.Endfile(*this);
break;
case Rewind:
ext.Rewind(*this);
break;
}
return ExternalIoStatementBase::EndIoStatement();
}
} // namespace Fortran::runtime::io