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