Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/najaeda/najaeda/docs/source/loading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,44 @@ Call :func:`najaeda.netlist.reset` at the beginning of scripts and tests when
you need an empty universe. Loading a design returns the top
:class:`najaeda.netlist.Instance` wrapper.

RTL specialization names
------------------------

The SystemVerilog and VHDL loaders share a specialization naming policy.
Instances with the same resolved parameters/generics share a model, including
explicit values equal to defaults. The selected top retains its source
module/entity name, including when its parameters are overridden. Its resolved
values remain available as metadata. For child models, the all-default
specialization keeps the source name. If a non-default top already owns that
name in a finite recursive hierarchy, the default-valued child uses the hash
fallback. If a VHDL default environment cannot be evaluated, naming uses all
resolved values; an unused overridden default does not prevent elaboration.
Other names list values differing from the declared
default environment, in declaration order: for example ``queue__DEPTH_12`` in
SystemVerilog or ``queue__depth_12`` in VHDL. SystemVerilog identifier case is
preserved; VHDL basic identifiers are canonicalized to lower case.

Integers use decimal with ``n`` for a minus sign, logic vectors use full-width
upper-case hexadecimal prefixed by ``h``, and vectors containing X/Z use binary
prefixed by ``b``. Scalar bits use ``0``/``1``, and VHDL booleans use
``true``/``false``. String values use readable names when sanitization preserves
all characters; otherwise they use hashes to avoid order-dependent collisions
between values such as ``"a-b"`` and ``"a b"``. A candidate longer than 64 characters, or an override without
a readable encoding, uses ``<module>__h<8 hex digits>`` from SHA-256 of a
versioned, length-prefixed canonical resolved environment. Digest-prefix
collisions promote both designs to 16 digits. Source module names are reserved
before elaboration; collisions with them use the hash form or report an error
if that is also occupied. Source identifiers themselves are never truncated.
SystemVerilog interface port bindings also contribute their resolved types and
alias relationships to identity; these implicit specializations use hash names.

Resolved values and the original source identifier are available from the raw
API; see :doc:`raw_api`. Names do not replace that metadata. Supported generic
types remain subject to each frontend's language subset. VHDL logic generics
preserve supported X/Z constants; other std_ulogic states and unsupported composite generic types produce diagnostics.
VHDL real generics support finite static real expressions; they do not imply
real-valued hardware support. Enumeration generics use their declared literal names.

Gate-level Verilog
------------------

Expand Down
30 changes: 30 additions & 0 deletions src/najaeda/najaeda/docs/source/raw_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,36 @@ by ``SNLInstance.getInstParameters()`` iterate in lexical parameter-name order.
This order is independent of name interning and is preserved across fresh-process
NajaIF reloads.

Elaborated RTL specializations
------------------------------

SystemVerilog and VHDL elaborated designs expose every resolved non-local
parameter/generic through ``SNLDesign.getParameters()``. The selected top retains
its source name even with non-default parameters; child models use specialization
names. Both expose the resolved values. ``getValue()`` returns
source-language literal text (including quotes on string literals), rather than
an instance override. These parameters describe fixed elaborated circuitry;
changing an instance parameter does not re-elaborate it. ``getInstParameters()``
therefore remains empty for these RTL instances. Use the raw API directly when
inspecting specialization metadata; high-level instance traversal still returns
the same specialized model.

The design attribute ``naja.source_module`` records the original module/entity
identifier. It is available without retaining source intent or a live AST:

.. code-block:: python

model = instance.getModel()
source_module = next(a.getValue() for a in model.getAttributes()
if a.getName() == "naja.source_module")
resolved = {p.getName(): p.getValue() for p in model.getParameters()}

The ``naja.elaboration_signature`` attribute is a versioned internal identity
record; callers should treat it as opaque. Both attributes and resolved values
survive NajaIF save/load, cloning and fresh-process reloads. Gate-level Verilog
uses the specialized design names directly and omits these informational
parameter declarations, including VHDL literal text.

``najaeda`` ships two Python API levels:

* :mod:`najaeda.netlist` is the supported high-level API for most tools.
Expand Down
6 changes: 3 additions & 3 deletions src/nl/formats/hdl/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ load("@rules_cc//cc:cc_library.bzl", "cc_library")

cc_library(
name = "naja_snl_hdl",
srcs = ["SNLRTLPrimitives.cpp"],
hdrs = ["SNLRTLPrimitives.h", "SNLHDLLibrary.h", "SNLHDLMuxSelection.h"],
srcs = ["SNLRTLPrimitives.cpp", "SNLHDLSpecialization.cpp"],
hdrs = ["SNLHDLSpecialization.h", "SNLRTLPrimitives.h", "SNLHDLLibrary.h", "SNLHDLMuxSelection.h"],
includes = ["."],
visibility = ["//visibility:public"],
deps = ["//src/nl/netlist:naja_nl"],
deps = ["//src/nl/netlist:naja_nl", "//thirdparty/sha256"],
)
5 changes: 3 additions & 2 deletions src/nl/formats/hdl/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# SPDX-License-Identifier: Apache-2.0

