use super::Condition;
use super::command::{Datum, Transfer};
use super::run::{AbendExit, At, CicsHost, EIBCALEN, EIBFN, EIBRSRCE, ExitTarget, Flow, Handler, Handlers, R};
use super::run::{bytes_cut, eib_bytes, eib_calen, eib_halfword, eib_text, int, ok, page, raise, text};
use crate::abend::{Abend, AbendCode, Ending};
use crate::lir::ParaId;
use crate::unit::{LoadError, Loader, RunUnit};
use crate::vocab::Pos;
pub(super) fn cics_return<'w, P: Copy, O, S>(
x: &mut impl CicsHost<'w, P, O, S>,
at: &At<P, O, S>,
transid: Option<&Datum<P, O, S>>,
commarea: Option<&Datum<P, O, S>>,
length: Option<&Datum<P, O, S>>,
) -> R<Flow> {
eib_bytes(x.unit(), EIBFN, &[0x0E, 0x08]);
let transid = text(x, transid, at.pos)?;
let commarea = bytes_cut(x, commarea, length, at.pos)?;
if !x.main() && (transid.is_some() || commarea.is_some()) {
return raise(x, at, Condition::INVREQ, 0);
}
if let Some(task) = x.unit().cics.as_mut() {
if let Some(t) = transid {
task.next_transid = Some(t.to_ascii_uppercase());
}
if commarea.is_some() {
task.returned_commarea = commarea;
}
}
Ok(Flow::End(Ending::Goback))
}
pub(super) fn link<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, t: &Transfer<P, O, S>, xctl: bool) -> R<Flow> {
eib_bytes(x.unit(), EIBFN, if xctl { &[0x0E, 0x04] } else { &[0x0E, 0x02] });
let Some(name) = text(x, t.program.as_ref(), at.pos)?.map(|n| n.to_ascii_uppercase()) else {
return Err(Abend::ironwork(format!("EXEC CICS {} needs PROGRAM", at.name), at.pos));
};
let page = page(x);
eib_text(x.unit(), page, EIBRSRCE, 8, &name);
let index = match x.unit().load(&name) {
Ok(i) => i,
Err(LoadError::NotFound) => return raise(x, at, Condition::PGMIDERR, 0),
Err(LoadError::Compile(m)) => return Err(Abend::ironwork(format!("EXEC CICS {} PROGRAM({name}): {m}", at.name), at.pos)),
};
let Some(program) = x.unit().programs[index].compiled.clone() else {
return Err(Abend::ironwork(format!("EXEC CICS {} PROGRAM({name}): the task's first program is already running", at.name), at.pos));
};
let mark = x.unit().mem.len();
let (area, item_len) = match &t.commarea {
Some(Datum::Place(p)) if !xctl => {
let loc = x.locate(*p, false)?;
(Some(loc.offset), loc.len)
}
Some(Datum::Place(_) | Datum::Value(_)) => {
let bytes = bytes_cut(x, t.commarea.as_ref(), t.length.as_ref(), at.pos)?.unwrap_or_default();
(Some(x.unit().push_temporary(&bytes)), bytes.len())
}
_ => (None, 0),
};
let length = int(x, t.length.as_ref(), at.pos)?.map_or(item_len, |n| n.max(0) as usize);
let saved = eib_calen(x.unit());
eib_halfword(x.unit(), EIBCALEN, length as i16);
if xctl {
x.handlers().abend = None;
}
let ending = enter(x, program, index, area, xctl, at.pos);
let unit = x.unit();
unit.release_temporaries(mark);
eib_halfword(unit, EIBCALEN, saved);
match ending? {
Ending::StopRun => Ok(Flow::End(Ending::StopRun)),
_ if xctl => Ok(Flow::End(Ending::Goback)),
_ => ok(x, at),
}
}
fn enter<'w, P: Copy, O, S, X: CicsHost<'w, P, O, S>>(x: &mut X, program: X::Program, index: usize, area: Option<usize>, xctl: bool, pos: Pos) -> R<Ending> {
x.unit().programs[index].initialized = false;
x.unit().enter(pos)?;
let ending = x.run_program(program, index, area, xctl);
let unit = x.unit();
unit.depth -= 1;
unit.programs[index].active = false;
ending
}
pub(super) fn abend<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, abcode: Option<&Datum<P, O, S>>, cancel: bool) -> R<Flow> {
let code = text(x, abcode, at.pos)?.unwrap_or_else(|| "????".into());
if cancel && let Some(task) = x.unit().cics.as_mut() {
task.cancelling = true;
}
Err(Abend { message: format!("EXEC CICS ABEND ABCODE({code})"), code: AbendCode::Cics(code), pos: at.pos, file: None })
}
fn interceptable(abend: &Abend) -> Option<String> {
match &abend.code {
AbendCode::Check(_) | AbendCode::Protection => Some("ASRA".into()),
AbendCode::Cics(code) if !code.starts_with("ASP") && code != "APSJ" => Some(code.clone()),
_ => None,
}
}
pub fn abend_exit<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, handlers: &mut Handlers, abend: &Abend) -> Option<ExitTarget> {
let code = interceptable(abend)?;
let task = unit.cics.as_mut().filter(|t| !t.cancelling)?;
let exit = handlers.abend.as_mut().filter(|e| e.active)?;
exit.active = false;
task.abcode = Some(code);
Some(exit.target.clone())
}
pub fn enter_exit_program<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, name: &str, pos: Pos) -> R<Ending> {
let apct = |message: String| Abend { code: AbendCode::Cics("APCT".into()), message, pos, file: None };
let index = match x.unit().load(name) {
Ok(i) => i,
Err(LoadError::NotFound) => return Err(apct(format!("HANDLE ABEND PROGRAM({name}): no program of the name"))),
Err(LoadError::Compile(m)) => return Err(Abend::ironwork(format!("HANDLE ABEND PROGRAM({name}): {m}"), pos)),
};
let Some(program) = x.unit().programs[index].compiled.clone() else {
return Err(apct(format!("HANDLE ABEND PROGRAM({name}): the task's first program is already running")));
};
let page = page(x);
eib_text(x.unit(), page, EIBRSRCE, 8, name);
let commarea = x.commarea();
enter(x, program, index, commarea, false, pos)
}
pub(super) fn handle_condition<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, labels: &[(Condition, Option<ParaId>)]) -> R<Flow> {
let conditions = &mut x.handlers().conditions;
for &(condition, label) in labels {
match label {
Some(p) => conditions.insert(condition, Handler::Label(p)),
None => conditions.remove(&condition),
};
}
ok(x, at)
}
pub(super) fn ignore_condition<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, ignored: &[Condition]) -> R<Flow> {
let conditions = &mut x.handlers().conditions;
for &condition in ignored {
conditions.insert(condition, Handler::Ignore);
}
ok(x, at)
}
pub(super) fn push_handle<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>) -> R<Flow> {
let handlers = x.handlers();
let saved = (std::mem::take(&mut handlers.conditions), handlers.abend.take());
handlers.stack.push(saved);
ok(x, at)
}
pub(super) fn pop_handle<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>) -> R<Flow> {
let handlers = x.handlers();
match handlers.stack.pop() {
Some((conditions, abend)) => {
handlers.conditions = conditions;
handlers.abend = abend;
ok(x, at)
}
None => raise(x, at, Condition::INVREQ, 0),
}
}
pub(super) fn handle_abend<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, program: Option<&Datum<P, O, S>>, label: Option<ParaId>, reset: bool) -> R<Flow> {
let target = match (text(x, program, at.pos)?, label) {
(Some(name), _) => {
let name = name.to_ascii_uppercase();
match x.unit().load(&name) {
Ok(_) => Some(ExitTarget::Program(name)),
Err(LoadError::NotFound) => return raise(x, at, Condition::PGMIDERR, 1),
Err(LoadError::Compile(m)) => return Err(Abend::ironwork(format!("EXEC CICS HANDLE ABEND PROGRAM({name}): {m}"), at.pos)),
}
}
(None, Some(p)) => Some(ExitTarget::Label(p)),
(None, None) => None,
};
let handlers = x.handlers();
match (target, &mut handlers.abend) {
(Some(target), exit) => *exit = Some(AbendExit { target, active: true }),
(None, Some(exit)) => exit.active = reset,
(None, None) => {}
}
ok(x, at)
}