-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzen.py
More file actions
2182 lines (1895 loc) · 70.8 KB
/
zen.py
File metadata and controls
2182 lines (1895 loc) · 70.8 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
"""
'--------____________________________--------'
| | -ZEN- | |
|____| Reducing recompilation times. |____|
'----------------------------------'
Copyright 2019 TryExceptElse
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 argparse
import enum
import hashlib
import itertools
import json
import os
from pathlib import Path
import re
import string
import subprocess as sub
import sys
import time
import typing as ty
class ParsingException(Exception):
"""
Exception class used to indicate problems parsing file content.
"""
class ComponentCreationError(ValueError):
"""
Exception thrown when a component cannot be instantiated from a
specified location in source.
"""
class Status(enum.IntEnum):
"""
Change status of a SourceFile, CompileObject, or Target.
"""
UNCHECKED = 1
NO_CHANGE = 2
MINOR_CHANGE = 3
CHANGED = 4
class TargetType(enum.Enum):
EXECUTABLE = 1
STATIC_LIB = 2
SHARED_LIB = 3
UNKNOWN = 4
LIB_TYPES = {TargetType.STATIC_LIB, TargetType.SHARED_LIB}
HEADER_EXT = '.h', '.hpp', '.hh', '.hxx'
BRACKETS = {
'(': ')',
'{': '}',
'[': ']',
'<': '>'
}
#######################################################################
# Build constructs
class BuildDir:
"""
Root build data class.
"""
CACHE_NAME = 'zen_cache'
def __init__(self, path: str) -> None:
self.path = Path(path)
self.targets = self._find_targets()
self.targets_by_path = {
target.file_path.absolute(): target
for target in self.targets.values()
}
self.sources = self._find_sources()
self._hash_cache: ty.Dict[str, int] = None
def meditate(self) -> None:
"""
Minimizes number of objects and targets that need to
be rebuilt.
:return: None
"""
[target.meditate() for target in self.targets.values()]
def remember(self) -> None:
"""
Stores information about the current form of the source code,
so that it may later be determined later what has been changed
substantially enough to require recompilation.
:return: None
"""
for dep in self.sources:
dep.remember(self.hash_cache)
for target in self.targets.values():
target.remember()
with self.cache_path.open('w') as f:
json.dump(self.hash_cache, f)
def _find_targets(self) -> ty.Dict[str, 'Target']:
"""
Gets list of previously built targets.
:return: List[Target]
"""
targets = {}
for target_dir in self.path.rglob('*.dir'):
name: str = os.path.splitext(target_dir.name)[0]
if name in targets:
raise ValueError(f'Multiple targets with name: {name} found.')
targets[name] = Target(name, target_dir, self)
return targets
def _find_sources(self) -> ty.Set['SourceFile']:
dependencies = set()
for target in self.targets.values():
for compile_object in target.objects:
for dependency in compile_object.sources:
dependencies.add(dependency)
return dependencies
@property
def hash_cache(self) -> ty.Dict[str, int]:
"""
Gets SourceCache storing previously compiled values.
:return: Cache dict.
"""
if self._hash_cache is None:
try:
with self.cache_path.open() as f:
self._hash_cache = json.load(f)
except FileNotFoundError:
self._hash_cache = {}
return self._hash_cache
@property
def cache_path(self) -> Path:
return Path(self.path, self.CACHE_NAME)
def __repr__(self) -> str:
return f'BuildDir[{self.path}]'
class Target:
"""
Class handling interaction with build files of a single target.
"""
def __init__(self, name: str, path: Path, build_dir: 'BuildDir') -> None:
"""
Initializes a new target handler.
:param name: name of target.
:param path: path to target build directory.
:param build_dir: BuildDir instance.
"""
self.name = name
self.path = path
self.build_dir = build_dir
self.objects = self._find_objects()
self.file_path: ty.Optional[Path] = None
self.type: 'TargetType' = TargetType.UNKNOWN
self.file_path, self.type = self._identify_target()
self.dependency_paths: ty.Set[Path] = self._find_dependencies()
self.status = Status.UNCHECKED
def meditate(self) -> None:
if self.status != Status.UNCHECKED:
return # Already meditated.
# Run on lib dependencies first; the status of the target will
# be determined in part by their change status.
if self.lib_dependencies:
for lib in self.lib_dependencies:
lib.meditate()
max_lib_status = max(lib.status for lib in self.lib_dependencies)
else:
max_lib_status = Status.NO_CHANGE
# Run on object dependencies.
if self.objects:
[o.meditate() for o in self.objects]
max_obj_status = max(o.status for o in self.objects)
else:
max_obj_status = Status.NO_CHANGE
# If file_path does not exist: the target must be built,
# and so should be considered changed.
if self.file_path.exists():
self.status = max((
max_obj_status,
max_lib_status,
self.other_status
))
else:
self.status = Status.CHANGED
if self.status == Status.MINOR_CHANGE and \
self.type != TargetType.UNKNOWN:
self.avoid_build()
def remember(self) -> None:
"""
Stores information about the current form of the target,
so that it may later be determined later what has been changed
substantially enough to require recompilation.
:return: None
"""
for obj in self.objects:
obj.remember()
def avoid_build(self) -> None:
"""
Un-Marks this target for re-linking.
This method should only be called if target is known.
:return: None
"""
sub.run(['touch', '-c', str(self.file_path.absolute())], check=True)
@staticmethod
def type_from_path(path: ty.Union[str, Path]) -> TargetType:
"""
Determine the TargetType from the name of the file
produced by the target.
:param path:
:return:
"""
ext = os.path.splitext(path)[1]
return {
'': TargetType.EXECUTABLE,
'.a': TargetType.STATIC_LIB,
'.so': TargetType.SHARED_LIB
}.get(ext, TargetType.UNKNOWN)
def _find_objects(self) -> ty.List['CompileObject']:
"""
Finds objects belonging to target.
:return: List[Object]
"""
depend_internal_path = Path(self.path, 'depend.internal')
if not depend_internal_path.exists():
return []
with depend_internal_path.open() as f:
d: ty.Dict[Path, ty.List[Path]] = {}
deps: ty.List[Path] = []
for line in f.readlines():
stripped = line.strip()
if not stripped:
continue
if stripped.endswith('.o'):
deps = d[Path(self.build_dir.path, stripped)] = []
elif line.startswith(' '):
deps.append(Path(self.build_dir.path, stripped).resolve())
return [CompileObject(o, deps, self.build_dir) for
o, deps in d.items()]
def _identify_target(self) -> ty.Tuple[ty.Optional[Path], 'TargetType']:
"""
Attempts to locate and identify the target file produced by
the Target.
:return: Tuple[Path, TargetType]
"""
clean_file_path = Path(self.path, 'cmake_clean.cmake')
# Get last line of remove recurse command,
# which should be target.
with clean_file_path.open() as f:
s = f.read()
start_key = 'file(REMOVE_RECURSE'
start = s.find(start_key)
if start == -1:
return None, TargetType.UNKNOWN
start += len(start_key)
end = s.find('\n)\n', start)
files = s[start:end].splitlines()
target_name = files[-1].strip()
assert target_name[0] == '"'
assert target_name[-1] == '"'
target_name = target_name[1:-1]
# Attempt to determine type from extension.
target_type = self.type_from_path(target_name)
# If target type is unknown, don't presume that the path
# that was found represents the target file.
if target_type == TargetType.UNKNOWN:
path = None
else:
path = Path(self.path, '..', '..', target_name).resolve()
return path, target_type
def _find_dependencies(self) -> ty.Set[Path]:
build_make_path = Path(self.path, 'build.make')
paths = set()
with build_make_path.open() as f:
prefix = f'{self.name}:'
for line in f.readlines():
if line.startswith(prefix):
rel_path = line[len(prefix):].strip()
paths.add(Path(self.build_dir.path, rel_path))
return paths
@property
def m_time(self):
"""
Gets modification time of compiled object.
:return: float time in seconds since epoch.
"""
return os.path.getmtime(self.file_path)
@property
def other_status(self) -> Status:
"""
Gets status of other files that the target relies upon, such as
make files. Since these files are not parsed, their status will
only ever be NO_CHANGE or CHANGED.
:return: Status.NO_CHANGE or Status.CHANGED
:rtype Status
"""
if any(os.path.getmtime(other) > self.m_time for
other in self.other_dependencies):
return Status.CHANGED
return Status.NO_CHANGE
@property
def lib_dependencies(self) -> ty.Set['Target']:
"""
Finds library Targets that this Target relies upon.
:return: Library Targets.
:rtype Set[Target]
"""
libraries = set()
for dep in self.dependency_paths:
if self.type_from_path(dep.absolute()) not in LIB_TYPES:
continue
try:
target = self.build_dir.targets_by_path[dep]
libraries.add(target)
except KeyError as e:
raise ValueError(
f'Could not find target with path: {dep}') from e
return libraries
@property
def other_dependencies(self) -> ty.Set[Path]:
"""
Finds dependencies other than objects and libraries,
such as build files.
:return: Set[Path]
"""
others = set()
for dep in self.dependency_paths:
if self.type_from_path(dep.absolute()) in LIB_TYPES:
continue
if os.path.splitext(str(dep))[1] == '.o':
continue
others.add(dep)
return others
def __repr__(self) -> str:
return f'Target[{self.name}]'
class CompileObject:
"""
Class handling specific compiled object.
"""
def __init__(
self,
path: Path,
sources: ty.List[Path],
build_dir: 'BuildDir'
) -> None:
"""
Create a handler for a compilation object.
:param path: Path to .o object.
:param sources: absolute paths to source
file dependencies.
:param build_dir: BuildDir instance.
"""
self.path = path
self.sources = [SourceFile(src) for src in sources]
self.build_dir = build_dir
self.status = Status.UNCHECKED
self._used_content_hash: ty.Optional[int] = None
def meditate(self) -> None:
"""
Determine whether the managed compilation object should be
rebuilt or whether compilation can be avoided.
:return: None
"""
if self.sources_modified:
verbose(f'{repr(self)} sources modified. Checking source.')
else:
self.status = Status.NO_CHANGE
return
if self._has_code_changes() and self._has_used_content_change():
self.status = Status.CHANGED
else:
self.status = Status.MINOR_CHANGE
self.avoid_build()
def remember(self) -> None:
"""
Remembers used parts of sources, so that differences can be
found the next time zen is run.
:return: None
"""
self.build_dir.hash_cache[self.hex] = self.used_content_hash
def _has_code_changes(self) -> bool:
"""
Checks whether any source file dependencies have had changes,
not including whitespace or comments.
:return: True if code changes are found in any source file.
:rtype: bool
"""
for source in self.sources:
if source.substantive_changes(self.build_dir.hash_cache):
return True
return False
def _has_used_content_change(self):
"""
Checks whether used content has changed.
:return: True if used content has changed.
:rtype: bool
"""
cached_hash = self.build_dir.hash_cache[self.hex]
return self.used_content_hash != cached_hash
def avoid_build(self) -> None:
"""
Un-Marks this object for re-compilation.
:return: None
"""
sub.run(['touch', '-c', str(self.path.absolute())], check=True)
@property
def m_time(self):
"""
Gets modification time of compiled object.
:return: float time in seconds since epoch.
"""
return os.path.getmtime(self.path.absolute())
@property
def sources_modified(self) -> bool:
"""
Checks whether any of the sources for this object are more
recent than this object's latest modification.
:return: bool
"""
try:
own_m_time = self.m_time
except FileNotFoundError:
return True
return any([own_m_time <= dep.m_time for dep in self.sources])
@property
def used_content_hash(self) -> int:
if self._used_content_hash is None:
constructs: ty.Dict[str, 'Construct'] = self.create_constructs()
def recurse_component(
component: 'Component'
) -> ty.Iterable['Component']:
"""
Yields components recursively from passed component,
yielding first the component itself, and then any sub-
components it possesses, sub-components of those
sub-components, etc.
:param component: Component to recurse over.
:return: Component generator
"""
yield component
for sub_component in component.sub_components:
yield from recurse_component(sub_component)
for construct in component.used_constructs(
constructs).values():
if construct.used:
continue
construct.used = True
for component in construct.content:
yield from recurse_component(component)
def used_components(
source: 'SourceFile') -> ty.Iterable['Component']:
content = source.content
block = content.component
for component in block.sub_components:
yield from recurse_component(component)
def used_chunk_strings(source: 'SourceFile') -> ty.Iterable[str]:
for component in used_components(source):
for chunk in component.exposed_content:
yield str(chunk).strip()
def source_hashes() -> ty.Iterable[int]:
for source in self.sources:
if source.is_header:
yield iter_hash(used_chunk_strings(source))
else:
yield source.stripped_hash
self._used_content_hash = join_hashes(source_hashes())
return self._used_content_hash
def create_constructs(self) -> ty.Dict[str, 'Construct']:
"""
Gets constructs produced by sources used by CompileObject.
:return: dict of constructs by name str.
:rtype Dict[str, Construct]
"""
def recurse_component(component_: 'Component'):
yield component_
for sub_component in component_.sub_components:
yield from recurse_component(sub_component)
constructs: ty.Dict[str, 'Construct'] = {}
for source in self.sources:
for component in recurse_component(source.content.component):
for name, content in component.construct_content.items():
try:
construct = constructs[name]
except KeyError:
construct = constructs[name] = Construct(name)
construct.add_content(content)
return constructs
@property
def hex(self) -> str:
"""
Gets the hash of the compile object's path.
:return: hex version of the hash code produced from the
object's path.
:rtype: str
"""
return hashlib.md5(str(self.path).encode()).hexdigest()
def __repr__(self) -> str:
return f'Object[{os.path.basename(str(self.path))}]'
class SourceFile:
"""
Handler for a specific source file on disk.
Only one SourceFile instance should exist for a given
absolute path. Instantiating SourceFile multiple times using the
same path will result in references to the same SourceFile instance
being returned.
"""
_source_files = {}
def __new__(cls, path: Path) -> 'SourceFile':
try:
src = cls._source_files[path.absolute()]
except KeyError:
src = cls._source_files[path.absolute()] = object.__new__(cls)
return src
def __init__(self, path: Path) -> None:
if hasattr(self, '_initialized'):
return
self.path = path
self._access_time: ty.Optional[float] = None
self._content: ty.Optional['SourceContent'] = None
self._initialized = True
@classmethod
def clear(cls) -> None:
cls._source_files.clear()
def substantive_changes(self, cache: ty.Dict[str, int]) -> bool:
"""
Check for changes against cache.
:param cache: SourceCache
:return: bool which is True if changes have occurred.
"""
try:
return self.stripped_hash != cache[self.hex]
except KeyError:
return True
def remember(self, cache: ty.Dict[str, int]) -> None:
cache[self.hex] = self.stripped_hash
@property
def is_header(self) -> bool:
return self.path.suffix in HEADER_EXT
@property
def m_time(self) -> float:
"""
Gets modification time of source file.
:return: float time in seconds since epoch.
"""
return os.path.getmtime(self.path.absolute())
@property
def content(self) -> 'SourceContent':
"""
Gets SourceContent object for accessing information about the
code contained within the SourceFile.
:return: SourceContent instance representing
SourceFile's content.
:rtype: SourceContent
"""
if self._content is None or self.m_time > self._access_time:
self._access_time = time.time()
with self.path.open() as f:
self._content = SourceContent(f)
return self._content
@property
def stripped_hash(self) -> int:
return self.content.stripped_hash
@property
def hex(self) -> str:
"""
Gets hex representation of source path hash.
:return: str
"""
return hashlib.md5(str(self.path).encode()).hexdigest()
def __repr__(self) -> str:
return f'SourceFile[{os.path.basename(str(self.path))}]'
#######################################################################
# Source analysis
class SourceContent:
path: Path
lines: ty.List['Line']
_raw_hash: ty.Optional[int]
def __init__(self, content: ty.Union[str, ty.TextIO]) -> None:
if isinstance(content, str):
self.lines = self._lines_from_str(content)
else:
self.lines = self._lines_from_f(content)
self._raw_hash: ty.Optional[int] = None
self._stripped_comments: bool = False
self._component: ty.Optional['Block'] = None
self._constructs: ty.Dict[str, 'Construct'] = None
self._chunk: ty.Optional['Chunk'] = None
def strip_comments(self) -> None:
"""
Removes comments from all lines in content.
:return: None
"""
if self._stripped_comments:
raise ValueError('Already stripped comments')
in_block: bool = False
for line in self.lines:
s: str = line.raw
i: int = 0
chunks: ty.List[str] = []
while True:
if in_block:
end_index = s.find('*/', i)
if end_index == -1:
break
i = end_index + len('*/')
in_block = False
else:
start_index = s.find('/*', i)
chunk_end = start_index if start_index != -1 else None
# Add found useful code to chunks
chunks.append(s[i:chunk_end])
if start_index == -1:
break
i = start_index + len('/*')
in_block = True
unblocked = ' '.join(chunks)
line_comment_start = unblocked.find('//')
if line_comment_start == -1:
uncommented = unblocked
else:
uncommented = unblocked[:line_comment_start]
if line.raw.endswith('\n') and not uncommented.endswith('\n'):
uncommented += '\n'
line.uncommented = uncommented
self._stripped_comments = True
def start_pos(self, form: 'SourceForm') -> 'SourcePos':
return SourcePos(self, 0, 0, form)
def end_pos(self, form: 'SourceForm') -> 'SourcePos':
return SourcePos(self, -1, len(self.lines[-1].s(form)), form)
@property
def has_uncommented(self) -> bool:
return self._stripped_comments
@property
def stripped_hash(self) -> int:
"""
Gets hash of raw content, before documentation has been
stripped from it.
:rtype: int
"""
if self._raw_hash is None:
if not self._stripped_comments:
self.strip_comments()
self._raw_hash = iter_hash(
line.stripped.strip() # remove newline, etc.
for line in self.lines if line.stripped != '\n')
assert isinstance(self._raw_hash, int)
return self._raw_hash
@property
def component(self) -> 'Block':
"""
Gets Component containing entirety of the source's content.
:return: Block Component
:rtype: Block
"""
if self._component is None:
self._component = Block(self)
assert isinstance(self._component, Block)
return self._component
@staticmethod
def _lines_from_str(content: str) -> ty.List['Line']:
return [Line(i, line_s) for i, line_s in
enumerate(content.splitlines(True))]
@staticmethod
def _lines_from_f(f: ty.TextIO) -> ty.List['Line']:
return [Line(i, line_s) for i, line_s in enumerate(f.readlines())]
class Line:
"""
Data storage class for storing information about a line of source.
"""
def __init__(self, i: int, s: str) -> None:
self.index = i
self.raw = s
self._uncommented: ty.Optional[str] = None
@property
def uncommented(self) -> str:
"""
Since the 'uncommented' value of a Line is set externally,
this property exists to check that it is not accessed before
it has been calculated, to avoid silent failure.
:return: str of uncommented content of line.
"""
if self._uncommented is None:
raise AttributeError(
f'Uncommented value of {repr(self)} has not been set.')
return self._uncommented
@uncommented.setter
def uncommented(self, s: str) -> None:
"""
Used by SourceContent to set Line instance's uncommented str.
:param s: uncommented content str
:return: None
"""
self._uncommented = s
@property
def stripped(self) -> str:
s = ' '.join(self.uncommented.split())
if self.uncommented.endswith('\n'):
s += '\n'
return s
def s(self, form: 'SourceForm') -> str:
"""
Gets line string in the specified form.
:param form: SourceForm; RAW, UNCOMMENTED, or STRIPPED
:return: str of line content.
:rtype: str
:raises ValueError if uncommented form has not been set and
UNCOMMENTED or STRIPPED form is passed as an arg.
"""
if form == SourceForm.RAW:
return self.raw
if form == SourceForm.UNCOMMENTED:
return self.uncommented
if form == SourceForm.STRIPPED:
return self.stripped
def __repr__(self) -> str:
preview_len = 40
# Produces Line[i: index, s: preview + '...' if preview runs over]
return f'Line[i: {self.index}, ' \
f'\'{self.raw[:preview_len]}' \
f'{"..." if len(self.raw) > preview_len else ""}\']'
class SourceForm(enum.Enum):
RAW = 1
UNCOMMENTED = 2
STRIPPED = 3
class SourcePos:
"""
Class storing position within source.
"""
def __init__(
self,
file_content: 'SourceContent',
line_i: int,
col_i: int,
form: 'SourceForm'
) -> None:
self.file_content = file_content
self.form = form
if not self.file_content.has_uncommented and form in (
SourceForm.UNCOMMENTED, SourceForm.STRIPPED):
self.file_content.strip_comments()
self.line_i = self._normalize_line_i(line_i)
col_i = self._normalize_col_i(col_i)
if col_i == len(self.file_content.lines[line_i].s(self.form)) and \
self.line_i < len(self.file_content.lines) - 1:
self.line_i += 1
col_i = 0
self.col_i = col_i
def __add__(self, n: int) -> 'SourcePos':
"""
Produces a new SourcePos object that has a char index n higher
than the SourcePos on which this method was called.
:param n: int
:return: newly created SourcePos.
:raise: ValueError if n is too large (either positive or
negative) to be added to the SourcePos.
"""
if n < 0:
return self - abs(n)
original_n = n
line = self.file_content.lines[self.line_i]
remaining_chars = len(line.s(self.form)) - self.col_i
if n <= remaining_chars:
return SourcePos(
self.file_content,
self.line_i,
self.col_i + n,
self.form
)
else:
n -= remaining_chars
for line in self.file_content.lines[self.line_i + 1:]:
line_chars = len(line.s(self.form))
if n <= line_chars:
return SourcePos(self.file_content, line.index, n, self.form)
n -= line_chars
else:
raise ValueError(
f'Cannot add {original_n} to {self}. '
f'{original_n} is too large.')
def __sub__(self, n: int) -> 'SourcePos':
"""
Produces a new SourcePos object that has a char index n lower
than the SourcePos on which this method was called.
:param n: int
:return: newly created SourcePos.
:raise: ValueError if n is too large (either positive or
negative) to be subtracted from the SourcePos.
"""
if n < 0:
return self + abs(n)
original_n = n
remaining_chars = self.col_i
if n <= remaining_chars:
return SourcePos(
self.file_content,
self.line_i,
self.col_i - n,
self.form
)
else:
n -= remaining_chars
for line in reversed(self.file_content.lines[:self.line_i]):
line_chars = len(line.s(self.form))
if n <= line_chars:
return SourcePos(
self.file_content,
line.index,
line_chars - n,
self.form)
n -= line_chars
else:
raise ValueError(
f'Cannot subtract {original_n} from {self}. '
f'{original_n} is too large.')
def __hash__(self) -> int:
"""
Custom hash for SourcePos that allows equivalent SourcePos
instances to have equal hashes.
:return: int
"""
return hash((self.file_content, self.line_i, self.col_i, self.form))
def __eq__(self, other) -> bool:
try:
return all((
self.file_content == other.file_content,
self.line_i == other.line_i,
self.col_i == other.col_i,
self.form == other.form
))
except AttributeError:
return False
@property
def next_line_pos(self) -> 'SourcePos':
return SourcePos(self.file_content, self.line_i + 1, 0, self.form)
def _normalize_line_i(self, i: int) -> int:
original_i = i
lines = self.file_content.lines
if i < 0:
i += len(lines)
if not 0 <= i < len(lines):
raise IndexError(
f'Line/row index invalid: {original_i}. '
f'{len(lines)} lines exist in {self.file_content}')
return i
def _normalize_col_i(self, i: int) -> int:
original_i = i
line = self.file_content.lines[self.line_i]
line_len = len(line.s(self.form))
if i < 0:
i += line_len
if not 0 <= i <= line_len:
raise IndexError(
f'Column index invalid: {original_i}. '
f'Line {self.line_i} is {line_len} chars long.')
return i
def __repr__(self) -> str:
return f'SourcePos[line: {self.line_i}, col: {self.col_i}]'
class Chunk:
"""
Intermediate class used to store data about code and provide
convenience accessors to help determine what kind of Component(s)
are stored within the Chunk's code.
"""
def __init__(
self,
file_content: 'SourceContent',
start: ty.Optional['SourcePos'] = None,
end: ty.Optional['SourcePos'] = None,
form: 'SourceForm' = SourceForm.STRIPPED
) -> None:
self.file_content = file_content
self.form = form
if not self.file_content.has_uncommented and form in (
SourceForm.UNCOMMENTED, SourceForm.STRIPPED):