Hsb Ip Def
NVIDIAOfficialCreated by Holoscan TeamDistributed by NVIDIA
- Skill
- Tool integration
- Software development
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The hsb-ip-def skill provides a structured approach to managing SystemVerilog configuration macros for the Holoscan Sensor Bridge (HSB) IP. It enables users to generate, validate, explain, and compare HOLOLINK_def.svh files, ensuring that macro definitions align with board-level requirements and IP constraints. The skill leverages bundled Python scripts to perform these operations, providing a reliable interface for configuring HSB IP revisions 16'h2603 and 16'h2604.
What it does
- Generates HOLOLINK_def.svh files based on user-confirmed board requirements.
- Validates existing configuration files using a dedicated linting script.
- Explains macro semantics, legal values, and their impact on top-level ports.
- Compares two configuration files to identify semantic differences.
- Provides warnings for potential configuration footguns, such as HD-W3xx issues.
- Integrates with other HSB skills for top-level wrapper creation and packetizer derivation.
When to use it
- When you need to create a new HOLOLINK_def.svh file for a custom HSB board design.
- When you need to verify that an existing configuration file is valid and follows IP constraints.
- When you need to understand the effect of specific macros on the HSB IP dataplane or clocking.
- When you need to diff two configurations to understand changes between board revisions.
Advantages
- Ensures configuration consistency through automated validation.
- Prevents common configuration errors with built-in rule checking.
- Provides clear, grounded explanations for complex macro interactions.
- Maintains compatibility with specific HSB IP revisions.
Usage examples
- “Generate a new HOLOLINK_def.svh for a high-bandwidth single-sensor board.”
- The agent will initiate the generation workflow, asking for board requirements one by one, building a profile, and running the generation script upon confirmation.
- “Validate my current HOLOLINK_def.svh and check for any warnings.”
- The agent will run the validation script, report any errors or warnings, and specifically highlight any HD-W3xx footgun warnings.
- “Is it legal to set HOST_WIDTH=512 and PTP_CLK_FREQ=90_000_000?”
- The agent will use the validation script or macro references to determine if the combination is legal and explain the reasoning.
- “Compare my local def file with the baseline configuration.”
- The agent will run the comparison script and provide a summary of the semantic differences between the two files.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/nvidia/hsb-ip-def/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip hsb-ip-def.zip -d .agents/skills
Documentation by Holoscan Team
HSB IP Def Skill
Purpose
Use this skill through four workflows:
Generate a
HOLOLINK_def.svhfrom confirmed board requirements.Validate an existing def file with the bundled validator.
Explain / Reason about HSB IP macros, legality, and macro-driven ports.
Compare two def files semantically.
Scope
This skill owns the contents of HOLOLINK_def.svh: \definedirectives,localparamarrays, theHOLOLINK_pkgwrapper, and boot-timeinit_reg[]sequence. The surrounding top-level wrapper is owned byhsb-ip-create-top; packetizer-only profile derivation can be delegated to hsb-ip-packetizer`.
The file must use the standard guard plus package HOLOLINK_pkg wrapper. Load references/macro-reference.md for the full wrapper requirement and per-macro semantics.
Prerequisites
Python 3.9+ is required for the bundled scripts; PyYAML is required when reading YAML profiles.
The user must confirm file writes and shell commands unless they already asked for that exact operation.
A concrete def file path, pasted content, or confirmed generation profile is required before script-backed validation or generation.
Live HSB IP source is optional but preferred when validating against a specific checked-out IP revision.
Instructions
Run bundled script preflight from
references/script-usage.mdbefore Generate, Validate, Compare, or script-backed legality checks.Never silently default a macro during Generate. Show the proposed value or inferred requirement and get user confirmation.
Ask one requirements question per turn during chat-driven Generate.
Use sensor-agnostic language unless the user says the design is camera-specific.
Avoid unsupported "typical", "common", "most designs", or corpus-frequency claims. Anchor choices to IP behavior, documented constraints, or user requirements.
Always surface HD-W3xx footgun warnings, even when the user asks only about errors.
Do not generate
FPGA_top.sv; offer handoff tohsb-ip-create-topafter a generated def file is validated.Treat unfamiliar macros as project-specific unless they are documented in this skill's references or live HSB IP source.
Security Considerations
This skill can read and write local files and run shell commands through its bundled scripts. Before running a command or writing a file, state the command or path and get user confirmation unless the user already explicitly requested that exact operation. For pasted HOLOLINK_def.svh content, write only to a safely generated file in an isolated temporary directory and remove it after validation unless the user asks to keep it.
Version, Compatibility, And Live Source
This skill targets HSB IP rev 16'h2604 and is backward-compatible with 16'h2603. Live HSB IP source supersedes bundled references.
When source-sensitive behavior matters:
Locate
<hsb-ip-root>/top/HOLOLINK_top.sv. Known roots includehw/nvcpu_dgx_fpga/vrtl/hololink/and public-releasefpga/nv_hsb_ip/.Read
HOLOLINK_REVandHOLOLINK_BACKWARD_COMPAT_REV.Trust live source for consumed macros, port gates, and RTL behavior when it differs from bundled references.
Pass
--ip-source <root>toscripts/validate_def.pywhen validating against a known source root.
Public-doc baseline:
https://github.com/nvidia-holoscan/holoscan-sensor-bridge/blob/release-2.6.0-EA/docs/user_guide/ip_integration.mdhttps://github.com/nvidia-holoscan/holoscan-sensor-bridge/blob/release-2.6.0-EA/docs/user_guide/port_description.md
Workflow Decision
Generate when the user asks to create, scaffold, draft, design, or produce a
HOLOLINK_def.svh.Validate when the user asks to lint, check, validate, or review a
HOLOLINK_def.svh.Explain / Reason when the user asks what a macro does, whether a combination is legal, why validation fails, or how a macro affects
HOLOLINK_top.Compare when the user asks to diff two def files or understand what changed between configurations.
Generate
Load references/generate-workflow.md and references/script-usage.md.
Follow the detailed Generate workflow in the reference: run preflight, classify supplied requirements, ask one requirements question per turn, build a flat YAML profile, run scripts/generate_def.py, show provenance for generated fields, and offer handoff to hsb-ip-create-top.
When packetizer fields are needed, invoke hsb-ip-packetizer with the known RX count, RX widths, and the user's data-manipulation description. Consume only that skill's packetizer_profile_overlay YAML keys, merge them into the in-progress profile, and continue full-file generation and validation here.
Validate
Load references/script-usage.md. Load references/validation-rules.md only when explaining specific rule IDs or validation behavior.
Steps:
Run bundled script preflight once per session.
Locate the file. If the user pastes content, tell them the generated temporary path before writing, ask for confirmation, use an isolated safe temp path, and clean it up after validation unless they ask to keep it. Otherwise use the provided path.
Run
<PY> scripts/validate_def.py <path> --jsonand do not reimplement validation in context.Group findings by severity: errors, warnings, then info. For each error, cite rule ID, line number, and macro when available.
Always surface footgun warnings, especially HD-W3xx silent-fallback warnings.
If clean, confirm the inferred archetype and IP version, then suggest the likely next check or handoff.
Explain / Reason
Load only the reference needed for the question:
| Question type | Reference |
|---|---|
| Macro semantics or legal values | references/macro-reference.md |
| Validation rule behavior | references/validation-rules.md |
| Macro-driven port effects | references/top-port-map.md |
init_reg[] and N_INIT_REG | references/init-reg-cookbook.md |
| Advanced macros | references/advanced-macros.md |
| Example legal configurations | references/archetypes.md |
For grounded legality questions, run preflight and prefer validating a concrete file or minimal synthetic file with scripts/validate_def.py over hand reasoning. Cite RTL line ranges from references when explaining why a rule exists.
Compare
Load references/script-usage.md, run preflight, then use <PY> scripts/compare_defs.py <a.svh> <b.svh> [--json|--text]. Summarize semantic differences, not whitespace or comment-only changes.
Limitations
Do not generate
FPGA_top.sv; usehsb-ip-create-topafter the defs file validates.Do not derive packetizer-only field sets here when the packetizer behavior is underspecified; delegate that slice to
hsb-ip-packetizer.Do not treat bundled archetypes or corpus metadata as norms. They are examples and maintenance metadata, not defaults.
Do not silently accept unknown macros as validated HSB IP behavior unless live source or references document them.
Troubleshooting
Script preflight fails: report the missing Python or PyYAML requirement and stop before generation or validation.
Validation reports errors: group by severity, cite rule ID and line, and fix the defs file before offering top-level handoff.
Validation reports HD-W3xx warnings: surface them even when there are no errors because they describe silent RTL fallback risks.
Unknown macro appears: treat it as project-specific unless live HSB IP source or bundled references document it.
Available Scripts
Use <PY> selected during preflight from references/script-usage.md for every command.
| Script | Purpose | Arguments |
|---|---|---|
scripts/generate_def.py | Generate HOLOLINK_def.svh from an archetype and/or YAML/JSON profile; validates before writing | --profile <path>, --archetype <slug>, -o <output>, optional --allow-random-uuid compatibility flag |
scripts/validate_def.py | Validate a HOLOLINK_def.svh and emit JSON or text findings | <path/to/HOLOLINK_def.svh>, optional --json or --text, optional --ip-source <root> |
scripts/compare_defs.py | Compare two def files semantically, ignoring whitespace/comment-only changes | <a.svh> <b.svh>, optional --json or --text |
scripts/build_corpus_metadata.py | Maintenance helper to rebuild anonymized corpus metadata; do not run during normal user workflows | <path1> [<path2> ...] |
Bundled Resources
| Resource | Use |
|---|---|
references/generate-workflow.md | Detailed Generate workflow, requirement order, question style, and per-topic prompt guidance |
references/script-usage.md | Preflight, command forms, and run_script() examples for bundled scripts |
references/macro-reference.md | Wrapper requirement, macro semantics, legal constraints, and RTL citations |
references/validation-rules.md | Rule catalog for validator findings |
references/archetypes.md | Illustrative legal configurations; never treat as templates or frequency guidance |
references/init-reg-cookbook.md | Boot-time APB write sequence patterns and address conventions |
references/top-port-map.md | Macro-to-HOLOLINK_top port effects |
references/advanced-macros.md | SYNC_CLK_HIF_APB, SYNC_CLK_HIF_PTP, PERI_RAM_DEPTH, and DISABLE_COE |
assets/metadata/corpus.json, assets/metadata/corpus-stats.json | Maintenance metadata only; do not cite corpus counts as user guidance |
scripts/generate_def.py | Generate a def file from a profile |
scripts/validate_def.py | Validate a def file and emit JSON/text findings |
scripts/compare_defs.py | Compare two def files semantically |
Examples
Use hsb-ip-def to generate a HOLOLINK_def.svh for a new HSB board.Treat as Generate, run script preflight, classify supplied requirements, ask one requirement question per turn, and runscripts/generate_def.pyonly after the profile is confirmed.Use hsb-ip-def to validate my existing HOLOLINK_def.svh and tell me whether any warnings are important.Treat as Validate, ask for or locate the file, runscripts/validate_def.py <path> --json, group findings by errors, warnings, and info, and always surface HD-W3xx footgun warnings.Use hsb-ip-def to explain whether HOST_WIDTH=512 and PTP_CLK_FREQ=90_000_000 is legal.Treat as Explain / Reason, prefer a concrete validator-backed check over hand reasoning, and load only the macro or validation reference needed to explain the result.
Files
- ATTRIBUTION.mdAdded by AutoGineer895 B
- BENCHMARK.md3.4 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- README.md5.0 KiB
- SKILL.md11.3 KiB
- assets/metadata/corpus-stats.json5.3 KiB
- assets/metadata/corpus.json16.9 KiB
- evals/evals.json4.4 KiB
- references/advanced-macros.md4.7 KiB
- references/archetypes.md22.3 KiB
- references/generate-workflow.md25.1 KiB
- references/init-reg-cookbook.md5.7 KiB
- references/macro-reference.md29.8 KiB
- references/script-usage.md3.1 KiB
- references/top-port-map.md10.2 KiB
- references/validation-rules.md14.8 KiB
- scripts/build_corpus_metadata.pyScript7.5 KiB
- scripts/compare_defs.pyScript6.0 KiB
- scripts/generate_def.pyScript8.6 KiB
- scripts/lib/__init__.pyScript0 B
- scripts/lib/emitter.pyScript25.7 KiB
- scripts/lib/parser.pyScript22.3 KiB
- scripts/lib/rules.pyScript29.1 KiB
- scripts/validate_def.pyScript5.6 KiB
- skill-card.md4.5 KiB
- skill.oms.sig8.9 KiB
scripts/lib/parser.py
"""Parser for HOLOLINK_def.svh files.
Public entry point: parse_file(path) -> ParsedDef
Handles:
- Verilog preprocessor directives: `ifdef / `ifndef / `elsif / `else / `endif / `define
- Block (/* ... */) and line (//) comments
- Commented-out `define directives (these MUST be treated as undefined)
- The package / `ifndef wrapper required by HOLOLINK_def.svh
- localparam declarations for SIF_RX_*[], SIF_TX_*[], GPIO_RESET_VALUE, init_reg[]
- Verilog integer literals (decimal, hex, binary) including sized forms (NN'h…)
- Macro expansion in array sizes (`MACRO-1:0)
- Array initializers '{default:X} and {a, b, c}
The parser is intentionally permissive: it extracts what it can, attaches
parse errors to fields it could not resolve, and lets the rules engine
decide which findings warrant errors.
"""
from dataclasses import dataclass, field
from pathlib import Path
import ast
import re
from typing import Dict, List, Optional, Tuple, Union
# -----------------------------------------------------------------------------
# Data types
# -----------------------------------------------------------------------------
@dataclass
class WrapperState:
has_ifndef_guard: bool = False # `ifndef HOLOLINK_def
has_define_guard: bool = False # `define HOLOLINK_def (after ifndef)
has_package_decl: bool = False # package HOLOLINK_pkg;
has_endpackage: bool = False # endpackage [: HOLOLINK_pkg]
has_endif: bool = False # final `endif
package_line: Optional[int] = None
endpackage_line: Optional[int] = None
@dataclass
class ArrayDecl:
"""A localparam array declaration."""
name: str
line: int
size_expr: str # e.g. "`SENSOR_RX_IF_INST-1:0" or "3"
size_value: Optional[int] # resolved length, or None if unresolvable
elements: List[str] # raw element strings
is_default_init: bool # True if '{default:X} form
default_value: Optional[str] # the default expression if applicable
raw_text: str # the full declaration source
@dataclass
class InitRegEntry:
line: int
addr_raw: str # raw address text, e.g. "32'h0200_0024"
data_raw: str
addr_value: Optional[int]
data_value: Optional[int]
@dataclass
class InitRegArray:
name: str = "init_reg"
line: int = 0
size_expr: str = ""
declared_size_value: Optional[int] = None
entries: List[InitRegEntry] = field(default_factory=list)
@dataclass
class GpioResetValue:
line: int
width_expr: str # e.g. "`GPIO_INST-1:0"
width_value: Optional[int]
literal: str # e.g. "16'b0000000000001111"
@dataclass
class ParseError:
line: Optional[int]
msg: str
@dataclass
class ParsedDef:
path: str
raw_lines: List[str] = field(default_factory=list)
wrapper: WrapperState = field(default_factory=WrapperState)
# Plain `defines (scalar): name -> (value_string_or_None, line)
# value is None for boolean defines like `define ENUM_EEPROM`
defines: Dict[str, Tuple[Optional[str], int]] = field(default_factory=dict)
# Array localparams keyed by name
arrays: Dict[str, ArrayDecl] = field(default_factory=dict)
init_reg: Optional[InitRegArray] = None
gpio_reset_value: Optional[GpioResetValue] = None
# Track defines that appeared inside an inactive `ifdef branch (skipped),
# so the validator doesn't complain about them.
defines_skipped: List[str] = field(default_factory=list)
parse_errors: List[ParseError] = field(default_factory=list)
# Lines that LOOK like commented-out `define`s — useful for footgun reporting.
commented_define_lines: List[Tuple[int, str]] = field(default_factory=list)
# -----------------------------------------------------------------------------
# Comment stripping
# -----------------------------------------------------------------------------
_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
def _strip_block_comments(text: str) -> str:
return _BLOCK_COMMENT_RE.sub(lambda m: " " * len(m.group(0)), text)
def _detect_commented_defines(raw_lines: List[str]) -> List[Tuple[int, str]]:
"""Return [(1-based line, define-name)] for lines that LOOK like
commented-out `define directives. Used for footgun reporting.
"""
pat = re.compile(r"^\s*//\s*`define\s+([A-Za-z_][A-Za-z0-9_]*)")
out = []
for i, line in enumerate(raw_lines, start=1):
m = pat.match(line)
if m:
out.append((i, m.group(1)))
return out
def _strip_line_comments(line: str) -> str:
"""Remove // comments from a single line (after block comments are gone)."""
# Be careful with // inside string literals — but HOLOLINK_def.svh
# contains no string literals, so a naive split is safe.
idx = line.find("//")
return line if idx < 0 else line[:idx]
# -----------------------------------------------------------------------------
# Verilog integer literal parsing
# -----------------------------------------------------------------------------
_VLOG_LITERAL_RE = re.compile(
r"""^\s*
(?P<width>\d+)? # optional bit width
\s*'(?P<base>[bBdDhHoO]) # base prefix
(?P<digits>[\dA-Fa-f_xXzZ?]+)
\s*$""",
re.VERBOSE,
)
def parse_int_literal(s: str) -> Optional[int]:
"""Parse a Verilog or plain integer literal. Returns None on failure.
Examples:
"156250000" -> 156250000
"16'h2604" -> 9732
"8'b00001111" -> 15
"128'h7A37_7BF7…" -> integer
"'0" -> 0 (SystemVerilog all-zeros literal)
"'1" -> 1 (SystemVerilog all-ones literal, sign-context dependent)
"""
if s is None:
return None
s = s.strip()
if not s:
return None
# SystemVerilog 'fill literals: '0, '1, 'z, 'x
if s in ("'0",):
return 0
if s in ("'1",):
return 1 # all-ones; the actual numeric value depends on width context
# Try plain decimal
try:
return int(s.replace("_", ""))
except ValueError:
pass
m = _VLOG_LITERAL_RE.match(s)
if not m:
return None
base_char = m.group("base").lower()
digits = m.group("digits").replace("_", "")
base_map = {"b": 2, "d": 10, "o": 8, "h": 16}
base = base_map[base_char]
# Replace x/z/? with 0 for parsing — these are unknown in Verilog
sanitized = re.sub(r"[xXzZ?]", "0", digits)
try:
return int(sanitized, base)
except ValueError:
return None
def vlog_literal_width(s: str) -> Optional[int]:
"""Return the declared bit width of a Verilog literal, or None."""
m = _VLOG_LITERAL_RE.match(s.strip())
if m and m.group("width"):
return int(m.group("width"))
return None
# -----------------------------------------------------------------------------
# Expression evaluator (extremely limited)
# -----------------------------------------------------------------------------
_ARITH_EXPR_RE = re.compile(r"^[\d_+\-*/()% \t]+$")
_ARITH_EXPR_MAX_CHARS = 256
_ARITH_EXPR_MAX_NODES = 64
_ARITH_EXPR_MAX_PAREN_DEPTH = 32
def _safe_eval_arith(expr: str) -> Optional[int]:
"""Evaluate a tiny integer-arithmetic expression safely.
Supported grammar is intentionally smaller than Python: integer constants,
parentheses, unary +/-, and binary +, -, *, /, %. Division follows the
previous behavior for positive integer expressions by using integer
truncation toward zero.
"""
if len(expr) > _ARITH_EXPR_MAX_CHARS or not _ARITH_EXPR_RE.fullmatch(expr):
return None
depth = 0
for ch in expr:
if ch == "(":
depth += 1
if depth > _ARITH_EXPR_MAX_PAREN_DEPTH:
return None
elif ch == ")":
depth -= 1
if depth < 0:
return None
if depth != 0:
return None
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError:
return None
node_count = 0
def walk(node: ast.AST) -> int:
nonlocal node_count
node_count += 1
if node_count > _ARITH_EXPR_MAX_NODES:
raise ValueError("expression too large")
if isinstance(node, ast.Expression):
return walk(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, int):
return node.value
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
value = walk(node.operand)
return value if isinstance(node.op, ast.UAdd) else -value
if isinstance(node, ast.BinOp):
left = walk(node.left)
right = walk(node.right)
if isinstance(node.op, ast.Add):
return left + right
if isinstance(node.op, ast.Sub):
return left - right
if isinstance(node.op, ast.Mult):
return left * right
if isinstance(node.op, ast.Div):
if right == 0:
raise ZeroDivisionError
return int(left / right)
if isinstance(node.op, ast.Mod):
if right == 0:
raise ZeroDivisionError
return left % right
raise ValueError("unsupported expression")
try:
return walk(tree)
except (ValueError, ZeroDivisionError, OverflowError):
return None
def eval_expr(expr: str, defines: Dict[str, Tuple[Optional[str], int]]) -> Optional[int]:
"""Try to evaluate a small arithmetic expression that may reference
`MACRO names. Returns int or None."""
if expr is None:
return None
expr = expr.strip()
# Substitute `MACRO with the macro's value (recursively, one level).
def sub(m):
name = m.group(1)
if name in defines and defines[name][0] is not None:
return defines[name][0]
return m.group(0)
expanded = re.sub(r"`([A-Za-z_][A-Za-z0-9_]*)", sub, expr)
# First try as a Verilog literal
v = parse_int_literal(expanded)
if v is not None:
return v
# Then try as a restricted integer arithmetic expression.
return _safe_eval_arith(expanded)
# -----------------------------------------------------------------------------
# Preprocessor: walk tokens with `ifdef awareness
# -----------------------------------------------------------------------------
DEFINE_RE = re.compile(
r"^\s*`define\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)(?:\s+(?P<value>.+?))?\s*$"
)
IFDEF_RE = re.compile(r"^\s*`ifdef\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*$")
IFNDEF_RE = re.compile(r"^\s*`ifndef\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*$")
ELSIF_RE = re.compile(r"^\s*`elsif\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*$")
ELSE_RE = re.compile(r"^\s*`else\s*$")
ENDIF_RE = re.compile(r"^\s*`endif") # tolerate trailing comments
PACKAGE_RE = re.compile(r"^\s*package\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*;\s*$")
ENDPACKAGE_RE = re.compile(r"^\s*endpackage(?:\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*$")
# -----------------------------------------------------------------------------
# localparam scanner
# -----------------------------------------------------------------------------
# Scalar-array declaration: `localparam integer NAME [SIZE] = '{...};`
# Accepts both `'{...}` (default-init or assignment-pattern) and `{...}`
# (positional concatenation initializer). Body may span multiple lines.
LP_ARRAY_RE = re.compile(
r"""localparam\s+
(?:integer|logic\s*\[(?P<bitwidth>[^\]]+)\]|int)?\s*
(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*
\[\s*(?P<size>[^\]]+)\s*\]\s*
=\s*'?\{(?P<body>.*?)\}\s*;""",
re.VERBOSE | re.DOTALL,
)
# GPIO_RESET_VALUE: `localparam [WIDTH-1:0] GPIO_RESET_VALUE = LITERAL;`
LP_VECTOR_RE = re.compile(
r"""localparam\s+
\[\s*(?P<width>[^\]]+)\s*\]\s*
(?P<name>GPIO_RESET_VALUE)\s*
=\s*(?P<literal>[^;]+);""",
re.VERBOSE,
)
def _split_array_body(body: str) -> List[str]:
"""Split an array initializer body by top-level commas, handling nested {}.
Returns the list of element strings (whitespace-trimmed)."""
out = []
depth = 0
cur = []
for ch in body:
if ch == "{":
depth += 1
cur.append(ch)
elif ch == "}":
depth -= 1
cur.append(ch)
elif ch == "," and depth == 0:
out.append("".join(cur).strip())
cur = []
else:
cur.append(ch)
last = "".join(cur).strip()
if last:
out.append(last)
return out
def _parse_array_decl(
match: re.Match, line_num: int, defines: Dict[str, Tuple[Optional[str], int]]
) -> ArrayDecl:
name = match.group("name")
size_expr = match.group("size")
size_value = eval_expr(size_expr.split(":")[0], defines)
if ":" in size_expr:
# Form `[N-1:0]`, so length is N
upper = eval_expr(size_expr.split(":")[0], defines)
lower = eval_expr(size_expr.split(":")[1], defines)
if upper is not None and lower is not None:
size_value = upper - lower + 1
body = match.group("body")
elements = _split_array_body(body)
is_default_init = False
default_value = None
if len(elements) == 1 and elements[0].lower().startswith("default"):
# '{default:X}' form
is_default_init = True
default_value = elements[0].split(":", 1)[1].strip()
elements = [] # individual elements not enumerated
return ArrayDecl(
name=name,
line=line_num,
size_expr=size_expr,
size_value=size_value,
elements=elements,
is_default_init=is_default_init,
default_value=default_value,
raw_text=match.group(0),
)
def _parse_init_reg(
match: re.Match, line_num: int, defines: Dict[str, Tuple[Optional[str], int]]
) -> InitRegArray:
decl = InitRegArray(name="init_reg", line=line_num, size_expr=match.group("size"))
decl.declared_size_value = eval_expr(match.group("size"), defines)
elements = _split_array_body(match.group("body"))
for elem in elements:
# Expect form `{32'haddr, 32'hdata}`
e = elem.strip()
if not (e.startswith("{") and e.endswith("}")):
decl.entries.append(InitRegEntry(line_num, e, "", None, None))
continue
inner = e[1:-1]
parts = _split_array_body(inner)
if len(parts) != 2:
decl.entries.append(InitRegEntry(line_num, e, "", None, None))
continue
addr_raw, data_raw = parts[0].strip(), parts[1].strip()
decl.entries.append(InitRegEntry(
line=line_num,
addr_raw=addr_raw,
data_raw=data_raw,
addr_value=parse_int_literal(addr_raw),
data_value=parse_int_literal(data_raw),
))
return decl
# -----------------------------------------------------------------------------
# Main parse
# -----------------------------------------------------------------------------
def parse_file(path: Union[str, Path]) -> ParsedDef:
p = Path(path)
text = p.read_text(encoding="utf-8", errors="replace")
return parse_text(text, str(p))
def parse_text(text: str, path: str = "<text>") -> ParsedDef:
raw_lines = text.split("\n")
parsed = ParsedDef(path=path, raw_lines=raw_lines)
parsed.commented_define_lines = _detect_commented_defines(raw_lines)
# Strip block comments (preserve line count)
cleaned_text = _strip_block_comments(text)
cleaned_lines = cleaned_text.split("\n")
# Strip line comments per-line
code_lines = [_strip_line_comments(l) for l in cleaned_lines]
# First pass: scan for the wrapper guard / package / endpackage / endif.
for i, line in enumerate(code_lines, start=1):
if not parsed.wrapper.has_ifndef_guard:
m = IFNDEF_RE.match(line)
if m and m.group("name") == "HOLOLINK_def":
parsed.wrapper.has_ifndef_guard = True
continue
if parsed.wrapper.has_ifndef_guard and not parsed.wrapper.has_define_guard:
m = DEFINE_RE.match(line)
if m and m.group("name") == "HOLOLINK_def":
parsed.wrapper.has_define_guard = True
continue
m = PACKAGE_RE.match(line)
if m and m.group("name") == "HOLOLINK_pkg":
parsed.wrapper.has_package_decl = True
parsed.wrapper.package_line = i
if ENDPACKAGE_RE.match(line):
parsed.wrapper.has_endpackage = True
parsed.wrapper.endpackage_line = i
if ENDIF_RE.match(line):
parsed.wrapper.has_endif = True
# Second pass: walk with `ifdef awareness, recording defines and arrays.
# Stack: list of (active: bool, branch_taken: bool). branch_taken tracks
# whether any branch in the current chain has been active (for `elsif).
cond_stack: List[Tuple[bool, bool]] = []
def is_active() -> bool:
return all(s[0] for s in cond_stack) if cond_stack else True
# Accumulate multi-line localparam declarations
accum: List[str] = []
accum_start: Optional[int] = None
def flush_accum_if_complete() -> None:
nonlocal accum, accum_start
joined = "\n".join(accum)
# Try to match either an array localparam or a vector localparam.
m = LP_ARRAY_RE.search(joined)
if m:
name = m.group("name")
if name == "init_reg":
parsed.init_reg = _parse_init_reg(m, accum_start or 0, parsed.defines)
else:
parsed.arrays[name] = _parse_array_decl(m, accum_start or 0, parsed.defines)
accum = []
accum_start = None
return
m = LP_VECTOR_RE.search(joined)
if m:
width_expr = m.group("width")
literal = m.group("literal").strip()
# Compute declared width: form `WIDTH-1:0` => width = WIDTH
width_value = None
if ":" in width_expr:
upper = eval_expr(width_expr.split(":")[0], parsed.defines)
lower = eval_expr(width_expr.split(":")[1], parsed.defines)
if upper is not None and lower is not None:
width_value = upper - lower + 1
parsed.gpio_reset_value = GpioResetValue(
line=accum_start or 0,
width_expr=width_expr,
width_value=width_value,
literal=literal,
)
accum = []
accum_start = None
for i, line in enumerate(code_lines, start=1):
stripped = line.strip()
# Conditional directives (must be processed regardless of active state)
m = IFDEF_RE.match(line)
if m:
name = m.group("name")
if name == "HOLOLINK_def":
# The wrapper guard — already counted in pass 1, skip
continue
outer_active = is_active()
local_active = name in parsed.defines and outer_active
cond_stack.append((local_active, local_active))
continue
m = IFNDEF_RE.match(line)
if m:
name = m.group("name")
if name == "HOLOLINK_def":
continue
outer_active = is_active()
local_active = (name not in parsed.defines) and outer_active
cond_stack.append((local_active, local_active))
continue
m = ELSIF_RE.match(line)
if m:
if not cond_stack:
parsed.parse_errors.append(ParseError(i, "`elsif without matching `ifdef"))
continue
top_active, top_taken = cond_stack[-1]
outer_active = all(s[0] for s in cond_stack[:-1]) if len(cond_stack) > 1 else True
new_active = (m.group("name") in parsed.defines) and (not top_taken) and outer_active
cond_stack[-1] = (new_active, top_taken or new_active)
continue
if ELSE_RE.match(line):
if not cond_stack:
parsed.parse_errors.append(ParseError(i, "`else without matching `ifdef"))
continue
top_active, top_taken = cond_stack[-1]
outer_active = all(s[0] for s in cond_stack[:-1]) if len(cond_stack) > 1 else True
new_active = (not top_taken) and outer_active
cond_stack[-1] = (new_active, top_taken or new_active)
continue
if ENDIF_RE.match(line):
if cond_stack:
cond_stack.pop()
continue
# Past the conditional handling — only continue if we're active
if not is_active():
# Track defines that appear in inactive branches so we can
# distinguish them from missing-entirely.
m = DEFINE_RE.match(line)
if m and m.group("name") != "HOLOLINK_def":
parsed.defines_skipped.append(m.group("name"))
continue
# `define directive
m = DEFINE_RE.match(line)
if m:
name = m.group("name")
if name == "HOLOLINK_def":
continue
value = m.group("value")
if value is not None:
value = value.strip()
# Strip trailing line comment artifacts (already removed by
# _strip_line_comments, but trailing whitespace is ok).
parsed.defines[name] = (value, i)
continue
# Accumulate localparam content
if "localparam" in line or accum:
if not accum:
accum_start = i
accum.append(line)
# Flush on terminating semicolon at top level
if ";" in line:
flush_accum_if_complete()
return parsed
# -----------------------------------------------------------------------------
# Convenience
# -----------------------------------------------------------------------------
def define_value(parsed: ParsedDef, name: str) -> Optional[str]:
"""Return the raw value string for a `define, or None if undefined."""
if name in parsed.defines:
return parsed.defines[name][0]
return None
def define_int(parsed: ParsedDef, name: str) -> Optional[int]:
"""Return the integer value of a `define if it parses to one, else None."""
v = define_value(parsed, name)
if v is None:
return None
return eval_expr(v, parsed.defines)
def is_defined(parsed: ParsedDef, name: str) -> bool:
return name in parsed.defines
def define_line(parsed: ParsedDef, name: str) -> Optional[int]:
if name in parsed.defines:
return parsed.defines[name][1]
return None
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
The author says: Targets HSB IP rev 16'h2604; backward-compatible with 16'h2603 (the public release rev). Prefer live HSB IP source when available; warn on unknown revisions. Requires Python 3.9+ with PyYAML for the generator.
Security
What our scanner noticed· Medium risk
- Large base64-encoded blobs
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Holoscan Team
- Publisher
- NVIDIA (Official)
- Distributed by
- NVIDIA
- Source
- NVIDIA/skills · skills/hsb-ip-def · commit fce3cca
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE-APACHE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Holoscan Team or NVIDIA.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download hsb-ip-def.zip