Skip to content

Writing and reading attributes

An attribute is a small piece of data that you write in front of a declaration. You declare it first, with its name, the places it may be written and its fields: attribute Route on method { path: string }. Then you write it with #[, as in #[Route(path: '/users')]. An attribute does nothing by itself. Your program reads it back with Core\Attributes.

Writing an attribute

An attribute attaches fixed values to a declaration. You declare it first, with attribute Table on class { name: string }. That line gives the attribute's name, the places it may be written and its fields. Then you write it as #[Table(name: 'users')] in front of a class.

The words after on list the places: class, method, property and parameter. An attribute written in any other place does not compile. Novis also checks your values against the fields.

An attribute declared inside a class or an interface may be used only by the classes that extend or implement that type. Outside that type, its name is written with the owner, as in Job::Meta.

Write repeatable before attribute to allow more than one use on the same declaration. A /// comment above a field describes it, and the editor shows that text.

An attribute is not a class. Novis creates no object for it, and every value is known while the program is compiled.

Good to know: # on its own starts a comment. Only #[ starts an attribute.

Label a class and read it back

<?nvs
// Shows how to declare an attribute, attach it to a class and read it back.
// `attribute Table on class` declares an attribute that a class may carry.
// The fields in the braces are the values each use must give.
attribute Table on class { name: string }
#[Table(name: 'users')]
class User
{
public string $email = '';
}
// `Core\Attributes::get` returns the values attached to the class, or `null`
// when the class has none. `User::constructor` names the class itself.
var $table = Core\Attributes::get<Table>(User::constructor);
if ($table != null) {
// This prints `users`.
echo $table->name, "\n";
}
// A class with no attribute on it. The result is `null`.
class Session
{}
var $none = Core\Attributes::get<Table>(Session::constructor);
echo $none == null ? "no table name\n" : "a table name\n";
Output
users
no table name

Several attributes on one declaration

