Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#194 define Preprocessor #262

Open
wants to merge 57 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
e0e714c
#194 define preprocessor
himaanisrivatsava Jan 5, 2025
508425b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
f4c8ec1
#194 define preprocessor
himaanisrivatsava Jan 5, 2025
c7352c5
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
61aff97
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
b5b55a3
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
06c0797
Merge branch 'main' into preprocessor
himaanisrivatsava Jan 5, 2025
fa8e638
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
4a726e9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
a9e1657
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
9414a1e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
64a4d12
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
7464515
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
c218488
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
d81c378
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
555b23e
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
89015e8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
a9c8db0
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
59b2d89
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
4b8a770
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
c842395
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
4331fc8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
9f195fb
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
ef44bbd
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
107f040
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
42b334f
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
ef58756
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
5c6adb0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
962c7ca
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
455629a
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
7ed60e3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
90f443c
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
a3f29c8
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
fb59300
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
bbdf765
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
3957917
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
d380521
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
b197339
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
2808ec6
#194 define preprocessor .... #'commit30?
himaanisrivatsava Jan 5, 2025
ef91086
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
1997294
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
1832d69
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 5, 2025
08fea6f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 5, 2025
e88e79d
Update test_preprocessor.py
himaanisrivatsava Jan 5, 2025
f30648c
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 6, 2025
2dac541
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 6, 2025
d576ecb
Delete test_preprocessor.py
himaanisrivatsava Jan 13, 2025
0696956
Create test_preprocessor.py
himaanisrivatsava Jan 13, 2025
55f8af3
Update test_preprocessor.py
himaanisrivatsava Jan 13, 2025
6121a87
Update test_preprocessor.py
himaanisrivatsava Jan 13, 2025
603f452
Update test_preprocessor.py
himaanisrivatsava Jan 13, 2025
39f1eb3
Update test_preprocessor.py
himaanisrivatsava Jan 13, 2025
eda2117
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 13, 2025
d1c788f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 13, 2025
add50e2
trial #2
himaanisrivatsava Jan 13, 2025
8554778
Merge branch 'preprocessor' of https://github.com/himaanisrivatsava/c…
himaanisrivatsava Jan 13, 2025
dad62ed
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 13, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions crosstl/backend/DirectX/DirectxCrossGLCodeGen.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,24 @@ def __init__(self):
"SV_DEPTH7": "gl_FragDepth7",
}

def convert(self, ast):

# Converts the provided AST to target GLSL code.

code = []
for node in ast.nodes:
if isinstance(node, IncludeNode):
code.append(self.handle_include_node(node))
# Handle other nodes with existing logic
else:
code.append(self.generate_function(node))
return "\n".join(code)

def handle_include_node(self, node):

# Handles `IncludeNode` specific conversion.
return f"// Included file: {node.path}"

def generate(self, ast):
code = "shader main {\n"
# Generate structs
Expand Down
8 changes: 6 additions & 2 deletions crosstl/backend/DirectX/DirectxLexer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
from typing import Iterator, Tuple, List
from .DirectxPreprocessor import DirectxPreprocessor

# using sets for faster lookup
SKIP_TOKENS = {"WHITESPACE", "COMMENT_SINGLE", "COMMENT_MULTI"}
Expand Down Expand Up @@ -111,9 +112,12 @@

class HLSLLexer:
def __init__(self, code: str):
# Integrating the preprocessor
preprocessor = DirectxPreprocessor()
self.code = preprocessor.preprocess(code)

self._token_patterns = [(name, re.compile(pattern)) for name, pattern in TOKENS]
self.code = code
self._length = len(code)
self._length = len(self.code)

def tokenize(self) -> List[Tuple[str, str]]:
# tokenize the input code and return list of tokens
Expand Down
72 changes: 72 additions & 0 deletions crosstl/backend/DirectX/DirectxPreprocessor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import os


class DirectxPreprocessor:
def __init__(self):
self.macros = {}
self.condition_stack = []

def preprocess(self, code):
# Preprocess the input HLSL shader code.
lines = code.splitlines()
processed_lines = []
skip_lines = False

for line in lines:
stripped_line = line.strip()

if stripped_line.startswith("#include"):
processed_lines.append(self.handle_include(stripped_line))
elif stripped_line.startswith("#define"):
self.handle_define(stripped_line)
elif stripped_line.startswith("#ifdef"):
skip_lines = not self.handle_ifdef(stripped_line)
elif stripped_line.startswith("#endif"):
skip_lines = self.handle_endif()
elif stripped_line.startswith("#else"):
skip_lines = not skip_lines
elif not skip_lines:
processed_lines.append(self.expand_macros(line))

