|
| 1 | +"""Parser: Scala case class definitions → SchemaForge IR. |
| 2 | +
|
| 3 | +Parses Scala case class definitions suitable for Doobie, Quill, |
| 4 | +or Slick into the internal schema representation. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import re |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from ..ir import Schema, Table, Column, ColumnType |
| 12 | + |
| 13 | + |
| 14 | +# Regex: extract case class |
| 15 | +_CASE_CLASS_RE = re.compile( |
| 16 | + r'(?:@(?:Entity|Table|Mapped)\s*(?:\([^)]*\))?\s*)?' |
| 17 | + r'(?:case\s+)?class\s+(\w+)' |
| 18 | + r'(?:\s*\(((?:[^()]|\([^()]*\))*)\))', |
| 19 | + re.MULTILINE, |
| 20 | +) |
| 21 | + |
| 22 | +# Regex: extract field from case class parameter list |
| 23 | +_FIELD_RE = re.compile( |
| 24 | + r'\s*(\w+)\s*:\s*([^=,]+)(?:\s*=\s*([^,]+))?\s*,?\s*' |
| 25 | +) |
| 26 | + |
| 27 | +# Map Scala types to ColumnType |
| 28 | +_SCALA_TYPE_MAP: dict[str, ColumnType] = { |
| 29 | + "Int": ColumnType.INTEGER, |
| 30 | + "Long": ColumnType.INTEGER, |
| 31 | + "Short": ColumnType.INTEGER, |
| 32 | + "Byte": ColumnType.INTEGER, |
| 33 | + "BigInt": ColumnType.INTEGER, |
| 34 | + "String": ColumnType.STRING, |
| 35 | + "Boolean": ColumnType.BOOLEAN, |
| 36 | + "Double": ColumnType.FLOAT, |
| 37 | + "Float": ColumnType.FLOAT, |
| 38 | + "BigDecimal": ColumnType.DECIMAL, |
| 39 | + "java.math.BigDecimal": ColumnType.DECIMAL, |
| 40 | + "Instant": ColumnType.DATETIME, |
| 41 | + "java.time.Instant": ColumnType.DATETIME, |
| 42 | + "LocalDateTime": ColumnType.DATETIME, |
| 43 | + "java.time.LocalDateTime": ColumnType.DATETIME, |
| 44 | + "OffsetDateTime": ColumnType.DATETIME, |
| 45 | + "java.time.OffsetDateTime": ColumnType.DATETIME, |
| 46 | + "ZonedDateTime": ColumnType.DATETIME, |
| 47 | + "java.time.ZonedDateTime": ColumnType.DATETIME, |
| 48 | + "LocalDate": ColumnType.DATE, |
| 49 | + "java.time.LocalDate": ColumnType.DATE, |
| 50 | + "LocalTime": ColumnType.TIME, |
| 51 | + "java.time.LocalTime": ColumnType.TIME, |
| 52 | + "UUID": ColumnType.UUID, |
| 53 | + "java.util.UUID": ColumnType.UUID, |
| 54 | + "java.util.Date": ColumnType.DATETIME, |
| 55 | + "DateTime": ColumnType.DATETIME, |
| 56 | + "org.joda.time.DateTime": ColumnType.DATETIME, |
| 57 | + "org.joda.time.LocalDate": ColumnType.DATE, |
| 58 | + "org.joda.time.LocalTime": ColumnType.TIME, |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | +def _clean_scala_type(raw: str) -> tuple[str, bool]: |
| 63 | + """Clean a Scala type string. |
| 64 | +
|
| 65 | + Returns (cleaned_type, is_optional) where is_optional is True for Option[T]. |
| 66 | + """ |
| 67 | + raw = raw.strip() |
| 68 | + is_optional = False |
| 69 | + |
| 70 | + # Handle Option[T] |
| 71 | + if raw.startswith("Option["): |
| 72 | + raw = raw[7:-1].strip() |
| 73 | + is_optional = True |
| 74 | + |
| 75 | + # Handle List[T], Seq[T], Vector[T] |
| 76 | + for prefix in ("List[", "Seq[", "Vector[", "Set[", "List["): |
| 77 | + if raw.startswith(prefix) and raw.endswith(">"): |
| 78 | + raw = raw[len(prefix) : -1].strip() |
| 79 | + break |
| 80 | + |
| 81 | + return raw, is_optional |
| 82 | + |
| 83 | + |
| 84 | +def _parse_default(value_str: str) -> Any: |
| 85 | + """Parse a Scala default value expression.""" |
| 86 | + val = value_str.strip().rstrip(",") |
| 87 | + |
| 88 | + if val == "true": |
| 89 | + return True |
| 90 | + if val == "false": |
| 91 | + return False |
| 92 | + if val == "null" or val == "None": |
| 93 | + return None |
| 94 | + |
| 95 | + # Quoted strings |
| 96 | + if (val.startswith('"') and val.endswith('"')) or \ |
| 97 | + (val.startswith('"""') and val.endswith('"""')): |
| 98 | + inner = val.strip('"') |
| 99 | + # Handle interpolation: s"..." |
| 100 | + idx = inner.find("$") |
| 101 | + if idx >= 0: |
| 102 | + inner = inner[:idx] |
| 103 | + return inner |
| 104 | + |
| 105 | + # Integer |
| 106 | + try: |
| 107 | + return int(val) |
| 108 | + except ValueError: |
| 109 | + pass |
| 110 | + |
| 111 | + # Float |
| 112 | + try: |
| 113 | + return float(val) |
| 114 | + except ValueError: |
| 115 | + pass |
| 116 | + |
| 117 | + # Function defaults (e.g., java.time.Instant.now()) |
| 118 | + if "(" in val and val.endswith(")"): |
| 119 | + fn_name = val.split("(")[0].split(".")[-1] |
| 120 | + return f"fn:{fn_name}()" |
| 121 | + |
| 122 | + return None |
| 123 | + |
| 124 | + |
| 125 | +class ScalaParser: |
| 126 | + """Parse Scala case class definitions into Schema IR.""" |
| 127 | + |
| 128 | + def parse(self, text: str) -> Schema: |
| 129 | + """Parse Scala source text into a Schema IR.""" |
| 130 | + schema = Schema() |
| 131 | + |
| 132 | + # Remove comments |
| 133 | + text = re.sub(r"//.*$", "", text, flags=re.MULTILINE) |
| 134 | + text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) |
| 135 | + |
| 136 | + for m in _CASE_CLASS_RE.finditer(text): |
| 137 | + class_name = m.group(1) |
| 138 | + params_str = m.group(2) |
| 139 | + |
| 140 | + if not class_name or not params_str: |
| 141 | + continue |
| 142 | + |
| 143 | + table = Table(name=self._to_snake(class_name)) |
| 144 | + fields = _FIELD_RE.findall(params_str) |
| 145 | + |
| 146 | + for field_name, field_type, default_str in fields: |
| 147 | + col = self._field_to_column(field_name, field_type.strip(), default_str.strip()) |
| 148 | + if col: |
| 149 | + table.columns.append(col) |
| 150 | + |
| 151 | + if table.columns: |
| 152 | + schema.tables.append(table) |
| 153 | + |
| 154 | + return schema |
| 155 | + |
| 156 | + def _field_to_column(self, name: str, raw_type: str, default_str: str) -> Column | None: |
| 157 | + """Convert a Scala field to a Column IR.""" |
| 158 | + clean_type, is_optional = _clean_scala_type(raw_type) |
| 159 | + |
| 160 | + col_type = _SCALA_TYPE_MAP.get(clean_type, ColumnType.CUSTOM) |
| 161 | + type_args: dict[str, Any] = {} |
| 162 | + default_val: Any = None |
| 163 | + custom_type = "" |
| 164 | + |
| 165 | + # Parse default value |
| 166 | + if default_str: |
| 167 | + default_val = _parse_default(default_str) |
| 168 | + |
| 169 | + # Handle String length from default values / heuristics |
| 170 | + if col_type == ColumnType.STRING and isinstance(default_val, str): |
| 171 | + pass # No length hint from Scala |
| 172 | + |
| 173 | + if col_type == ColumnType.CUSTOM: |
| 174 | + custom_type = clean_type |
| 175 | + |
| 176 | + return Column( |
| 177 | + name=name, |
| 178 | + type=col_type, |
| 179 | + type_args=type_args, |
| 180 | + nullable=is_optional, |
| 181 | + unique=False, |
| 182 | + primary_key=False, |
| 183 | + default=default_val, |
| 184 | + custom_type=custom_type, |
| 185 | + ) |
| 186 | + |
| 187 | + def _to_snake(self, name: str) -> str: |
| 188 | + """Convert PascalCase to snake_case.""" |
| 189 | + result = re.sub(r"([A-Z])", r"_\1", name).lower().lstrip("_") |
| 190 | + result = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", result).lower() |
| 191 | + return result.strip("_") |
0 commit comments