Skip to content
Merged
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
81 changes: 81 additions & 0 deletions docs/syntax/instance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
Instances of types can be associated to a package, allowing structured constant
values to be declared.

## Example

The Packtype definition can either use a Python dataclass style or the Packtype
custom grammar:

=== "Python (.py)"

```python linenums="1"
import packtype
from packtype import Constant, Scalar

@packtype.package()
class MyPackage:
pass

@MyPackage.enum()
class Month:
JAN : Constant
FEB : Constant
...
DEC : Constant

@MyPackage.struct()
class Date:
year : Scalar[12]
month : Month
day : Scalar[5]

MyPackage._pt_attach_instance("SUMMER_START", Month.JUN)
MyPackage._pt_attach_instance("SUMMER_END", Month.AUG)
MyPackage._pt_attach_instance("CHRISTMAS", Date(year=2025, month=Month.DEC, day=25))
```

=== "Packtype (.pt)"

```sv linenums="1"
package my_package {
enum month_e {
JAN : constant
FEB : constant
...
DEC : constant
}

struct date_t {
year : scalar[12]
month : month_e
day : scalar[5]
}

SUMMER_START : month_e = month_e::JUN
SUMMER_END : month_e = month_e::AUG
CHRISTMAS : date_t = {
year = 2025
month = month_e::DEC
day = 25
}
}
```

As rendered to SystemVerilog:

```sv linenums="1"
package my_package;

localparam month_e SUMMER_START = month_e'(7);

localparam month_e SUMMER_END = month_e'(9);

// CHRISTMAS
localparam date_t CHRISTMAS = '{
day: 5'h19
, month: month_e'(11)
, year: 12'h7E9
};

endpackage : my_package
```
52 changes: 52 additions & 0 deletions examples/constants/spec.pt
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package date_consts {

// Basic definitions
DAYS_PER_YEAR : constant = 365
DAYS_PER_WEEK : constant = 7
HOURS_PER_DAY : constant[8] = 24
MINS_PER_HOUR : constant = 60

// Weekdays
enum weekday_e {
MON : constant
TUE : constant
WED : constant
THU : constant
FRI : constant
SAT : constant
SUN : constant
}

START_OF_WEEK : weekday_e = weekday_e::MON
END_OF_WEEK : weekday_e = weekday_e::SUN

// Months
enum month_e {
JAN : constant
FEB : constant
MAR : constant
APR : constant
MAY : constant
JUN : constant
JUL : constant
AUG : constant
SEP : constant
OCT : constant
NOV : constant
DEC : constant
}

// Date
struct date_t {
year : scalar[12]
month : month_e
day : scalar[5]
}

CHRISTMAS : date_t = {
year = 2025
month = month_e::DEC
day = 25
}

}
41 changes: 40 additions & 1 deletion examples/constants/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#

import packtype
from packtype import Constant
from packtype import Constant, Scalar


@packtype.package()
Expand All @@ -14,3 +14,42 @@ class DateConsts:
DAYS_PER_WEEK: Constant = 7
HOURS_PER_DAY: Constant[8] = 24
MINS_PER_HOUR: Constant = 60


@DateConsts.enum()
class Weekday:
MON: Constant
TUE: Constant
WED: Constant
THU: Constant
FRI: Constant
SAT: Constant
SUN: Constant


@DateConsts.enum()
class Month:
JAN: Constant
FEB: Constant
MAR: Constant
APR: Constant
MAY: Constant
JUN: Constant
JUL: Constant
AUG: Constant
SEP: Constant
OCT: Constant
NOV: Constant
DEC: Constant


@DateConsts.struct()
class Date:
year: Scalar[12]
month: Month
day: Scalar[5]


DateConsts._pt_attach_instance("START_OF_WEEK", Weekday.MON)
DateConsts._pt_attach_instance("END_OF_WEEK", Weekday.SUN)
DateConsts._pt_attach_instance("CHRISTMAS", Date(year=2025, month=Month.DEC, day=25))
5 changes: 4 additions & 1 deletion examples/constants/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ this_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
export PYTHONPATH=${this_dir}/../..:$PYTHONPATH

# Invoke packtype
python3 -m packtype --debug code package sv ${this_dir}/out spec.py
python3 -m packtype --debug code package sv ${this_dir}/out_py spec.py

# Invoke packtype on Packtype syntax
python3 -m packtype --debug code package sv --type-filter none ${this_dir}/out_pt ${this_dir}/spec.pt
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ nav:
- Arrays: syntax/arrays.md
- Constants: syntax/constant.md
- Enumerations: syntax/enum.md
- Instances: syntax/instance.md
- Packages: syntax/package.md
- Scalars: syntax/scalar.md
- Structs: syntax/struct.md
Expand Down
4 changes: 4 additions & 0 deletions packtype/common/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ def evaluate(self, cb_lookup: Callable[[str], int]) -> int:
# Check if the LHS is a _PT_BASE attribute
elif hasattr(lhs, "_PT_BASE") and type(lhs).__name__ != "Constant":
return lhs
# Check if the LHS is a foreign-reference (supports enum references)
elif type(lhs).__name__ == "ForeignRef":
f_type = cb_lookup(lhs.package)
return int(getattr(f_type, lhs.name))
# Otherwise, cast LHS to an integer
else:
return int(lhs)
Expand Down
49 changes: 48 additions & 1 deletion packtype/grammar/declarations.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from dataclasses import dataclass
from pathlib import Path

