function.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PostScriptEvaluator = exports.PostScriptCompiler = exports.PDFFunctionFactory = void 0;
  27. exports.isPDFFunction = isPDFFunction;
  28. var _primitives = require("./primitives.js");
  29. var _util = require("../shared/util.js");
  30. var _ps_parser = require("./ps_parser.js");
  31. var _base_stream = require("./base_stream.js");
  32. var _image_utils = require("./image_utils.js");
  33. class PDFFunctionFactory {
  34. constructor({
  35. xref,
  36. isEvalSupported = true
  37. }) {
  38. this.xref = xref;
  39. this.isEvalSupported = isEvalSupported !== false;
  40. }
  41. create(fn) {
  42. const cachedFunction = this.getCached(fn);
  43. if (cachedFunction) {
  44. return cachedFunction;
  45. }
  46. const parsedFunction = PDFFunction.parse({
  47. xref: this.xref,
  48. isEvalSupported: this.isEvalSupported,
  49. fn: fn instanceof _primitives.Ref ? this.xref.fetch(fn) : fn
  50. });
  51. this._cache(fn, parsedFunction);
  52. return parsedFunction;
  53. }
  54. createFromArray(fnObj) {
  55. const cachedFunction = this.getCached(fnObj);
  56. if (cachedFunction) {
  57. return cachedFunction;
  58. }
  59. const parsedFunction = PDFFunction.parseArray({
  60. xref: this.xref,
  61. isEvalSupported: this.isEvalSupported,
  62. fnObj: fnObj instanceof _primitives.Ref ? this.xref.fetch(fnObj) : fnObj
  63. });
  64. this._cache(fnObj, parsedFunction);
  65. return parsedFunction;
  66. }
  67. getCached(cacheKey) {
  68. let fnRef;
  69. if (cacheKey instanceof _primitives.Ref) {
  70. fnRef = cacheKey;
  71. } else if (cacheKey instanceof _primitives.Dict) {
  72. fnRef = cacheKey.objId;
  73. } else if (cacheKey instanceof _base_stream.BaseStream) {
  74. fnRef = cacheKey.dict && cacheKey.dict.objId;
  75. }
  76. if (fnRef) {
  77. const localFunction = this._localFunctionCache.getByRef(fnRef);
  78. if (localFunction) {
  79. return localFunction;
  80. }
  81. }
  82. return null;
  83. }
  84. _cache(cacheKey, parsedFunction) {
  85. if (!parsedFunction) {
  86. throw new Error('PDFFunctionFactory._cache - expected "parsedFunction" argument.');
  87. }
  88. let fnRef;
  89. if (cacheKey instanceof _primitives.Ref) {
  90. fnRef = cacheKey;
  91. } else if (cacheKey instanceof _primitives.Dict) {
  92. fnRef = cacheKey.objId;
  93. } else if (cacheKey instanceof _base_stream.BaseStream) {
  94. fnRef = cacheKey.dict && cacheKey.dict.objId;
  95. }
  96. if (fnRef) {
  97. this._localFunctionCache.set(null, fnRef, parsedFunction);
  98. }
  99. }
  100. get _localFunctionCache() {
  101. return (0, _util.shadow)(this, "_localFunctionCache", new _image_utils.LocalFunctionCache());
  102. }
  103. }
  104. exports.PDFFunctionFactory = PDFFunctionFactory;
  105. function toNumberArray(arr) {
  106. if (!Array.isArray(arr)) {
  107. return null;
  108. }
  109. const length = arr.length;
  110. for (let i = 0; i < length; i++) {
  111. if (typeof arr[i] !== "number") {
  112. const result = new Array(length);
  113. for (let j = 0; j < length; j++) {
  114. result[j] = +arr[j];
  115. }
  116. return result;
  117. }
  118. }
  119. return arr;
  120. }
  121. class PDFFunction {
  122. static getSampleArray(size, outputSize, bps, stream) {
  123. let i, ii;
  124. let length = 1;
  125. for (i = 0, ii = size.length; i < ii; i++) {
  126. length *= size[i];
  127. }
  128. length *= outputSize;
  129. const array = new Array(length);
  130. let codeSize = 0;
  131. let codeBuf = 0;
  132. const sampleMul = 1.0 / (2.0 ** bps - 1);
  133. const strBytes = stream.getBytes((length * bps + 7) / 8);
  134. let strIdx = 0;
  135. for (i = 0; i < length; i++) {
  136. while (codeSize < bps) {
  137. codeBuf <<= 8;
  138. codeBuf |= strBytes[strIdx++];
  139. codeSize += 8;
  140. }
  141. codeSize -= bps;
  142. array[i] = (codeBuf >> codeSize) * sampleMul;
  143. codeBuf &= (1 << codeSize) - 1;
  144. }
  145. return array;
  146. }
  147. static parse({
  148. xref,
  149. isEvalSupported,
  150. fn
  151. }) {
  152. const dict = fn.dict || fn;
  153. const typeNum = dict.get("FunctionType");
  154. switch (typeNum) {
  155. case 0:
  156. return this.constructSampled({
  157. xref,
  158. isEvalSupported,
  159. fn,
  160. dict
  161. });
  162. case 1:
  163. break;
  164. case 2:
  165. return this.constructInterpolated({
  166. xref,
  167. isEvalSupported,
  168. dict
  169. });
  170. case 3:
  171. return this.constructStiched({
  172. xref,
  173. isEvalSupported,
  174. dict
  175. });
  176. case 4:
  177. return this.constructPostScript({
  178. xref,
  179. isEvalSupported,
  180. fn,
  181. dict
  182. });
  183. }
  184. throw new _util.FormatError("Unknown type of function");
  185. }
  186. static parseArray({
  187. xref,
  188. isEvalSupported,
  189. fnObj
  190. }) {
  191. if (!Array.isArray(fnObj)) {
  192. return this.parse({
  193. xref,
  194. isEvalSupported,
  195. fn: fnObj
  196. });
  197. }
  198. const fnArray = [];
  199. for (const fn of fnObj) {
  200. fnArray.push(this.parse({
  201. xref,
  202. isEvalSupported,
  203. fn: xref.fetchIfRef(fn)
  204. }));
  205. }
  206. return function (src, srcOffset, dest, destOffset) {
  207. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  208. fnArray[i](src, srcOffset, dest, destOffset + i);
  209. }
  210. };
  211. }
  212. static constructSampled({
  213. xref,
  214. isEvalSupported,
  215. fn,
  216. dict
  217. }) {
  218. function toMultiArray(arr) {
  219. const inputLength = arr.length;
  220. const out = [];
  221. let index = 0;
  222. for (let i = 0; i < inputLength; i += 2) {
  223. out[index++] = [arr[i], arr[i + 1]];
  224. }
  225. return out;
  226. }
  227. function interpolate(x, xmin, xmax, ymin, ymax) {
  228. return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
  229. }
  230. let domain = toNumberArray(dict.getArray("Domain"));
  231. let range = toNumberArray(dict.getArray("Range"));
  232. if (!domain || !range) {
  233. throw new _util.FormatError("No domain or range");
  234. }
  235. const inputSize = domain.length / 2;
  236. const outputSize = range.length / 2;
  237. domain = toMultiArray(domain);
  238. range = toMultiArray(range);
  239. const size = toNumberArray(dict.getArray("Size"));
  240. const bps = dict.get("BitsPerSample");
  241. const order = dict.get("Order") || 1;
  242. if (order !== 1) {
  243. (0, _util.info)("No support for cubic spline interpolation: " + order);
  244. }
  245. let encode = toNumberArray(dict.getArray("Encode"));
  246. if (!encode) {
  247. encode = [];
  248. for (let i = 0; i < inputSize; ++i) {
  249. encode.push([0, size[i] - 1]);
  250. }
  251. } else {
  252. encode = toMultiArray(encode);
  253. }
  254. let decode = toNumberArray(dict.getArray("Decode"));
  255. if (!decode) {
  256. decode = range;
  257. } else {
  258. decode = toMultiArray(decode);
  259. }
  260. const samples = this.getSampleArray(size, outputSize, bps, fn);
  261. return function constructSampledFn(src, srcOffset, dest, destOffset) {
  262. const cubeVertices = 1 << inputSize;
  263. const cubeN = new Float64Array(cubeVertices);
  264. const cubeVertex = new Uint32Array(cubeVertices);
  265. let i, j;
  266. for (j = 0; j < cubeVertices; j++) {
  267. cubeN[j] = 1;
  268. }
  269. let k = outputSize,
  270. pos = 1;
  271. for (i = 0; i < inputSize; ++i) {
  272. const domain_2i = domain[i][0];
  273. const domain_2i_1 = domain[i][1];
  274. const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
  275. let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
  276. const size_i = size[i];
  277. e = Math.min(Math.max(e, 0), size_i - 1);
  278. const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
  279. const n0 = e0 + 1 - e;
  280. const n1 = e - e0;
  281. const offset0 = e0 * k;
  282. const offset1 = offset0 + k;
  283. for (j = 0; j < cubeVertices; j++) {
  284. if (j & pos) {
  285. cubeN[j] *= n1;
  286. cubeVertex[j] += offset1;
  287. } else {
  288. cubeN[j] *= n0;
  289. cubeVertex[j] += offset0;
  290. }
  291. }
  292. k *= size_i;
  293. pos <<= 1;
  294. }
  295. for (j = 0; j < outputSize; ++j) {
  296. let rj = 0;
  297. for (i = 0; i < cubeVertices; i++) {
  298. rj += samples[cubeVertex[i] + j] * cubeN[i];
  299. }
  300. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  301. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  302. }
  303. };
  304. }
  305. static constructInterpolated({
  306. xref,
  307. isEvalSupported,
  308. dict
  309. }) {
  310. const c0 = toNumberArray(dict.getArray("C0")) || [0];
  311. const c1 = toNumberArray(dict.getArray("C1")) || [1];
  312. const n = dict.get("N");
  313. const diff = [];
  314. for (let i = 0, ii = c0.length; i < ii; ++i) {
  315. diff.push(c1[i] - c0[i]);
  316. }
  317. const length = diff.length;
  318. return function constructInterpolatedFn(src, srcOffset, dest, destOffset) {
  319. const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
  320. for (let j = 0; j < length; ++j) {
  321. dest[destOffset + j] = c0[j] + x * diff[j];
  322. }
  323. };
  324. }
  325. static constructStiched({
  326. xref,
  327. isEvalSupported,
  328. dict
  329. }) {
  330. const domain = toNumberArray(dict.getArray("Domain"));
  331. if (!domain) {
  332. throw new _util.FormatError("No domain");
  333. }
  334. const inputSize = domain.length / 2;
  335. if (inputSize !== 1) {
  336. throw new _util.FormatError("Bad domain for stiched function");
  337. }
  338. const fns = [];
  339. for (const fn of dict.get("Functions")) {
  340. fns.push(this.parse({
  341. xref,
  342. isEvalSupported,
  343. fn: xref.fetchIfRef(fn)
  344. }));
  345. }
  346. const bounds = toNumberArray(dict.getArray("Bounds"));
  347. const encode = toNumberArray(dict.getArray("Encode"));
  348. const tmpBuf = new Float32Array(1);
  349. return function constructStichedFn(src, srcOffset, dest, destOffset) {
  350. const clip = function constructStichedFromIRClip(v, min, max) {
  351. if (v > max) {
  352. v = max;
  353. } else if (v < min) {
  354. v = min;
  355. }
  356. return v;
  357. };
  358. const v = clip(src[srcOffset], domain[0], domain[1]);
  359. const length = bounds.length;
  360. let i;
  361. for (i = 0; i < length; ++i) {
  362. if (v < bounds[i]) {
  363. break;
  364. }
  365. }
  366. let dmin = domain[0];
  367. if (i > 0) {
  368. dmin = bounds[i - 1];
  369. }
  370. let dmax = domain[1];
  371. if (i < bounds.length) {
  372. dmax = bounds[i];
  373. }
  374. const rmin = encode[2 * i];
  375. const rmax = encode[2 * i + 1];
  376. tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  377. fns[i](tmpBuf, 0, dest, destOffset);
  378. };
  379. }
  380. static constructPostScript({
  381. xref,
  382. isEvalSupported,
  383. fn,
  384. dict
  385. }) {
  386. const domain = toNumberArray(dict.getArray("Domain"));
  387. const range = toNumberArray(dict.getArray("Range"));
  388. if (!domain) {
  389. throw new _util.FormatError("No domain.");
  390. }
  391. if (!range) {
  392. throw new _util.FormatError("No range.");
  393. }
  394. const lexer = new _ps_parser.PostScriptLexer(fn);
  395. const parser = new _ps_parser.PostScriptParser(lexer);
  396. const code = parser.parse();
  397. if (isEvalSupported && _util.FeatureTest.isEvalSupported) {
  398. const compiled = new PostScriptCompiler().compile(code, domain, range);
  399. if (compiled) {
  400. return new Function("src", "srcOffset", "dest", "destOffset", compiled);
  401. }
  402. }
  403. (0, _util.info)("Unable to compile PS function");
  404. const numOutputs = range.length >> 1;
  405. const numInputs = domain.length >> 1;
  406. const evaluator = new PostScriptEvaluator(code);
  407. const cache = Object.create(null);
  408. const MAX_CACHE_SIZE = 2048 * 4;
  409. let cache_available = MAX_CACHE_SIZE;
  410. const tmpBuf = new Float32Array(numInputs);
  411. return function constructPostScriptFn(src, srcOffset, dest, destOffset) {
  412. let i, value;
  413. let key = "";
  414. const input = tmpBuf;
  415. for (i = 0; i < numInputs; i++) {
  416. value = src[srcOffset + i];
  417. input[i] = value;
  418. key += value + "_";
  419. }
  420. const cachedValue = cache[key];
  421. if (cachedValue !== undefined) {
  422. dest.set(cachedValue, destOffset);
  423. return;
  424. }
  425. const output = new Float32Array(numOutputs);
  426. const stack = evaluator.execute(input);
  427. const stackIndex = stack.length - numOutputs;
  428. for (i = 0; i < numOutputs; i++) {
  429. value = stack[stackIndex + i];
  430. let bound = range[i * 2];
  431. if (value < bound) {
  432. value = bound;
  433. } else {
  434. bound = range[i * 2 + 1];
  435. if (value > bound) {
  436. value = bound;
  437. }
  438. }
  439. output[i] = value;
  440. }
  441. if (cache_available > 0) {
  442. cache_available--;
  443. cache[key] = output;
  444. }
  445. dest.set(output, destOffset);
  446. };
  447. }
  448. }
  449. function isPDFFunction(v) {
  450. let fnDict;
  451. if (typeof v !== "object") {
  452. return false;
  453. } else if (v instanceof _primitives.Dict) {
  454. fnDict = v;
  455. } else if (v instanceof _base_stream.BaseStream) {
  456. fnDict = v.dict;
  457. } else {
  458. return false;
  459. }
  460. return fnDict.has("FunctionType");
  461. }
  462. class PostScriptStack {
  463. static get MAX_STACK_SIZE() {
  464. return (0, _util.shadow)(this, "MAX_STACK_SIZE", 100);
  465. }
  466. constructor(initialStack) {
  467. this.stack = initialStack ? Array.from(initialStack) : [];
  468. }
  469. push(value) {
  470. if (this.stack.length >= PostScriptStack.MAX_STACK_SIZE) {
  471. throw new Error("PostScript function stack overflow.");
  472. }
  473. this.stack.push(value);
  474. }
  475. pop() {
  476. if (this.stack.length <= 0) {
  477. throw new Error("PostScript function stack underflow.");
  478. }
  479. return this.stack.pop();
  480. }
  481. copy(n) {
  482. if (this.stack.length + n >= PostScriptStack.MAX_STACK_SIZE) {
  483. throw new Error("PostScript function stack overflow.");
  484. }
  485. const stack = this.stack;
  486. for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  487. stack.push(stack[i]);
  488. }
  489. }
  490. index(n) {
  491. this.push(this.stack[this.stack.length - n - 1]);
  492. }
  493. roll(n, p) {
  494. const stack = this.stack;
  495. const l = stack.length - n;
  496. const r = stack.length - 1;
  497. const c = l + (p - Math.floor(p / n) * n);
  498. for (let i = l, j = r; i < j; i++, j--) {
  499. const t = stack[i];
  500. stack[i] = stack[j];
  501. stack[j] = t;
  502. }
  503. for (let i = l, j = c - 1; i < j; i++, j--) {
  504. const t = stack[i];
  505. stack[i] = stack[j];
  506. stack[j] = t;
  507. }
  508. for (let i = c, j = r; i < j; i++, j--) {
  509. const t = stack[i];
  510. stack[i] = stack[j];
  511. stack[j] = t;
  512. }
  513. }
  514. }
  515. class PostScriptEvaluator {
  516. constructor(operators) {
  517. this.operators = operators;
  518. }
  519. execute(initialStack) {
  520. const stack = new PostScriptStack(initialStack);
  521. let counter = 0;
  522. const operators = this.operators;
  523. const length = operators.length;
  524. let operator, a, b;
  525. while (counter < length) {
  526. operator = operators[counter++];
  527. if (typeof operator === "number") {
  528. stack.push(operator);
  529. continue;
  530. }
  531. switch (operator) {
  532. case "jz":
  533. b = stack.pop();
  534. a = stack.pop();
  535. if (!a) {
  536. counter = b;
  537. }
  538. break;
  539. case "j":
  540. a = stack.pop();
  541. counter = a;
  542. break;
  543. case "abs":
  544. a = stack.pop();
  545. stack.push(Math.abs(a));
  546. break;
  547. case "add":
  548. b = stack.pop();
  549. a = stack.pop();
  550. stack.push(a + b);
  551. break;
  552. case "and":
  553. b = stack.pop();
  554. a = stack.pop();
  555. if (typeof a === "boolean" && typeof b === "boolean") {
  556. stack.push(a && b);
  557. } else {
  558. stack.push(a & b);
  559. }
  560. break;
  561. case "atan":
  562. a = stack.pop();
  563. stack.push(Math.atan(a));
  564. break;
  565. case "bitshift":
  566. b = stack.pop();
  567. a = stack.pop();
  568. if (a > 0) {
  569. stack.push(a << b);
  570. } else {
  571. stack.push(a >> b);
  572. }
  573. break;
  574. case "ceiling":
  575. a = stack.pop();
  576. stack.push(Math.ceil(a));
  577. break;
  578. case "copy":
  579. a = stack.pop();
  580. stack.copy(a);
  581. break;
  582. case "cos":
  583. a = stack.pop();
  584. stack.push(Math.cos(a));
  585. break;
  586. case "cvi":
  587. a = stack.pop() | 0;
  588. stack.push(a);
  589. break;
  590. case "cvr":
  591. break;
  592. case "div":
  593. b = stack.pop();
  594. a = stack.pop();
  595. stack.push(a / b);
  596. break;
  597. case "dup":
  598. stack.copy(1);
  599. break;
  600. case "eq":
  601. b = stack.pop();
  602. a = stack.pop();
  603. stack.push(a === b);
  604. break;
  605. case "exch":
  606. stack.roll(2, 1);
  607. break;
  608. case "exp":
  609. b = stack.pop();
  610. a = stack.pop();
  611. stack.push(a ** b);
  612. break;
  613. case "false":
  614. stack.push(false);
  615. break;
  616. case "floor":
  617. a = stack.pop();
  618. stack.push(Math.floor(a));
  619. break;
  620. case "ge":
  621. b = stack.pop();
  622. a = stack.pop();
  623. stack.push(a >= b);
  624. break;
  625. case "gt":
  626. b = stack.pop();
  627. a = stack.pop();
  628. stack.push(a > b);
  629. break;
  630. case "idiv":
  631. b = stack.pop();
  632. a = stack.pop();
  633. stack.push(a / b | 0);
  634. break;
  635. case "index":
  636. a = stack.pop();
  637. stack.index(a);
  638. break;
  639. case "le":
  640. b = stack.pop();
  641. a = stack.pop();
  642. stack.push(a <= b);
  643. break;
  644. case "ln":
  645. a = stack.pop();
  646. stack.push(Math.log(a));
  647. break;
  648. case "log":
  649. a = stack.pop();
  650. stack.push(Math.log(a) / Math.LN10);
  651. break;
  652. case "lt":
  653. b = stack.pop();
  654. a = stack.pop();
  655. stack.push(a < b);
  656. break;
  657. case "mod":
  658. b = stack.pop();
  659. a = stack.pop();
  660. stack.push(a % b);
  661. break;
  662. case "mul":
  663. b = stack.pop();
  664. a = stack.pop();
  665. stack.push(a * b);
  666. break;
  667. case "ne":
  668. b = stack.pop();
  669. a = stack.pop();
  670. stack.push(a !== b);
  671. break;
  672. case "neg":
  673. a = stack.pop();
  674. stack.push(-a);
  675. break;
  676. case "not":
  677. a = stack.pop();
  678. if (typeof a === "boolean") {
  679. stack.push(!a);
  680. } else {
  681. stack.push(~a);
  682. }
  683. break;
  684. case "or":
  685. b = stack.pop();
  686. a = stack.pop();
  687. if (typeof a === "boolean" && typeof b === "boolean") {
  688. stack.push(a || b);
  689. } else {
  690. stack.push(a | b);
  691. }
  692. break;
  693. case "pop":
  694. stack.pop();
  695. break;
  696. case "roll":
  697. b = stack.pop();
  698. a = stack.pop();
  699. stack.roll(a, b);
  700. break;
  701. case "round":
  702. a = stack.pop();
  703. stack.push(Math.round(a));
  704. break;
  705. case "sin":
  706. a = stack.pop();
  707. stack.push(Math.sin(a));
  708. break;
  709. case "sqrt":
  710. a = stack.pop();
  711. stack.push(Math.sqrt(a));
  712. break;
  713. case "sub":
  714. b = stack.pop();
  715. a = stack.pop();
  716. stack.push(a - b);
  717. break;
  718. case "true":
  719. stack.push(true);
  720. break;
  721. case "truncate":
  722. a = stack.pop();
  723. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  724. stack.push(a);
  725. break;
  726. case "xor":
  727. b = stack.pop();
  728. a = stack.pop();
  729. if (typeof a === "boolean" && typeof b === "boolean") {
  730. stack.push(a !== b);
  731. } else {
  732. stack.push(a ^ b);
  733. }
  734. break;
  735. default:
  736. throw new _util.FormatError(`Unknown operator ${operator}`);
  737. }
  738. }
  739. return stack.stack;
  740. }
  741. }
  742. exports.PostScriptEvaluator = PostScriptEvaluator;
  743. class AstNode {
  744. constructor(type) {
  745. this.type = type;
  746. }
  747. visit(visitor) {
  748. (0, _util.unreachable)("abstract method");
  749. }
  750. }
  751. class AstArgument extends AstNode {
  752. constructor(index, min, max) {
  753. super("args");
  754. this.index = index;
  755. this.min = min;
  756. this.max = max;
  757. }
  758. visit(visitor) {
  759. visitor.visitArgument(this);
  760. }
  761. }
  762. class AstLiteral extends AstNode {
  763. constructor(number) {
  764. super("literal");
  765. this.number = number;
  766. this.min = number;
  767. this.max = number;
  768. }
  769. visit(visitor) {
  770. visitor.visitLiteral(this);
  771. }
  772. }
  773. class AstBinaryOperation extends AstNode {
  774. constructor(op, arg1, arg2, min, max) {
  775. super("binary");
  776. this.op = op;
  777. this.arg1 = arg1;
  778. this.arg2 = arg2;
  779. this.min = min;
  780. this.max = max;
  781. }
  782. visit(visitor) {
  783. visitor.visitBinaryOperation(this);
  784. }
  785. }
  786. class AstMin extends AstNode {
  787. constructor(arg, max) {
  788. super("max");
  789. this.arg = arg;
  790. this.min = arg.min;
  791. this.max = max;
  792. }
  793. visit(visitor) {
  794. visitor.visitMin(this);
  795. }
  796. }
  797. class AstVariable extends AstNode {
  798. constructor(index, min, max) {
  799. super("var");
  800. this.index = index;
  801. this.min = min;
  802. this.max = max;
  803. }
  804. visit(visitor) {
  805. visitor.visitVariable(this);
  806. }
  807. }
  808. class AstVariableDefinition extends AstNode {
  809. constructor(variable, arg) {
  810. super("definition");
  811. this.variable = variable;
  812. this.arg = arg;
  813. }
  814. visit(visitor) {
  815. visitor.visitVariableDefinition(this);
  816. }
  817. }
  818. class ExpressionBuilderVisitor {
  819. constructor() {
  820. this.parts = [];
  821. }
  822. visitArgument(arg) {
  823. this.parts.push("Math.max(", arg.min, ", Math.min(", arg.max, ", src[srcOffset + ", arg.index, "]))");
  824. }
  825. visitVariable(variable) {
  826. this.parts.push("v", variable.index);
  827. }
  828. visitLiteral(literal) {
  829. this.parts.push(literal.number);
  830. }
  831. visitBinaryOperation(operation) {
  832. this.parts.push("(");
  833. operation.arg1.visit(this);
  834. this.parts.push(" ", operation.op, " ");
  835. operation.arg2.visit(this);
  836. this.parts.push(")");
  837. }
  838. visitVariableDefinition(definition) {
  839. this.parts.push("var ");
  840. definition.variable.visit(this);
  841. this.parts.push(" = ");
  842. definition.arg.visit(this);
  843. this.parts.push(";");
  844. }
  845. visitMin(max) {
  846. this.parts.push("Math.min(");
  847. max.arg.visit(this);
  848. this.parts.push(", ", max.max, ")");
  849. }
  850. toString() {
  851. return this.parts.join("");
  852. }
  853. }
  854. function buildAddOperation(num1, num2) {
  855. if (num2.type === "literal" && num2.number === 0) {
  856. return num1;
  857. }
  858. if (num1.type === "literal" && num1.number === 0) {
  859. return num2;
  860. }
  861. if (num2.type === "literal" && num1.type === "literal") {
  862. return new AstLiteral(num1.number + num2.number);
  863. }
  864. return new AstBinaryOperation("+", num1, num2, num1.min + num2.min, num1.max + num2.max);
  865. }
  866. function buildMulOperation(num1, num2) {
  867. if (num2.type === "literal") {
  868. if (num2.number === 0) {
  869. return new AstLiteral(0);
  870. } else if (num2.number === 1) {
  871. return num1;
  872. } else if (num1.type === "literal") {
  873. return new AstLiteral(num1.number * num2.number);
  874. }
  875. }
  876. if (num1.type === "literal") {
  877. if (num1.number === 0) {
  878. return new AstLiteral(0);
  879. } else if (num1.number === 1) {
  880. return num2;
  881. }
  882. }
  883. const min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  884. const max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  885. return new AstBinaryOperation("*", num1, num2, min, max);
  886. }
  887. function buildSubOperation(num1, num2) {
  888. if (num2.type === "literal") {
  889. if (num2.number === 0) {
  890. return num1;
  891. } else if (num1.type === "literal") {
  892. return new AstLiteral(num1.number - num2.number);
  893. }
  894. }
  895. if (num2.type === "binary" && num2.op === "-" && num1.type === "literal" && num1.number === 1 && num2.arg1.type === "literal" && num2.arg1.number === 1) {
  896. return num2.arg2;
  897. }
  898. return new AstBinaryOperation("-", num1, num2, num1.min - num2.max, num1.max - num2.min);
  899. }
  900. function buildMinOperation(num1, max) {
  901. if (num1.min >= max) {
  902. return new AstLiteral(max);
  903. } else if (num1.max <= max) {
  904. return num1;
  905. }
  906. return new AstMin(num1, max);
  907. }
  908. class PostScriptCompiler {
  909. compile(code, domain, range) {
  910. const stack = [];
  911. const instructions = [];
  912. const inputSize = domain.length >> 1,
  913. outputSize = range.length >> 1;
  914. let lastRegister = 0;
  915. let n, j;
  916. let num1, num2, ast1, ast2, tmpVar, item;
  917. for (let i = 0; i < inputSize; i++) {
  918. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  919. }
  920. for (let i = 0, ii = code.length; i < ii; i++) {
  921. item = code[i];
  922. if (typeof item === "number") {
  923. stack.push(new AstLiteral(item));
  924. continue;
  925. }
  926. switch (item) {
  927. case "add":
  928. if (stack.length < 2) {
  929. return null;
  930. }
  931. num2 = stack.pop();
  932. num1 = stack.pop();
  933. stack.push(buildAddOperation(num1, num2));
  934. break;
  935. case "cvr":
  936. if (stack.length < 1) {
  937. return null;
  938. }
  939. break;
  940. case "mul":
  941. if (stack.length < 2) {
  942. return null;
  943. }
  944. num2 = stack.pop();
  945. num1 = stack.pop();
  946. stack.push(buildMulOperation(num1, num2));
  947. break;
  948. case "sub":
  949. if (stack.length < 2) {
  950. return null;
  951. }
  952. num2 = stack.pop();
  953. num1 = stack.pop();
  954. stack.push(buildSubOperation(num1, num2));
  955. break;
  956. case "exch":
  957. if (stack.length < 2) {
  958. return null;
  959. }
  960. ast1 = stack.pop();
  961. ast2 = stack.pop();
  962. stack.push(ast1, ast2);
  963. break;
  964. case "pop":
  965. if (stack.length < 1) {
  966. return null;
  967. }
  968. stack.pop();
  969. break;
  970. case "index":
  971. if (stack.length < 1) {
  972. return null;
  973. }
  974. num1 = stack.pop();
  975. if (num1.type !== "literal") {
  976. return null;
  977. }
  978. n = num1.number;
  979. if (n < 0 || !Number.isInteger(n) || stack.length < n) {
  980. return null;
  981. }
  982. ast1 = stack[stack.length - n - 1];
  983. if (ast1.type === "literal" || ast1.type === "var") {
  984. stack.push(ast1);
  985. break;
  986. }
  987. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  988. stack[stack.length - n - 1] = tmpVar;
  989. stack.push(tmpVar);
  990. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  991. break;
  992. case "dup":
  993. if (stack.length < 1) {
  994. return null;
  995. }
  996. if (typeof code[i + 1] === "number" && code[i + 2] === "gt" && code[i + 3] === i + 7 && code[i + 4] === "jz" && code[i + 5] === "pop" && code[i + 6] === code[i + 1]) {
  997. num1 = stack.pop();
  998. stack.push(buildMinOperation(num1, code[i + 1]));
  999. i += 6;
  1000. break;
  1001. }
  1002. ast1 = stack.at(-1);
  1003. if (ast1.type === "literal" || ast1.type === "var") {
  1004. stack.push(ast1);
  1005. break;
  1006. }
  1007. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  1008. stack[stack.length - 1] = tmpVar;
  1009. stack.push(tmpVar);
  1010. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  1011. break;
  1012. case "roll":
  1013. if (stack.length < 2) {
  1014. return null;
  1015. }
  1016. num2 = stack.pop();
  1017. num1 = stack.pop();
  1018. if (num2.type !== "literal" || num1.type !== "literal") {
  1019. return null;
  1020. }
  1021. j = num2.number;
  1022. n = num1.number;
  1023. if (n <= 0 || !Number.isInteger(n) || !Number.isInteger(j) || stack.length < n) {
  1024. return null;
  1025. }
  1026. j = (j % n + n) % n;
  1027. if (j === 0) {
  1028. break;
  1029. }
  1030. stack.push(...stack.splice(stack.length - n, n - j));
  1031. break;
  1032. default:
  1033. return null;
  1034. }
  1035. }
  1036. if (stack.length !== outputSize) {
  1037. return null;
  1038. }
  1039. const result = [];
  1040. for (const instruction of instructions) {
  1041. const statementBuilder = new ExpressionBuilderVisitor();
  1042. instruction.visit(statementBuilder);
  1043. result.push(statementBuilder.toString());
  1044. }
  1045. for (let i = 0, ii = stack.length; i < ii; i++) {
  1046. const expr = stack[i],
  1047. statementBuilder = new ExpressionBuilderVisitor();
  1048. expr.visit(statementBuilder);
  1049. const min = range[i * 2],
  1050. max = range[i * 2 + 1];
  1051. const out = [statementBuilder.toString()];
  1052. if (min > expr.min) {
  1053. out.unshift("Math.max(", min, ", ");
  1054. out.push(")");
  1055. }
  1056. if (max < expr.max) {
  1057. out.unshift("Math.min(", max, ", ");
  1058. out.push(")");
  1059. }
  1060. out.unshift("dest[destOffset + ", i, "] = ");
  1061. out.push(";");
  1062. result.push(out.join(""));
  1063. }
  1064. return result.join("\n");
  1065. }
  1066. }
  1067. exports.PostScriptCompiler = PostScriptCompiler;