Skip to content

Core\Ast\Node::column

$node->column(): int

The column where this part of the source starts, counted from 1.

The count is in characters, not bytes, so an accented letter or an emoji counts as one. That is what an editor shows and what a person counts along a line. Use line together with it to name a place somebody can go to and look at, and offset when you need the position in bytes instead.

Good to know: the column is the first character of that part, not of the line it sits on. A statement indented by four spaces starts at column 5.

The examples below show where each part of a program begins, a line holding an accented letter, and a report that points at the exact place with a mark under it.

Return value

Returns int. The column of the node's first character. The first character of the line is 1. A character such as ß counts as one column.

Examples

Where each part of a program begins

<?nvs
// Shows where each part of a program begins. `column` counts from 1, and it is
// the first character of that part, so an indented line starts further along.
string $source = <<<'NVS'
<?nvs
if (1) {
echo 2;
}
NVS;
foreach (Core\Ast::parse($source)->nodes() as Core\Ast\Node $node) {
echo $node->kind(), ' on line ', $node->line(), ', column ', $node->column(), "\n";
}
Output
If on line 2, column 1
Int on line 2, column 5
Block on line 2, column 8
Echo on line 3, column 5
Int on line 3, column 10

A line with an accented letter

<?nvs
// Shows that the column counts characters and not bytes. `offset` counts
// bytes, so the two numbers move apart on a line holding an accented letter.
Core\Ast\Node $file = Core\Ast::parse("<?nvs\necho \"Grüße\", 7;\n");
foreach ($file->nodes() as Core\Ast\Node $node) {
echo $node->kind(), ' at column ', $node->column(), ', byte ', $node->offset(), "\n";
}
Output
Echo at column 1, byte 6
Str at column 6, byte 11
Int at column 15, byte 22

Pointing at the exact place

<?nvs
// Shows how to point at a place in a line, the way a compiler does when it
// reports a problem. The column says how far along the line to put the mark.
string $source = <<<'NVS'
<?nvs
class Report {
public static function run(): void {
exit(1);
}
}
NVS;
array<string> $lines = Core\Str::lines($source);
Core\Ast\Node $file = Core\Ast::parse($source);
foreach ($file->nodes() as Core\Ast\Node $node) {
if ($node->kind() == 'Exit') {
echo $lines[$node->line() - 1], "\n";
echo Core\Str::repeat(' ', ($node->column() - 1) as uint), "^ exit is not allowed here\n";
}
}
Output
exit(1);
^ exit is not allowed here