from .. import utils
from ..common.expression import Expression
from ..types.alias import Alias
from ..types.array import ArraySpec
Expand Down Expand Up @@ -80,7 +81,7 @@ def resolve(
if isinstance(raw_dim, Expression):
eval_dims.append(raw_dim.evaluate(cb_resolve))
else:
raise Exception("Unexpected width type in DeclScalar")
raise ValueError("Unexpected width type in DeclScalar")
return eval_dims


Expand Down Expand Up @@ -143,6 +144,52 @@ def to_instance(
return const


@dataclass
class FieldAssignment:
field: str
value: Expression


@dataclass()
class FieldAssignments:
assignments: list[FieldAssignment]


@dataclass()
class DeclInstance:
position: Position
name: str
ref: str
assignment: Expression | FieldAssignments
description: Description | None = None

def to_instance(
self,
cb_resolve: Callable[
[
str,
],
int | type[Base],
],
) -> Base:
# Get the referenced type
ref = cb_resolve(self.ref)
# If the assignment is a simple expression, referenced type needs to be
# either a scalar or an enum
if isinstance(self.assignment, Expression):
if not issubclass(ref, Scalar | Enum):
raise TypeError(f"{ref} must be a scalar or enum for simple expression assignment")
return utils.unpack(ref, self.assignment.evaluate(cb_resolve))
# If instead we get a field assigment, referenced type needs to be a
# struct or union
elif isinstance(self.assignment, FieldAssignments):
if not issubclass(ref, Struct | Union):
raise TypeError(f"{ref} must be a struct or union for field assignment")
return ref(
**{x.field: x.value.evaluate(cb_resolve) for x in self.assignment.assignments}
)


@dataclass()
class DeclScalar:
position: Position
Expand Down
34 changes: 25 additions & 9 deletions packtype/grammar/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
DeclConstant,
DeclEnum,
DeclImport,
DeclInstance,
DeclPackage,
DeclScalar,
DeclStruct,
Expand Down Expand Up @@ -135,6 +136,8 @@ def _resolve(ref: str | ForeignRef) -> int:
match decl:
# Imports
case DeclImport():
# Check for name collisions
_check_collision(decl.foreign.name)
# Resolve the package
if (foreign_pkg := namespaces.get(decl.foreign.package, None)) is None:
raise ImportError(f"Unknown package '{decl.foreign.package}'")
Expand All @@ -144,31 +147,31 @@ def _resolve(ref: str | ForeignRef) -> int:
f"'{decl.foreign.name}' not declared in package "
f"'{decl.foreign.package}'"
)
# Check for name collisions
_check_collision(decl.foreign.name)
# Remember this type
if isinstance(foreign_type, Constant):
known_entities[decl.foreign.name] = (foreign_type, decl.position)
else:
known_entities[decl.foreign.name] = (foreign_type, decl.position)
# Aliases
case DeclAlias():
# Check for name collisions
_check_collision(decl.name)
# Attach to the package
package._pt_attach(
alias := decl.to_class(_resolve),
name=decl.name,
)
# Check for name collisions
_check_collision(decl.name)
# Remember this type
known_entities[decl.name] = (alias, decl.position)
# Build constants
case DeclConstant():
# Check for name collisions
_check_collision(decl.name)
# Attach to the package
constant = decl.to_instance(_resolve)
if keep_expression:
constant._PT_EXPRESSION = decl.expr
package._pt_attach_constant(decl.name, constant)
# Check for name collisions
_check_collision(decl.name)
# Check for a constant override
if decl.name in constant_overrides:
get_log().debug(
Expand All @@ -178,21 +181,34 @@ def _resolve(ref: str | ForeignRef) -> int:
constant._pt_set(int(constant_overrides[decl.name]))
# Remember this constant
known_entities[decl.name] = (constant, decl.position)
# Build instances (constants that reference other types)
case DeclInstance():
# Check for name collisions
_check_collision(decl.name)
# Attach to the package
package._pt_attach_instance(
decl.name,
inst := decl.to_instance(_resolve),
)
# Remember this type
known_entities[decl.name] = (inst, decl.position)
# Build aliases and scalars
case DeclScalar() | DeclAlias():
# Check for name collisions
_check_collision(decl.name)
# Attach to the package
package._pt_attach(
obj := decl.to_class(_resolve),
name=decl.name,
)
# Check for name collisions
_check_collision(decl.name)
# Remember this type
known_entities[decl.name] = (obj, decl.position)
# Build enums, structs, and unions
case DeclEnum() | DeclStruct() | DeclUnion():
package._pt_attach(obj := decl.to_class(source, _resolve))
# Check for name collisions
_check_collision(decl.name)
# Attach to the package
package._pt_attach(obj := decl.to_class(source, _resolve))
# Remember this type
known_entities[decl.name] = (obj, decl.position)
case _:
Expand Down
Loading