CompilerDirectives 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of CompilerDirectives might be problematic. Click here for more details.
- compilerdirectives-1.0.0/LICENSE +19 -0
- compilerdirectives-1.0.0/PKG-INFO +73 -0
- compilerdirectives-1.0.0/README.md +60 -0
- compilerdirectives-1.0.0/pyproject.toml +17 -0
- compilerdirectives-1.0.0/setup.cfg +4 -0
- compilerdirectives-1.0.0/src/CompilerDirectives.egg-info/PKG-INFO +73 -0
- compilerdirectives-1.0.0/src/CompilerDirectives.egg-info/SOURCES.txt +10 -0
- compilerdirectives-1.0.0/src/CompilerDirectives.egg-info/dependency_links.txt +1 -0
- compilerdirectives-1.0.0/src/CompilerDirectives.egg-info/top_level.txt +1 -0
- compilerdirectives-1.0.0/src/CompilerDirectives_NickC_UK/PreProcess.py +243 -0
- compilerdirectives-1.0.0/src/CompilerDirectives_NickC_UK/__init__.py +1 -0
- compilerdirectives-1.0.0/tests/Test.py +9 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2018 The Python Packaging Authority
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: CompilerDirectives
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python pre-proccess compiler directives
|
|
5
|
+
Author-email: Nick Causton <Development@AssociatedData.co.uk>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.15
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# **Pre-process compiler directive**
|
|
15
|
+
|
|
16
|
+
## Normal usage:
|
|
17
|
+
|
|
18
|
+
`import PreProcess
|
|
19
|
+
import Constants # file containing our constant definitions`
|
|
20
|
+
|
|
21
|
+
## Diagnostics:
|
|
22
|
+
|
|
23
|
+
For diagnostic purposes an intermediate modified file can be saved in the `__pycache__` directory by setting the diagnostic variable:
|
|
24
|
+
`DIAG_PY2_SAVE = True`
|
|
25
|
+
The writing of this file is automatically disabled when Python is run with `__debug__` False.
|
|
26
|
+
Setting this to True also enables display of speed testing in the Python Console.
|
|
27
|
+
This can be either done before the import:
|
|
28
|
+
`DIAG_PY2_SAVE = True
|
|
29
|
+
import PreProcess`
|
|
30
|
+
Or after:
|
|
31
|
+
`import PreProcess
|
|
32
|
+
PreProcess.PreProcess.DIAG_PY2_SAVE = True`
|
|
33
|
+
|
|
34
|
+
## Compiler directives:
|
|
35
|
+
|
|
36
|
+
Define constant
|
|
37
|
+
`#DEFINE / #DEF <const> <value> `
|
|
38
|
+
Undefine constant
|
|
39
|
+
`#UNDEF <const>`
|
|
40
|
+
Compile time conditionals
|
|
41
|
+
`#IF <expr> / #ELIF <expr> / #ENDIF `
|
|
42
|
+
Compile time definition conditionals
|
|
43
|
+
`#IFDEF <expr> / #IFNDEF <expr> / #ENDIF `
|
|
44
|
+
Include file
|
|
45
|
+
`#INCLUDE <file>`
|
|
46
|
+
‘Compile’ time expression evaluation, remove ‘#COMP’ from resulting line
|
|
47
|
+
`#COMP <expr>`
|
|
48
|
+
Multiple items can be included on the same line delimited by ‘,’ (comma):
|
|
49
|
+
`#DEF <const1> <value1>, <const2> <value2>
|
|
50
|
+
#UNDEF <const1>, <const2>
|
|
51
|
+
#INCLUDE <file1>, <file2>`
|
|
52
|
+
|
|
53
|
+
## Constant replacement:
|
|
54
|
+
|
|
55
|
+
After PreProcess is imported all further imports will be subject to replacement of their Constants with their respective values if previously defined.
|
|
56
|
+
All files imported can contain further constant definitions and un-definitions which will be added to / removed from the application level ‘global’ Constants list.
|
|
57
|
+
Constant replacement will happen only once for each import with the resulting byte-code being saved in the *.pyc `__pycache__ `file. When a modified file is imported which contains any compiler directives all *.pyc files in the `__pycache__` directory older than that imported file will be deleted so as to force their re-compilation the next time they are accessed.
|
|
58
|
+
|
|
59
|
+
## Development:
|
|
60
|
+
|
|
61
|
+
For development purposes the following can be used to remove all earlier *.pyc files than whenever the test module is modified so that these get recreated and pre-processed.:
|
|
62
|
+
`import PreProcess
|
|
63
|
+
PreProcess.stale_pyc_del(__file__)
|
|
64
|
+
`
|
|
65
|
+
Alternatively to remove all earlier *.pyc files on each run so that Pre-Process runs every time regardless of whether the test module is modified or not pass just the directory.:
|
|
66
|
+
`import os
|
|
67
|
+
import PreProcess
|
|
68
|
+
PreProcess.PreProcess.stale_pyc_del(os.path.dirname(__file__))`
|
|
69
|
+
|
|
70
|
+
## Known issue:
|
|
71
|
+
|
|
72
|
+
There is a known issue with `tokenize.tokenize` not indenting & dedenting correctly when a `#CompilerDirective` (comment) is the first line after aforementioned indentation change.
|
|
73
|
+
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# **Pre-process compiler directive**
|
|
2
|
+
|
|
3
|
+
## Normal usage:
|
|
4
|
+
|
|
5
|
+
`import PreProcess
|
|
6
|
+
import Constants # file containing our constant definitions`
|
|
7
|
+
|
|
8
|
+
## Diagnostics:
|
|
9
|
+
|
|
10
|
+
For diagnostic purposes an intermediate modified file can be saved in the `__pycache__` directory by setting the diagnostic variable:
|
|
11
|
+
`DIAG_PY2_SAVE = True`
|
|
12
|
+
The writing of this file is automatically disabled when Python is run with `__debug__` False.
|
|
13
|
+
Setting this to True also enables display of speed testing in the Python Console.
|
|
14
|
+
This can be either done before the import:
|
|
15
|
+
`DIAG_PY2_SAVE = True
|
|
16
|
+
import PreProcess`
|
|
17
|
+
Or after:
|
|
18
|
+
`import PreProcess
|
|
19
|
+
PreProcess.PreProcess.DIAG_PY2_SAVE = True`
|
|
20
|
+
|
|
21
|
+
## Compiler directives:
|
|
22
|
+
|
|
23
|
+
Define constant
|
|
24
|
+
`#DEFINE / #DEF <const> <value> `
|
|
25
|
+
Undefine constant
|
|
26
|
+
`#UNDEF <const>`
|
|
27
|
+
Compile time conditionals
|
|
28
|
+
`#IF <expr> / #ELIF <expr> / #ENDIF `
|
|
29
|
+
Compile time definition conditionals
|
|
30
|
+
`#IFDEF <expr> / #IFNDEF <expr> / #ENDIF `
|
|
31
|
+
Include file
|
|
32
|
+
`#INCLUDE <file>`
|
|
33
|
+
‘Compile’ time expression evaluation, remove ‘#COMP’ from resulting line
|
|
34
|
+
`#COMP <expr>`
|
|
35
|
+
Multiple items can be included on the same line delimited by ‘,’ (comma):
|
|
36
|
+
`#DEF <const1> <value1>, <const2> <value2>
|
|
37
|
+
#UNDEF <const1>, <const2>
|
|
38
|
+
#INCLUDE <file1>, <file2>`
|
|
39
|
+
|
|
40
|
+
## Constant replacement:
|
|
41
|
+
|
|
42
|
+
After PreProcess is imported all further imports will be subject to replacement of their Constants with their respective values if previously defined.
|
|
43
|
+
All files imported can contain further constant definitions and un-definitions which will be added to / removed from the application level ‘global’ Constants list.
|
|
44
|
+
Constant replacement will happen only once for each import with the resulting byte-code being saved in the *.pyc `__pycache__ `file. When a modified file is imported which contains any compiler directives all *.pyc files in the `__pycache__` directory older than that imported file will be deleted so as to force their re-compilation the next time they are accessed.
|
|
45
|
+
|
|
46
|
+
## Development:
|
|
47
|
+
|
|
48
|
+
For development purposes the following can be used to remove all earlier *.pyc files than whenever the test module is modified so that these get recreated and pre-processed.:
|
|
49
|
+
`import PreProcess
|
|
50
|
+
PreProcess.stale_pyc_del(__file__)
|
|
51
|
+
`
|
|
52
|
+
Alternatively to remove all earlier *.pyc files on each run so that Pre-Process runs every time regardless of whether the test module is modified or not pass just the directory.:
|
|
53
|
+
`import os
|
|
54
|
+
import PreProcess
|
|
55
|
+
PreProcess.PreProcess.stale_pyc_del(os.path.dirname(__file__))`
|
|
56
|
+
|
|
57
|
+
## Known issue:
|
|
58
|
+
|
|
59
|
+
There is a known issue with `tokenize.tokenize` not indenting & dedenting correctly when a `#CompilerDirective` (comment) is the first line after aforementioned indentation change.
|
|
60
|
+
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "CompilerDirectives"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
authors = [
|
|
5
|
+
{ name="Nick Causton", email="Development@AssociatedData.co.uk" },
|
|
6
|
+
]
|
|
7
|
+
description = "Python pre-proccess compiler directives"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.15"
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Operating System :: OS Independent",
|
|
13
|
+
]
|
|
14
|
+
license = "MIT"
|
|
15
|
+
license-files = ["LICEN[CS]E*"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: CompilerDirectives
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python pre-proccess compiler directives
|
|
5
|
+
Author-email: Nick Causton <Development@AssociatedData.co.uk>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.15
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# **Pre-process compiler directive**
|
|
15
|
+
|
|
16
|
+
## Normal usage:
|
|
17
|
+
|
|
18
|
+
`import PreProcess
|
|
19
|
+
import Constants # file containing our constant definitions`
|
|
20
|
+
|
|
21
|
+
## Diagnostics:
|
|
22
|
+
|
|
23
|
+
For diagnostic purposes an intermediate modified file can be saved in the `__pycache__` directory by setting the diagnostic variable:
|
|
24
|
+
`DIAG_PY2_SAVE = True`
|
|
25
|
+
The writing of this file is automatically disabled when Python is run with `__debug__` False.
|
|
26
|
+
Setting this to True also enables display of speed testing in the Python Console.
|
|
27
|
+
This can be either done before the import:
|
|
28
|
+
`DIAG_PY2_SAVE = True
|
|
29
|
+
import PreProcess`
|
|
30
|
+
Or after:
|
|
31
|
+
`import PreProcess
|
|
32
|
+
PreProcess.PreProcess.DIAG_PY2_SAVE = True`
|
|
33
|
+
|
|
34
|
+
## Compiler directives:
|
|
35
|
+
|
|
36
|
+
Define constant
|
|
37
|
+
`#DEFINE / #DEF <const> <value> `
|
|
38
|
+
Undefine constant
|
|
39
|
+
`#UNDEF <const>`
|
|
40
|
+
Compile time conditionals
|
|
41
|
+
`#IF <expr> / #ELIF <expr> / #ENDIF `
|
|
42
|
+
Compile time definition conditionals
|
|
43
|
+
`#IFDEF <expr> / #IFNDEF <expr> / #ENDIF `
|
|
44
|
+
Include file
|
|
45
|
+
`#INCLUDE <file>`
|
|
46
|
+
‘Compile’ time expression evaluation, remove ‘#COMP’ from resulting line
|
|
47
|
+
`#COMP <expr>`
|
|
48
|
+
Multiple items can be included on the same line delimited by ‘,’ (comma):
|
|
49
|
+
`#DEF <const1> <value1>, <const2> <value2>
|
|
50
|
+
#UNDEF <const1>, <const2>
|
|
51
|
+
#INCLUDE <file1>, <file2>`
|
|
52
|
+
|
|
53
|
+
## Constant replacement:
|
|
54
|
+
|
|
55
|
+
After PreProcess is imported all further imports will be subject to replacement of their Constants with their respective values if previously defined.
|
|
56
|
+
All files imported can contain further constant definitions and un-definitions which will be added to / removed from the application level ‘global’ Constants list.
|
|
57
|
+
Constant replacement will happen only once for each import with the resulting byte-code being saved in the *.pyc `__pycache__ `file. When a modified file is imported which contains any compiler directives all *.pyc files in the `__pycache__` directory older than that imported file will be deleted so as to force their re-compilation the next time they are accessed.
|
|
58
|
+
|
|
59
|
+
## Development:
|
|
60
|
+
|
|
61
|
+
For development purposes the following can be used to remove all earlier *.pyc files than whenever the test module is modified so that these get recreated and pre-processed.:
|
|
62
|
+
`import PreProcess
|
|
63
|
+
PreProcess.stale_pyc_del(__file__)
|
|
64
|
+
`
|
|
65
|
+
Alternatively to remove all earlier *.pyc files on each run so that Pre-Process runs every time regardless of whether the test module is modified or not pass just the directory.:
|
|
66
|
+
`import os
|
|
67
|
+
import PreProcess
|
|
68
|
+
PreProcess.PreProcess.stale_pyc_del(os.path.dirname(__file__))`
|
|
69
|
+
|
|
70
|
+
## Known issue:
|
|
71
|
+
|
|
72
|
+
There is a known issue with `tokenize.tokenize` not indenting & dedenting correctly when a `#CompilerDirective` (comment) is the first line after aforementioned indentation change.
|
|
73
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/CompilerDirectives.egg-info/PKG-INFO
|
|
5
|
+
src/CompilerDirectives.egg-info/SOURCES.txt
|
|
6
|
+
src/CompilerDirectives.egg-info/dependency_links.txt
|
|
7
|
+
src/CompilerDirectives.egg-info/top_level.txt
|
|
8
|
+
src/CompilerDirectives_NickC_UK/PreProcess.py
|
|
9
|
+
src/CompilerDirectives_NickC_UK/__init__.py
|
|
10
|
+
tests/Test.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
CompilerDirectives_NickC_UK
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import tokenize as t
|
|
2
|
+
from io import BytesIO, StringIO
|
|
3
|
+
|
|
4
|
+
import sys
|
|
5
|
+
lazy import os, ast, textwrap
|
|
6
|
+
from importlib.machinery import SourceFileLoader, FileFinder
|
|
7
|
+
|
|
8
|
+
TYPE_CHECKING = __debug__
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from types import CodeType, FrameLocalsProxyType
|
|
11
|
+
from collections.abc import Buffer
|
|
12
|
+
from typing import Any, Generator
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_caller() -> FrameLocalsProxyType | dict[str, Any]:
|
|
16
|
+
try:
|
|
17
|
+
frame = sys._getframe(15) # PreProcess imported from Package
|
|
18
|
+
if "importlib" not in frame.f_globals.get("__name__") == "__main__" and "__init__" not in frame.f_globals.get('__file__', ""):
|
|
19
|
+
return frame.f_locals
|
|
20
|
+
else:
|
|
21
|
+
raise ValueError
|
|
22
|
+
except ValueError:
|
|
23
|
+
try:
|
|
24
|
+
frame = sys._getframe(7) # PreProcess imported dfirectly as file
|
|
25
|
+
if "importlib" not in frame.f_globals.get("__name__") == "__main__" and "__init__" not in frame.f_globals.get('__file__', ""):
|
|
26
|
+
return frame.f_locals
|
|
27
|
+
else:
|
|
28
|
+
raise ValueError
|
|
29
|
+
except ValueError:
|
|
30
|
+
frame = sys._getframe(2)
|
|
31
|
+
try:
|
|
32
|
+
while "importlib" in frame.f_globals.get('__name__', "") or "__init__" in frame.f_globals.get('__file__', ""):
|
|
33
|
+
frame = frame.f_back
|
|
34
|
+
return frame.f_locals
|
|
35
|
+
except ValueError:
|
|
36
|
+
return {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
caller = get_caller()
|
|
40
|
+
DIAG_PY2_SAVE = caller["DIAG_PY2_SAVE"] if "DIAG_PY2_SAVE" in caller and __debug__ else False
|
|
41
|
+
if DIAG_PY2_SAVE:
|
|
42
|
+
import time
|
|
43
|
+
start = time.perf_counter()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
__consts__: dict[str, str | int | float] = {}
|
|
47
|
+
last_spd = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def stale_pyc_del(path: str) -> None:
|
|
51
|
+
spd_start = time.perf_counter()
|
|
52
|
+
global last_spd
|
|
53
|
+
if last_spd is None or time.time() > last_spd + 10:
|
|
54
|
+
if os.path.isdir(path): # path = directory
|
|
55
|
+
pycache_dir = path + "\\__pycache__"
|
|
56
|
+
cutoff_time = time.time()
|
|
57
|
+
else: # path = file
|
|
58
|
+
pycache_dir = os.path.dirname(path) + "\\__pycache__"
|
|
59
|
+
cutoff_time = os.path.getmtime(path)
|
|
60
|
+
last_spd = time.time()
|
|
61
|
+
if os.path.isdir(pycache_dir):
|
|
62
|
+
for root, dirs, files in os.walk(pycache_dir):
|
|
63
|
+
for file in files:
|
|
64
|
+
if file.endswith('.pyc') and (os.path.getmtime(filepath := root + "\\" + file)) < cutoff_time:
|
|
65
|
+
os.remove(filepath)
|
|
66
|
+
spd_end = time.perf_counter()
|
|
67
|
+
print("stale_pyc_del:", os.path.basename(path), "-", f"{((spd_end - spd_start) * 1000):.3f}", "ms")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def process_toks(orig_toks: Generator[t.TokenInfo, None, None], path: str) -> list[t.TokenInfo]:
|
|
71
|
+
global __consts__
|
|
72
|
+
if_exclude = False
|
|
73
|
+
if_fulfilled = None
|
|
74
|
+
modi_toks = []
|
|
75
|
+
drct_found = None
|
|
76
|
+
|
|
77
|
+
def split2str(in_str: str, split_str: str = " ") -> tuple[str, str]:
|
|
78
|
+
pos = in_str.find(split_str)
|
|
79
|
+
if pos != -1:
|
|
80
|
+
return in_str[:pos], in_str[pos + len(split_str):].lstrip()
|
|
81
|
+
else:
|
|
82
|
+
return in_str, ""
|
|
83
|
+
|
|
84
|
+
def remove_prefixes(in_str: str) -> str:
|
|
85
|
+
return in_str.removeprefix('"').removesuffix('"').removeprefix("'").removesuffix("'")
|
|
86
|
+
|
|
87
|
+
def replace_constant(token: t.TokenInfo) -> tuple[Any, str | int | float]:
|
|
88
|
+
global __consts__
|
|
89
|
+
new_type = token.type
|
|
90
|
+
new_str = token.string
|
|
91
|
+
if new_str in __consts__:
|
|
92
|
+
repl_val = __consts__[new_str]
|
|
93
|
+
if type(repl_val) in (int, float, complex):
|
|
94
|
+
new_type = t.NUMBER
|
|
95
|
+
new_str = str(repl_val)
|
|
96
|
+
else:
|
|
97
|
+
new_type = t.STRING
|
|
98
|
+
new_str = '"' + str(repl_val) + '"'
|
|
99
|
+
return new_type, new_str
|
|
100
|
+
|
|
101
|
+
def indent(in_str: str, pad) -> str:
|
|
102
|
+
return (pad + in_str.replace("\n", "\n" + pad)).rstrip(pad)
|
|
103
|
+
|
|
104
|
+
drct_found = None
|
|
105
|
+
for tok in orig_toks:
|
|
106
|
+
tok_type = tok.type
|
|
107
|
+
tok_str = tok.string
|
|
108
|
+
lstrip_line = tok.line.lstrip()
|
|
109
|
+
start_if_exclude = if_exclude
|
|
110
|
+
incl_toks = []
|
|
111
|
+
match tok.type:
|
|
112
|
+
case t.COMMENT if lstrip_line[0] == "#" and lstrip_line[1] != " ":
|
|
113
|
+
tok_drct_found = True
|
|
114
|
+
drct, args = split2str(tok_str)
|
|
115
|
+
match drct.upper():
|
|
116
|
+
case "#IFDEF":
|
|
117
|
+
if args in __consts__:
|
|
118
|
+
if_exclude = False; if_fulfilled = True
|
|
119
|
+
else:
|
|
120
|
+
if_exclude = True; if_fulfilled = False
|
|
121
|
+
case "#IFNDEF":
|
|
122
|
+
if args not in __consts__:
|
|
123
|
+
if_exclude = False; if_fulfilled = True
|
|
124
|
+
else:
|
|
125
|
+
if_exclude = True; if_fulfilled = False
|
|
126
|
+
case "#IF":
|
|
127
|
+
if args and eval(args):
|
|
128
|
+
if_exclude = False; if_fulfilled = True
|
|
129
|
+
else:
|
|
130
|
+
if_exclude = True; if_fulfilled = False
|
|
131
|
+
case "#ELIF":
|
|
132
|
+
if if_fulfilled:
|
|
133
|
+
if_exclude = True
|
|
134
|
+
else:
|
|
135
|
+
if args and eval(args):
|
|
136
|
+
if_exclude = False; if_fulfilled = True
|
|
137
|
+
else:
|
|
138
|
+
if_exclude = True; if_fulfilled = False
|
|
139
|
+
case "#ELSE":
|
|
140
|
+
if if_fulfilled:
|
|
141
|
+
if_exclude = True
|
|
142
|
+
else:
|
|
143
|
+
if_exclude = False
|
|
144
|
+
case "#ENDIF":
|
|
145
|
+
if_exclude = False; if_fulfilled = None
|
|
146
|
+
case _:
|
|
147
|
+
if not if_exclude:
|
|
148
|
+
match drct.upper():
|
|
149
|
+
case "#DEFINE" | '#DEF':
|
|
150
|
+
for pair in args.split(",") if args else []:
|
|
151
|
+
var, val = pair.split()
|
|
152
|
+
__consts__[var] = ast.literal_eval(val)
|
|
153
|
+
case "#UNDEF":
|
|
154
|
+
for var in args.split(",") if args else []:
|
|
155
|
+
var = var.lstrip()
|
|
156
|
+
if var in __consts__:
|
|
157
|
+
del __consts__[var]
|
|
158
|
+
case "#COMP":
|
|
159
|
+
modi_expr_toks = []
|
|
160
|
+
expr_toks = t.generate_tokens(StringIO(args).readline)
|
|
161
|
+
for expr_tok in expr_toks:
|
|
162
|
+
expr_tok_type = expr_tok.type
|
|
163
|
+
expr_tok_str = expr_tok.string
|
|
164
|
+
if expr_tok_type == t.NAME:
|
|
165
|
+
expr_tok_type, expr_tok_str = replace_constant(expr_tok)
|
|
166
|
+
modi_expr_toks.append((expr_tok_type, expr_tok_str))
|
|
167
|
+
new_expr = t.untokenize(modi_expr_toks)
|
|
168
|
+
try:
|
|
169
|
+
tok_str = eval(new_expr)
|
|
170
|
+
except (Exception, ):
|
|
171
|
+
tok_str = new_expr
|
|
172
|
+
|
|
173
|
+
case "#INCLUDE" | '#INCL':
|
|
174
|
+
padding = tok.line.find("#")
|
|
175
|
+
for file in args.split(","):
|
|
176
|
+
file = (remove_prefixes(file.strip()))
|
|
177
|
+
if os.path.exists(file):
|
|
178
|
+
with t.open(file) as f: # tokenizes as text mode not bytes
|
|
179
|
+
new_source = f.read()
|
|
180
|
+
if padding and padding != -1: # padding
|
|
181
|
+
new_source = indent(new_source, " " * padding)
|
|
182
|
+
end = time.perf_counter()
|
|
183
|
+
file_toks = t.generate_tokens(StringIO(new_source).readline)
|
|
184
|
+
new_toks = process_toks(file_toks, file)
|
|
185
|
+
incl_toks += new_toks
|
|
186
|
+
case _: # non-directive comment
|
|
187
|
+
tok_drct_found = False
|
|
188
|
+
if tok_drct_found:
|
|
189
|
+
drct_found = True
|
|
190
|
+
case t.NAME if not if_exclude:
|
|
191
|
+
tok_type, tok_str = replace_constant(tok)
|
|
192
|
+
case _: # tok is not compiler directive
|
|
193
|
+
pass
|
|
194
|
+
if not if_exclude: # include
|
|
195
|
+
modi_toks.append((tok_type, tok_str))
|
|
196
|
+
if incl_toks:
|
|
197
|
+
modi_toks.append((t.NEWLINE, '\r\n')); modi_toks.extend(incl_toks)
|
|
198
|
+
elif start_if_exclude != if_exclude: # exclude but include/exclude has changed so for diags include the line which changed it
|
|
199
|
+
modi_toks.append((tok.type, tok_str)); modi_toks.append((t.NEWLINE, '\r\n'))
|
|
200
|
+
if drct_found:
|
|
201
|
+
stale_pyc_del(path)
|
|
202
|
+
return modi_toks
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def pre_process(
|
|
206
|
+
data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
|
|
207
|
+
path: str) -> str:
|
|
208
|
+
if DIAG_PY2_SAVE:
|
|
209
|
+
start = time.perf_counter()
|
|
210
|
+
global __consts__
|
|
211
|
+
if isinstance(data, Buffer):
|
|
212
|
+
orig_toks = t.tokenize(BytesIO(data).readline)
|
|
213
|
+
modi_toks = process_toks(orig_toks, path)
|
|
214
|
+
new_source = t.untokenize(modi_toks)
|
|
215
|
+
if DIAG_PY2_SAVE:
|
|
216
|
+
end = time.perf_counter()
|
|
217
|
+
print("Preprocess:", os.path.basename(path), "-", f"{((end-start)*1000):.3f}","ms")
|
|
218
|
+
pos = path.rfind("\\")
|
|
219
|
+
py2_file = path[:pos+1] + "__pycache__" + path[pos:] + sys.implementation.cache_tag + ".py2"
|
|
220
|
+
if not os.path.exists(py2_file):
|
|
221
|
+
directory = os.path.dirname(py2_file)
|
|
222
|
+
if directory: # Prevents an error if filepath is just a filename in the current folder
|
|
223
|
+
os.makedirs(directory, exist_ok=True)
|
|
224
|
+
with open(py2_file, "w") as f:
|
|
225
|
+
f.write(new_source.decode())
|
|
226
|
+
return new_source
|
|
227
|
+
return ""
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class PreProcessLoader(SourceFileLoader): # SourceLoader
|
|
231
|
+
def source_to_code(self,
|
|
232
|
+
data: Buffer | str | ast.Module | ast.Expression | ast.Interactive,
|
|
233
|
+
path: bytes | str | os.PathLike[str],
|
|
234
|
+
fullname: str | None = None, *, _optimize: int = -1) -> CodeType:
|
|
235
|
+
return super().source_to_code(pre_process(data, os.fsdecode(path)), path, fullname, _optimize=_optimize)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
sys.path_hooks.insert(0, FileFinder.path_hook( (PreProcessLoader, [".py"]) ))
|
|
239
|
+
sys.path_importer_cache.clear()
|
|
240
|
+
|
|
241
|
+
if __name__ == "__main__":
|
|
242
|
+
# invalidate_caches()
|
|
243
|
+
stale_pyc_del()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import PreProcess
|