2
0

function.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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.isPDFFunction = isPDFFunction;
  27. exports.PostScriptEvaluator = exports.PostScriptCompiler = exports.PDFFunctionFactory = void 0;
  28. var _primitives = require("./primitives.js");
  29. var _util = require("../shared/util.js");
  30. var _ps_parser = require("./ps_parser.js");
  31. var _image_utils = require("./image_utils.js");
  32. class PDFFunctionFactory {
  33. constructor({
  34. xref,
  35. isEvalSupported = true
  36. }) {
  37. this.xref = xref;
  38. this.isEvalSupported = isEvalSupported !== false;
  39. }
  40. create(fn) {
  41. const cachedFunction = this.getCached(fn);
  42. if (cachedFunction) {
  43. return cachedFunction;
  44. }
  45. const parsedFunction = PDFFunction.parse({
  46. xref: this.xref,
  47. isEvalSupported: this.isEvalSupported,
  48. fn: fn instanceof _primitives.Ref ? this.xref.fetch(fn) : fn
  49. });
  50. this._cache(fn, parsedFunction);
  51. return parsedFunction;
  52. }
  53. createFromArray(fnObj) {
  54. const cachedFunction = this.getCached(fnObj);
  55. if (cachedFunction) {
  56. return cachedFunction;
  57. }
  58. const parsedFunction = PDFFunction.parseArray({
  59. xref: this.xref,
  60. isEvalSupported: this.isEvalSupported,
  61. fnObj: fnObj instanceof _primitives.Ref ? this.xref.fetch(fnObj) : fnObj
  62. });
  63. this._cache(fnObj, parsedFunction);
  64. return parsedFunction;
  65. }
  66. getCached(cacheKey) {
  67. let fnRef;
  68. if (cacheKey instanceof _primitives.Ref) {
  69. fnRef = cacheKey;
  70. } else if (cacheKey instanceof _primitives.Dict) {
  71. fnRef = cacheKey.objId;
  72. } else if ((0, _primitives.isStream)(cacheKey)) {
  73. fnRef = cacheKey.dict && cacheKey.dict.objId;
  74. }
  75. if (fnRef) {
  76. const localFunction = this._localFunctionCache.getByRef(fnRef);
  77. if (localFunction) {
  78. return localFunction;
  79. }
  80. }
  81. return null;
  82. }
  83. _cache(cacheKey, parsedFunction) {
  84. if (!parsedFunction) {
  85. throw new Error('PDFFunctionFactory._cache - expected "parsedFunction" argument.');
  86. }
  87. let fnRef;
  88. if (cacheKey instanceof _primitives.Ref) {
  89. fnRef = cacheKey;
  90. } else if (cacheKey instanceof _primitives.Dict) {
  91. fnRef = cacheKey.objId;
  92. } else if ((0, _primitives.isStream)(cacheKey)) {
  93. fnRef = cacheKey.dict && cacheKey.dict.objId;
  94. }
  95. if (fnRef) {
  96. this._localFunctionCache.set(null, fnRef, parsedFunction);
  97. }
  98. }
  99. get _localFunctionCache() {
  100. return (0, _util.shadow)(this, "_localFunctionCache", new _image_utils.LocalFunctionCache());
  101. }
  102. }
  103. exports.PDFFunctionFactory = PDFFunctionFactory;
  104. function toNumberArray(arr) {
  105. if (!Array.isArray(arr)) {
  106. return null;
  107. }
  108. const length = arr.length;
  109. for (let i = 0; i < length; i++) {
  110. if (typeof arr[i] !== "number") {
  111. const result = new Array(length);
  112. for (let j = 0; j < length; j++) {
  113. result[j] = +arr[j];
  114. }
  115. return result;
  116. }
  117. }
  118. return arr;
  119. }
  120. class PDFFunction {
  121. static getSampleArray(size, outputSize, bps, stream) {
  122. let i, ii;
  123. let length = 1;
  124. for (i = 0, ii = size.length; i < ii; i++) {
  125. length *= size[i];
  126. }
  127. length *= outputSize;
  128. const array = new Array(length);
  129. let codeSize = 0;
  130. let codeBuf = 0;
  131. const sampleMul = 1.0 / (2.0 ** bps - 1);
  132. const strBytes = stream.getBytes((length * bps + 7) / 8);
  133. let strIdx = 0;
  134. for (i = 0; i < length; i++) {
  135. while (codeSize < bps) {
  136. codeBuf <<= 8;
  137. codeBuf |= strBytes[strIdx++];
  138. codeSize += 8;
  139. }
  140. codeSize -= bps;
  141. array[i] = (codeBuf >> codeSize) * sampleMul;
  142. codeBuf &= (1 << codeSize) - 1;
  143. }
  144. return array;
  145. }
  146. static parse({
  147. xref,
  148. isEvalSupported,
  149. fn
  150. }) {
  151. const dict = fn.dict || fn;
  152. const typeNum = dict.get("FunctionType");
  153. switch (typeNum) {
  154. case 0:
  155. return this.constructSampled({
  156. xref,
  157. isEvalSupported,
  158. fn,
  159. dict
  160. });
  161. case 1:
  162. break;
  163. case 2:
  164. return this.constructInterpolated({
  165. xref,
  166. isEvalSupported,
  167. dict
  168. });
  169. case 3:
  170. return this.constructStiched({
  171. xref,
  172. isEvalSupported,
  173. dict
  174. });
  175. case 4:
  176. return this.constructPostScript({
  177. xref,
  178. isEvalSupported,
  179. fn,
  180. dict
  181. });
  182. }
  183. throw new _util.FormatError("Unknown type of function");
  184. }
  185. static parseArray({
  186. xref,
  187. isEvalSupported,
  188. fnObj
  189. }) {
  190. if (!Array.isArray(fnObj)) {
  191. return this.parse({
  192. xref,
  193. isEvalSupported,
  194. fn: fnObj
  195. });
  196. }
  197. const fnArray = [];
  198. for (let j = 0, jj = fnObj.length; j < jj; j++) {
  199. fnArray.push(this.parse({
  200. xref,
  201. isEvalSupported,
  202. fn: xref.fetchIfRef(fnObj[j])
  203. }));
  204. }
  205. return function (src, srcOffset, dest, destOffset) {
  206. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  207. fnArray[i](src, srcOffset, dest, destOffset + i);
  208. }
  209. };
  210. }
  211. static constructSampled({
  212. xref,
  213. isEvalSupported,
  214. fn,
  215. dict
  216. }) {
  217. function toMultiArray(arr) {
  218. const inputLength = arr.length;
  219. const out = [];
  220. let index = 0;
  221. for (let i = 0; i < inputLength; i += 2) {
  222. out[index++] = [arr[i], arr[i + 1]];
  223. }
  224. return out;
  225. }
  226. function interpolate(x, xmin, xmax, ymin, ymax) {
  227. return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
  228. }
  229. let domain = toNumberArray(dict.getArray("Domain"));
  230. let range = toNumberArray(dict.getArray("Range"));
  231. if (!domain || !range) {
  232. throw new _util.FormatError("No domain or range");
  233. }
  234. const inputSize = domain.length / 2;
  235. const outputSize = range.length / 2;
  236. domain = toMultiArray(domain);
  237. range = toMultiArray(range);
  238. const size = toNumberArray(dict.getArray("Size"));
  239. const bps = dict.get("BitsPerSample");
  240. const order = dict.get("Order") || 1;
  241. if (order !== 1) {
  242. (0, _util.info)("No support for cubic spline interpolation: " + order);
  243. }
  244. let encode = toNumberArray(dict.getArray("Encode"));
  245. if (!encode) {
  246. encode = [];
  247. for (let i = 0; i < inputSize; ++i) {
  248. encode.push([0, size[i] - 1]);
  249. }
  250. } else {
  251. encode = toMultiArray(encode);
  252. }
  253. let decode = toNumberArray(dict.getArray("Decode"));
  254. if (!decode) {
  255. decode = range;
  256. } else {
  257. decode = toMultiArray(decode);
  258. }
  259. const samples = this.getSampleArray(size, outputSize, bps, fn);
  260. return function constructSampledFn(src, srcOffset, dest, destOffset) {
  261. const cubeVertices = 1 << inputSize;
  262. const cubeN = new Float64Array(cubeVertices);
  263. const cubeVertex = new Uint32Array(cubeVertices);
  264. let i, j;
  265. for (j = 0; j < cubeVertices; j++) {
  266. cubeN[j] = 1;
  267. }
  268. let k = outputSize,
  269. pos = 1;
  270. for (i = 0; i < inputSize; ++i) {
  271. const domain_2i = domain[i][0];
  272. const domain_2i_1 = domain[i][1];
  273. const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
  274. let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
  275. const size_i = size[i];
  276. e = Math.min(Math.max(e, 0), size_i - 1);
  277. const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
  278. const n0 = e0 + 1 - e;
  279. const n1 = e - e0;
  280. const offset0 = e0 * k;
  281. const offset1 = offset0 + k;
  282. for (j = 0; j < cubeVertices; j++) {
  283. if (j & pos) {
  284. cubeN[j] *= n1;
  285. cubeVertex[j] += offset1;
  286. } else {
  287. cubeN[j] *= n0;
  288. cubeVertex[j] += offset0;
  289. }
  290. }
  291. k *= size_i;
  292. pos <<= 1;
  293. }
  294. for (j = 0; j < outputSize; ++j) {
  295. let rj = 0;
  296. for (i = 0; i < cubeVertices; i++) {
  297. rj += samples[cubeVertex[i] + j] * cubeN[i];
  298. }
  299. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  300. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  301. }
  302. };
  303. }
  304. static constructInterpolated({
  305. xref,
  306. isEvalSupported,
  307. dict
  308. }) {
  309. const c0 = toNumberArray(dict.getArray("C0")) || [0];
  310. const c1 = toNumberArray(dict.getArray("C1")) || [1];
  311. const n = dict.get("N");
  312. const diff = [];
  313. for (let i = 0, ii = c0.length; i < ii; ++i) {
  314. diff.push(c1[i] - c0[i]);
  315. }
  316. const length = diff.length;
  317. return function constructInterpolatedFn(src, srcOffset, dest, destOffset) {
  318. const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
  319. for (let j = 0; j < length; ++j) {
  320. dest[destOffset + j] = c0[j] + x * diff[j];
  321. }
  322. };
  323. }
  324. static constructStiched({
  325. xref,
  326. isEvalSupported,
  327. dict
  328. }) {
  329. const domain = toNumberArray(dict.getArray("Domain"));
  330. if (!domain) {
  331. throw new _util.FormatError("No domain");
  332. }
  333. const inputSize = domain.length / 2;
  334. if (inputSize !== 1) {
  335. throw new _util.FormatError("Bad domain for stiched function");
  336. }
  337. const fnRefs = dict.get("Functions");
  338. const fns = [];
  339. for (let i = 0, ii = fnRefs.length; i < ii; ++i) {
  340. fns.push(this.parse({
  341. xref,
  342. isEvalSupported,
  343. fn: xref.fetchIfRef(fnRefs[i])
  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.IsEvalSupportedCached.value) {
  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 ((0, _primitives.isDict)(v)) {
  454. fnDict = v;
  455. } else if ((0, _primitives.isStream)(v)) {
  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.prototype.slice.call(initialStack, 0);
  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 ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  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 ((0, _util.isBool)(a)) {
  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 ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  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 ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
  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. const PostScriptCompiler = function PostScriptCompilerClosure() {
  744. class AstNode {
  745. constructor(type) {
  746. this.type = type;
  747. }
  748. visit(visitor) {
  749. (0, _util.unreachable)("abstract method");
  750. }
  751. }
  752. class AstArgument extends AstNode {
  753. constructor(index, min, max) {
  754. super("args");
  755. this.index = index;
  756. this.min = min;
  757. this.max = max;
  758. }
  759. visit(visitor) {
  760. visitor.visitArgument(this);
  761. }
  762. }
  763. class AstLiteral extends AstNode {
  764. constructor(number) {
  765. super("literal");
  766. this.number = number;
  767. this.min = number;
  768. this.max = number;
  769. }
  770. visit(visitor) {
  771. visitor.visitLiteral(this);
  772. }
  773. }
  774. class AstBinaryOperation extends AstNode {
  775. constructor(op, arg1, arg2, min, max) {
  776. super("binary");
  777. this.op = op;
  778. this.arg1 = arg1;
  779. this.arg2 = arg2;
  780. this.min = min;
  781. this.max = max;
  782. }
  783. visit(visitor) {
  784. visitor.visitBinaryOperation(this);
  785. }
  786. }
  787. class AstMin extends AstNode {
  788. constructor(arg, max) {
  789. super("max");
  790. this.arg = arg;
  791. this.min = arg.min;
  792. this.max = max;
  793. }
  794. visit(visitor) {
  795. visitor.visitMin(this);
  796. }
  797. }
  798. class AstVariable extends AstNode {
  799. constructor(index, min, max) {
  800. super("var");
  801. this.index = index;
  802. this.min = min;
  803. this.max = max;
  804. }
  805. visit(visitor) {
  806. visitor.visitVariable(this);
  807. }
  808. }
  809. class AstVariableDefinition extends AstNode {
  810. constructor(variable, arg) {
  811. super("definition");
  812. this.variable = variable;
  813. this.arg = arg;
  814. }
  815. visit(visitor) {
  816. visitor.visitVariableDefinition(this);
  817. }
  818. }
  819. class ExpressionBuilderVisitor {
  820. constructor() {
  821. this.parts = [];
  822. }
  823. visitArgument(arg) {
  824. this.parts.push("Math.max(", arg.min, ", Math.min(", arg.max, ", src[srcOffset + ", arg.index, "]))");
  825. }
  826. visitVariable(variable) {
  827. this.parts.push("v", variable.index);
  828. }
  829. visitLiteral(literal) {
  830. this.parts.push(literal.number);
  831. }
  832. visitBinaryOperation(operation) {
  833. this.parts.push("(");
  834. operation.arg1.visit(this);
  835. this.parts.push(" ", operation.op, " ");
  836. operation.arg2.visit(this);
  837. this.parts.push(")");
  838. }
  839. visitVariableDefinition(definition) {
  840. this.parts.push("var ");
  841. definition.variable.visit(this);
  842. this.parts.push(" = ");
  843. definition.arg.visit(this);
  844. this.parts.push(";");
  845. }
  846. visitMin(max) {
  847. this.parts.push("Math.min(");
  848. max.arg.visit(this);
  849. this.parts.push(", ", max.max, ")");
  850. }
  851. toString() {
  852. return this.parts.join("");
  853. }
  854. }
  855. function buildAddOperation(num1, num2) {
  856. if (num2.type === "literal" && num2.number === 0) {
  857. return num1;
  858. }
  859. if (num1.type === "literal" && num1.number === 0) {
  860. return num2;
  861. }
  862. if (num2.type === "literal" && num1.type === "literal") {
  863. return new AstLiteral(num1.number + num2.number);
  864. }
  865. return new AstBinaryOperation("+", num1, num2, num1.min + num2.min, num1.max + num2.max);
  866. }
  867. function buildMulOperation(num1, num2) {
  868. if (num2.type === "literal") {
  869. if (num2.number === 0) {
  870. return new AstLiteral(0);
  871. } else if (num2.number === 1) {
  872. return num1;
  873. } else if (num1.type === "literal") {
  874. return new AstLiteral(num1.number * num2.number);
  875. }
  876. }
  877. if (num1.type === "literal") {
  878. if (num1.number === 0) {
  879. return new AstLiteral(0);
  880. } else if (num1.number === 1) {
  881. return num2;
  882. }
  883. }
  884. const min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  885. const max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  886. return new AstBinaryOperation("*", num1, num2, min, max);
  887. }
  888. function buildSubOperation(num1, num2) {
  889. if (num2.type === "literal") {
  890. if (num2.number === 0) {
  891. return num1;
  892. } else if (num1.type === "literal") {
  893. return new AstLiteral(num1.number - num2.number);
  894. }
  895. }
  896. if (num2.type === "binary" && num2.op === "-" && num1.type === "literal" && num1.number === 1 && num2.arg1.type === "literal" && num2.arg1.number === 1) {
  897. return num2.arg2;
  898. }
  899. return new AstBinaryOperation("-", num1, num2, num1.min - num2.max, num1.max - num2.min);
  900. }
  901. function buildMinOperation(num1, max) {
  902. if (num1.min >= max) {
  903. return new AstLiteral(max);
  904. } else if (num1.max <= max) {
  905. return num1;
  906. }
  907. return new AstMin(num1, max);
  908. }
  909. class PostScriptCompiler {
  910. compile(code, domain, range) {
  911. const stack = [];
  912. const instructions = [];
  913. const inputSize = domain.length >> 1,
  914. outputSize = range.length >> 1;
  915. let lastRegister = 0;
  916. let n, j;
  917. let num1, num2, ast1, ast2, tmpVar, item;
  918. for (let i = 0; i < inputSize; i++) {
  919. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  920. }
  921. for (let i = 0, ii = code.length; i < ii; i++) {
  922. item = code[i];
  923. if (typeof item === "number") {
  924. stack.push(new AstLiteral(item));
  925. continue;
  926. }
  927. switch (item) {
  928. case "add":
  929. if (stack.length < 2) {
  930. return null;
  931. }
  932. num2 = stack.pop();
  933. num1 = stack.pop();
  934. stack.push(buildAddOperation(num1, num2));
  935. break;
  936. case "cvr":
  937. if (stack.length < 1) {
  938. return null;
  939. }
  940. break;
  941. case "mul":
  942. if (stack.length < 2) {
  943. return null;
  944. }
  945. num2 = stack.pop();
  946. num1 = stack.pop();
  947. stack.push(buildMulOperation(num1, num2));
  948. break;
  949. case "sub":
  950. if (stack.length < 2) {
  951. return null;
  952. }
  953. num2 = stack.pop();
  954. num1 = stack.pop();
  955. stack.push(buildSubOperation(num1, num2));
  956. break;
  957. case "exch":
  958. if (stack.length < 2) {
  959. return null;
  960. }
  961. ast1 = stack.pop();
  962. ast2 = stack.pop();
  963. stack.push(ast1, ast2);
  964. break;
  965. case "pop":
  966. if (stack.length < 1) {
  967. return null;
  968. }
  969. stack.pop();
  970. break;
  971. case "index":
  972. if (stack.length < 1) {
  973. return null;
  974. }
  975. num1 = stack.pop();
  976. if (num1.type !== "literal") {
  977. return null;
  978. }
  979. n = num1.number;
  980. if (n < 0 || !Number.isInteger(n) || stack.length < n) {
  981. return null;
  982. }
  983. ast1 = stack[stack.length - n - 1];
  984. if (ast1.type === "literal" || ast1.type === "var") {
  985. stack.push(ast1);
  986. break;
  987. }
  988. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  989. stack[stack.length - n - 1] = tmpVar;
  990. stack.push(tmpVar);
  991. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  992. break;
  993. case "dup":
  994. if (stack.length < 1) {
  995. return null;
  996. }
  997. 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]) {
  998. num1 = stack.pop();
  999. stack.push(buildMinOperation(num1, code[i + 1]));
  1000. i += 6;
  1001. break;
  1002. }
  1003. ast1 = stack[stack.length - 1];
  1004. if (ast1.type === "literal" || ast1.type === "var") {
  1005. stack.push(ast1);
  1006. break;
  1007. }
  1008. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  1009. stack[stack.length - 1] = tmpVar;
  1010. stack.push(tmpVar);
  1011. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  1012. break;
  1013. case "roll":
  1014. if (stack.length < 2) {
  1015. return null;
  1016. }
  1017. num2 = stack.pop();
  1018. num1 = stack.pop();
  1019. if (num2.type !== "literal" || num1.type !== "literal") {
  1020. return null;
  1021. }
  1022. j = num2.number;
  1023. n = num1.number;
  1024. if (n <= 0 || !Number.isInteger(n) || !Number.isInteger(j) || stack.length < n) {
  1025. return null;
  1026. }
  1027. j = (j % n + n) % n;
  1028. if (j === 0) {
  1029. break;
  1030. }
  1031. Array.prototype.push.apply(stack, stack.splice(stack.length - n, n - j));
  1032. break;
  1033. default:
  1034. return null;
  1035. }
  1036. }
  1037. if (stack.length !== outputSize) {
  1038. return null;
  1039. }
  1040. const result = [];
  1041. for (const instruction of instructions) {
  1042. const statementBuilder = new ExpressionBuilderVisitor();
  1043. instruction.visit(statementBuilder);
  1044. result.push(statementBuilder.toString());
  1045. }
  1046. for (let i = 0, ii = stack.length; i < ii; i++) {
  1047. const expr = stack[i],
  1048. statementBuilder = new ExpressionBuilderVisitor();
  1049. expr.visit(statementBuilder);
  1050. const min = range[i * 2],
  1051. max = range[i * 2 + 1];
  1052. const out = [statementBuilder.toString()];
  1053. if (min > expr.min) {
  1054. out.unshift("Math.max(", min, ", ");
  1055. out.push(")");
  1056. }
  1057. if (max < expr.max) {
  1058. out.unshift("Math.min(", max, ", ");
  1059. out.push(")");
  1060. }
  1061. out.unshift("dest[destOffset + ", i, "] = ");
  1062. out.push(";");
  1063. result.push(out.join(""));
  1064. }
  1065. return result.join("\n");
  1066. }
  1067. }
  1068. return PostScriptCompiler;
  1069. }();
  1070. exports.PostScriptCompiler = PostScriptCompiler;