|
| 1 | +# Copyright 2025 Marimo. All rights reserved. |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import io |
| 5 | +import token as token_types |
| 6 | +from dataclasses import dataclass |
| 7 | +from tokenize import TokenError, tokenize |
| 8 | +from typing import Callable |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class CommentToken: |
| 13 | + text: str |
| 14 | + line: int |
| 15 | + col: int |
| 16 | + |
| 17 | + |
| 18 | +class CommentPreserver: |
| 19 | + """Functor to preserve comments during source code transformations.""" |
| 20 | + |
| 21 | + def __init__(self, sources: list[str]): |
| 22 | + self.sources = sources |
| 23 | + self.comments_by_source: dict[int, list[CommentToken]] = {} |
| 24 | + self._extract_all_comments() |
| 25 | + |
| 26 | + def _extract_all_comments(self) -> None: |
| 27 | + """Extract comments from all sources during initialization.""" |
| 28 | + for i, source in enumerate(self.sources): |
| 29 | + self.comments_by_source[i] = self._extract_comments_from_source( |
| 30 | + source |
| 31 | + ) |
| 32 | + |
| 33 | + def _extract_comments_from_source(self, source: str) -> list[CommentToken]: |
| 34 | + """Extract comments from a single source string.""" |
| 35 | + if not source.strip(): |
| 36 | + return [] |
| 37 | + |
| 38 | + comments = [] |
| 39 | + try: |
| 40 | + tokens = tokenize(io.BytesIO(source.encode("utf-8")).readline) |
| 41 | + for token in tokens: |
| 42 | + if token.type == token_types.COMMENT: |
| 43 | + comments.append( |
| 44 | + CommentToken( |
| 45 | + text=token.string, |
| 46 | + line=token.start[0], |
| 47 | + col=token.start[1], |
| 48 | + ) |
| 49 | + ) |
| 50 | + except (TokenError, SyntaxError): |
| 51 | + # If tokenization fails, return empty list - no comments preserved |
| 52 | + pass |
| 53 | + |
| 54 | + return comments |
| 55 | + |
| 56 | + def __call__( |
| 57 | + self, transform_func: Callable[..., list[str]] |
| 58 | + ) -> Callable[..., list[str]]: |
| 59 | + """ |
| 60 | + Method decorator that returns a comment-preserving version of transform_func. |
| 61 | +
|
| 62 | + Usage: preserver(transform_func)(sources, *args, **kwargs) |
| 63 | + """ |
| 64 | + |
| 65 | + def wrapper(*args: object, **kwargs: object) -> list[str]: |
| 66 | + # Apply the original transformation |
| 67 | + transformed_sources = transform_func(*args, **kwargs) |
| 68 | + |
| 69 | + # If sources weren't provided or transformation failed, return as-is |
| 70 | + if not args or not isinstance(args[0], list): |
| 71 | + return transformed_sources |
| 72 | + |
| 73 | + original_sources = args[0] |
| 74 | + |
| 75 | + # Merge comments back into transformed sources |
| 76 | + result = self._merge_comments( |
| 77 | + original_sources, transformed_sources |
| 78 | + ) |
| 79 | + |
| 80 | + # Update our internal comment data to track only the clean transformed sources |
| 81 | + # This clears old comments that no longer apply |
| 82 | + self._update_comments_for_transformed_sources(transformed_sources) |
| 83 | + |
| 84 | + return result |
| 85 | + |
| 86 | + return wrapper |
| 87 | + |
| 88 | + def _merge_comments( |
| 89 | + self, |
| 90 | + original_sources: list[str], |
| 91 | + transformed_sources: list[str], |
| 92 | + ) -> list[str]: |
| 93 | + """Merge comments from original sources into transformed sources.""" |
| 94 | + if len(original_sources) != len(transformed_sources): |
| 95 | + # If cell count changed, we can't preserve comments reliably |
| 96 | + return transformed_sources |
| 97 | + |
| 98 | + result = [] |
| 99 | + for i, (original, transformed) in enumerate( |
| 100 | + zip(original_sources, transformed_sources) |
| 101 | + ): |
| 102 | + comments = self.comments_by_source.get(i, []) |
| 103 | + if not comments: |
| 104 | + result.append(transformed) |
| 105 | + continue |
| 106 | + |
| 107 | + # Apply comment preservation with variable name updates if needed |
| 108 | + preserved_source = self._apply_comments_to_source( |
| 109 | + original, transformed, comments |
| 110 | + ) |
| 111 | + result.append(preserved_source) |
| 112 | + |
| 113 | + return result |
| 114 | + |
| 115 | + def _apply_comments_to_source( |
| 116 | + self, |
| 117 | + original: str, |
| 118 | + transformed: str, |
| 119 | + comments: list[CommentToken], |
| 120 | + ) -> str: |
| 121 | + """Apply comments to a single transformed source.""" |
| 122 | + if not comments: |
| 123 | + return transformed |
| 124 | + |
| 125 | + original_lines = original.split("\n") |
| 126 | + transformed_lines = transformed.split("\n") |
| 127 | + |
| 128 | + # Create a mapping of line numbers to comments |
| 129 | + comments_by_line: dict[int, list[CommentToken]] = {} |
| 130 | + for comment in comments: |
| 131 | + line_num = comment.line |
| 132 | + if line_num not in comments_by_line: |
| 133 | + comments_by_line[line_num] = [] |
| 134 | + comments_by_line[line_num].append(comment) |
| 135 | + |
| 136 | + # Apply comments to transformed lines |
| 137 | + result_lines = transformed_lines.copy() |
| 138 | + |
| 139 | + for line_num, line_comments in comments_by_line.items(): |
| 140 | + target_line_idx = min( |
| 141 | + line_num - 1, len(result_lines) - 1 |
| 142 | + ) # Convert to 0-based, clamp to bounds |
| 143 | + |
| 144 | + if target_line_idx < 0: |
| 145 | + continue |
| 146 | + |
| 147 | + # Select the best comment for this line (line comments take precedence) |
| 148 | + line_comment = None |
| 149 | + inline_comment = None |
| 150 | + |
| 151 | + for comment in line_comments: |
| 152 | + if comment.col == 0: # Line comment (starts at column 0) |
| 153 | + line_comment = comment |
| 154 | + break # Line comment takes precedence, no need to check others |
| 155 | + else: # Inline comment |
| 156 | + inline_comment = comment |
| 157 | + |
| 158 | + # Prefer line comment over inline comment |
| 159 | + chosen_comment = line_comment if line_comment else inline_comment |
| 160 | + |
| 161 | + if chosen_comment: |
| 162 | + comment_text = chosen_comment.text |
| 163 | + if chosen_comment.col > 0 and target_line_idx < len( |
| 164 | + original_lines |
| 165 | + ): |
| 166 | + # Inline comment - append to the line if not already present |
| 167 | + current_line = result_lines[target_line_idx] |
| 168 | + if not current_line.rstrip().endswith( |
| 169 | + comment_text.rstrip() |
| 170 | + ): |
| 171 | + result_lines[target_line_idx] = ( |
| 172 | + current_line.rstrip() + " " + comment_text |
| 173 | + ) |
| 174 | + elif target_line_idx >= 0 and comment_text not in result_lines: |
| 175 | + # Standalone comment - insert above the line if not already present |
| 176 | + result_lines.insert(target_line_idx, comment_text) |
| 177 | + |
| 178 | + return "\n".join(result_lines) |
| 179 | + |
| 180 | + def _update_comments_for_transformed_sources( |
| 181 | + self, sources: list[str] |
| 182 | + ) -> None: |
| 183 | + """Update internal comment data to track the transformed sources.""" |
| 184 | + self.sources = sources |
| 185 | + self.comments_by_source = {} |
| 186 | + self._extract_all_comments() |
0 commit comments