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