reimplement lammps_commands_string() library function with C++ and support for heredocs

This commit is contained in:
Axel Kohlmeyer
2023-08-19 14:07:18 -04:00
parent b904534ac2
commit c1b5fe4e84

View File

@ -628,16 +628,9 @@ executing.
void lammps_commands_string(void *handle, const char *str) void lammps_commands_string(void *handle, const char *str)
{ {
auto lmp = (LAMMPS *) handle; auto lmp = (LAMMPS *) handle;
std::string cmd;
// copy str and convert from CR-LF (DOS-style) to LF (Unix style) line bool append = false;
int n = strlen(str); bool triple = false;
char *ptr, *copy = new char[n+1];
for (ptr = copy; *str != '\0'; ++str) {
if ((str[0] == '\r') && (str[1] == '\n')) continue;
*ptr++ = *str;
}
*ptr = '\0';
BEGIN_CAPTURE BEGIN_CAPTURE
{ {
@ -645,27 +638,30 @@ void lammps_commands_string(void *handle, const char *str)
lmp->error->all(FLERR,"Library error: issuing LAMMPS command during run"); lmp->error->all(FLERR,"Library error: issuing LAMMPS command during run");
} }
n = strlen(copy); // process continuation characters and here docs
ptr = copy; for (const auto &line : utils::split_lines(str)) {
for (int i=0; i < n; ++i) { if (append || triple)
cmd += line;
else
cmd = line;
// handle continuation character as last character in line or string if (utils::strmatch(line, "\"\"\".*\"\"\"")) {
if ((copy[i] == '&') && (copy[i+1] == '\n')) triple = false;
copy[i+1] = copy[i] = ' '; } else if (utils::strmatch(line, "\"\"\"")) {
else if ((copy[i] == '&') && (copy[i+1] == '\0')) triple = !triple;
copy[i] = ' '; }
if (triple) cmd += '\n';
if (copy[i] == '\n') { if (!triple && utils::strmatch(cmd, "&$")) {
copy[i] = '\0'; append = true;
lmp->input->one(ptr); cmd.back() = ' ';
ptr = copy + i+1; } else append = false;
} else if (copy[i+1] == '\0')
lmp->input->one(ptr); if (!append && !triple)
lmp->input->one(cmd.c_str());
} }
} }
END_CAPTURE END_CAPTURE
delete[] copy;
} }
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------