-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy patharlington.py
1656 lines (1531 loc) · 79.9 KB
/
arlington.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright 2021 PDF Association, Inc. https://www.pdfa.org
#
# This material is based upon work supported by the Defense Advanced
# Research Projects Agency (DARPA) under Contract No. HR001119C0079.
# Any opinions, findings and conclusions or recommendations expressed
# in this material are those of the author(s) and do not necessarily
# reflect the views of the Defense Advanced Research Projects Agency
# (DARPA). Approved for public release.
#
# SPDX-License-Identifier: Apache-2.0
# Contributors: Peter Wyatt, PDF Association
#
# Converts the Arlington TSV data into Pythonesque equivalent.
# Can also export as JSON.
# The conversion process may generate errors for various kinds of data entry issues
# (i.e. mistakes in the TSV data) but there is also a validate_pdf_dom() method that will
# perform other checks.
#
# Example usage (Linux CLI):
# $ python3 arlington.py --tsvdir ../tsv/latest --validate
#
# Requires:
# - Python 3
# - pip3 install sly pikepdf
# - See https://sly.readthedocs.io/en/latest/sly.html
# - PikePDF is a wrapper around qpdf. See https://pikepdf.readthedocs.io/en/latest/api/main.html
#
# Python QA:
# Note that Sly causes various errors because of the lexer magic!!!
# - flake8 --ignore E501,E221,E226 arlington.py
# - pyflakes arlington.py
# - mypy arlington.py
#
import sys
import csv
import os
import glob
import re
import argparse
import pprint
import logging
import json
import decimal
import pikepdf
import traceback
from typing import Any, Dict, List, Optional, Tuple, Union
import sly # type: ignore
class ArlingtonFnLexer(sly.Lexer):
# debugfile = 'arlington-parser.out'
# Set of token names. This is always required.
tokens = {
FUNC_NAME, KEY_VALUE, KEY_NAME, KEY_PATH, MOD, PDF_PATH, EQ, NE, GE, LE, GT, LT,
LOGICAL_AND, LOGICAL_OR, REAL, INTEGER, PLUS, MINUS, TIMES, DIVIDE, LPAREN,
RPAREN, COMMA, ARRAY_START, ARRAY_END, ELLIPSIS, PDF_TRUE, PDF_FALSE, PDF_STRING
}
# Precedence rules
precedence = (
('nonassoc', EQ, NE, LE, GE, LT, GT), # Non-associative operators
('left', PLUS, MINUS),
('left', TIMES, DIVIDE, MOD),
('left', LOGICAL_AND, LOGICAL_OR)
)
# String containing ignored characters between tokens (just SPACE)
ignore = ' '
# Regular expression rules for tokens
# Longer rules need to be at the top
FUNC_NAME = r'fn\:[A-Z][a-zA-Z0-9]+\('
PDF_TRUE = r'(true)|(TRUE)'
PDF_FALSE = r'(false)|(FALSE)'
PDF_STRING = r'\'[^\']+\''
MOD = r'mod'
ELLIPSIS = r'\.\.\.'
KEY_VALUE = r'@(\*|[0-9]+|[0-9]+\*|[a-zA-Z0-9_\.\-]+)'
# Key name is both a PDF name or a TSV filename
# Key name of just '*' is potentially ambiguous with TIMES (multiply) operator.
# Key name which is numeric array index ([0-9+) and is potentially ambiguous with integers.
# Array indices are integers, or integer followed by ASTERISK (wildcard) - need to use SPACEs to disambiguate with TIMES
KEY_PATH = r'(parent::)?(([a-zA-Z]|[a-zA-Z][0-9]*|[0-9]*\*|[0-9]*[a-zA-Z])[a-zA-Z0-9_\.\-]*::)+'
KEY_NAME = r'([_a-zA-Z]|[_a-zA-Z][0-9]*|[0-9]*\*|[0-9]*[_a-zA-Z])[a-zA-Z0-9_:\.\-]*'
PDF_PATH = r'::'
ARRAY_START = r'\['
ARRAY_END = r'\]'
EQ = r'=='
NE = r'!='
GE = r'>='
LE = r'<='
LOGICAL_AND = r'\&\&'
LOGICAL_OR = r'\|\|'
GT = r'>'
LT = r'<'
REAL = r'\-?\d+\.\d+'
INTEGER = r'\-?\d+'
PLUS = r'\+'
MINUS = r'-'
TIMES = r'\*'
DIVIDE = r'/'
LPAREN = r'\('
RPAREN = r'\)'
COMMA = r'\,'
@_(r'\-?\d+\.\d+')
def REAL(self, t):
t.value = float(t.value)
return t
@_(r'\-?\d+')
def INTEGER(self, t):
t.value = int(t.value)
return t
@_(r'(false)|(FALSE)')
def PDF_FALSE(self, t):
t.value = False
return t
@_(r'(true)|(TRUE)')
def PDF_TRUE(self, t):
t.value = True
return t
# Terse version of sly.lex.Token.__str__/__repr__ dunder methods
def MyTokenStr(self) -> str:
return "TOKEN(type='%s', value='%s')" % (self.type, self.value)
# Function to JSON-ify sly.lex.Token objects
def sly_lex_Token_to_json(self) -> Dict[str, Union[str, sly.lex.Token]]:
if isinstance(self, sly.lex.Token):
return {'object': 'sly.lex.Token', 'type': self.type, 'value': self.value}
return {'error': '!not a sly.lex.Token!'}
class Arlington:
"""
Wrapper class around a set of Arlington TSV PDF definition files
"""
# All the Arlington pre-defined types (pre-sorted alphabetically)
__known_types = frozenset(['array', 'bitmask', 'boolean', 'date', 'dictionary', 'integer',
'matrix', 'name', 'name-tree', 'null', 'number', 'number-tree',
'rectangle', 'stream', 'string', 'string-ascii', 'string-byte', 'string-text'])
# Arlington 'Types' for which a valid Link is required
__links_required = frozenset(['array', 'dictionary', 'name-tree', 'number-tree', 'stream'])
# Current set of versions for the SinceVersion and Deprecated columns, as well as some functions
__pdf_versions = frozenset(['1.0', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '1.7', '2.0'])
# Base PDF tokens that will get "flattened away" during declarative function AST processing
__basePDFtokens = frozenset(['REAL', 'INTEGER', 'PDF_TRUE', 'PDF_FALSE', 'KEY_NAME', 'PDF_STRING'])
# Mathematical comparison operators for declarative functions
__comparison_ops = frozenset(['EQ', 'NE', 'GE', 'LE', 'GT', 'LT'])
# Type definition
AST = List[sly.lex.Token]
def validate_fn_void(self, ast: AST) -> bool:
"""
Validates all functions which take no parameters
@param ast: AST to be validated.
@returns: True if a valid void function. False otherwise
"""
if (len(ast) == 0):
return True
return False
def validate_fn_array_length(self, ast: AST) -> bool:
"""
fn:ArrayLength( <key-name/key-path/array-index> ) <condition-op> <integer>
@param ast: AST to be validated.
@returns: True if a valid 'fn:ArrayLength' function. False otherwise
"""
if ((len(ast) == 1) and
not isinstance(ast[0], list) and (ast[0].type in ('KEY_NAME', 'INTEGER'))):
return True
elif (len(ast) >= 1) and isinstance(ast[0], list):
return True
elif (len(ast) > 1) and (ast[0].type == 'KEY_PATH') and (ast[1].type == 'KEY_NAME'):
return True
return False
def validate_fn_array_sort_ascending(self, ast: AST) -> bool:
"""
Validates fn:ArraySortAscending(key, step)
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if ((len(ast) == 2) and (ast[0].type in ('KEY_NAME')) and (ast[1].type in ('INTEGER'))):
return True
return False
def validate_fn_extension(self, ast: AST) -> bool:
"""
Validates the fn:Extension predicate with a first argument that a name and an optional second argument.
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if ((len(ast) >= 1) and (ast[0].type == 'KEY_NAME')):
return True
return False
def validate_fn_version(self, ast: AST) -> bool:
"""
Validates a declarative function with a first argument that is a PDF version string and optional
second argument.
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if ((len(ast) >= 1) and (ast[0].type == 'REAL') and (str(ast[0].value) in self.__pdf_versions)):
return True
return False
def validate_fn_bit(self, ast: AST) -> bool:
"""
Validates a single bit set/clear declarative function with a single bit position argument (1-32 inclusive)
@param ast: AST to be validated.
@returns: True if a valid 'fn:BitSet/Clear(' function. False otherwise
"""
if (len(ast) == 1) and (ast[0].type == 'INTEGER') and (ast[0].value >= 1) and (ast[0].value <= 32):
return True
return False
def validate_fn_bits(self, ast: AST) -> bool:
"""
Validates a bit range set/clear declarative function with a two bit position arguments (each 1-32
inclusive). The first argument must be less than the second argument to form a valid bit range.
@param ast: AST to be validated.
@returns: True if a valid 'fn:BitsSet/Clear(' function. False otherwise
"""
if ((len(ast) == 2) and
(ast[0].type == 'INTEGER') and (ast[0].value >= 1) and (ast[0].value <= 32) and
(ast[1].type == 'INTEGER') and (ast[1].value >= 1) and (ast[1].value <= 32) and
(ast[0].value < ast[1].value)):
return True
return False
def validate_fn_contains(self, ast: AST) -> bool:
"""
Validates the fn:Contains predicate with key-value 1st argument and a statement (anything) 2nd arg.
@param ast: AST to be validated.
@returns: True if a valid 'fn:BitsSet/Clear(' function. False otherwise
"""
if ((len(ast) == 2) and (ast[0].type == 'KEY_VALUE')):
return True
return False
def validate_fn_anything(self, ast: AST) -> bool:
"""
Validates all generic predicates. At least one argument is required.
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
return (len(ast) > 0)
def validate_fn_get_page_property(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) >= 2) and (ast[0].type == 'KEY_VALUE') and (ast[1].type in ['KEY_NAME', 'KEY_PATH']):
return True
return False
def validate_fn_colorants(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 2) and (ast[0].type == 'KEY_PATH') and (ast[1].type == 'INTEGER'):
return True
return False
def validate_fn_ignore(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 0) or isinstance(ast[0], list):
return True
if (len(ast) == 1) and (ast[0].type in ('KEY_NAME', 'INTEGER')):
return True
if (len(ast) >= 3) and (ast[0].type == 'KEY_VALUE') and (ast[1].type in self.__comparison_ops):
return True
return False
def validate_fn_in_map(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 2) and (ast[0].type == 'KEY_PATH') and (ast[1].type in ('KEY_NAME', 'INTEGER')):
return True
elif (len(ast) == 1) and (ast[0].type == 'KEY_NAME'):
return True
return False
def validate_fn_is_meaningful(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 0) or isinstance(ast[0], list):
return True
elif (len(ast) >= 3) and (ast[0].type == 'KEY_VALUE') and (ast[1].type in self.__comparison_ops):
return True
elif (len(ast) >= 4) and (ast[0].type == 'KEY_PATH') and (ast[1].type == 'KEY_VALUE') and (ast[2].type in self.__comparison_ops):
return True
return False
def validate_fn_is_required(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 0) or isinstance(ast[0], list):
return True
if (len(ast) >= 3):
if (ast[0].type == 'FUNC_NAME'):
return True
if (ast[0].type == 'KEY_VALUE') and (ast[1].type in self.__comparison_ops):
return True
if (len(ast) >= 4) and (ast[0].type == 'KEY_PATH') and (ast[1].type in ('KEY_NAME', 'KEY_VALUE')) and (ast[2].type in self.__comparison_ops):
return True
return False
def validate_fn_must_be_direct(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 0) or isinstance(ast[0], list):
return True
if (len(ast) == 1) and (ast[0].type == 'KEY_VALUE'):
return True
if (len(ast) == 2) and (ast[0].type == 'KEY_PATH') and (ast[1].type in ('KEY_NAME', 'INTEGER')):
return True
return False
def validate_fn_must_be_indirect(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 0) or isinstance(ast[0], list):
return True
if (len(ast) == 1) and (ast[0].type == 'KEY_VALUE'):
return True
if (len(ast) == 2) and (ast[0].type == 'FUNC_NAME') and (ast[1].type in ('REAL', 'INTEGER')):
return True
return False
def validate_fn_rect(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid 'fn:RectWidth(' function. False otherwise
"""
if (len(ast) == 1) and (ast[0].type in ('KEY_NAME', 'INTEGER')):
return True
return False
def validate_fn_required_value(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if not isinstance(ast[0], list):
if ((len(ast) == 4) and (ast[0].type in ('KEY_VALUE','FUNC_NAME'))):
return True
else:
if (len(ast) == 2):
if (isinstance(ast[0][0], list) and (ast[0][0][0].type == 'FUNC_NAME')):
return True
elif (len(ast) >= 3):
if ((((ast[0][0].type == 'KEY_VALUE') and (ast[0][1].type in self.__comparison_ops)) and
(ast[1].type in ('LOGICAL_OR', 'LOGICAL_AND')) and
((ast[2][0].type == 'KEY_VALUE') and (ast[2][1].type in self.__comparison_ops))) or
((ast[0][0].type == 'FUNC_NAME'))):
return True
return False
def validate_fn_is_present(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid 'fn:IsPresent(' function. False otherwise
"""
if (len(ast) >= 1):
if (isinstance(ast[0], list) or (ast[0].type in ('KEY_NAME', 'INTEGER', 'KEY_PATH', 'KEY_VALUE'))):
return True
return False
def validate_fn_is_field_name(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid 'fn:IsFieldName(' function. False otherwise
"""
if (len(ast) >= 1):
if (isinstance(ast[0], list) or (ast[0].type in ('KEY_VALUE'))):
return True
return False
def validate_fn_stream_length(self, ast: AST) -> bool:
"""
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
return True # TODO ###################################
def validate_fn_string_length(self, ast: AST) -> bool:
"""
fn:StringLength(<key-name/array-index> , [ <condition> ] ) <comparison-op> <integer>
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) == 1) and (ast[0].type in ('KEY_NAME', 'INTEGER')):
return True
elif (len(ast) > 1) and (ast[0].type in ('KEY_NAME', 'INTEGER')):
# ToDo: validate optional <condition> statement
return True
return False
def validate_fn_default_value(self, ast: AST) -> bool:
"""
fn:DefaultValue( <condition>, value )
@param ast: AST to be validated.
@returns: True if a valid function. False otherwise
"""
if (len(ast) >= 4) and (ast[len(ast)-1].type in ('KEY_NAME', 'PDF_STRING', 'INTEGER')):
# ToDo: check condition
return True
return False
# Validation functions for every Arlington declarative function
__validate_fns = {
'fn:AlwaysUnencrypted(': validate_fn_void,
'fn:ArrayLength(': validate_fn_array_length,
'fn:ArraySortAscending(': validate_fn_array_sort_ascending,
'fn:BeforeVersion(': validate_fn_version,
'fn:BitClear(': validate_fn_bit,
'fn:BitSet(': validate_fn_bit,
'fn:BitsClear(': validate_fn_bits,
'fn:BitsSet(': validate_fn_bits,
'fn:Contains(': validate_fn_contains,
'fn:Deprecated(': validate_fn_version,
'fn:Eval(': validate_fn_anything,
'fn:FileSize(': validate_fn_void,
'fn:FontHasLatinChars(': validate_fn_void,
'fn:PageProperty(': validate_fn_get_page_property,
'fn:Ignore(': validate_fn_ignore,
'fn:HasProcessColorants(': validate_fn_colorants,
'fn:HasSpotColorants(': validate_fn_colorants,
'fn:ImageIsStructContentItem(': validate_fn_void,
'fn:ImplementationDependent(': validate_fn_void,
'fn:InKeyMap(': validate_fn_in_map,
'fn:InNameTree(': validate_fn_in_map,
'fn:IsAssociatedFile(': validate_fn_void,
'fn:IsEncryptedWrapper(': validate_fn_void,
'fn:IsFieldName(': validate_fn_is_field_name,
'fn:IsHexString(': validate_fn_void,
'fn:IsLastInNumberFormatArray(': validate_fn_anything,
'fn:IsMeaningful(': validate_fn_is_meaningful,
'fn:IsPDFTagged(': validate_fn_void,
'fn:IsPDFVersion(': validate_fn_version,
'fn:IsPresent(': validate_fn_is_present,
'fn:IsRequired(': validate_fn_is_required,
'fn:KeyNameIsColorant(': validate_fn_void,
'fn:MustBeDirect(': validate_fn_must_be_direct,
'fn:MustBeIndirect(': validate_fn_must_be_indirect,
'fn:NoCycle(': validate_fn_void,
'fn:NotStandard14Font(': validate_fn_void,
'fn:NumberOfPages(': validate_fn_void,
'fn:PageContainsStructContentItems(': validate_fn_void,
'fn:RectHeight(': validate_fn_rect,
'fn:RectWidth(': validate_fn_rect,
'fn:RequiredValue(': validate_fn_required_value,
'fn:Extension(': validate_fn_extension,
'fn:SinceVersion(': validate_fn_version,
'fn:StreamLength(': validate_fn_stream_length,
'fn:StringLength(': validate_fn_string_length,
'fn:DefaultValue(': validate_fn_default_value,
'fn:Not(': validate_fn_anything
}
@staticmethod
def __strip_square_brackets(li: Optional[Union[str, List[str]]]) -> Union[str, Optional[List[Optional[str]]]]:
"""
Only strip off outer "[...]" as inner square brackets may exist for PDF arrays
@param li: a string or nested list of strings/lists
"""
if (li is None):
return None
elif isinstance(li, str):
# Single string
if (li[0] == r'[') and (li[-1] == r']'):
return li[1:len(li)-1]
else:
return li
elif isinstance(li, list):
# Was SEMI-COLON separated, now a Python list
lst: List[Optional[str]] = []
for i in li:
if (i == r'[]'):
lst.append(None)
elif (i[0] == r'[') and (i[-1] == r']'):
lst.append(i[1:len(i)-1])
else:
lst.append(i)
return lst
else:
raise TypeError("Unexpected type (%s) when removing square brackets" % type(li))
@staticmethod
def __convert_booleans(obj: Any) -> Any:
"""
Convert spreadsheet booleans to Python: "FALSE" to False, "TRUE" to True
(lowercase "false"/"true" are retained as PDF keywords)
Note also that declarative functions may be used in place of Booleans!
@param obj: the Python object (str or list) to convert
@returns: an updated object of the same type that was passed in
"""
if isinstance(obj, str):
if (obj == r'FALSE') or (obj == r'[FALSE]'):
return False
elif (obj == r'TRUE') or (obj == r'[TRUE]'):
return True
else:
return obj
elif isinstance(obj, list):
li = []
for o in obj:
if (o == r'FALSE') or (o == r'[FALSE]'):
li.append(False)
elif (o == r'TRUE') or (o == r'[TRUE]'):
li.append(True)
else:
li.append(o)
return li
else:
raise TypeError("Unexpected type '%s' for converting booleans!" % obj)
def __reduce_linkslist(self, linkslist: List[str], reduced_list: List[str] = []) -> List[str]:
"""
Reduces a 'Link' list of strings (potentially including declarative functions) to a
simple list of Arlington TSV links in the same order as the original list.
Recursive function.
@param typelist: list of Arlington 'Links' (TSV filenames) including declarative functions
@param typelist: reduced list of just Arlington 'Link' TSV names (appended to)
@returns: reduced list (of at least length 1)
"""
if (linkslist is None):
return None
for lk in linkslist:
if isinstance(lk, str):
reduced_list.append(lk)
elif isinstance(lk, list):
# Declarative functions are lists so recurse
reduced_list = self.__reduce_linkslist(lk, reduced_list)
return reduced_list
def __reduce_typelist(self, typelist: List[str], reduced_list: List[str] = []) -> List:
"""
Reduces a 'Types' list of strings (potentially including declarative functions) to a simple
alphabetically sorted list of Arlington type strings in the same order as TSV.
Recursive function.
@param typelist: list of Arlington Types
@param reduced_list: reduced list of Arlington Types (appended to)
@returns: reduced list (of at least length 1)
"""
for t in typelist:
if isinstance(t, str):
if (t in self.__known_types):
reduced_list.append(t)
elif isinstance(t, list):
# Declarative functions are lists so recurse
reduced_list = self.__reduce_typelist(t, reduced_list)
return reduced_list
def __find_pdf_type(self, types: Union[str, List[str]], typelist: List[str]) -> int:
"""
Recurse through a 'Types' list of strings seeing if one of a string in 'types' list
is present (including anywhere in a declarative functions). This is NOT smart and
does not process/understand declarative functions!
@param types: a list of known Arlington 'Type' strings
@param typelist: list of Arlington Types
@returns: index into typelist if a type in 'types' is found, -1 otherwise
"""
i: int
t: str
for i, t in enumerate(typelist):
if isinstance(t, str):
if (t not in self.__known_types):
logging.critical("'%s' is not a well known Arlington type!", t)
if isinstance(types, list):
for ea in types:
if isinstance(ea, str) and (ea in t):
return i
return -1
elif isinstance(types, str) and (types in t):
return i
elif isinstance(t, list):
# Declarative functions are lists so recurse on the function
if (self.__find_pdf_type(types, t) != -1):
return i
return -1
def to_nested_AST(self, stk: AST, idx: int = 0) -> Tuple[int, AST]:
"""
Assumes a fully valid parse tree with fully bracketed "( .. )" expressions
Also nests PDF array objects "[ ... ]". Recursive.
@param stk: AST stack
@param idx: index into AST stack
@returns: index to next item in AST stack, AST stack
"""
ast: List[sly.lex.Token] = []
i: int = idx
while (i < len(stk)):
if (stk[i].type == 'FUNC_NAME'):
j, k = self.to_nested_AST(stk, i+1)
if (self.__validating):
if (stk[i].value in self.__validate_fns):
fn_ok = self.__validate_fns[stk[i].value](self, k)
if not fn_ok:
logging.error("Invalid declarative function %s: %s", stk[i].value, k)
else:
logging.error("Unknown declarative function %s: %s", stk[i].value, k)
k = [stk[i]] + [k] # Insert the func name at the start
ast.append(k)
i = j
elif (stk[i].type == 'LPAREN') or (stk[i].type == 'ARRAY_START'):
j, k = self.to_nested_AST(stk, i+1)
ast.append(k)
i = j
elif (stk[i].type == 'RPAREN') or (stk[i].type == 'ARRAY_END'):
# go up recursion 1 level
return i+1, ast
elif (stk[i].type == 'COMMA'):
# skip COMMAs
i += 1
else:
ast.append(stk[i])
i += 1
return i, ast
def __flatten_ast(self, ast: AST) -> None:
"""
De-tokenize for all the base PDF stuff (integers, numbers, true/false keywords, strings)
Recursive.
@param ast: AST list
"""
i = 0
while (i < len(ast)):
if not isinstance(ast[i], list):
if (ast[i].type in self.__basePDFtokens):
ast[i] = ast[i].value
else:
self.__flatten_ast(ast[i])
i += 1
def _parse_functions(self, func: str, col: str, obj: str, key: str) -> AST:
"""
Use Sly to parse any string with TSV names, PDF names or declaractive functions.
Sly will raise exceptions if there are errors.
@param func: string from a TSV column that contains a 'fn:' declarative function
@param col: column name from TSV file (just for error messages)
@param obj: object name (TSV filename) for this function (just for error messages)
@param key: name of the key on 'obj' for this function (just for error messages)
@returns: Python list with top level TSV names or PDF names as strings and functions as lists
"""
logging.info("In row['%s'] %s::%s: '%s'", col, obj, key, func)
stk = []
for tok in self.__lexer.tokenize(func):
stk.append(tok)
num_toks = len(stk)
i, ast = self.to_nested_AST(stk)
# logging.debug("AST: %s", pprint.pformat(ast))
self.__flatten_ast(ast)
if (num_toks == 1) and (stk[0].type not in ('FUNC_NAME', 'KEY_VALUE')):
if (len(ast) > 0):
ast = ast[0]
# logging.info("Out: %s", pprint.pformat(ast))
if (num_toks == 0) or (len(stk) == 0) or (ast is None): # or (not isinstance(ast, list)):
logging.error("_parse_functions('%s', '%s::%s', '%s')", col, obj, key, func)
return ast
def __init__(self, dir: str = ".", pdfver: str = "2.0", validating: bool = False):
"""
Constructor. Reads TSV set file-by-file and converts to Pythonese
@param dir: directory folder contain TSV files
@param pdfver: the PDF version used for determination (default is '2.0')
"""
self.__directory: str = dir
self.__filecount: int = 0
self.__pdfver: str = pdfver
self.__pdfdom: Dict[str, Any] = {}
self.__validating: bool = validating
# "Monkey patch" sly.lex.Token __str__ and __repr__ dunder methods to make JSON nicer
# Don't do this if we want to read the JSON back in!
self.__old_str = sly.lex.Token.__str__
sly.lex.Token.__str__ = MyTokenStr
self.__old_repr = sly.lex.Token.__repr__
sly.lex.Token.__repr__ = MyTokenStr
self.__lexer = ArlingtonFnLexer()
try:
# Load Arlington into Python
filepath: str
for filepath in glob.iglob(os.path.join(dir, r"*.tsv")):
obj_name = os.path.splitext(os.path.basename(filepath))[0]
self.__filecount += 1
logging.debug("Reading '%s'", obj_name)
with open(filepath, newline='') as csvfile:
tsvreader = csv.DictReader(csvfile, delimiter='\t')
tsvobj = {}
row: Any
for row in tsvreader:
keyname = row['Key']
if (len(row) != 12):
logging.error("%s::%s does not have 12 columns!", obj_name, keyname)
row.pop('Key')
if (keyname == ''):
raise TypeError("Key name field cannot be empty!")
# Make multi-type fields into arrays (aka Python lists)
if (r';' in row['Type']):
row['Type'] = re.split(r';', row['Type'])
else:
row['Type'] = [row['Type']]
for i, v in enumerate(row['Type']):
if (r'fn:' in v):
row['Type'][i] = self._parse_functions(v, 'Type', obj_name, keyname)
row['Required'] = self._parse_functions(row['Required'], 'Required', obj_name, keyname)
if (row['Required'] is not None) and not isinstance(row['Required'], list):
row['Required'] = [row['Required']]
# SinceVersion now has basic predicates for Extensions
row['SinceVersion'] = self._parse_functions(row['SinceVersion'], 'SinceVersion', obj_name, keyname)
# Optional, but must be a known PDF version
if (row['DeprecatedIn'] == ''):
row['DeprecatedIn'] = None
if (r';' in row['IndirectReference']):
row['IndirectReference'] = Arlington.__strip_square_brackets(re.split(r';', row['IndirectReference']))
for i, v in enumerate(row['IndirectReference']):
if (v is not None):
row['IndirectReference'][i] = self._parse_functions(v, 'IndirectReference', obj_name, keyname)
else:
row['IndirectReference'] = self._parse_functions(row['IndirectReference'], 'IndirectReference', obj_name, keyname)
if not isinstance(row['IndirectReference'], list):
row['IndirectReference'] = [row['IndirectReference']]
# For conciseness in some cases a single FALSE/TRUE is used in place of an expanded array [];[];[]
# Expand this out so direct indexing is always possible
if (len(row['Type']) > len(row['IndirectReference'])) and (len(row['IndirectReference']) == 1):
for i in range(len(row['Type']) - len(row['IndirectReference'])):
row['IndirectReference'].append(row['IndirectReference'][0])
# Must be FALSE or TRUE (uppercase only!)
row['Inheritable'] = Arlington.__convert_booleans(row['Inheritable'])
# Can only be one value for Key, but Key can be multi-typed or predicate
if (row['DefaultValue'] == ''):
row['DefaultValue'] = None
elif (r';' in row['DefaultValue']):
row['DefaultValue'] = self.__strip_square_brackets(re.split(r';', row['DefaultValue']))
for i, v in enumerate(row['DefaultValue']):
if (v is not None):
row['DefaultValue'][i] = self._parse_functions(v, 'DefaultValue', obj_name, keyname)
else:
row['DefaultValue'] = self._parse_functions(row['DefaultValue'], 'DefaultValue', obj_name, keyname)
if (row['DefaultValue'] is not None) and not isinstance(row['DefaultValue'], list):
row['DefaultValue'] = [row['DefaultValue']]
if (row['PossibleValues'] == ''):
row['PossibleValues'] = None
elif (r';' in row['PossibleValues']):
row['PossibleValues'] = self.__strip_square_brackets(re.split(r';', row['PossibleValues']))
for i, pv in enumerate(row['PossibleValues']):
if (pv is not None):
row['PossibleValues'][i] = self._parse_functions(pv, 'PossibleValues', obj_name, keyname)
else:
row['PossibleValues'] = self._parse_functions(row['PossibleValues'], 'PossibleValues', obj_name, keyname)
if (row['PossibleValues'] is not None) and not isinstance(row['PossibleValues'], list):
row['PossibleValues'] = [row['PossibleValues']]
# Below is a hack(!!!) because a few PDF key values look like floats or keywords but are really names.
# Sly-based parsing in Python does not use any hints from other rows so it will convert to int/float/bool as it sees fit
# See Catalog::Version, DocMDPTransformParameters::V, DevExtensions::BaseVersion, SigFieldSeedValue::LockDocument
if (row['Type'][0] == 'name'):
if (row['DefaultValue'] is not None) and isinstance(row['DefaultValue'][0], (int, float)):
logging.info("Converting DefaultValue int/float/bool '%s' back to name for %s::%s", str(row['DefaultValue'][0]), obj_name, keyname)
row['DefaultValue'][0] = str(row['DefaultValue'][0])
if (row['PossibleValues'] is not None) and (row['PossibleValues'][0] is not None):
for i, v in enumerate(row['PossibleValues'][0]):
if isinstance(v, (int, float)):
logging.info("Converting PossibleValues int/float/bool '%s' back to name for %s::%s", str(v), obj_name, keyname)
row['PossibleValues'][0][i] = str(v)
if (row['SpecialCase'] == ''):
row['SpecialCase'] = None
elif (r';' in row['SpecialCase']):
row['SpecialCase'] = self.__strip_square_brackets(re.split(r';', row['SpecialCase']))
for i, v in enumerate(row['SpecialCase']):
if (v is not None):
row['SpecialCase'][i] = self._parse_functions(v, 'SpecialCase', obj_name, keyname)
else:
row['SpecialCase'] = self._parse_functions(row['SpecialCase'], 'SpecialCase', obj_name, keyname)
if (row['SpecialCase'] is not None) and not isinstance(row['SpecialCase'], list):
row['SpecialCase'] = [row['SpecialCase']]
if (row['Link'] == ''):
row['Link'] = None
else:
if (r';' in row['Link']):
row['Link'] = re.split(r';', row['Link'])
for i, v in enumerate(row['Link']):
if (v == '[]'):
row['Link'][i] = None
else:
row['Link'][i] = self._parse_functions(v, 'Link', obj_name, keyname)
else:
row['Link'] = self._parse_functions(row['Link'], 'Link', obj_name, keyname)
if (row['Link'] is not None) and not isinstance(row['Link'], list):
row['Link'] = [row['Link']]
if (row['Note'] == ''):
row['Note'] = None
tsvobj[keyname] = row
self.__pdfdom[obj_name] = tsvobj
csvfile.close()
if (self.__validating):
self.__validate_pdf_dom()
if (self.__filecount == 0):
logging.critical("There were no TSV files in directory '%s'!", self.__directory)
return
logging.info("%d TSV files processed from %s", self.__filecount, self.__directory)
self.__validating = False
except Exception as e:
logging.critical("Exception: " + str(e))
traceback.print_exception(type(e), e, e.__traceback__)
def __validate_pdf_dom(self) -> None:
"""
Does a detailed Validation of the in-memory Python data structure of the
Arlington TSV data files.
"""
if (self.__filecount == 0) or (len(self.__pdfdom) == 0):
logging.critical("There is no Arlington DOM to validate!")
return
# logging.info("Validating against PDF version %s", self.__pdfver)
for obj_name in self.__pdfdom:
logging.debug("Validating '%s'", obj_name)
obj = self.__pdfdom[obj_name]
# Check if object contain any duplicate keys or has no keys
if (len(obj) != len(set(obj))):
logging.critical("Duplicate keys in '%s'!", obj_name)
if (len(obj) == 0):
logging.critical("Object '%s' has no keys/array entries!", obj_name)
for keyname in obj:
row = obj[keyname]
logging.debug("Validating %s::%s", obj_name, keyname)
# Check validity of key names and array indices
m = re.search(r'^[a-zA-Z0-9_:\-\.]*\*?$', keyname)
if (m is None):
logging.error("Key '%s' in object %s has unexpected characters", keyname, obj_name)
# Check if Types are sorted alphabetically
reduced_types = self.__reduce_typelist(row['Type'], [])
is_sorted = all((reduced_types[i] <= reduced_types[i+1]) for i in range(len(reduced_types)-1))
if not is_sorted:
logging.error("Types '%s' are not sorted alphabetically for %s::%s", row['Type'], obj_name, keyname)
if isinstance(row['SinceVersion'], list):
for v in row['SinceVersion']:
if (v[0].type != 'FUNC_NAME') and ((v[0].value != 'fn:IsExtension(') or (v[0].value != 'fn:SinceVersion(')):
logging.error("SinceVersion predicate '%s' is not correct for %s::%s", v, obj_name, keyname)
elif isinstance(row['SinceVersion'], float):
v = row['SinceVersion']
if (v != 1.0) and (v != 1.1) and (v != 1.2) and (v != 1.3) and (v != 1.4) and (v != 1.5) and (v != 1.6) and (v != 1.7) and (v != 2.0):
logging.error("SinceVersion '%s' in %s::%s has unexpected version!", row['SinceVersion'], obj_name, keyname)
else:
logging.error("SinceVersion '%s' in %s::%s has unexpected value!", row['SinceVersion'], obj_name, keyname)
if (row['DeprecatedIn'] is not None) and (row['DeprecatedIn'] not in self.__pdf_versions):
logging.error("DeprecatedIn '%s' in %s::%s has unexpected value!", row['DeprecatedIn'], obj_name, keyname)
for v in row['Required']:
if isinstance(v, list):
if (v[0].type != 'FUNC_NAME') and (v[0].value != 'fn:IsRequired('):
logging.error("Required function '%s' does not start with 'fn:IsRequired' for %s::%s", row['Required'], obj_name, keyname)
if (isinstance(row['IndirectReference'], list) and (len(row['IndirectReference']) > 1)):
if (len(row['Type']) != len(row['IndirectReference'])):
logging.error("Incorrect number of elements between Type (%d) and IndirectReference (%d) for %s::%s",
len(row['Type']), len(row['IndirectReference']), obj_name, keyname)
i = self.__find_pdf_type('stream', row['Type'])
if (i != -1):
if (row['IndirectReference'][i] is not True):
logging.error("Type 'stream' requires IndirectReference (%s) to be TRUE for %s::%s", row['IndirectReference'][i], obj_name, keyname)
if not ((row['Inheritable'] is True) or (row['Inheritable'] is False)):
logging.error("Inheritable %s '%s' in %s::%s is not FALSE or TRUE!", type(row['Inheritable']), row['Inheritable'], obj_name, keyname)
if (row['DefaultValue'] is not None):
if (len(row['Type']) != len(row['DefaultValue'])):
logging.error("Incorrect number of elements between Type and DefaultValue for %s::%s", obj_name, keyname)
# Validate all types are known and match DefaultValue into PossibleValues
for i, t in enumerate(row['Type']):
if isinstance(t, str):
if (t not in self.__known_types):
logging.error("Unknown Arlington type '%s' for %s::%s!", t, obj_name, keyname)
# Check if type and DefaultValue match in data type
if (row['DefaultValue'] is not None) and (row['DefaultValue'][i] is not None):
# nested lists below represent declarative functions - but they are NOT checked to see
# if the first element is a FUNC_NAME!!
if (t == 'name') and not isinstance(row['DefaultValue'][i], (str, list)):
logging.error("DefaultValue '%s' is not a name for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif (t == 'array') and not isinstance(row['DefaultValue'][i], (list)):
logging.error("DefaultValue '%s' is not an array for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif (t == 'boolean') and not isinstance(row['DefaultValue'][i], (bool, list)):
logging.error("DefaultValue '%s' is not a boolean for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif (t == 'number') and not isinstance(row['DefaultValue'][i], (int, float, list)):
logging.error("DefaultValue '%s' is not a number for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif (t == 'integer') and not isinstance(row['DefaultValue'][i], (int, list)):
logging.error("DefaultValue '%s' is not an integer for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif ('string' in t):
if not isinstance(row['DefaultValue'][i], (str, list)):
logging.error("DefaultValue '%s' is not a string for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif isinstance(row['DefaultValue'][i], str):
if (row['DefaultValue'][i][0] != '\''):
logging.error("DefaultValue '%s' does not start with '\'' for %s::%s", row['DefaultValue'][i], obj_name, keyname)
elif (row['DefaultValue'][i][-1] != '\''):
logging.error("DefaultValue '%s' does not end with '\'' for %s::%s", row['DefaultValue'][i], obj_name, keyname)
# Check if type and PossibleValues match in data type
# PossibleValues are SETS of values!
if (row['PossibleValues'] is not None) and (row['PossibleValues'][i] is not None):
if (t == 'name'):
if isinstance(row['PossibleValues'][i], list):
for j, v in enumerate(row['PossibleValues'][i]):
if not isinstance(row['PossibleValues'][i][j], (str, list)):
logging.error("PossibleValues '%s' is not a name for %s::%s", row['PossibleValues'][i][j], obj_name, keyname)
elif not isinstance(row['PossibleValues'][i], str):
logging.error("PossibleValues '%s' is not a name for %s::%s", row['PossibleValues'][i], obj_name, keyname)
elif (t == 'array'):
if isinstance(row['PossibleValues'][i], list):
for j, v in enumerate(row['PossibleValues'][i]):
if not isinstance(row['PossibleValues'][i][j], (list)):
logging.error("PossibleValues '%s' is not an array for %s::%s", row['PossibleValues'][i][j], obj_name, keyname)
else:
logging.error("PossibleValues '%s' is not an array for %s::%s", row['PossibleValues'][i], obj_name, keyname)
elif (t == 'boolean'):
if isinstance(row['PossibleValues'][i], list):
for j, v in enumerate(row['PossibleValues'][i]):
if not isinstance(row['PossibleValues'][i][j], (bool, list)):
logging.error("PossibleValues '%s' is not a boolean for %s::%s", row['PossibleValues'][i][j], obj_name, keyname)
elif not isinstance(row['PossibleValues'][i], bool):
logging.error("PossibleValues '%s' is not a boolean for %s::%s", row['PossibleValues'][i], obj_name, keyname)
elif (t == 'number'):
if isinstance(row['PossibleValues'][i], list):
for j, v in enumerate(row['PossibleValues'][i]):
if not isinstance(row['PossibleValues'][i][j], (int, float, list)):
logging.error("PossibleValues '%s' is not a number for %s::%s", row['PossibleValues'][i][j], obj_name, keyname)
elif not isinstance(row['PossibleValues'][i], (int, float)):
logging.error("PossibleValues '%s' is not a number for %s::%s", row['PossibleValues'][i], obj_name, keyname)
elif (t == 'integer'):
if isinstance(row['PossibleValues'][i], list):
for j, v in enumerate(row['PossibleValues'][i]):
if not isinstance(row['PossibleValues'][i][j], (int, list)):
logging.error("PossibleValues '%s' is not an integer for %s::%s", row['PossibleValues'][i][j], obj_name, keyname)
elif not isinstance(row['PossibleValues'][i], int):
logging.error("PossibleValues '%s' is not an integer for %s::%s", row['PossibleValues'][i], obj_name, keyname)
elif ('string' in t):
if isinstance(row['PossibleValues'][i], list):