add_library(naja_snl_hdl STATIC SNLRTLPrimitives.cpp)
add_library(naja_snl_hdl STATIC SNLRTLPrimitives.cpp SNLHDLSpecialization.cpp)
set_property(TARGET naja_snl_hdl PROPERTY POSITION_INDEPENDENT_CODE ON)
target_link_libraries(naja_snl_hdl PUBLIC naja_nl)
target_include_directories(naja_snl_hdl PRIVATE ${PROJECT_SOURCE_DIR}/thirdparty/sha256)
target_include_directories(naja_snl_hdl PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

if(NOT BUILD_NAJA_PYTHON)
set_target_properties(naja_snl_hdl PROPERTIES PUBLIC_HEADER "SNLRTLPrimitives.h;SNLHDLLibrary.h")
set_target_properties(naja_snl_hdl PROPERTIES PUBLIC_HEADER "SNLRTLPrimitives.h;SNLHDLLibrary.h;SNLHDLSpecialization.h")
install(TARGETS naja_snl_hdl
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
Expand Down
164 changes: 164 additions & 0 deletions src/nl/formats/hdl/SNLHDLSpecialization.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// SPDX-FileCopyrightText: 2026 The Naja authors <https://github.com/najaeda/naja/blob/main/AUTHORS>
// SPDX-License-Identifier: Apache-2.0
#include "SNLHDLSpecialization.h"

#include "NLLibrary.h"
#include "NLException.h"
#include "SNLDesign.h"
#include "SNLAttributes.h"
#include "SNLParameter.h"
#include "sha-256.h"

namespace naja::NL {
namespace {
constexpr auto sourceAttribute = "naja.source_module";
constexpr auto signatureAttribute = "naja.elaboration_signature";
std::string digest(const std::string& text) {
uint8_t bytes[32];
calc_sha_256(bytes, text.data(), text.size());
std::string result;
for (auto byte : bytes) {
result += "0123456789abcdef"[byte >> 4];
result += "0123456789abcdef"[byte & 15];
}
return result;
}
void append(std::string& result, const std::string& value) {
result += std::to_string(value.size()) + ":" + value;
}
}

std::string SNLHDLSpecialization::signature(const std::vector<SNLHDLParameter>& parameters, const std::string& context) {
std::string result = "naja-elaboration-v1:";
for (const auto& parameter : parameters) {
append(result, parameter.name);
append(result, parameter.identity);
}
if (!context.empty()) append(result, context);
return result;
}

std::string SNLHDLSpecialization::attribute(const SNLDesign* design, const std::string& name) {
for (const auto& attr : SNLAttributes::getAttributes(design))
if (attr.getName().getString() == name) return attr.getValue().getString();
return {};
}
bool SNLHDLSpecialization::isElaborated(const SNLDesign* design) {
return !attribute(design, sourceAttribute).empty();
}

std::string SNLHDLSpecialization::name(NLLibrary* library, const std::string& source,
const std::vector<SNLHDLParameter>& parameters, const std::set<std::string>& sourceNames,
const std::string& context, bool isTop) {
const auto identity = signature(parameters, context);
auto candidate = source;
bool defaults = context.empty(), readable = context.empty();
for (const auto& parameter : parameters) {
if (parameter.isDefault) continue;
defaults = false;
if (!parameter.nameValue) readable = false;
else {
const auto safe = [](const std::string& value) {
return value.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") == std::string::npos;
};
if (!safe(parameter.name) || !safe(*parameter.nameValue)) readable = false;
candidate += "__" + parameter.name + "_" + *parameter.nameValue;
}
}
const auto matches = [&](SNLDesign* design) {
return attribute(design, sourceAttribute) == source &&
attribute(design, signatureAttribute) == identity;
};
const auto available = [&](const std::string& value) {
auto* existing = library->getSNLDesign(NLName(value));
return (!existing || matches(existing)) && (value == source || !sourceNames.contains(value));
};
// The selected root is an external interface. Parameter specialization only
// changes child model names; root metadata still records the resolved values.
if (isTop || defaults) {
if (available(source)) return source;
auto* existing = library->getSNLDesign(NLName(source));
if (isTop || !existing || attribute(existing, sourceAttribute) != source)
throw NLException("Conflicting HDL source design name: " + source);
// A non-default root may own the plain name in a finite recursive
// hierarchy. Its default-valued child follows the usual hash fallback.
}
if (readable && candidate.size() <= 64 && available(candidate)) return candidate;
const auto hash = digest(identity);
candidate = source + "__h" + hash.substr(0, 8);
// Once a prefix has collided, all members of that bucket use 64 bits.
for (auto* design : library->getSNLDesigns()) {
if (attribute(design, sourceAttribute) != source) continue;
const auto previousHash = digest(attribute(design, signatureAttribute));
if (previousHash.substr(0, 8) == hash.substr(0, 8) &&
design->getName().getString() == source + "__h" + previousHash.substr(0, 16)) {
const auto longer = source + "__h" + hash.substr(0, 16);
if (available(longer)) return longer;
throw NLException("Conflicting hashed HDL specialization: " + longer);
}
}
if (available(candidate)) return candidate;
// A genuine truncated-digest collision promotes both specializations. User
// names never get renamed and cannot be bypassed with a longer digest.
auto* previous = library->getSNLDesign(NLName(candidate));
if (previous && attribute(previous, sourceAttribute) == source && !sourceNames.contains(candidate)) {
const auto previousIdentity = attribute(previous, signatureAttribute);
const auto previousHash = digest(previousIdentity);
if (previousHash.substr(0, 8) == hash.substr(0, 8) && previousIdentity != identity) {
const auto longer = source + "__h" + hash.substr(0, 16);
const auto previousLonger = source + "__h" + previousHash.substr(0, 16);
if (longer != previousLonger && available(longer) &&
!sourceNames.contains(previousLonger) && !library->getSNLDesign(NLName(previousLonger))) {
previous->setName(NLName(previousLonger));
return longer;
}
}
}
// Reuse an already-promoted specialization on a later load.
const auto longer = source + "__h" + hash.substr(0, 16);
if (auto* existing = library->getSNLDesign(NLName(longer)); existing && matches(existing)) return longer;
throw NLException("Conflicting hashed HDL specialization: " + candidate);
}

void SNLHDLSpecialization::annotate(SNLDesign* design, const std::string& source,
const std::vector<SNLHDLParameter>& parameters, const std::string& context) {
SNLAttributes::addAttribute(design, SNLAttribute(NLName(sourceAttribute), SNLAttributeValue(source)));
SNLAttributes::addAttribute(design, SNLAttribute(NLName(signatureAttribute), SNLAttributeValue(signature(parameters, context))));
for (const auto& parameter : parameters)
SNLParameter::create(design, NLName(parameter.name), SNLParameter::Type::Decimal, parameter.literal);
}

std::string SNLHDLSpecialization::identifierValue(std::string value) {
for (auto& c : value)
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) c = '_';
return value;
}
std::string SNLHDLSpecialization::integerValue(std::string value) {
std::string result;
for (char c : value) {
if (c == '+') continue;
if (c == '-') c = 'n';
else if (c == '.') c = 'p';
else if (c == 'E') c = 'e';
result += c;
}
return result;
}
std::string SNLHDLSpecialization::bitValue(const std::string& bits, bool scalar) {
if (scalar && bits.size() == 1 && (bits[0] == '0' || bits[0] == '1')) return bits;
if (bits.find_first_not_of("01") != std::string::npos) {
std::string result = "b" + bits;
for (auto& c : result) if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
return result;
}
std::string padded((4 - bits.size() % 4) % 4, '0');
padded += bits;
std::string result = "h";
for (size_t i = 0; i < padded.size(); i += 4) {
unsigned digit = 0;
for (size_t j = 0; j < 4; ++j) digit = digit * 2 + (padded[i + j] == '1');
result += "0123456789ABCDEF"[digit];
}
return result;
}
}
39 changes: 39 additions & 0 deletions src/nl/formats/hdl/SNLHDLSpecialization.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// SPDX-FileCopyrightText: 2026 The Naja authors <https://github.com/najaeda/naja/blob/main/AUTHORS>
// SPDX-License-Identifier: Apache-2.0
#pragma once

#include <optional>
#include <set>
#include <string>
#include <vector>

namespace naja::NL {
class NLLibrary;
class SNLDesign;

// Frontends supply resolved values in declaration order. Identity text must
// include type/shape information; literal text is valid in the source language.
struct SNLHDLParameter {
std::string name;
std::string identity;
std::string literal;
std::optional<std::string> nameValue;
bool isDefault = false;
};

class SNLHDLSpecialization {
public:
static std::string signature(const std::vector<SNLHDLParameter>& parameters, const std::string& context = {});
static std::string name(NLLibrary* library, const std::string& source,
const std::vector<SNLHDLParameter>& parameters,
const std::set<std::string>& sourceNames, const std::string& context = {},
bool isTop = false);
static void annotate(SNLDesign* design, const std::string& source,
const std::vector<SNLHDLParameter>& parameters, const std::string& context = {});
static bool isElaborated(const SNLDesign* design);
static std::string attribute(const SNLDesign* design, const std::string& name);
static std::string identifierValue(std::string value);
static std::string integerValue(std::string value);
static std::string bitValue(const std::string& bits, bool scalar = false);
};
}
Loading
Loading