use super::command::{Cics, CicsCommand, Datum, Record, Resp};
use super::{Condition, Task, file_control, maps, program, services};
use crate::abend::{Abend, AbendCode, Ending};
use crate::bms::Mapset;
use crate::host::{self, Host};
use crate::lir::{ParaId, Step};
use crate::storage::{Loc, Val};
use crate::store::{self, ProgramFacts};
use crate::unit::{ADDRESS_BASE, Loader, RunUnit};
use crate::vocab::Pos;
use std::collections::HashMap;
use zarch::decimal::{self, Decimal};
use zarch::ebcdic::{self, CodePage};
pub(super) type R<T> = Result<T, Abend>;
pub const EIBTIME: usize = 0x00;
pub const EIBDATE: usize = 0x04;
pub const EIBTRNID: usize = 0x08;
pub const EIBTASKN: usize = 0x0C;
pub const EIBTRMID: usize = 0x10;
pub const EIBCPOSN: usize = 0x16;
pub const EIBCALEN: usize = 0x18;
pub const EIBAID: usize = 0x1A;
pub const EIBFN: usize = 0x1B;
pub const EIBRSRCE: usize = 0x33;
pub const EIBRESP: usize = 0x4C;
pub const EIBRESP2: usize = 0x50;
pub trait CicsHost<'w, P: Copy, O, S>: Host<P> {
type Program: Clone;
type Loader: Loader<Self::Program>;
fn unit(&mut self) -> &mut RunUnit<'w, Self::Program, Self::Loader>;
fn handlers(&mut self) -> &mut Handlers;
fn content(&mut self, operand: &O, pos: Pos) -> R<Vec<u8>>;
fn integer_of(&mut self, operand: &O, pos: Pos) -> R<i64>;
fn text(&self, text: &S) -> String;
fn main(&self) -> bool;
fn program_id(&self) -> String;
fn commarea(&self) -> Option<usize>;
fn mapset(&mut self, name: &str) -> Option<Result<Mapset, String>>;
fn item_named(&mut self, name: &str, pos: Pos) -> R<Option<Loc>>;
fn locate_named(&mut self, name: &str, pos: Pos) -> R<Loc>;
fn run_program(&mut self, program: Self::Program, index: usize, commarea: Option<usize>, xctl: bool) -> R<Ending>;
}
#[derive(Clone, Debug, Default)]
pub struct Handlers {
pub conditions: HashMap<Condition, Handler>,
pub stack: Vec<(HashMap<Condition, Handler>, Option<AbendExit>)>,
pub abend: Option<AbendExit>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AbendExit {
pub target: ExitTarget,
pub active: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExitTarget {
Label(ParaId),
Program(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Handler {
Label(ParaId),
Ignore,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Flow {
Next,
GoTo(ParaId),
End(Ending),
}
impl From<Flow> for Step {
fn from(flow: Flow) -> Self {
match flow {
Flow::Next => Step::Next,
Flow::GoTo(p) => Step::GoTo(p),
Flow::End(e) => Step::End(e),
}
}
}
pub struct At<'c, P, O, S> {
pub name: &'c str,
pub resp: &'c Resp<P, O, S>,
pub pos: Pos,
}
pub fn in_task<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>, name: &str, pos: Pos) -> R<()> {
match unit.cics {
Some(_) => Ok(()),
None => Err(Abend::ironwork(format!("EXEC CICS {name} was reached outside a CICS task: run the program with `ironwork cics`"), pos)),
}
}
pub fn begin_command<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>) {
eib_fullword(unit, EIBRESP, 0);
eib_fullword(unit, EIBRESP2, 0);
}
pub fn run<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, command: &CicsCommand<P, O, S>, pos: Pos) -> R<Flow> {
let name = x.text(&command.name);
in_task(x.unit(), &name, pos)?;
begin_command(x.unit());
let at = At { name: &name, resp: &command.resp, pos };
match &command.command {
Cics::File { verb, file, options } => file_control::run(x, &at, *verb, file.as_ref(), options),
Cics::Return { transid, commarea, length } => program::cics_return(x, &at, transid.as_ref(), commarea.as_ref(), length.as_ref()),
Cics::Link(t) => program::link(x, &at, t, false),
Cics::Xctl(t) => program::link(x, &at, t, true),
Cics::Abend { abcode, cancel } => program::abend(x, &at, abcode.as_ref(), *cancel),
Cics::HandleCondition(labels) => program::handle_condition(x, &at, labels),
Cics::IgnoreCondition(conditions) => program::ignore_condition(x, &at, conditions),
Cics::PushHandle => program::push_handle(x, &at),
Cics::PopHandle => program::pop_handle(x, &at),
Cics::HandleAbend { program, label, reset } => program::handle_abend(x, &at, program.as_ref(), *label, *reset),
Cics::HandleAid | Cics::Freemain | Cics::Enq | Cics::Deq | Cics::Delay => ok(x, &at),
Cics::SendMap { map, mapset, from, maponly, dataonly, cursor, control } => {
maps::send_map(x, &at, maps::MapNames { map: map.as_ref(), mapset: mapset.as_ref() }, from.as_ref(), (*maponly, *dataonly), cursor.as_ref(), *control)
}
Cics::ReceiveMap { map, mapset, into, set } => maps::receive_map(x, &at, maps::MapNames { map: map.as_ref(), mapset: mapset.as_ref() }, into.as_ref(), set.as_ref()),
Cics::SendControl { cursor, control } => maps::send_control(x, &at, cursor.as_ref(), *control),
Cics::Receive(record) => maps::receive_raw(x, &at, record),
Cics::Asktime { abstime } => services::asktime(x, &at, abstime.as_ref()),
Cics::Formattime { abstime, datesep, timesep, outputs } => services::formattime(x, &at, abstime.as_ref(), datesep.as_ref(), timesep.as_ref(), outputs),
Cics::Assign(assign) => services::assign(x, &at, assign),
Cics::Getmain { flength, length, initimg, set } => services::getmain(x, &at, flength.as_ref(), length.as_ref(), initimg.as_ref(), set.as_ref()),
Cics::Syncpoint { rollback } => services::syncpoint(x, &at, *rollback),
Cics::Address { eib, commarea, cwa, twa } => services::address(x, &at, eib.as_ref(), commarea.as_ref(), cwa.as_ref(), twa.as_ref()),
Cics::SendText { from, length } => services::send_text(x, &at, from.as_ref(), length.as_ref()),
Cics::WriteOperator { text, textlength } => services::write_operator(x, &at, text.as_ref(), textlength.as_ref()),
Cics::WriteqTs { queue, from, length, rewrite, item, numitems } => {
services::writeq_ts(x, &at, queue.as_ref(), (from.as_ref(), length.as_ref()), *rewrite, item.as_ref(), numitems.as_ref())
}
Cics::ReadqTs { queue, next, item, numitems, record } => services::readq_ts(x, &at, queue.as_ref(), *next, item.as_ref(), numitems.as_ref(), record),
Cics::DeleteqTs { queue } => services::deleteq_ts(x, &at, queue.as_ref()),
Cics::WriteqTd { queue, from, length } => services::writeq_td(x, &at, queue.as_ref(), from.as_ref(), length.as_ref()),
Cics::ReadqTd { queue, record } => services::readq_td(x, &at, queue.as_ref(), record),
Cics::DeleteqTd { queue } => services::deleteq_td(x, &at, queue.as_ref()),
Cics::Unsupported => Err(Abend::ironwork(unsupported(&name), pos)),
}
}
pub fn unsupported(name: &str) -> String {
format!("EXEC CICS {name} is not supported yet")
}
pub(super) fn task<'a, 'w: 'a, P: Copy + 'a, O: 'a, S: 'a>(x: &'a mut impl CicsHost<'w, P, O, S>) -> &'a mut Task {
x.unit().cics.as_mut().expect("EXEC CICS runs only in a task")
}
pub(super) fn page<'w, P: Copy, O, S>(x: &impl CicsHost<'w, P, O, S>) -> &'static CodePage {
x.facts().page()
}
pub(super) fn encoded(page: &CodePage, text: &str) -> Vec<u8> {
text.chars().map(|c| page.encode_char(c).unwrap_or(ebcdic::SPACE)).collect()
}
pub fn bytes<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<Vec<u8>>> {
Ok(match d {
Some(Datum::Place(p)) => {
let loc = x.locate(*p, false)?;
Some(store::bytes(x.mem(), loc).to_vec())
}
Some(Datum::Value(o)) => Some(x.content(o, pos)?),
_ => None,
})
}
pub(super) fn bytes_cut<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, data: Option<&Datum<P, O, S>>, length: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<Vec<u8>>> {
let Some(mut bytes) = bytes(x, data, pos)? else { return Ok(None) };
if let Some(n) = int(x, length, pos)? {
bytes.truncate(n.max(0) as usize);
}
Ok(Some(bytes))
}
pub(super) fn sent<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, data: Option<&Datum<P, O, S>>, length: Option<&Datum<P, O, S>>, from: &str) -> R<Vec<u8>> {
bytes_cut(x, data, length, at.pos)?.ok_or_else(|| Abend::ironwork(format!("EXEC CICS {} needs {from}", at.name), at.pos))
}
pub(super) fn int<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<i64>> {
match d {
Some(Datum::Place(p)) => x.integer(*p, pos).map(Some),
Some(Datum::Value(o)) => x.integer_of(o, pos).map(Some),
_ => Ok(None),
}
}
pub(super) fn text<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<String>> {
if let Some(Datum::Text(t)) = d {
return Ok(Some(x.text(t).trim().trim_matches(|c| c == '\'' || c == '"').to_owned()));
}
let page = page(x);
Ok(bytes(x, d, pos)?.map(|b| page.decode(&b).trim_end().to_owned()))
}
pub(super) fn store_bytes<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, d: Option<&Datum<P, O, S>>, name: &str, bytes: &[u8]) -> R<()> {
match d {
Some(Datum::Place(p)) => {
let loc = x.locate(*p, false)?;
x.assign(loc, Val::Bytes(bytes.to_vec()), None, at.pos)
}
Some(Datum::Value(_)) => Err(Abend::ironwork(format!("EXEC CICS {}: {name} must name a data item", at.name), at.pos)),
_ => Ok(()),
}
}
pub(super) fn store_int<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, value: i64, pos: Pos) -> R<()> {
match d {
Some(Datum::Place(p)) => host::set_integer(x, *p, value, pos),
_ => Ok(()),
}
}
pub(super) fn store_pointer<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, offset: Option<usize>, pos: Pos) -> R<()> {
if let Some(Datum::Place(p)) = d {
let loc = x.locate(*p, false)?;
let address = offset.map_or(0, |o| ADDRESS_BASE + o as u32);
x.assign(loc, Val::Address(address), None, pos)?;
}
Ok(())
}
pub(super) fn eib_bytes<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, bytes: &[u8]) {
let at = unit.eib + offset;
unit.mem[at..at + bytes.len()].copy_from_slice(bytes);
}
pub(super) fn eib_halfword<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i16) {
eib_bytes(unit, offset, &value.to_be_bytes());
}
pub(super) fn eib_fullword<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i32) {
eib_bytes(unit, offset, &value.to_be_bytes());
}
pub(super) fn eib_packed<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i64) {
let mut field = [0u8; 4];
let _ = decimal::encode(&mut field, Decimal { negative: value < 0, magnitude: value.unsigned_abs() as u128 });
eib_bytes(unit, offset, &field);
}
pub(super) fn eib_text<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, page: &CodePage, offset: usize, len: usize, text: &str) {
let mut bytes = encoded(page, text);
bytes.resize(len, ebcdic::SPACE);
eib_bytes(unit, offset, &bytes);
}
pub(super) fn eib_calen<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>) -> i16 {
let at = unit.eib + EIBCALEN;
i16::from_be_bytes([unit.mem[at], unit.mem[at + 1]])
}
pub fn begin_task<H: Clone, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, page: &CodePage, length: usize) {
let (seconds, hundredths) = unit.now();
let abstime = super::abstime(seconds, hundredths);
let (transid, termid, number) = unit.cics.as_ref().map(|t| (t.transid.clone(), t.termid.clone(), t.number)).unwrap_or_default();
eib_packed(unit, EIBTIME, super::eib_time(abstime));
eib_packed(unit, EIBDATE, super::eib_date(abstime));
eib_text(unit, page, EIBTRNID, 4, &transid);
eib_packed(unit, EIBTASKN, i64::from(number));
eib_text(unit, page, EIBTRMID, 4, &termid);
eib_halfword(unit, EIBCALEN, length as i16);
if let Some(aid) = unit.cics.as_ref().and_then(|t| t.initial_aid) {
eib_bytes(unit, EIBAID, &[aid]);
}
}
pub(super) fn deliver<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, record: &Record<P, O, S>, data: &[u8]) -> R<Flow> {
let limit = match int(x, record.length.as_ref(), at.pos)? {
Some(n) => n.max(0) as usize,
None => match &record.into {
Some(Datum::Place(p)) => x.locate(*p, false)?.len,
_ => data.len(),
},
};
if record.set.is_some() {
let area = x.unit().push_temporary(data);
store_pointer(x, record.set.as_ref(), Some(area), at.pos)?;
} else {
store_bytes(x, at, record.into.as_ref(), "INTO", &data[..data.len().min(limit)])?;
}
store_int(x, record.length.as_ref(), data.len() as i64, at.pos)?;
if data.len() > limit && record.set.is_none() {
return raise(x, at, Condition::LENGERR, 0);
}
ok(x, at)
}
pub fn ok<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>) -> R<Flow> {
store_int(x, at.resp.resp.as_ref(), 0, at.pos)?;
store_int(x, at.resp.resp2.as_ref(), 0, at.pos)?;
Ok(Flow::Next)
}
pub fn raise<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, condition: Condition, resp2: i32) -> R<Flow> {
let resp = condition.resp();
eib_fullword(x.unit(), EIBRESP, resp);
eib_fullword(x.unit(), EIBRESP2, resp2);
if at.resp.resp.is_some() {
store_int(x, at.resp.resp.as_ref(), i64::from(resp), at.pos)?;
store_int(x, at.resp.resp2.as_ref(), i64::from(resp2), at.pos)?;
return Ok(Flow::Next);
}
if at.resp.nohandle {
return Ok(Flow::Next);
}
let handlers = x.handlers();
match handlers.conditions.get(&condition).or_else(|| handlers.conditions.get(&Condition::ERROR)).copied() {
Some(Handler::Ignore) => Ok(Flow::Next),
Some(Handler::Label(p)) => Ok(Flow::GoTo(p)),
None => Err(Abend {
code: AbendCode::Cics(condition.default_abend().into()),
message: format!("EXEC CICS {}: {} was raised with no RESP, HANDLE CONDITION or IGNORE CONDITION", at.name, condition.name()),
pos: at.pos,
file: None,
}),
}
}