return "\n".join(processed_lines)

def handle_include(self, line):
# Handle #include directive.
file_path = line.split()[1].strip('"<>"')
if not os.path.exists(file_path):
raise FileNotFoundError(f"Included file '{file_path}' not found.")
with open(file_path, "r") as file:
return file.read()

def handle_define(self, line):
# Handle #define directive.
parts = line.split(maxsplit=2)
if len(parts) == 3:
self.macros[parts[1]] = parts[2]
else:
self.macros[parts[1]] = ""

def handle_ifdef(self, line):
# Handle #ifdef directive.
macro = line.split(maxsplit=1)[1]
is_defined = macro in self.macros
self.condition_stack.append(is_defined)
return is_defined

def handle_endif(self):
# Handle #endif directive.
if not self.condition_stack:
raise SyntaxError("#endif without matching #ifdef")
self.condition_stack.pop()
return False if self.condition_stack and not self.condition_stack[-1] else True

def expand_macros(self, line):
# Expand defined macros in the line.
for macro, value in self.macros.items():
line = line.replace(macro, value)

# Check for undefined macros.
if any(macro not in self.macros for macro in line.split()):
raise ValueError(f"Undefined macro encountered in line: {line}")

return line
9 changes: 9 additions & 0 deletions crosstl/backend/DirectX/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
from .DirectxLexer import HLSLLexer
from .DirectxParser import HLSLParser
from .DirectxCrossGLCodeGen import HLSLToCrossGLConverter


def process_shader(shader_code):
lexer = HLSLLexer(shader_code)
tokens = lexer.tokenize()
parser = HLSLParser(tokens)
ast = parser.parse()
converter = HLSLToCrossGLConverter()
return converter.convert(ast)
112 changes: 112 additions & 0 deletions tests/test_backend/test_directx/test_preprocessor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import unittest
from crosstl.backend.DirectX.DirectxPreprocessor import DirectxPreprocessor


class TestDirectxPreprocessor(unittest.TestCase):

def test_preprocessor_with_defines_and_ifdef(self):
shader_code = """
#define PI 3.14159
#define DEBUG 1

#ifdef DEBUG
float debugValue = 1.0;
#else
float debugValue = 0.0;
#endif

float computeCircleArea(float radius) {
return PI * radius * radius;
}
"""

expected_output = """
float debugValue = 1.0;

float computeCircleArea(float radius) {
return 3.14159 * radius * radius;
}
"""

preprocessor = DirectxPreprocessor()
result = preprocessor.preprocess(shader_code)

# Clean up the result by stripping leading/trailing whitespace for easier comparison
result = result.strip()
expected_output = expected_output.strip()

self.assertEqual(result, expected_output)

def test_preprocessor_with_no_debug(self):
shader_code = """
#define PI 3.14159
#undef DEBUG

#ifdef DEBUG
float debugValue = 1.0;
#else
float debugValue = 0.0;
#endif

float computeCircleArea(float radius) {
return PI * radius * radius;
}
"""

expected_output = """
float debugValue = 0.0;

float computeCircleArea(float radius) {
return 3.14159 * radius * radius;
}
"""

preprocessor = DirectxPreprocessor()
result = preprocessor.preprocess(shader_code)

result = result.strip()
expected_output = expected_output.strip()

self.assertEqual(result, expected_output)

def test_preprocessor_without_include(self):
shader_code = """
#define PI 3.14159

float computeCircleArea(float radius) {
return PI * radius * radius;
}
"""

expected_output = """
float computeCircleArea(float radius) {
return 3.14159 * radius * radius;
}
"""

preprocessor = DirectxPreprocessor()
result = preprocessor.preprocess(shader_code)

result = result.strip()
expected_output = expected_output.strip()

self.assertEqual(result, expected_output)

def test_preprocessor_with_invalid_include(self):
shader_code = """
#include "common.h"
#define PI 3.14159

float computeCircleArea(float radius) {
return PI * radius * radius;
}
"""

preprocessor = DirectxPreprocessor()

with self.assertRaises(FileNotFoundError):
preprocessor.preprocess(shader_code)


if __name__ == "__main__":
unittest.main()
Loading