function.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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 (let j = 0, jj = fnObj.length; j < jj; j++) {
  200. fnArray.push(this.parse({
  201. xref,
  202. isEvalSupported,
  203. fn: xref.fetchIfRef(fnObj[j])
  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 fnRefs = dict.get("Functions");
  339. const fns = [];
  340. for (let i = 0, ii = fnRefs.length; i < ii; ++i) {
  341. fns.push(this.parse({
  342. xref,
  343. isEvalSupported,
  344. fn: xref.fetchIfRef(fnRefs[i])
  345. }));
  346. }
  347. const bounds = toNumberArray(dict.getArray("Bounds"));
  348. const encode = toNumberArray(dict.getArray("Encode"));
  349. const tmpBuf = new Float32Array(1);
  350. return function constructStichedFn(src, srcOffset, dest, destOffset) {
  351. const clip = function constructStichedFromIRClip(v, min, max) {
  352. if (v > max) {
  353. v = max;
  354. } else if (v < min) {
  355. v = min;
  356. }
  357. return v;
  358. };
  359. const v = clip(src[srcOffset], domain[0], domain[1]);
  360. const length = bounds.length;
  361. let i;
  362. for (i = 0; i < length; ++i) {
  363. if (v < bounds[i]) {
  364. break;
  365. }
  366. }
  367. let dmin = domain[0];
  368. if (i > 0) {
  369. dmin = bounds[i - 1];
  370. }
  371. let dmax = domain[1];
  372. if (i < bounds.length) {
  373. dmax = bounds[i];
  374. }
  375. const rmin = encode[2 * i];
  376. const rmax = encode[2 * i + 1];
  377. tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  378. fns[i](tmpBuf, 0, dest, destOffset);
  379. };
  380. }
  381. static constructPostScript({
  382. xref,
  383. isEvalSupported,
  384. fn,
  385. dict
  386. }) {
  387. const domain = toNumberArray(dict.getArray("Domain"));
  388. const range = toNumberArray(dict.getArray("Range"));
  389. if (!domain) {
  390. throw new _util.FormatError("No domain.");
  391. }
  392. if (!range) {
  393. throw new _util.FormatError("No range.");
  394. }
  395. const lexer = new _ps_parser.PostScriptLexer(fn);
  396. const parser = new _ps_parser.PostScriptParser(lexer);
  397. const code = parser.parse();
  398. if (isEvalSupported && _util.FeatureTest.isEvalSupported) {
  399. const compiled = new PostScriptCompiler().compile(code, domain, range);
  400. if (compiled) {
  401. return new Function("src", "srcOffset", "dest", "destOffset", compiled);
  402. }
  403. }
  404. (0, _util.info)("Unable to compile PS function");
  405. const numOutputs = range.length >> 1;
  406. const numInputs = domain.length >> 1;
  407. const evaluator = new PostScriptEvaluator(code);
  408. const cache = Object.create(null);
  409. const MAX_CACHE_SIZE = 2048 * 4;
  410. let cache_available = MAX_CACHE_SIZE;
  411. const tmpBuf = new Float32Array(numInputs);
  412. return function constructPostScriptFn(src, srcOffset, dest, destOffset) {
  413. let i, value;
  414. let key = "";
  415. const input = tmpBuf;
  416. for (i = 0; i < numInputs; i++) {
  417. value = src[srcOffset + i];
  418. input[i] = value;
  419. key += value + "_";
  420. }
  421. const cachedValue = cache[key];
  422. if (cachedValue !== undefined) {
  423. dest.set(cachedValue, destOffset);
  424. return;
  425. }
  426. const output = new Float32Array(numOutputs);
  427. const stack = evaluator.execute(input);
  428. const stackIndex = stack.length - numOutputs;
  429. for (i = 0; i < numOutputs; i++) {
  430. value = stack[stackIndex + i];
  431. let bound = range[i * 2];
  432. if (value < bound) {
  433. value = bound;
  434. } else {
  435. bound = range[i * 2 + 1];
  436. if (value > bound) {
  437. value = bound;
  438. }
  439. }
  440. output[i] = value;
  441. }
  442. if (cache_available > 0) {
  443. cache_available--;
  444. cache[key] = output;
  445. }
  446. dest.set(output, destOffset);
  447. };
  448. }
  449. }
  450. function isPDFFunction(v) {
  451. let fnDict;
  452. if (typeof v !== "object") {
  453. return false;
  454. } else if (v instanceof _primitives.Dict) {
  455. fnDict = v;
  456. } else if (v instanceof _base_stream.BaseStream) {
  457. fnDict = v.dict;
  458. } else {
  459. return false;
  460. }
  461. return fnDict.has("FunctionType");
  462. }
  463. class PostScriptStack {
  464. static get MAX_STACK_SIZE() {
  465. return (0, _util.shadow)(this, "MAX_STACK_SIZE", 100);
  466. }
  467. constructor(initialStack) {
  468. this.stack = !initialStack ? [] : Array.prototype.slice.call(initialStack, 0);
  469. }
  470. push(value) {
  471. if (this.stack.length >= PostScriptStack.MAX_STACK_SIZE) {
  472. throw new Error("PostScript function stack overflow.");
  473. }
  474. this.stack.push(value);
  475. }
  476. pop() {
  477. if (this.stack.length <= 0) {
  478. throw new Error("PostScript function stack underflow.");
  479. }
  480. return this.stack.pop();
  481. }
  482. copy(n) {
  483. if (this.stack.length + n >= PostScriptStack.MAX_STACK_SIZE) {
  484. throw new Error("PostScript function stack overflow.");
  485. }
  486. const stack = this.stack;
  487. for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  488. stack.push(stack[i]);
  489. }
  490. }
  491. index(n) {
  492. this.push(this.stack[this.stack.length - n - 1]);
  493. }
  494. roll(n, p) {
  495. const stack = this.stack;
  496. const l = stack.length - n;
  497. const r = stack.length - 1;
  498. const c = l + (p - Math.floor(p / n) * n);
  499. for (let i = l, j = r; i < j; i++, j--) {
  500. const t = stack[i];
  501. stack[i] = stack[j];
  502. stack[j] = t;
  503. }
  504. for (let i = l, j = c - 1; i < j; i++, j--) {
  505. const t = stack[i];
  506. stack[i] = stack[j];
  507. stack[j] = t;
  508. }
  509. for (let i = c, j = r; i < j; i++, j--) {
  510. const t = stack[i];
  511. stack[i] = stack[j];
  512. stack[j] = t;
  513. }
  514. }
  515. }
  516. class PostScriptEvaluator {
  517. constructor(operators) {
  518. this.operators = operators;
  519. }
  520. execute(initialStack) {
  521. const stack = new PostScriptStack(initialStack);
  522. let counter = 0;
  523. const operators = this.operators;
  524. const length = operators.length;
  525. let operator, a, b;
  526. while (counter < length) {
  527. operator = operators[counter++];
  528. if (typeof operator === "number") {
  529. stack.push(operator);
  530. continue;
  531. }
  532. switch (operator) {
  533. case "jz":
  534. b = stack.pop();
  535. a = stack.pop();
  536. if (!a) {
  537. counter = b;
  538. }
  539. break;
  540. case "j":
  541. a = stack.pop();
  542. counter = a;
  543. break;
  544. case "abs":
  545. a = stack.pop();
  546. stack.push(Math.abs(a));
  547. break;
  548. case "add":
  549. b = stack.pop();
  550. a = stack.pop();
  551. stack.push(a + b);
  552. break;
  553. case "and":
  554. b = stack.pop();
  555. a = stack.pop();
  556. if (typeof a === "boolean" && typeof b === "boolean") {
  557. stack.push(a && b);
  558. } else {
  559. stack.push(a & b);
  560. }
  561. break;
  562. case "atan":
  563. a = stack.pop();
  564. stack.push(Math.atan(a));
  565. break;
  566. case "bitshift":
  567. b = stack.pop();
  568. a = stack.pop();
  569. if (a > 0) {
  570. stack.push(a << b);
  571. } else {
  572. stack.push(a >> b);
  573. }
  574. break;
  575. case "ceiling":
  576. a = stack.pop();
  577. stack.push(Math.ceil(a));
  578. break;
  579. case "copy":
  580. a = stack.pop();
  581. stack.copy(a);
  582. break;
  583. case "cos":
  584. a = stack.pop();
  585. stack.push(Math.cos(a));
  586. break;
  587. case "cvi":
  588. a = stack.pop() | 0;
  589. stack.push(a);
  590. break;
  591. case "cvr":
  592. break;
  593. case "div":
  594. b = stack.pop();
  595. a = stack.pop();
  596. stack.push(a / b);
  597. break;
  598. case "dup":
  599. stack.copy(1);
  600. break;
  601. case "eq":
  602. b = stack.pop();
  603. a = stack.pop();
  604. stack.push(a === b);
  605. break;
  606. case "exch":
  607. stack.roll(2, 1);
  608. break;
  609. case "exp":
  610. b = stack.pop();
  611. a = stack.pop();
  612. stack.push(a ** b);
  613. break;
  614. case "false":
  615. stack.push(false);
  616. break;
  617. case "floor":
  618. a = stack.pop();
  619. stack.push(Math.floor(a));
  620. break;
  621. case "ge":
  622. b = stack.pop();
  623. a = stack.pop();
  624. stack.push(a >= b);
  625. break;
  626. case "gt":
  627. b = stack.pop();
  628. a = stack.pop();
  629. stack.push(a > b);
  630. break;
  631. case "idiv":
  632. b = stack.pop();
  633. a = stack.pop();
  634. stack.push(a / b | 0);
  635. break;
  636. case "index":
  637. a = stack.pop();
  638. stack.index(a);
  639. break;
  640. case "le":
  641. b = stack.pop();
  642. a = stack.pop();
  643. stack.push(a <= b);
  644. break;
  645. case "ln":
  646. a = stack.pop();
  647. stack.push(Math.log(a));
  648. break;
  649. case "log":
  650. a = stack.pop();
  651. stack.push(Math.log(a) / Math.LN10);
  652. break;
  653. case "lt":
  654. b = stack.pop();
  655. a = stack.pop();
  656. stack.push(a < b);
  657. break;
  658. case "mod":
  659. b = stack.pop();
  660. a = stack.pop();
  661. stack.push(a % b);
  662. break;
  663. case "mul":
  664. b = stack.pop();
  665. a = stack.pop();
  666. stack.push(a * b);
  667. break;
  668. case "ne":
  669. b = stack.pop();
  670. a = stack.pop();
  671. stack.push(a !== b);
  672. break;
  673. case "neg":
  674. a = stack.pop();
  675. stack.push(-a);
  676. break;
  677. case "not":
  678. a = stack.pop();
  679. if (typeof a === "boolean") {
  680. stack.push(!a);
  681. } else {
  682. stack.push(~a);
  683. }
  684. break;
  685. case "or":
  686. b = stack.pop();
  687. a = stack.pop();
  688. if (typeof a === "boolean" && typeof b === "boolean") {
  689. stack.push(a || b);
  690. } else {
  691. stack.push(a | b);
  692. }
  693. break;
  694. case "pop":
  695. stack.pop();
  696. break;
  697. case "roll":
  698. b = stack.pop();
  699. a = stack.pop();
  700. stack.roll(a, b);
  701. break;
  702. case "round":
  703. a = stack.pop();
  704. stack.push(Math.round(a));
  705. break;
  706. case "sin":
  707. a = stack.pop();
  708. stack.push(Math.sin(a));
  709. break;
  710. case "sqrt":
  711. a = stack.pop();
  712. stack.push(Math.sqrt(a));
  713. break;
  714. case "sub":
  715. b = stack.pop();
  716. a = stack.pop();
  717. stack.push(a - b);
  718. break;
  719. case "true":
  720. stack.push(true);
  721. break;
  722. case "truncate":
  723. a = stack.pop();
  724. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  725. stack.push(a);
  726. break;
  727. case "xor":
  728. b = stack.pop();
  729. a = stack.pop();
  730. if (typeof a === "boolean" && typeof b === "boolean") {
  731. stack.push(a !== b);
  732. } else {
  733. stack.push(a ^ b);
  734. }
  735. break;
  736. default:
  737. throw new _util.FormatError(`Unknown operator ${operator}`);
  738. }
  739. }
  740. return stack.stack;
  741. }
  742. }
  743. exports.PostScriptEvaluator = PostScriptEvaluator;
  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.at(-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. exports.PostScriptCompiler = PostScriptCompiler;