<?nvs
// Shows several attributes on one declaration, and an attribute on a property
// and on a parameter.
// `repeatable` allows more than one `Tag` on the same declaration.
// `on class, property` lists where a `Tag` may be written.
repeatable attribute Tag on class, property { label: string }
// A second attribute, for parameters only.
attribute Inject on parameter { from: string }
#[Tag(label: 'billing')]
#[Tag(label: 'nightly')]
class Invoice
{
#[Tag(label: 'money')]
public int $cents = 0;
public function send(#[Inject(from: 'config')] string $to): string
{
return $to;
}
}
// `Core\Attributes::all` returns every `Tag` on the class, in the order you
// wrote them. This prints 2, `billing` and `nightly`.
var $tags = Core\Attributes::all<Tag>(Invoice::constructor);
echo Core\Arr::count($tags), "\n";
foreach ($tags as var $tag) {
echo $tag->label, "\n";
}
// The second argument is the name of the property or the parameter.
// This prints `money`.
var $onProperty = Core\Attributes::get<Tag>(Invoice::constructor, 'cents');
if ($onProperty != null) {
echo $onProperty->label, "\n";
}
// The parameter `$to` of the method `send` has an `Inject`. This prints `config`.
var $onParameter = Core\Attributes::get<Inject>(Invoice::send, 'to');
if ($onParameter != null) {
echo $onParameter->from, "\n";
}
Output
2
billing
nightly
money
config

A schedule read from the job classes

<?nvs
// A nightly schedule that reads itself from the job classes. Each class says
// how often it runs, so adding a job means writing one class. There is no
// second list to keep up to date.
class Every
{
public const int HOUR = 60;
public const int QUARTER_HOUR = 15;
}
// Only a class that implements `Job` may use the attribute `Meta`. Outside
// `Job`, you write the names as `Job::Level` and `Job::Meta`.
interface Job
{
enum Level: int
{
Normal = 1,
Urgent = 2,
}
attribute Meta on class { name: string, everyMinutes: int, level: Level }
}
// A class constant and an enum case are both allowed in an attribute, because
// their values are known while the program is compiled.
#[Meta(name: 'send invoices', everyMinutes: Every::HOUR, level: Job::Level::Normal)]
class SendInvoices implements Job
{
public static function run(): string
{
return '12 invoices sent';
}
}
#[Meta(name: 'clean sessions', everyMinutes: Every::QUARTER_HOUR, level: Job::Level::Normal)]
class CleanSessions implements Job
{
public static function run(): string
{
return '84 sessions removed';
}
}
#[Meta(name: 'charge cards', everyMinutes: Every::HOUR, level: Job::Level::Urgent)]
class ChargeCards implements Job
{
public static function run(): string
{
return '3 cards charged';
}
}
var $schedule = [
Core\Attributes::get<Job::Meta>(SendInvoices::constructor) ?? throw new RuntimeError('no job'),
Core\Attributes::get<Job::Meta>(CleanSessions::constructor) ?? throw new RuntimeError('no job'),
Core\Attributes::get<Job::Meta>(ChargeCards::constructor) ?? throw new RuntimeError('no job'),
];
foreach ($schedule as var $job) {
string $mark = $job->level == Job::Level::Urgent ? ' (urgent)' : '';
echo $job->name, ': every ', $job->everyMinutes as string, ' minutes', $mark, "\n";
}
Output
send invoices: every 60 minutes
clean sessions: every 15 minutes
charge cards: every 60 minutes (urgent)

A value that is not known while compiling

<?nvs
// Shows that every value in an attribute must be known while the program is
// compiled. `$host` is a variable, so this program does not compile.
// proof: compile-error
attribute Cache on method { key: string }
string $host = 'example.test';
class Page
{
#[Cache(key: 'host-' . $host)]
public function show(): int
{
return 1;
}
}
Output
error[E0725]: an attribute's field value is not a compile-time constant
--> 04-a-value-that-is-not-known-while-compiling.nvs:11:18
|
11 | #[Cache(key: 'host-' . $host)]
| ^^^^^^^^^^^^^^^ this is computed when the program runs
= help: an attribute's value is a literal, a class constant or an enum case. It is fixed when the program compiles, so it cannot be a variable, a call or a `new`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

A base class declares its attributes

<?nvs
// Shows a base class that declares its own attributes, with a comment on each field.
abstract class Storable
{
/// Adds a database index over one or more columns of this table.
repeatable attribute Index on class {
/// The column names, separated by commas.
columns: string,
/// `true` means no two rows may have the same values in these columns.
unique?: bool,
}
/// Sets how a property is stored.
attribute Column on property {
/// The longest text this column can store.
length: int,
}
}
// `Customer` extends `Storable`, so it may use `Index` and `Column`.
// A class that does not extend `Storable` cannot use them.
#[Index(columns: 'email', unique: true)]
#[Index(columns: 'country, city')]
class Customer extends Storable
{
#[Column(length: 200)]
public string $email = '';
}
// Outside `Storable`, the full name is `Storable::Index`. This prints both indexes.
foreach (Core\Attributes::all<Storable::Index>(Customer::constructor) as var $index) {
string $kind = ($index->unique ?? false) ? 'unique' : 'plain';
echo $index->columns, ' (', $kind, ")\n";
}
// This prints `200`.
var $column = Core\Attributes::get<Storable::Column>(Customer::constructor, 'email');
echo $column?->length ?? 0, "\n";
Output
email (unique)
country, city (plain)
200

Details

A declaration is written attribute Name on <places> { fields }. The places are class, method, property and parameter, and the list needs at least one of them. Any other word in the list is E1004. A field is written name: T, or name?: T when a use may leave it out.

A /// comment above the declaration describes the attribute. A /// comment above a field describes that field. The editor shows the text when you type the name or point at it.

The name after #[ is checked first. A name that nothing declares is E0303. A class, an interface, an enum or a type alias is E1005, because only an attribute declaration may follow #[. An attribute with no name, such as #[{ inject: "repo" }], is E0140.

Then the place is checked. An attribute written where its on list does not allow it is E0874, and the message names the places it allows.

An attribute declared inside a class or an interface is used only on the classes that extend or implement it, and on their members. A use anywhere else is E1006. That includes the class or interface that declares it.

An attribute may be written once on each declaration. Write repeatable before attribute to allow it more than once. A second use without it is E0763. Novis keeps every copy of a repeatable attribute, in the order you wrote them.

Your values are then checked against the fields. A missing field or a value of the wrong type is E0401, and the help line names the missing field. A use may also give fields that the declaration does not list, and they are not checked. #[Name] with no parentheses gives no fields, so it is E0401 when the declaration has a required field.

Each value needs its field name. #[Tag(5)] is a syntax error, and the same field written twice is E0494.

A value may be a number (also a negative one), a string, true, false or null. It may also be an anonymous object, an array, a class constant, an enum case or Foo::class. A variable, a call, new, arithmetic such as 1 + 2 and a string with {$name} in it are each E0725. A class constant that is secret is E0727.

An array is checked like any other value. [1, 2] fits a field typed array<int>, and ['a'] does not.

In front of a statement or a local variable, an attribute is E0101.

Several attributes can share one bracket, with commas between them: #[A(n: 1), B(s: "x")]. This is the same as writing each one in its own bracket.

Reading attributes back

Core\Attributes::get and Core\Attributes::all read the attributes attached to a declaration. You write the name of an attribute declaration between < and >, as in get<Tag>. get returns the one Tag on the declaration, or null when it has none. all returns every Tag, in the order they are written, and an empty list when there is none.

You name the declaration with a method reference: Users::show for a method, and Users::constructor for the class itself. A second argument names one property or one parameter of that declaration, and you then get the attributes on that one. This second name must be written out. If you write a variable there, the result is null or an empty list.

The result has the fields of the declaration. Write var for the variable that receives it, as in var $tag = Core\Attributes::get<Tag>(Users::show);.

Novis does all of this while it compiles your program. The call is replaced by the value it found, so there is no lookup while the program runs.

Read every attribute with all

<?nvs
// Shows how to read every attribute of one kind attached to one declaration.
// `Core\Attributes::all` returns them in the order they are written.
// `repeatable` allows more than one `Tag` on the same method.
repeatable attribute Tag on method { name: string }
class Article
{
#[Tag(name: 'news')]
#[Tag(name: 'sport')]
#[Tag(name: 'local')]
public function publish(): int
{
return 1;
}
public function archive(): int
{
return 2;
}
}
// This prints `news`, `sport` and `local`, one per line, in that order.
var $tags = Core\Attributes::all<Tag>(Article::publish);
foreach ($tags as var $tag) {
echo $tag->name, "\n";
}
// `archive` has no attribute. The result is an empty list, so this prints 0.
var $none = Core\Attributes::all<Tag>(Article::archive);
echo Core\Arr::count($none), "\n";
Output
news
sport
local
0

Read an attribute on a property or a parameter

<?nvs
// Shows the second argument of `Core\Attributes::get`. It names one property
// or one parameter, and you then get the attributes on that one.
attribute Column on property { name: string }
attribute Range on parameter { min: int, max: int }
class Product
{
#[Column(name: 'product_title')]
public string $title = '';
public function discount(#[Range(min: 0, max: 90)] int $percent): int
{
return $percent;
}
}
// A property of a class. `Product::constructor` names the class, and
// `"title"` names the property. This prints `product_title`.
var $column = Core\Attributes::get<Column>(Product::constructor, 'title');
if ($column != null) {
echo $column->name, "\n";
}
// A parameter of a method. `Product::discount` names the method, and
// `"percent"` names the parameter. This prints `0 to 90`.
var $range = Core\Attributes::get<Range>(Product::discount, 'percent');
if ($range != null) {
echo $range->min, ' to ', $range->max, "\n";
}
// The name must be written out, as it is above. If you write a variable there,
// the result is `null`.
string $field = 'title';
var $computed = Core\Attributes::get<Column>(Product::constructor, $field);
echo $computed == null ? "null\n" : "a column name\n";
Output
product_title
0 to 90
null

A permission check built from the methods

<?nvs
// A permission check that reads itself from the methods. Each method says
// which permission it needs, so adding a method means writing one attribute.
// There is no second list to keep up to date.
attribute Requires on method { permission: string }
class Orders
{
#[Requires(permission: 'orders.read')]
public static function show(): string
{
return 'order 1042';
}
#[Requires(permission: 'orders.write')]
public static function cancel(): string
{
return 'order 1042 cancelled';
}
public static function ping(): string
{
return 'ok';
}
}
class Access
{
// The parameter type is the fields of `Requires`. A `Requires` attribute
// is read back as a value of this type.
public static function check(string $action, ?{ permission: string } $needs, array<string> $granted): string
{
if ($needs == null) {
return $action . ': open to everyone';
}
if (Core\Arr::contains($granted, $needs->permission)) {
return $action . ': allowed';
}
return $action . ': needs ' . $needs->permission;
}
}
array<string> $granted = ['orders.read'];
// This prints one line per action: `show` is allowed, `cancel` needs a
// permission this user does not have, and `ping` needs none at all.
echo Access::check('show', Core\Attributes::get<Requires>(Orders::show), $granted), "\n";
echo Access::check('cancel', Core\Attributes::get<Requires>(Orders::cancel), $granted), "\n";
echo Access::check('ping', Core\Attributes::get<Requires>(Orders::ping), $granted), "\n";
Output
show: allowed
cancel: needs orders.write
ping: open to everyone

Get with two matching attributes

<?nvs
// Shows that `get` needs at most one attribute of the kind you name. `Engine`
// has two `Tag` attributes, so this program does not compile. Use `all` instead.
// proof: compile-error
repeatable attribute Tag on class { label: string }
#[Tag(label: 'fast')]
#[Tag(label: 'safe')]
class Engine
{}
var $tag = Core\Attributes::get<Tag>(Engine::constructor);
Output
error[E0728]: `Engine::constructor` has 2 `Tag` attributes
--> 04-get-with-two-matching-attributes.nvs:13:12
|
13 | var $tag = Core\Attributes::get<Tag>(Engine::constructor);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `get` returns at most one
= help: write `Core\Attributes::all<T>(…)`, which returns every match
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

get on a declaration with two Tag attributes is E0728. all has no such limit.

The name between < and > must be an attribute declaration. An attribute declared inside a class or an interface is written with its owner, as in get<Job::Meta>. A shape such as { label: string }, a type alias, a class and int are each E1008. get with no type is E0442.

The retrieval finds only attributes written with the name you give. Two declarations with the same fields are still two different attributes, and get for one never returns the other.

You can also name an attribute that Novis reads itself, such as Core\Route or Core\Command. The result is the fields written in that attribute. A field the attribute does not need may be missing, so read it with ??, as in $command->about ?? ''.

Every class has a constructor, even when you do not write one. So Users::constructor always names the class.

The first argument must be a method reference written in the call. A variable that contains one is E0730. A method that is private is E0471 outside its class. A static method is named the same way, as Orders::show.

A property or parameter name written in quotes is checked. A name that the class or the method does not have is E0798. For the parameters of the constructor, use Users::constructor and the parameter's name. For a promoted constructor parameter, you get the attributes on the parameter and on the property together.

A subclass does not get its parent's class attributes. B::constructor finds nothing when only the parent class A has the attribute. A method is read where it is declared. When B does not override show, B::show is the method A declares, and you get the attributes A wrote on it. When B overrides show, you get only the attributes on B's method. An interface method's attributes are read with I::m.

A class constant, an enum case or Foo::class in an attribute is read back as its value. The value comes from the place where the attribute is written. In a file with namespace Shop;, K::class is read back as "Shop\K". A class constant whose own value is another class's constant is E0792 in an attribute. When get or all matches that attribute, the call is E0731 too.

Each call gives a new copy of the value. A change to the copy does not change what the next call returns.

The attributes Novis reads

Most attributes are metadata. Novis stores what you attach and your program reads it back, and nothing else happens. A small set of names is different. Novis owns those names, and when an attribute points to one of them the compiler acts on it: it writes a JSON codec for the class, adds a row to the route table, adds a row to the command table, or registers a test.

Novis decides by the declaration a name points to, not by the way the name is written. #[Core\Command] and an imported #[Command] are one attribute. An attribute of your own called Command is a different declaration, so it stays ordinary metadata however you write it. An import binds one whole name, so use Core\Json; followed by #[Json\Derive] points at nothing and does not compile.

Each name Novis owns has a fixed list of options. An option it does not know, an option of the wrong type, and an option given twice are each an error while your program compiles.

The examples show one attribute written both ways, an attribute of your own that shares a name with one of these, and a class that carries both kinds at once.

One attribute written two ways

<?nvs
// Shows the two ways to write one of the attributes Novis owns. Novis reads the
// name after it works out which declaration it points to. `#[Core\Command]` and
// an imported `#[Command]` point to the same declaration, so both methods below
// are commands.
use Core\Command;
class Jobs
{
#[Core\Command(name: 'import', about: 'Read rows from a file')]
public static function import(): void
{}
// The `use Core\Command;` above makes this short name the same attribute.
#[Command(name: 'export', about: 'Write rows to a file')]
public static function export(): void
{}
}
// `Core\Command::help(null)` lists every command. This prints both of them.
echo Core\Command::help(null);
Output
usage: <command> [arguments]
commands:
import Read rows from a file
export Write rows to a file

An attribute of your own with the same name

<?nvs
// Shows an attribute of your own whose name is also a name Novis owns. Only
// `#[Core\Command]` declares a command. The `#[Command]` below is your own
// attribute, so it is data you store and read back yourself.
attribute Command on method { name: string, note: string }
class Jobs
{
// Novis reads this one. The command table has a command called `import`.
#[Core\Command(name: 'import', about: 'Read rows from a file')]
public static function import(): void
{}
}
class Reports
{
// Your own `Command` attribute. This method is not a command, so the word
// `import` is free to use again here.
#[Command(name: 'import', note: 'runs every night')]
public static function daily(): void
{}
}
var $mine = Core\Attributes::get<Command>(Reports::daily);
// This prints `import runs every night`.
if ($mine != null) {
echo $mine->name, ' ', $mine->note, "\n";
}
Output
import runs every night

A class that carries both kinds

<?nvs
// A class with both kinds of attribute, which is the usual case at work.
// Novis reads `#[Core\Json\Derive]` and writes the JSON encoder for the class.
// `#[Audited]` is your own attribute, so Novis stores it and your code reads it.
attribute Audited on class { by: string, since: string }
#[Core\Json\Derive]
#[Audited(by: 'payments', since: '2026-01-14')]
class Payment
{
public string $reference;
public uint $cents;
public function constructor(string $reference, uint $cents)
{
$this->reference = $reference;
$this->cents = $cents;
}
}
var $payment = new Payment('PAY-1042', 2599);
// The encoder comes from the attribute. This prints the payment as JSON.
echo Core\Json::encode($payment), "\n";
// Your own attribute is read with `Core\Attributes::get`.
var $owner = Core\Attributes::get<Audited>(Payment::constructor);
if ($owner != null) {
echo 'owned by ', $owner->by, ' since ', $owner->since, "\n";
}
Output
{"reference":"PAY-1042","cents":2599}
owned by payments since 2026-01-14

An option the attribute does not have

<?nvs
// Shows that Novis checks the options of the attributes it reads itself.
// `Core\Route` has no `colour` option, so this program does not compile.
// proof: compile-error
class Home
{
#[Core\Route(path: '/', method: Core\Http\Method::Get, colour: 'red')]
#[Core\Access(allow: Core\Audience::Public)]
public function show(): string
{
return 'home';
}
}
Output
error[E0454]: `colour` is not an option of `#[Route]`
--> 04-an-option-the-attribute-does-not-have.nvs:8:60
|
8 | #[Core\Route(path: '/', method: Core\Http\Method::Get, colour: 'red')]
| ^^^^^^^^^^^^^ no such option
= help: the options are: path: string, method: Core\Http\Method, slotted: bool
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

An option the attribute does not have is E0454, and the help line lists every option with its type. An option of the wrong type is E0401, and an option given twice is E0304. A value that is not known while compiling is E0725, as in any attribute. A missing option that the attribute needs has an error of its own, such as E0767 for a #[Core\Command] with no name.

A name under Core\ that Novis does not declare, such as #[Core\Nope], is E0303. These names are never written with ::, so #[Core\Json::Derive] is E0405. An import cannot be renamed, so use Core\Command as Cmd; is E0212.

An attribute of your own with the same fields as Core\Command is still your own attribute. Novis does not read it.

Core\Attributes can read these attributes too. Core\Attributes::get<Core\Route>(Home::show) returns the fields written in the route attribute, such as its path. Some also have a reader of their own, such as Core\Command::help for the command table.

Each of these attributes belongs on one kind of declaration. A #[Core\Command] belongs on a static method, and on a method that is not static it is E0789.

These are the names Novis reads: Core\Json\Derive, Core\Json\Field, Core\Route, Core\Access, Core\Query, Core\Api, Core\Command, Core\Option and the testing attributes. The next pages show what each one does.

  • Do list only the places where your program reads the attribute after on. Any other place does not compile.
  • Do declare an attribute inside a base class when only its subclasses use it. Other classes then cannot use it.
  • Do write a /// comment above each field. The editor shows it when you type the field’s name.
  • Don’t put a variable or a function call in an attribute. Use a class constant.
  • Don’t name your own attribute after a Novis attribute. The program compiles, but the code is harder to read.