FlowControl.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import Recipe from "./Recipe";
  2. import Dish from "./Dish";
  3. /**
  4. * Flow Control operations.
  5. *
  6. * @author n1474335 [n1474335@gmail.com]
  7. * @copyright Crown Copyright 2016
  8. * @license Apache-2.0
  9. *
  10. * @namespace
  11. */
  12. const FlowControl = {
  13. /**
  14. * Fork operation.
  15. *
  16. * @param {Object} state - The current state of the recipe.
  17. * @param {number} state.progress - The current position in the recipe.
  18. * @param {Dish} state.dish - The Dish being operated on.
  19. * @param {Operation[]} state.opList - The list of operations in the recipe.
  20. * @returns {Object} The updated state of the recipe.
  21. */
  22. runFork: async function(state) {
  23. const opList = state.opList,
  24. inputType = opList[state.progress].inputType,
  25. outputType = opList[state.progress].outputType,
  26. input = await state.dish.get(inputType),
  27. ings = opList[state.progress].ingValues,
  28. splitDelim = ings[0],
  29. mergeDelim = ings[1],
  30. ignoreErrors = ings[2],
  31. subOpList = [];
  32. let inputs = [],
  33. i;
  34. if (input)
  35. inputs = input.split(splitDelim);
  36. // Create subOpList for each tranche to operate on
  37. // (all remaining operations unless we encounter a Merge)
  38. for (i = state.progress + 1; i < opList.length; i++) {
  39. if (opList[i].name === "Merge" && !opList[i].disabled) {
  40. break;
  41. } else {
  42. subOpList.push(opList[i]);
  43. }
  44. }
  45. const recipe = new Recipe();
  46. let output = "",
  47. progress = 0;
  48. state.forkOffset += state.progress + 1;
  49. recipe.addOperations(subOpList);
  50. // Take a deep(ish) copy of the ingredient values
  51. const ingValues = subOpList.map(op => JSON.parse(JSON.stringify(op.ingValues)));
  52. // Run recipe over each tranche
  53. for (i = 0; i < inputs.length; i++) {
  54. log.debug(`Entering tranche ${i + 1} of ${inputs.length}`);
  55. // Baseline ing values for each tranche so that registers are reset
  56. subOpList.forEach((op, i) => {
  57. op.ingValues = JSON.parse(JSON.stringify(ingValues[i]));
  58. });
  59. const dish = new Dish();
  60. dish.set(inputs[i], inputType);
  61. try {
  62. progress = await recipe.execute(dish, 0, state);
  63. } catch (err) {
  64. if (!ignoreErrors) {
  65. throw err;
  66. }
  67. progress = err.progress + 1;
  68. }
  69. output += await dish.get(outputType) + mergeDelim;
  70. }
  71. state.dish.set(output, outputType);
  72. state.progress += progress;
  73. return state;
  74. },
  75. /**
  76. * Merge operation.
  77. *
  78. * @param {Object} state - The current state of the recipe.
  79. * @param {number} state.progress - The current position in the recipe.
  80. * @param {Dish} state.dish - The Dish being operated on.
  81. * @param {Operation[]} state.opList - The list of operations in the recipe.
  82. * @returns {Object} The updated state of the recipe.
  83. */
  84. runMerge: function(state) {
  85. // No need to actually do anything here. The fork operation will
  86. // merge when it sees this operation.
  87. return state;
  88. },
  89. /**
  90. * Register operation.
  91. *
  92. * @param {Object} state - The current state of the recipe.
  93. * @param {number} state.progress - The current position in the recipe.
  94. * @param {Dish} state.dish - The Dish being operated on.
  95. * @param {Operation[]} state.opList - The list of operations in the recipe.
  96. * @returns {Object} The updated state of the recipe.
  97. */
  98. runRegister: async function(state) {
  99. const ings = state.opList[state.progress].ingValues,
  100. extractorStr = ings[0],
  101. i = ings[1],
  102. m = ings[2];
  103. let modifiers = "";
  104. if (i) modifiers += "i";
  105. if (m) modifiers += "m";
  106. const extractor = new RegExp(extractorStr, modifiers),
  107. input = await state.dish.get(Dish.STRING),
  108. registers = input.match(extractor);
  109. if (!registers) return state;
  110. if (ENVIRONMENT_IS_WORKER()) {
  111. self.setRegisters(state.forkOffset + state.progress, state.numRegisters, registers.slice(1));
  112. }
  113. /**
  114. * Replaces references to registers (e.g. $R0) with the contents of those registers.
  115. *
  116. * @param {string} str
  117. * @returns {string}
  118. */
  119. function replaceRegister(str) {
  120. // Replace references to registers ($Rn) with contents of registers
  121. return str.replace(/(\\*)\$R(\d{1,2})/g, (match, slashes, regNum) => {
  122. const index = parseInt(regNum, 10) + 1;
  123. if (index <= state.numRegisters || index >= state.numRegisters + registers.length)
  124. return match;
  125. if (slashes.length % 2 !== 0) return match.slice(1); // Remove escape
  126. return slashes + registers[index - state.numRegisters];
  127. });
  128. }
  129. // Step through all subsequent ops and replace registers in args with extracted content
  130. for (let i = state.progress + 1; i < state.opList.length; i++) {
  131. if (state.opList[i].disabled) continue;
  132. let args = state.opList[i].ingValues;
  133. args = args.map(arg => {
  134. if (typeof arg !== "string" && typeof arg !== "object") return arg;
  135. if (typeof arg === "object" && arg.hasOwnProperty("string")) {
  136. arg.string = replaceRegister(arg.string);
  137. return arg;
  138. }
  139. return replaceRegister(arg);
  140. });
  141. state.opList[i].setIngValues(args);
  142. }
  143. state.numRegisters += registers.length - 1;
  144. return state;
  145. },
  146. /**
  147. * Jump operation.
  148. *
  149. * @param {Object} state - The current state of the recipe.
  150. * @param {number} state.progress - The current position in the recipe.
  151. * @param {Dish} state.dish - The Dish being operated on.
  152. * @param {Operation[]} state.opList - The list of operations in the recipe.
  153. * @param {number} state.numJumps - The number of jumps taken so far.
  154. * @returns {Object} The updated state of the recipe.
  155. */
  156. runJump: function(state) {
  157. const ings = state.opList[state.progress].ingValues,
  158. label = ings[0],
  159. maxJumps = ings[1],
  160. jmpIndex = FlowControl._getLabelIndex(label, state);
  161. if (state.numJumps >= maxJumps || jmpIndex === -1) {
  162. log.debug("Maximum jumps reached or label cannot be found");
  163. return state;
  164. }
  165. state.progress = jmpIndex;
  166. state.numJumps++;
  167. log.debug(`Jumping to label '${label}' at position ${jmpIndex} (jumps = ${state.numJumps})`);
  168. return state;
  169. },
  170. /**
  171. * Conditional Jump operation.
  172. *
  173. * @param {Object} state - The current state of the recipe.
  174. * @param {number} state.progress - The current position in the recipe.
  175. * @param {Dish} state.dish - The Dish being operated on.
  176. * @param {Operation[]} state.opList - The list of operations in the recipe.
  177. * @param {number} state.numJumps - The number of jumps taken so far.
  178. * @returns {Object} The updated state of the recipe.
  179. */
  180. runCondJump: async function(state) {
  181. const ings = state.opList[state.progress].ingValues,
  182. dish = state.dish,
  183. regexStr = ings[0],
  184. invert = ings[1],
  185. label = ings[2],
  186. maxJumps = ings[3],
  187. jmpIndex = FlowControl._getLabelIndex(label, state);
  188. if (state.numJumps >= maxJumps || jmpIndex === -1) {
  189. log.debug("Maximum jumps reached or label cannot be found");
  190. return state;
  191. }
  192. if (regexStr !== "") {
  193. const strMatch = await dish.get(Dish.STRING).search(regexStr) > -1;
  194. if (!invert && strMatch || invert && !strMatch) {
  195. state.progress = jmpIndex;
  196. state.numJumps++;
  197. log.debug(`Jumping to label '${label}' at position ${jmpIndex} (jumps = ${state.numJumps})`);
  198. }
  199. }
  200. return state;
  201. },
  202. /**
  203. * Return operation.
  204. *
  205. * @param {Object} state - The current state of the recipe.
  206. * @param {number} state.progress - The current position in the recipe.
  207. * @param {Dish} state.dish - The Dish being operated on.
  208. * @param {Operation[]} state.opList - The list of operations in the recipe.
  209. * @returns {Object} The updated state of the recipe.
  210. */
  211. runReturn: function(state) {
  212. state.progress = state.opList.length;
  213. return state;
  214. },
  215. /**
  216. * Comment operation.
  217. *
  218. * @param {Object} state - The current state of the recipe.
  219. * @param {number} state.progress - The current position in the recipe.
  220. * @param {Dish} state.dish - The Dish being operated on.
  221. * @param {Operation[]} state.opList - The list of operations in the recipe.
  222. * @returns {Object} The updated state of the recipe.
  223. */
  224. runComment: function(state) {
  225. return state;
  226. },
  227. /**
  228. * Returns the index of a label.
  229. *
  230. * @private
  231. * @param {Object} state
  232. * @param {string} name
  233. * @returns {number}
  234. */
  235. _getLabelIndex: function(name, state) {
  236. for (let o = 0; o < state.opList.length; o++) {
  237. const operation = state.opList[o];
  238. if (operation.name === "Label"){
  239. const ings = operation.ingValues;
  240. if (name === ings[0]) {
  241. return o;
  242. }
  243. }
  244. }
  245. return -1;
  246. },
  247. };
  248. export default FlowControl;