Coverage for jinja2_async_environment/compiler_modules/patterns.py: 100%

1"""Pre-compiled regex patterns for template compilation optimization."""

2

3 import re

4

5

6 class CompiledPatterns:

7 """Pre-compiled regex patterns for template compilation optimization."""

8

9 # Pattern for async yield detection

10 ASYNC_YIELD_PATTERN = re.compile( # REGEX OK: template compilation optimization

11 r"async for event in self\._async_yield_from\([^)]+\):\s*$", re.MULTILINE

12 )

13

14 # Pattern for undefined variable detection

15 UNDEFINED_VAR_PATTERN = re.compile( # REGEX OK: template compilation optimization

16 r"undefined\(name='([^']+)'\) if l_0_\1 is missing else l_0_\1"

17 )

18

19 # Pattern for loop variable optimization

20 LOOP_VAR_PATTERN = re.compile(

21 r"l_0_(\w+)"

22 ) # REGEX OK: template compilation optimization

23

24 # Pattern for context block detection

25 CONTEXT_BLOCK_PATTERN = re.compile(

26 r"yield from context\.blocks"

27 ) # REGEX OK: template compilation optimization

28

29 # Additional performance patterns

30 HASATTR_CHECK_PATTERN = re.compile(

31 r"hasattr\(([^,]+),\s*'__await__'\)"

32 ) # REGEX OK: template compilation optimization

33 AUTO_AITER_PATTERN = re.compile(

34 r"auto_aiter\(([^)]+)\)"

35 ) # REGEX OK: template compilation optimization

36 TEMPLATE_RUNTIME_ERROR_PATTERN = re.compile(

37 r'TemplateRuntimeError\("([^"]+)"\)'

38 ) # REGEX OK: template compilation optimization

39 DUPLICATE_IMPORT_PATTERN = re.compile(

40 r"^from ([\w.]+) import (.+)$", re.MULTILINE

41 ) # REGEX OK: template compilation optimization

42 REDUNDANT_ESCAPE_PATTERN = re.compile(

43 r"escape\(escape\(([^)]+)\)\)"

44 ) # REGEX OK: template compilation optimization

45 CONSTANT_UNDEFINED_PATTERN = re.compile(

46 r"undefined\(name=None\)"

47 ) # REGEX OK: template compilation optimization

48

49 # Cached import statements for faster code generation

50 _CACHED_IMPORTS = {

51 "runtime": "from jinja2.runtime import Undefined, Macro, missing, LoopContext, AsyncLoopContext, auto_aiter, Namespace, TemplateRuntimeError",

52 "markupsafe": "from markupsafe import escape",

53 "defaults": "from jinja2.defaults import DEFAULT_FILTERS",

54 }

55

56 @classmethod

57 def get_optimized_imports(cls) -> str:

58 """Return optimized import statements as a single string."""

59 return "\n".join(cls._CACHED_IMPORTS.values())

60

61 @classmethod

62 def optimize_generated_code(cls, code: str) -> str:

63 """Apply pattern-based optimizations to generated template code."""

64 optimized_code = code

65

66 # Fast string replacements for common patterns

67 optimizations = [

68 ("yield from context.blocks", "pass # yield from replaced"),

69 # NOTE: Do NOT optimize away "undefined(name='x') if l_0_x is missing else l_0_x"

70 # This pattern is CRITICAL for proper undefined variable handling

71 ("undefined(name=None)", "Undefined()"),

72 ("escape(escape(", "escape("), # Remove double escaping

73 (

74 "if hasattr(value, '__await__'):\n return await value\nelse:\n return value",

75 "return await value if hasattr(value, '__await__') else value",

76 ),

77 ]

78

79 for pattern, replacement in optimizations:

80 optimized_code = optimized_code.replace(pattern, replacement)

81

82 # Use regex patterns for more complex optimizations

83 optimized_code = cls._optimize_with_regex(optimized_code)

84

85 # Remove duplicate imports

86 optimized_code = cls._deduplicate_imports(optimized_code)

87

88 return optimized_code

89

90 @classmethod

91 def _optimize_with_regex(cls, code: str) -> str:

92 """Apply regex-based optimizations."""

93

94 # Optimize hasattr checks

95 def optimize_hasattr(match: re.Match[str]) -> str:

96 var = match.group(1)

97 return f"getattr({var}, '__await__', None) is not None"

98

99 code = cls.HASATTR_CHECK_PATTERN.sub(optimize_hasattr, code)

100

101 # Remove redundant escape calls

102 code = cls.REDUNDANT_ESCAPE_PATTERN.sub(r"escape(\1)", code)

103

104 return code

105

106 @classmethod

107 def _deduplicate_imports(cls, code: str) -> str:

108 """Remove duplicate import statements."""

109 lines = code.split("\n")

110 seen_imports = set()

111 deduplicated_lines = []

112

113 for line in lines:

114 if line.strip().startswith("from ") and " import " in line:

115 if line not in seen_imports:

116 seen_imports.add(line)

117 deduplicated_lines.append(line)

118 else:

119 deduplicated_lines.append(line)

120

121 return "\n".join(deduplicated_lines)