Skip to content

Core\Ast\Node::offset

$node->offset(): int

The place where this part of the source starts, counted in bytes from the beginning of the text.

The first byte of the source is 0. This is what you use to cut a part of the program out of the text you gave to Core\Ast::parse. Take the offset of one part and the offset of the part after it, and the bytes between them are the first part's own source.

Bytes are not characters. An accented letter takes two bytes and an emoji takes four, so a line holding one puts every later part further along in bytes than a person counts along the line. Use column for the number a person counts, and line with it when you want to name a place somebody can go and look at.

The examples below show where each part of a program starts, how to cut the source of one part out of the text, and how to find the part an editor's cursor is sitting in.

Return value

Returns int. The offset into the string you gave to parse, counting from 0. Use it to cut the node's text out of that string. The node does not return its text itself.

Examples

Where each part starts in bytes

<?nvs
// Shows where each part of a program starts, in bytes from the beginning of
// the source. The first byte is 0, so the `<?nvs` tag and the newline after it
// take the first six.
string $source = "<?nvs\necho 1;\necho 2;\n";
// This prints 6, then 14.
foreach (Core\Ast::parse($source)->children() as Core\Ast\Node $part) {
echo $part->offset(), "\n";
}
Output
6
14

Cutting the source of a part out

<?nvs
// Shows how to cut the source of one part out of the text. The bytes between
// one part's offset and the next part's offset are the first part's own
// source. A report that quotes the code it is about does this.
string $source = "<?nvs\necho 1;\necho 2;\n";
array<Core\Ast\Node> $parts = Core\Ast::parse($source)->children();
bytes $raw = $source as bytes;
int $start = $parts[0]->offset();
int $end = $parts[1]->offset();
string $cut = Core\Bytes::slice($raw, $start, $end - $start) as string;
// The cut ends where the next part begins, so it carries the newline between
// them. `Core\Str::trim` takes that off, and this prints echo 1;
echo Core\Str::trim($cut), "\n";
Output
echo 1;

Finding the part under the cursor

<?nvs
// Shows how to find the part of a program an editor's cursor is sitting in.
// The cursor is a byte position, and the last part starting at or before it is
// the one the cursor is inside.
string $source = "<?nvs\necho 1;\necho 2;\necho 3;\n";
int $cursor = 20;
string $found = 'nothing';
foreach (Core\Ast::parse($source)->nodes() as Core\Ast\Node $node) {
if ($node->offset() <= $cursor) {
$found = $node->kind();
}
}
// This prints Int: the cursor is on the number of the second `echo`.
echo $found, "\n";
Output
Int