annotations.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Validation helpers for versioned board-viewer annotations."""
  2. from __future__ import annotations
  3. import copy
  4. from collections.abc import Mapping
  5. import re
  6. TEMPLATE_VARIABLE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
  7. class AnnotationError(ValueError):
  8. """Raised when an annotation points outside the parsed board."""
  9. def _substitute_template(
  10. value: object,
  11. variables: Mapping[str, object],
  12. *,
  13. context: str,
  14. ) -> object:
  15. if isinstance(value, str):
  16. def replace(match: re.Match[str]) -> str:
  17. name = match.group(1)
  18. if name not in variables:
  19. raise AnnotationError(
  20. f"missing template variable {name} for {context}"
  21. )
  22. return str(variables[name])
  23. return TEMPLATE_VARIABLE.sub(replace, value)
  24. if isinstance(value, list):
  25. return [
  26. _substitute_template(item, variables, context=context)
  27. for item in value
  28. ]
  29. if isinstance(value, Mapping):
  30. return {
  31. str(key): _substitute_template(item, variables, context=context)
  32. for key, item in value.items()
  33. }
  34. return copy.deepcopy(value)
  35. def _deep_merge(base: object, override: object) -> object:
  36. if isinstance(base, Mapping) and isinstance(override, Mapping):
  37. result = {str(key): copy.deepcopy(value) for key, value in base.items()}
  38. for key, value in override.items():
  39. name = str(key)
  40. result[name] = _deep_merge(result[name], value) if name in result else copy.deepcopy(value)
  41. return result
  42. return copy.deepcopy(override)
  43. def expand_annotation_templates(annotations: Mapping[str, object]) -> dict[str, object]:
  44. """Expand versioned repeated annotations without mutating the source mapping."""
  45. result = {str(key): copy.deepcopy(value) for key, value in annotations.items()}
  46. templates = annotations.get("annotation_templates", {})
  47. instances = annotations.get("template_instances", {})
  48. touchpoints = annotations.get("touchpoints", {})
  49. if not isinstance(templates, Mapping):
  50. raise AnnotationError("annotation_templates must be an object")
  51. if not isinstance(instances, Mapping):
  52. raise AnnotationError("template_instances must be an object")
  53. if not isinstance(touchpoints, Mapping):
  54. raise AnnotationError("touchpoints annotation must be an object")
  55. expanded_touchpoints = {
  56. str(reference): copy.deepcopy(value)
  57. for reference, value in touchpoints.items()
  58. }
  59. for reference_value, instance in instances.items():
  60. reference = str(reference_value)
  61. if not isinstance(instance, Mapping):
  62. raise AnnotationError(f"template instance {reference} must be an object")
  63. template_name = str(instance.get("template") or "")
  64. template = templates.get(template_name)
  65. if not template_name or not isinstance(template, Mapping):
  66. raise AnnotationError(
  67. f"unknown annotation template {template_name or '<empty>'} for {reference}"
  68. )
  69. variables = instance.get("variables", {})
  70. if not isinstance(variables, Mapping):
  71. raise AnnotationError(f"template variables {reference} must be an object")
  72. expanded = _substitute_template(
  73. template,
  74. variables,
  75. context=f"{reference} via {template_name}",
  76. )
  77. explicit = expanded_touchpoints.get(reference, {})
  78. expanded_touchpoints[reference] = _deep_merge(expanded, explicit)
  79. result["touchpoints"] = expanded_touchpoints
  80. return result
  81. def validate_annotation_references(
  82. annotations: Mapping[str, object], touchpoints: Mapping[str, Mapping[str, object]]
  83. ) -> None:
  84. annotated_touchpoints = annotations.get("touchpoints", {})
  85. if not isinstance(annotated_touchpoints, Mapping):
  86. raise AnnotationError("touchpoints annotation must be an object")
  87. for reference, annotation in annotated_touchpoints.items():
  88. if reference not in touchpoints:
  89. raise AnnotationError(f"unknown touchpoint {reference}")
  90. if not isinstance(annotation, Mapping):
  91. raise AnnotationError(f"touchpoint annotation {reference} must be an object")
  92. pins = annotation.get("pins", {})
  93. if not isinstance(pins, Mapping):
  94. raise AnnotationError(f"pins annotation {reference} must be an object")
  95. actual_pins = touchpoints[reference].get("pins", [])
  96. actual_numbers = {
  97. str(pin.get("number"))
  98. for pin in actual_pins
  99. if isinstance(pin, Mapping) and pin.get("number") is not None
  100. }
  101. for number in pins:
  102. if str(number) not in actual_numbers:
  103. raise AnnotationError(f"unknown pin {reference}.{number}")
  104. connector_profiles = annotations.get("connector_profiles", {})
  105. if not isinstance(connector_profiles, Mapping):
  106. raise AnnotationError("connector_profiles annotation must be an object")
  107. owners: dict[str, str] = {}
  108. for profile_name, profile in connector_profiles.items():
  109. if not isinstance(profile, Mapping):
  110. raise AnnotationError(f"connector profile {profile_name} must be an object")
  111. references = profile.get("references", [])
  112. if not isinstance(references, list):
  113. raise AnnotationError(f"connector profile {profile_name} references must be an array")
  114. for reference_value in references:
  115. reference = str(reference_value)
  116. if reference in owners:
  117. raise AnnotationError(f"connector {reference} appears in multiple profiles")
  118. owners[reference] = str(profile_name)
  119. for profile_name, profile in connector_profiles.items():
  120. if not isinstance(profile, Mapping):
  121. continue
  122. contact_values = profile.get("contact_pins", [])
  123. shield_values = profile.get("shield_pads", [])
  124. references = profile.get("references", [])
  125. if not isinstance(contact_values, list) or not isinstance(shield_values, list):
  126. raise AnnotationError(f"connector profile {profile_name} pin classifications must be arrays")
  127. contacts = {str(value) for value in contact_values}
  128. shields = {str(value) for value in shield_values}
  129. overlap = sorted(contacts.intersection(shields))
  130. if overlap:
  131. raise AnnotationError(
  132. f"connector profile {profile_name} has overlapping contact and shield pads: {', '.join(overlap)}"
  133. )
  134. for reference_value in references if isinstance(references, list) else []:
  135. reference = str(reference_value)
  136. if reference not in touchpoints:
  137. raise AnnotationError(f"unknown connector {reference}")
  138. touchpoint = touchpoints[reference]
  139. expected_component_value = str(profile.get("component_value", profile_name))
  140. if str(touchpoint.get("component_value") or "") != expected_component_value:
  141. raise AnnotationError(
  142. f"component value mismatch {reference}: "
  143. f"{touchpoint.get('component_value')} != {expected_component_value}"
  144. )
  145. actual_pins = touchpoint.get("pins", [])
  146. actual_numbers = {
  147. str(pin.get("number"))
  148. for pin in actual_pins
  149. if isinstance(pin, Mapping) and str(pin.get("number") or "")
  150. }
  151. classified = contacts.union(shields)
  152. unknown = sorted(classified.difference(actual_numbers))
  153. if unknown:
  154. raise AnnotationError(f"unknown classified pads {reference}: {', '.join(unknown)}")
  155. unclassified = sorted(actual_numbers.difference(classified))
  156. if unclassified:
  157. raise AnnotationError(f"unclassified numbered pads {reference}: {', '.join(unclassified)}")