Skip to main content

ironwork_rt/
fileio.rs

1//! The file statements (lir.md ยง9.4): OPEN, CLOSE, READ, WRITE, REWRITE, DELETE and START on one
2//! file, FILE STATUS, LINAGE and the print carriage. A sequential file streams through its DD; an
3//! indexed or relative file, or a sequential file opened I-O, is held in memory ([`Keyed`]). Each
4//! verb returns the status its phrases or the file's error path read; the executor runs those.
5
6use crate::abend::Abend;
7use crate::files::{self, Dd, FileStatus, Format, Keyed, Keying, Move, Open, Record};
8use crate::host::{self, Host};
9use crate::linage::{Geometry, Motion, Page};
10use crate::lir::{Access, Carriage, Organization, Spacing, StartRel};
11use crate::printer::{self, Controls};
12use crate::storage::{Loc, Val};
13use crate::store::{self, ProgramFacts};
14use crate::unit::Event;
15use crate::vocab::{Closing, OpenMode, Pos};
16use numeric::precision::{Fixed, Places};
17use std::cmp::Ordering;
18use zarch::ebcdic;
19
20type R<T> = Result<T, Abend>;
21
22/// A file as SELECT and FD declare it ([`crate::lir::FileDesc`]), with the executor's handles: `P`
23/// a data item, `X` an integer it evaluates. Its keys are the executor's to resolve
24/// ([`Files::keying`]).
25#[derive(Clone, Copy)]
26pub struct File<'a, P, X> {
27    pub index: usize,
28    pub name: &'a str,
29    /// The DD name ASSIGN gives.
30    pub assign: &'a str,
31    pub organization: Organization,
32    pub access: Access,
33    pub optional: bool,
34    /// How records are held when the DD does not say.
35    pub format: Format,
36    pub status: Option<P>,
37    pub relative: Option<P>,
38    pub linage: Option<Linage<X>>,
39    pub carriage: Option<Carriage>,
40    /// Where the record area is in run-unit memory, and its length.
41    pub area: (usize, usize),
42    /// The shortest and longest variable-length record a READ takes without a record length
43    /// conflict ([`crate::lir::FileDesc::read_lengths`]).
44    pub read_lengths: (usize, usize),
45    pub depending: Option<Depending<P>>,
46}
47
48/// RECORD IS VARYING DEPENDING ON: the item holding a record's length, and the shortest and longest
49/// record the clause allows.
50#[derive(Clone, Copy)]
51pub struct Depending<P> {
52    pub item: P,
53    pub lengths: (usize, usize),
54}
55
56/// LINAGE's values, evaluated in this order whenever the page's geometry is taken, and
57/// LINAGE-COUNTER.
58#[derive(Clone, Copy)]
59pub struct Linage<X> {
60    pub lines: X,
61    pub footing: Option<X>,
62    pub top: Option<X>,
63    pub bottom: Option<X>,
64    pub counter: Option<Loc>,
65}
66
67/// READ ([`crate::lir::FileVerb::Read`]). `key` is READ ... KEY IS.
68#[derive(Clone, Copy)]
69pub struct Read<P> {
70    pub sequential: bool,
71    pub previous: bool,
72    pub into: Option<P>,
73    pub key: Option<P>,
74}
75
76/// WRITE's ADVANCING phrase ([`crate::lir::Advance`]). A mnemonic-name's `space` is None when its
77/// environment-name is no printer channel.
78#[derive(Clone, Copy)]
79pub enum Advance<'a, X> {
80    Lines { before: bool, count: X },
81    Page { before: bool },
82    Mnemonic { before: bool, space: Option<Spacing>, name: &'a str, environment: &'a str },
83}
84
85/// How a verb ended.
86pub enum Outcome {
87    /// FILE STATUS holds its status and nothing is left to run.
88    Done,
89    /// The status the statement's AT END (`at_end`) or INVALID KEY phrase, or else the file's
90    /// error path, reads.
91    Status { status: FileStatus, at_end: bool },
92    /// A WRITE to a LINAGE file, with FILE STATUS set: END-OF-PAGE or NOT END-OF-PAGE runs.
93    Page { end_of_page: bool },
94    /// A failing status that takes the file's error path at once.
95    Failed(Failure),
96}
97
98/// `mode` is the mode the file is open in, or being opened in.
99pub struct Failure {
100    pub status: FileStatus,
101    pub mode: Option<OpenMode>,
102    pub message: String,
103}
104
105/// What the file verbs ask of the executor beyond [`Host`].
106pub trait Files<P: Copy, X: Copy>: Host<P> {
107    /// The program's file `k` while it is open.
108    fn slot(&mut self, k: usize) -> &mut Option<Open>;
109    /// Whether CLOSE WITH LOCK has closed file `k`.
110    fn locked(&mut self, k: usize) -> &mut bool;
111    fn dd(&self, assign: &str) -> Option<Dd>;
112    fn notify(&mut self, event: Event<'_>);
113    fn int(&mut self, value: X, pos: Pos) -> R<i64>;
114    /// How file `k` finds its records by key.
115    fn keying(&mut self, k: usize, pos: Pos) -> R<Keying>;
116    /// Which key of indexed file `k` the item names (0 the prime key, then each alternate), and
117    /// its value in the record area. With `partial` (START) it may be a leading part of the key.
118    fn key_value(&mut self, k: usize, keying: &Keying, key: P, partial: bool, pos: Pos) -> R<(usize, Vec<u8>)>;
119}
120
121pub fn set_status<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, status: FileStatus, pos: Pos) -> R<()> {
122    if let Some(p) = file.status {
123        let loc = x.locate(p, false)?;
124        let bytes = x.facts().page().encode(status.as_str()).map_err(|e| Abend::ironwork(e.to_string(), pos))?;
125        x.assign(loc, Val::Bytes(bytes), None, pos)?;
126    }
127    Ok(())
128}
129
130/// A failure in the mode file `k` is open in now.
131fn failed<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, status: FileStatus, message: String) -> Outcome {
132    let mode = x.slot(file.index).as_ref().map(|f| f.mode);
133    Outcome::Failed(Failure { status, mode, message })
134}
135
136pub fn sequential<P, X>(file: &File<'_, P, X>) -> bool {
137    file.access == Access::Sequential || file.organization == Organization::Sequential
138}
139
140/// Whether the file's DD holds a byte before each record for the printer control character: a
141/// print file under ADV, unless the DD is text, which shows the character as line spacing.
142pub fn adds_control_byte<P, X>(file: &File<'_, P, X>, format: Format) -> bool {
143    file.carriage.is_some_and(|c| !c.reserved) && format != Format::Text
144}
145
146/// How the file's DD holds its records.
147pub fn dd_format<P: Copy, X: Copy>(x: &impl Files<P, X>, file: &File<'_, P, X>) -> Format {
148    x.dd(file.assign).and_then(|d| d.format).unwrap_or(file.format)
149}
150
151fn record_area<P: Copy>(x: &mut impl Host<P>, (offset, size): (usize, usize)) -> &[u8] {
152    &x.mem()[offset..offset + size]
153}
154
155fn relative_value<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, pos: Pos) -> R<i64> {
156    let r = file.relative.ok_or_else(|| Abend::ironwork(format!("{} has no RELATIVE KEY", file.name), pos))?;
157    x.integer(r, pos)
158}
159
160/// The RELATIVE KEY's record number as a key, or None when it is below 1.
161fn relative_number<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, pos: Pos) -> R<Option<Vec<u8>>> {
162    let n = relative_value(x, file, pos)?;
163    Ok((n >= 1).then(|| files::record_number(n as u64)))
164}
165
166/// Whether record number `n` fits the RELATIVE KEY item, as sequential READ and WRITE store it
167/// there.
168fn relative_fits<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, n: u64) -> R<bool> {
169    let Some(r) = file.relative else { return Ok(true) };
170    let loc = x.locate(r, false)?;
171    Ok(match loc.kind.digits_scale() {
172        Some((digits, scale)) => digits.saturating_sub(scale) >= 19 || n < 10u64.pow(digits.saturating_sub(scale)),
173        None => true,
174    })
175}
176
177/// Runs `op` on file `k` when it is open and held in memory.
178fn held<P: Copy, X: Copy, F: Files<P, X>, T>(x: &mut F, k: usize, op: impl FnOnce(&mut F, OpenMode, Format, &mut Keyed) -> R<T>) -> R<Option<T>> {
179    let Some(mut f) = x.slot(k).take() else { return Ok(None) };
180    let (mode, format) = (f.mode, f.format);
181    let result = match f.keyed() {
182        Some(keyed) => op(x, mode, format, keyed).map(Some),
183        None => Ok(None),
184    };
185    *x.slot(k) = Some(f);
186    result
187}
188
189fn is_held<P: Copy, X: Copy>(x: &mut impl Files<P, X>, k: usize) -> bool {
190    x.slot(k).as_ref().is_some_and(|f| f.is_keyed())
191}
192
193/// Whether the file is a print file opened I-O whose records hold the byte ADV adds
194/// ([`numeric::assumptions::PRINT_FILE_UPDATE`]).
195fn held_control_byte<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>) -> bool {
196    x.slot(file.index).as_ref().is_some_and(|f| f.is_keyed() && adds_control_byte(file, f.format))
197}
198
199/// A record as WRITE or REWRITE puts it in the file: a fixed record at the length of the area.
200fn record_bytes<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, format: Format) -> Vec<u8> {
201    let mut bytes = store::bytes(x.mem(), loc).to_vec();
202    if format != Format::Variable {
203        bytes.resize(file.area.1.max(bytes.len()), ebcdic::SPACE);
204    }
205    bytes
206}
207
208/// The record WRITE, REWRITE or RELEASE puts out: under DEPENDING ON the record area's first n
209/// bytes, n the item's value, or status 44 when n is outside the clause's lengths (Language
210/// Reference SC27-8713-03, pp. 188, 302).
211pub fn record_length<P: Copy, X: Copy>(x: &mut impl Host<P>, file: &File<'_, P, X>, loc: Loc, pos: Pos) -> R<Result<Loc, FileStatus>> {
212    let Some(d) = file.depending else { return Ok(Ok(loc)) };
213    let n = x.integer(d.item, pos)?;
214    let (shortest, longest) = d.lengths;
215    if n < shortest as i64 || n > longest.min(file.area.1) as i64 {
216        return Ok(Err(FileStatus::RecordLengthChanged));
217    }
218    Ok(Ok(Loc { offset: file.area.0, len: n as usize, ..loc }))
219}
220
221/// Moves a record into the file's area, and to INTO's item; a variable-length record fills only
222/// its own length, which DEPENDING ON's item receives. True when the record was longer than the
223/// area.
224fn deliver<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, record: &[u8], variable: bool, into: Option<P>, pos: Pos) -> R<bool> {
225    let (offset, size) = file.area;
226    let n = record.len().min(size);
227    let mem = x.mem();
228    mem[offset..offset + n].copy_from_slice(&record[..n]);
229    if !variable {
230        mem[offset + n..offset + size].fill(ebcdic::SPACE);
231    }
232    if let Some(d) = file.depending {
233        host::set_integer(x, d.item, n as i64, pos)?;
234    }
235    if let Some(r) = into {
236        let dest = x.locate(r, true)?;
237        let bytes = x.mem()[offset..offset + if variable { n } else { size }].to_vec();
238        x.assign(dest, Val::Bytes(bytes), None, pos)?;
239    }
240    Ok(record.len() > size)
241}
242
243/// Whether a record READ delivered has a record length conflict, status 04: it was longer than the
244/// record area, or it is a variable-length record outside the file's read lengths
245/// ([`numeric::assumptions::VLR_RECORDS_CHECKED`]).
246fn length_conflict<P, X>(file: &File<'_, P, X>, len: usize, variable: bool, long: bool) -> bool {
247    let (shortest, longest) = file.read_lengths;
248    long || variable && !(shortest..=longest).contains(&len)
249}
250
251/// OPEN: a file whose data set is unavailable is status 35, or 05 when it is OPTIONAL, which
252/// OPEN EXTEND then creates (Language Reference SC27-8713-03, pp. 300-301).
253pub fn open<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, mode: OpenMode, pos: Pos) -> R<Outcome> {
254    let (k, name) = (file.index, file.name);
255    let failure = |status, message| Ok(Outcome::Failed(Failure { status, mode: Some(mode), message }));
256    if *x.locked(k) {
257        return failure(FileStatus::ClosedWithLock, format!("{name} was closed WITH LOCK"));
258    }
259    if x.slot(k).is_some() {
260        return failure(FileStatus::AlreadyOpen, format!("{name} is already open"));
261    }
262    let page = match (&file.linage, mode) {
263        (Some(_), OpenMode::Output | OpenMode::Extend) => Some(Page::opened(geometry(x, file, pos)?)),
264        _ => None,
265    };
266    let default = file.format;
267    let dd = x.dd(file.assign);
268    if let Some(d) = &dd {
269        x.notify(Event::Open { dd: file.assign, mode, path: &d.path });
270    }
271    let no_dd = format!("{name}: no DD {} was given (--dd {}=path)", file.assign, file.assign);
272    let held = match file.organization {
273        Organization::Indexed | Organization::Relative => true,
274        Organization::Sequential => mode == OpenMode::InputOutput,
275        Organization::LineSequential => false,
276    };
277    if held {
278        let status = match &dd {
279            Some(d) if mode == OpenMode::Output || d.path.exists() => FileStatus::Success,
280            _ if file.optional && mode != OpenMode::Output => FileStatus::SuccessOptional,
281            None => return failure(FileStatus::FileNotFound, no_dd),
282            Some(d) => return failure(FileStatus::FileNotFound, format!("{name}: {}: no such file", d.path.display())),
283        };
284        let keying = x.keying(k, pos)?;
285        let format = dd.as_ref().and_then(|d| d.format).unwrap_or(default);
286        let record_len = file.area.1 + usize::from(adds_control_byte(file, format));
287        return match files::open_keyed(dd.as_ref(), mode, format, keying, record_len, x.facts().page()) {
288            Ok(f) => opened(x, file, f, status, pos),
289            Err(e) => failure(FileStatus::PermanentError, format!("{name}: {e}")),
290        };
291    }
292    match dd {
293        _ if file.optional && mode == OpenMode::Input && dd.as_ref().is_none_or(|d| !d.path.exists()) => opened(x, file, files::absent(), FileStatus::SuccessOptional, pos),
294        None => failure(FileStatus::FileNotFound, no_dd),
295        Some(dd) if mode == OpenMode::Extend && !file.optional && !dd.path.exists() => failure(FileStatus::FileNotFound, format!("{name}: {}: no such file", dd.path.display())),
296        Some(dd) => {
297            let created = mode == OpenMode::Extend && !dd.path.exists();
298            match files::open(&dd, mode, dd.format.unwrap_or(default)) {
299                Ok(mut f) => {
300                    f.page = page;
301                    opened(x, file, f, if created { FileStatus::SuccessOptional } else { FileStatus::Success }, pos)
302                }
303                Err(e) => {
304                    let status = match e.kind() {
305                        std::io::ErrorKind::NotFound => FileStatus::FileNotFound,
306                        std::io::ErrorKind::Unsupported => FileStatus::OpenModeUnsupported,
307                        _ => FileStatus::PermanentError,
308                    };
309                    failure(status, format!("{name}: {}: {e}", dd.path.display()))
310                }
311            }
312        }
313    }
314}
315
316/// Holds the file open; OPEN sets a LINAGE file's LINAGE-COUNTER to 1 (Language Reference
317/// SC27-8713-03, p. 24).
318fn opened<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, f: Open, status: FileStatus, pos: Pos) -> R<Outcome> {
319    *x.slot(file.index) = Some(f);
320    set_linage_counter(x, file, 1, pos)?;
321    set_status(x, file, status, pos)?;
322    Ok(Outcome::Done)
323}
324
325/// The page the file's LINAGE clause gives as its data items stand now.
326fn geometry<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, pos: Pos) -> R<Geometry> {
327    let Some(linage) = file.linage else { return Err(Abend::ironwork(format!("{} has no LINAGE clause", file.name), pos)) };
328    let body = x.int(linage.lines, pos)?;
329    let footing = match linage.footing {
330        Some(v) => Some(x.int(v, pos)?),
331        None => None,
332    };
333    let top = match linage.top {
334        Some(v) => x.int(v, pos)?,
335        None => 0,
336    };
337    let bottom = match linage.bottom {
338        Some(v) => x.int(v, pos)?,
339        None => 0,
340    };
341    Geometry::new(body, footing, top, bottom).map_err(|why| Abend::ironwork(format!("{}: {why} ({})", file.name, numeric::assumptions::LINAGE_VALUES), pos))
342}
343
344fn set_linage_counter<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, value: u64, pos: Pos) -> R<()> {
345    let Some(loc) = file.linage.and_then(|l| l.counter) else { return Ok(()) };
346    x.store_fixed(loc, &Fixed::new(value as i128, Places::new(19, 0)), pos)
347}
348
349/// CLOSE, and its phrases as IBM's table has them for a file on a medium without reels or units
350/// (Language Reference for Enterprise COBOL 6.4, 'Effect of CLOSE statement on file types'): REEL
351/// or UNIT leaves the file open and sets status 07, NO REWIND closes it with 07, and LOCK closes it
352/// so that OPEN refuses it with 38.
353pub fn close<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, closing: Option<Closing>, pos: Pos) -> R<Outcome> {
354    let name = file.name;
355    if closing == Some(Closing::Volume) && x.slot(file.index).is_some() {
356        set_status(x, file, FileStatus::SuccessNonReel, pos)?;
357        return Ok(Outcome::Done);
358    }
359    match x.slot(file.index).take() {
360        None => Ok(failed(x, file, FileStatus::NotOpen, format!("{name} is not open"))),
361        Some(f) => {
362            let mode = Some(f.mode);
363            match f.close() {
364                Ok(()) => {
365                    if let Some(d) = x.dd(file.assign) {
366                        x.notify(Event::Close { dd: file.assign, path: &d.path });
367                    }
368                    *x.locked(file.index) |= closing == Some(Closing::Lock);
369                    let status = if closing == Some(Closing::NoRewind) { FileStatus::SuccessNonReel } else { FileStatus::Success };
370                    set_status(x, file, status, pos)?;
371                    Ok(Outcome::Done)
372                }
373                Err(e) => Ok(Outcome::Failed(Failure { status: FileStatus::PermanentError, mode, message: format!("{name}: {e}") })),
374            }
375        }
376    }
377}
378
379/// READ of a held file by key or in sequence, else of a stream, whose phrase is AT END.
380pub fn read<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, r: Read<P>, pos: Pos) -> R<Outcome> {
381    let k = file.index;
382    if !is_held(x, k) {
383        return read_stream(x, file, r.into, pos);
384    }
385    let sequential = r.sequential;
386    let added = held_control_byte(x, file);
387    let (status, found, variable) = held(x, k, |x, mode, format, keyed| {
388        let variable = format == Format::Variable;
389        if !matches!(mode, OpenMode::Input | OpenMode::InputOutput) {
390            return Ok((FileStatus::NotOpenInput, None, variable));
391        }
392        if sequential {
393            return Ok(match keyed.read_next(r.previous) {
394                Err(status) => (status, None, variable),
395                Ok(None) => (FileStatus::AtEnd, None, variable),
396                Ok(Some(found)) if keyed.keying == Keying::Relative && !relative_fits(x, file, files::number_of(&found.key))? => (FileStatus::RelativeKeyOverflow, None, variable),
397                Ok(Some(found)) => (if found.duplicate { FileStatus::SuccessDuplicate } else { FileStatus::Success }, Some(found), variable),
398            });
399        }
400        let keying = keyed.keying.clone();
401        let (which, value) = match (&keying, r.key) {
402            (Keying::Indexed { .. }, Some(key)) => x.key_value(k, &keying, key, false, pos)?,
403            (Keying::Indexed { prime, .. }, None) => (0, prime.of(record_area(x, file.area))),
404            _ => match relative_number(x, file, pos)? {
405                Some(key) => (0, key),
406                None => {
407                    keyed.lose_position();
408                    return Ok((FileStatus::NotFound, None, variable));
409                }
410            },
411        };
412        Ok(match keyed.get(which, &value) {
413            None => {
414                keyed.lose_position();
415                (FileStatus::NotFound, None, variable)
416            }
417            Some(found) => {
418                keyed.read_at(which, &found.key);
419                (if found.duplicate { FileStatus::SuccessDuplicate } else { FileStatus::Success }, Some(found), variable)
420            }
421        })
422    })?
423    .unwrap_or((FileStatus::NotOpenInput, None, false));
424    let mut status = status;
425    if let Some(found) = found {
426        if sequential && file.organization == Organization::Relative
427            && let Some(rk) = file.relative
428        {
429            host::set_integer(x, rk, files::number_of(&found.key) as i64, pos)?;
430        }
431        let record = found.record.get(usize::from(added)..).unwrap_or_default();
432        let long = deliver(x, file, record, variable, r.into, pos)?;
433        if length_conflict(file, record.len(), variable, long) && status == FileStatus::Success {
434            status = FileStatus::SuccessWrongLength;
435        }
436    }
437    Ok(Outcome::Status { status, at_end: sequential })
438}
439
440fn read_stream<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, into: Option<P>, pos: Pos) -> R<Outcome> {
441    let k = file.index;
442    let at_end = |status| Ok(Outcome::Status { status, at_end: true });
443    let size = file.area.1;
444    let Some(mut f) = x.slot(k).take() else {
445        return at_end(FileStatus::NotOpenInput);
446    };
447    let added = adds_control_byte(file, f.format);
448    let read = f.read(size + usize::from(added));
449    let format = f.format;
450    let input = f.mode == OpenMode::Input;
451    *x.slot(k) = Some(f);
452    if !input {
453        return at_end(FileStatus::NotOpenInput);
454    }
455    let (record, wrong_length) = match read {
456        Err(e) => return Ok(failed(x, file, FileStatus::PermanentError, format!("READ {}: {e}", file.name))),
457        Ok(Record::End) => return at_end(FileStatus::AtEnd),
458        Ok(Record::Data(bytes)) => (bytes, false),
459        Ok(Record::WrongLength(bytes)) => (bytes, true),
460    };
461    let record = if added { record.get(1..).unwrap_or_default().to_vec() } else { record };
462    let record = if format == Format::Text {
463        let page = x.facts().page();
464        let unknown = page.encode_char('?').unwrap_or(0x6F);
465        String::from_utf8_lossy(&record).chars().map(|c| page.encode_char(c).unwrap_or(unknown)).collect()
466    } else {
467        record
468    };
469    let variable = format == Format::Variable;
470    let long = deliver(x, file, &record, variable, into, pos)?;
471    at_end(if wrong_length || length_conflict(file, record.len(), variable, long) { FileStatus::SuccessWrongLength } else { FileStatus::Success })
472}
473
474/// WRITE of the record at `loc`: to a LINAGE file's page, a stream, or a held file.
475pub fn write<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, advancing: Option<Advance<'_, X>>, pos: Pos) -> R<Outcome> {
476    let k = file.index;
477    let loc = match record_length(x, file, loc, pos)? {
478        Ok(loc) => loc,
479        Err(status) => return Ok(Outcome::Status { status, at_end: false }),
480    };
481    if paged(x, k) {
482        return write_page(x, file, loc, advancing, pos);
483    }
484    if !is_held(x, k) {
485        let (before, space) = match advancing {
486            Some(a) => advance(x, a, pos)?,
487            None => (false, Spacing::Lines(1)),
488        };
489        return write_stream(x, file, loc, before, space, pos);
490    }
491    let sequential = sequential(file);
492    let status = held(x, k, |x, mode, format, keyed| {
493        let allowed = match mode {
494            OpenMode::Output => true,
495            OpenMode::Extend => sequential,
496            OpenMode::InputOutput => !sequential,
497            OpenMode::Input => false,
498        };
499        if !allowed || keyed.keying == Keying::Position {
500            return Ok(FileStatus::NotOpenOutput);
501        }
502        keyed.last_read = None;
503        let bytes = record_bytes(x, file, loc, format);
504        let key = match &keyed.keying {
505            Keying::Indexed { prime, .. } => {
506                let key = prime.of(&bytes);
507                if sequential && keyed.highest_key().is_some_and(|h| key <= *h) {
508                    return Ok(FileStatus::SequenceError);
509                }
510                key
511            }
512            _ if sequential => {
513                let n = keyed.highest_key().map_or(0, |h| files::number_of(h)) + 1;
514                if n > files::MAX_RELATIVE || !relative_fits(x, file, n)? {
515                    return Ok(FileStatus::BoundaryViolation);
516                }
517                if let Some(rk) = file.relative {
518                    host::set_integer(x, rk, n as i64, pos)?;
519                }
520                files::record_number(n)
521            }
522            _ => match relative_number(x, file, pos)? {
523                Some(key) if files::number_of(&key) <= files::MAX_RELATIVE => key,
524                _ => return Ok(FileStatus::BoundaryViolation),
525            },
526        };
527        Ok(match keyed.insert(key, bytes) {
528            Err(status) => status,
529            Ok(true) => FileStatus::SuccessDuplicate,
530            Ok(false) => FileStatus::Success,
531        })
532    })?
533    .unwrap_or(FileStatus::NotOpenOutput);
534    Ok(Outcome::Status { status, at_end: false })
535}
536
537fn paged<P: Copy, X: Copy>(x: &mut impl Files<P, X>, k: usize) -> bool {
538    x.slot(k).as_ref().is_some_and(|f| f.page.is_some())
539}
540
541/// A WRITE to a LINAGE file: the page decides how far the paper moves, and once the record is
542/// written LINAGE-COUNTER changes and an END-OF-PAGE phrase runs (Language Reference
543/// SC27-8713-03, pp. 474-475; Programming Guide SC27-8714-03, p. 178).
544fn write_page<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, advancing: Option<Advance<'_, X>>, pos: Pos) -> R<Outcome> {
545    let k = file.index;
546    let (before, motion) = match advancing {
547        None => (false, Motion::Lines(1)),
548        Some(Advance::Lines { before, count }) => (before, Motion::Lines(x.int(count, pos)?.max(0) as u64)),
549        Some(Advance::Page { before }) => (before, Motion::Page),
550        Some(Advance::Mnemonic { name, .. }) => {
551            return Err(Abend::ironwork(format!("ADVANCING {name} on {}, whose FD has LINAGE, is not supported yet", file.name), pos));
552        }
553    };
554    let Some(mut page) = x.slot(k).as_ref().and_then(|f| f.page) else { return Ok(Outcome::Done) };
555    let step = page.write(before, motion, || geometry(x, file, pos))?;
556    let controls = file.carriage.map(|c| printer::moving(c.machine, step.ahead, step.behind));
557    let text = (Some(Move::Lines(step.ahead)), before.then_some(Move::Lines(step.behind)));
558    if let failure @ Outcome::Failed(_) = put_line(x, file, loc, controls, text, pos)? {
559        return Ok(failure);
560    }
561    if let Some(f) = x.slot(k).as_mut() {
562        f.page = Some(page);
563    }
564    set_linage_counter(x, file, page.counter, pos)?;
565    Ok(Outcome::Page { end_of_page: step.end_of_page })
566}
567
568/// A WRITE's ADVANCING phrase as a movement, BEFORE or AFTER the line; a count below zero moves as
569/// zero ([`numeric::assumptions::PRINT_CONTROL_RUN_TIME`]).
570fn advance<P: Copy, X: Copy>(x: &mut impl Files<P, X>, a: Advance<'_, X>, pos: Pos) -> R<(bool, Spacing)> {
571    Ok(match a {
572        Advance::Lines { before, count } => (before, Spacing::Lines(x.int(count, pos)?.max(0) as u64)),
573        Advance::Page { before } => (before, Spacing::Channel(1)),
574        Advance::Mnemonic { before, space, name, environment } => {
575            let space = space.ok_or_else(|| Abend::ironwork(format!("ADVANCING {name}: {environment} is not a printer channel"), pos))?;
576            (before, space)
577        }
578    })
579}
580
581/// A WRITE to a sequential file: a print file's records carry the control character, a text DD
582/// shows it as line and form feeds.
583pub fn write_stream<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, before: bool, space: Spacing, pos: Pos) -> R<Outcome> {
584    let controls = file.carriage.map(|c| printer::controls(c.machine, before, space));
585    put_line(x, file, loc, controls, printer::text_motion(before, space), pos)
586}
587
588/// Writes the record at `loc` to the sequential file behind `controls`, or to a text DD with the
589/// paper moved as `text` says before and after its line.
590fn put_line<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, controls: Option<Controls>, text: (Option<Move>, Option<Move>), pos: Pos) -> R<Outcome> {
591    let (k, name) = (file.index, file.name);
592    let Some(mut f) = x.slot(k).take() else {
593        return Ok(failed(x, file, FileStatus::NotOpenOutput, format!("WRITE {name}: {}", FileStatus::NotOpenOutput.meaning())));
594    };
595    if f.mode == OpenMode::Input {
596        *x.slot(k) = Some(f);
597        return Ok(failed(x, file, FileStatus::NotOpenOutput, format!("WRITE {name}: {}", FileStatus::NotOpenOutput.meaning())));
598    }
599    let reserved = usize::from(file.carriage.is_some_and(|c| c.reserved));
600    if let Some(c) = controls.filter(|_| reserved == 1 && loc.len > 0) {
601        x.mem()[loc.offset] = c.data;
602    }
603    let bytes = record_bytes(x, file, loc, f.format);
604    let written = match (f.format, controls) {
605        (Format::Text, _) => {
606            let line = x.facts().page().decode(bytes.get(reserved..).unwrap_or_default()).trim_end().to_owned();
607            f.print(text.0, &line, text.1)
608        }
609        (_, None) => f.write(&bytes),
610        (_, Some(c)) => c.records().try_for_each(|(control, line)| {
611            let mut record = Vec::with_capacity(bytes.len() + 1);
612            record.push(control);
613            if line {
614                record.extend_from_slice(&bytes[reserved.min(bytes.len())..]);
615            } else {
616                record.resize(bytes.len() + 1 - reserved.min(bytes.len()), ebcdic::SPACE);
617            }
618            f.write(&record)
619        }),
620    };
621    *x.slot(k) = Some(f);
622    match written {
623        Ok(()) => set_status(x, file, FileStatus::Success, pos).map(|()| Outcome::Done),
624        Err(e) => Ok(failed(x, file, FileStatus::PermanentError, format!("WRITE {name}: {e}"))),
625    }
626}
627
628/// REWRITE of the record at `loc`; its phrase is INVALID KEY.
629pub fn rewrite<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, loc: Loc, pos: Pos) -> R<FileStatus> {
630    let loc = match record_length(x, file, loc, pos)? {
631        Ok(loc) => loc,
632        Err(status) => return Ok(status),
633    };
634    let sequential = sequential(file);
635    let added = held_control_byte(x, file);
636    Ok(held(x, file.index, |x, mode, format, keyed| {
637        if mode != OpenMode::InputOutput {
638            return Ok(FileStatus::NotOpenInputOutput);
639        }
640        let mut bytes = record_bytes(x, file, loc, format);
641        if added {
642            let control = keyed.last_read.as_ref().and_then(|key| keyed.record(key)).and_then(|old| old.first().copied()).unwrap_or(ebcdic::SPACE);
643            bytes.insert(0, control);
644        }
645        let prior = keyed.last_read.take();
646        let key = if sequential {
647            let Some(prior) = prior else { return Ok(FileStatus::NoPriorRead) };
648            if keyed.prime_key(&bytes).is_some_and(|key| key != prior) {
649                return Ok(FileStatus::SequenceError);
650            }
651            prior
652        } else {
653            match keyed.prime_key(&bytes) {
654                Some(key) => key,
655                None => match relative_number(x, file, pos)? {
656                    Some(key) => key,
657                    None => return Ok(FileStatus::NotFound),
658                },
659            }
660        };
661        if keyed.keying == Keying::Position && keyed.record(&key).is_some_and(|old| old.len() != bytes.len()) {
662            return Ok(FileStatus::RecordLengthChanged);
663        }
664        Ok(match keyed.replace(key, bytes) {
665            Err(status) => status,
666            Ok(true) => FileStatus::SuccessDuplicate,
667            Ok(false) => FileStatus::Success,
668        })
669    })?
670    .unwrap_or(FileStatus::NotOpenInputOutput))
671}
672
673/// DELETE; its phrase is INVALID KEY.
674pub fn delete<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, pos: Pos) -> R<FileStatus> {
675    let sequential = sequential(file);
676    Ok(held(x, file.index, |x, mode, _, keyed| {
677        if mode != OpenMode::InputOutput || keyed.keying == Keying::Position {
678            return Ok(FileStatus::NotOpenInputOutput);
679        }
680        let prior = keyed.last_read.take();
681        let key = match (&keyed.keying, sequential) {
682            (_, true) => match prior {
683                Some(key) => key,
684                None => return Ok(FileStatus::NoPriorRead),
685            },
686            (Keying::Indexed { prime, .. }, false) => prime.of(record_area(x, file.area)),
687            _ => match relative_number(x, file, pos)? {
688                Some(key) => key,
689                None => return Ok(FileStatus::NotFound),
690            },
691        };
692        Ok(if keyed.remove(&key).is_some() { FileStatus::Success } else { FileStatus::NotFound })
693    })?
694    .unwrap_or(FileStatus::NotOpenInputOutput))
695}
696
697/// START; `key` is START ... KEY, and its phrase is INVALID KEY.
698pub fn start<P: Copy, X: Copy>(x: &mut impl Files<P, X>, file: &File<'_, P, X>, rel: StartRel, key: Option<P>, pos: Pos) -> R<FileStatus> {
699    let (wanted, or_equal) = match rel {
700        StartRel::Equal => (Ordering::Equal, false),
701        StartRel::Greater => (Ordering::Greater, false),
702        StartRel::NotLess => (Ordering::Greater, true),
703    };
704    let k = file.index;
705    Ok(held(x, k, |x, mode, _, keyed| {
706        if !matches!(mode, OpenMode::Input | OpenMode::InputOutput) || keyed.keying == Keying::Position {
707            return Ok(FileStatus::NotOpenInput);
708        }
709        let keying = keyed.keying.clone();
710        let (which, value) = match (&keying, key) {
711            (Keying::Indexed { .. }, Some(r)) => x.key_value(k, &keying, r, true, pos)?,
712            (Keying::Indexed { prime, .. }, None) => (0, prime.of(record_area(x, file.area))),
713            (_, Some(r)) => (0, files::record_number(x.integer(r, pos)?.max(0) as u64)),
714            (_, None) => (0, files::record_number(relative_value(x, file, pos)?.max(0) as u64)),
715        };
716        Ok(if keyed.start(which, wanted, or_equal, &value) { FileStatus::Success } else { FileStatus::NotFound })
717    })?
718    .unwrap_or(FileStatus::NotOpenInput))
719}