Adding and Printing the Tokens
Before we get into it, some C / ASM explanations are needed. I made some changes to the code to make things visually clearer. Short note: the new code takes two 32-byte views from the source, which means that we will work with a u64, not u32, for the final masked bits.
Writing a struct with NASM:
struc lex_masks_params
.source: resq 1
.source_size: resq 1
.word_starts: resq 1
.word_ends: resq 1
.string_starts: resq 1
.string_ends: resq 1
.word_class: resb 1
._pad: resb 7
endstruc
In C, that is:
struct lex_masks_params {
const u8 *source;
u64 source_size;
u64 *word_starts;
u64 *word_ends;
u64 *string_starts;
u64 *string_ends;
enum CLASSES word_class;
u8 _pad[7];
};
_Static_assert(sizeof(struct lex_masks_params) == 56, "utils.asm lex_masks_params struc must match");
extern void _lex_masks(struct lex_masks_params params);
#define lex_masks(...) \
_lex_masks((struct lex_masks_params){ \
.word_class = CLASS_WORD, \
__VA_ARGS__ \
})
This makes two things clearer:
- We can read argument names (in C, you cannot use parameter names from a function when passing arguments).
/*lex_masks is the macro that wraps the struct*/
lex_masks(.source = source,
.source_size = source_size,
.word_starts = word_starts,
.word_ends = word_ends,
.string_starts = string_starts,
.string_ends = string_ends);
- This also makes it nicer in nasm:
;void _lex_masks(struct lex_masks_params params); params is 56 bytes, so it arrives on the stack
_lex_masks:
push rbx
push rbp
push r12
push r13
push r14
push r15
;56 here is the 6 pushes (48) + the return address (8), not the size of params
%define params rsp + 56
mov source_cursor, [params + lex_masks_params.source]
mov source_end, [params + lex_masks_params.source_size]
add source_end, source_cursor
mov out_word_starts, [params + lex_masks_params.word_starts]
mov out_word_ends, [params + lex_masks_params.word_ends]
mov out_string_starts, [params + lex_masks_params.string_starts]
mov out_string_ends, [params + lex_masks_params.string_ends]
Now we don't have to be confused as to what register is what C parameter.
Some common operations from the previous post are nasm macros now.
;this is the load 32, then and with the nibble mask on the source's nibbles,
;shift right to get the high nibble in the low nibble position
;and mask that as well with the nibble mask,
;then use them as indices in the low and high tables to get the class masks for both and AND them
%macro classify_32 1
vmovdqu ymm0, %1
vpand ymm5, ymm0, vec_nibble_mask
vpsrlw ymm6, ymm0, 4
vpand ymm6, ymm6, vec_nibble_mask
order_indices ymm5, vec_table_low_class, ymm5
order_indices ymm6, vec_table_high_class, ymm6
vpand vec_class, ymm5, ymm6
%endmacro
;this is the one that extracts the word_class mask into a single u32
%macro words_32 1
vpand ymm7, vec_class, vec_word_class
select_32 ymm7, ymm7, vec_zero
vpmovmskb %1, ymm7
not %1
%endmacro
We will be dealing with string tokens and identifier tokens.
String tokens require more handling compared to other token types.
The word mask from the previous post matches the letters in both module and "main".
Turning these into tokens requires knowing which bytes belong to strings and where they start and end.
Two vectors, one block
Catch-up on the updated code:
- the classifier still works on 32 bytes at a time.
classify_32looks up the low and high nibbles and ANDs the two results to get the class flags for each byte.- the loop does this twice and builds three masks for the 64-byte block.
For the current plan:
wordsmarks ASCII letters, digits and underscores.quotesmarks double quotes.CLASS_QUOTEis on bit 7, the bitvpmovmskbreads from each byte, so it can be taken straight out of each byte’s class flags.slashesmarks backslashes. It comes from comparing the source bytes with'\\'.
Each half gives us one 32-bit mask of each kind. The second mask goes in the high 32 bits and the first goes in the low 32 bits. Bit 0 is the first byte of the block, so a left shift moves a match one byte forward, including from byte 31 to byte 32.
Which quotes count?
Take a"b\"c"d;. The mask is in source order, with bit 0 on the left.
byte offset 0 1 2 3 4 5 6 7 8
source a " b \ " c " d ;
words 1 0 1 0 0 1 0 1 0
quotes 0 1 0 0 1 0 1 0 0
slashes 0 0 0 1 0 0 0 0 0
escaped 0 0 0 0 1 0 0 0 0
quotes & ~escaped 0 1 0 0 0 0 1 0 0
The backslash at byte 3 escapes the quote at byte 4. Two consecutive backslashes would escape each other and leave the following quote free to close the string. In general, an odd run escapes the byte after it. An even run leaves that byte alone.
The escape code first clears bit 0 of the slash mask if that byte was already escaped by the previous block. The code calls the cleared mask unescaped. It finds the starts of the remaining runs with unescaped & ~(unescaped << 1). Adding a run’s start bit to unescaped carries the 1 through the run to the following byte. The code does this in two groups, using alternating bit masks to separate runs that start at even and odd positions. After each add, andn removes the backslash bits themselves, so only the bytes after the carried runs are left. For an odd-length run, the following byte and the first backslash have opposite parity. That’s how the code picks out which bytes after runs are escaped. It then clears the escaped positions from the quote mask.
From quotes to strings
With the escaped quotes cleared, every remaining quote toggles whether we’re in a string. At bit i, I want the XOR of all the quote bits from 0 through i. That gives 1 starting at the opening quote and goes back to 0 at the closing quote.
byte offset 0 1 2 3 4 5 6 7 8
source a " b \ " c " d ;
quotes 0 1 0 0 0 0 1 0 0
in_string 0 1 1 1 1 1 0 0 0
string_starts 0 1 0 0 0 0 0 0 0
string_ends 0 0 0 0 0 0 1 0 0
Carry-less multiplication does that prefix XOR in one instruction.
Multiplying by an all-ones mask combines shifted copies of the quote mask with XOR.
In the low 64 bits, each position gets exactly the quote bits at or before it.
The code uses vpclmulqdq for this step. Intel instruction reference
A quote on a 1 in in_string opens a string. A quote on a 0 closes one.
That gives us quotes & in_string for starts and quotes & ~in_string for ends.
Then, it clears the whole quoted span from the word mask with words &= ~(in_string | quotes).
In the example, that clears the word bits for b and c.
From word bytes to word edges
This compares every word bit with the one before it.
A word starts at a byte with a 1 whose predecessor was 0. Its end is the first 0 after a run of 1s. prev_word is the last word bit of the previous block (explained below).
u64 previous = (words << 1) | prev_word;
u64 word_starts = words & ~previous;
u64 word_ends = previous & ~words;
For our example, the words start at bytes 0 and 7 and end at bytes 1 and 8.
Byte 1 is both the end of a and the start of the string.
A block boundary can fall anywhere in the source. The loop keeps three pieces of state for the next 64 bytes.
prev_escapesays whether the first byte is escaped by the preceding block. That is the case when the preceding block ends in an odd run of backslashes.string_carrysays whether a string is still open. If it is, the next block’s prefix XOR is inverted so it starts from inside the string.prev_wordsupplies the preceding word bit at byte 0. A word that continues across the boundary has a single start and a single end.
The source is padded with zeros up to the next multiple of 64. If the file already ends on a block boundary, a full block of zeros is added. That gives a word at the end of the file a following non-word byte where its end bit can land.
Appending the tokens
The function lex_masks writes four masks per block. On the C side, tokens_starts_append merges the word and string starts in source order.
It counts trailing zeros in each mask and takes the lower offset. The bit scan returns 64 for an empty mask, so any real position comes first.
Adding the block’s base gives the byte offset in the file, and the mask it came from gives the token kind.
To move on, mask & (mask - 1) clears the lowest set bit. The code subtracts is_word from the word mask and is_word ^ 1 from the string mask (words &= words - is_word;), which is 1 for the chosen mask and 0 for the other, leaving the other candidate for the next iteration.
The function tokens_ends_append does the same for the two end masks. Word ends already point one byte past the token. String ends point at the closing quote, so C adds one. Both kinds now use the same half-open span. To print token i, C takes end[i] - start[i] bytes from start[i]. An open string leaves one extra start, which the C code reports as an unterminated string.
Here’s the output for a"b\"c"d;.
identifier : a
string : "b\"c"
identifier : d
Output
/simd_lexer$ ./main
identifier : module
string : "main"
identifier : import
identifier : println
string : "io"
identifier : println
identifier : println
identifier : config
identifier : bytes_reserved
identifier : kib
identifier : 64
identifier : main
identifier : function_mutate
identifier : p
identifier : StcProcess
identifier : Error
identifier : StcError
identifier : err
identifier : try
identifier : println
string : "{} \" escaped \" \" "
identifier : 5
identifier : 5
identifier : onfail
identifier : return
identifier : err
identifier : return
identifier : Error
identifier : OK
Target source file.stc
The println line is different from the previous post's file: its string now has escaped quotes in it.
module("main");
import{
println :: "io".println,
};
println :: config {
.bytes_reserved = @kib(64)
};
main :: function_mutate(p: &StcProcess) -> Error.StcError
{
err := try println("{} \" escaped \" \" ", .{5 + 5}) onfail {
return err;
};
return Error.OK;
}
NASM and C source code
bits 64
default rel
extern table_low_class
extern table_high_class
section .rodata
align 32
nibble_mask: times 32 db 0x0F
section .text
%define vec_nibble_mask ymm1
%define vec_table_low_class ymm2
%define vec_table_high_class ymm3
%define vec_class ymm4
%macro order_indices 3
vpshufb %1, %2, %3 ; dest = table[indices]
%endmacro
%macro select_32 3
vpcmpeqb %1, %2, %3
%endmacro
section .rodata
align 32
backslash_mask: times 32 db '\'
EVEN_BITS equ 0x5555555555555555
ODD_BITS equ 0xAAAAAAAAAAAAAAAA
struc lex_masks_params
.source: resq 1
.source_size: resq 1
.word_starts: resq 1
.word_ends: resq 1
.string_starts: resq 1
.string_ends: resq 1
.word_class: resb 1
._pad: resb 7
endstruc
%define vec_zero ymm8
%define vec_word_class ymm10
%define vec_backslash ymm12
%define vec_all_ones xmm14
%define source_cursor rdi
%define source_end rsi
%define out_word_starts r8
%define out_word_ends r9
%define out_string_starts r10
%define out_string_ends r11
%define prev_word r12
%define string_carry r13
%define prev_escape r14
%define words rax
%define words_head eax
%define quotes rdx
%define quotes_head edx
%define slashes rbx
%define slashes_head ebx
%define unescaped rbx
%define parity_bits rbx
%define in_string rbx
%define string_mask rbx
%define word_edges rbx
%define scratch rcx
%define scratch_32 ecx
%define escape_carry rcx
%define escape_carry_32 ecx
%define escape_carry_8 cl
%define run_starts r15
%define odd_starts r15
%define odd_carries r15
%define odd_ends r15
%define string_edges r15
%define words_shifted r15
%define even_starts rbp
%define even_carries rbp
%define even_ends rbp
%define escaped rbp
%define vec_quotes_low xmm13
%macro classify_32 1
vmovdqu ymm0, %1
vpand ymm5, ymm0, vec_nibble_mask
vpsrlw ymm6, ymm0, 4
vpand ymm6, ymm6, vec_nibble_mask
order_indices ymm5, vec_table_low_class, ymm5
order_indices ymm6, vec_table_high_class, ymm6
vpand vec_class, ymm5, ymm6
%endmacro
%macro words_32 1
vpand ymm7, vec_class, vec_word_class
select_32 ymm7, ymm7, vec_zero
vpmovmskb %1, ymm7
not %1
%endmacro
%macro high_half 2
shl %2, 32
or %1, %2
%endmacro
section .text
global _lex_masks
;void _lex_masks(struct lex_masks_params params); params is 56 bytes, so it arrives on the stack
_lex_masks:
push rbx
push rbp
push r12
push r13
push r14
push r15
%define params rsp + 56
mov source_cursor, [params + lex_masks_params.source]
mov source_end, [params + lex_masks_params.source_size]
add source_end, source_cursor
mov out_word_starts, [params + lex_masks_params.word_starts]
mov out_word_ends, [params + lex_masks_params.word_ends]
mov out_string_starts, [params + lex_masks_params.string_starts]
mov out_string_ends, [params + lex_masks_params.string_ends]
vmovdqu vec_nibble_mask, [nibble_mask]
vmovdqu vec_table_low_class, [table_low_class]
vmovdqu vec_table_high_class, [table_high_class]
vpbroadcastb vec_word_class, [params + lex_masks_params.word_class]
vmovdqu vec_backslash, [backslash_mask]
vpxor vec_zero, vec_zero, vec_zero
vpcmpeqd vec_all_ones, vec_all_ones, vec_all_ones
xor prev_word, prev_word
xor string_carry, string_carry
xor prev_escape, prev_escape
.loop:
classify_32 [source_cursor]
words_32 words_head
vpmovmskb quotes_head, vec_class
vpcmpeqb ymm7, ymm0, vec_backslash
vpmovmskb slashes_head, ymm7
classify_32 [source_cursor + 32]
words_32 scratch_32
high_half words, scratch
vpmovmskb scratch_32, vec_class
high_half quotes, scratch
vpcmpeqb ymm7, ymm0, vec_backslash
vpmovmskb scratch_32, ymm7
high_half slashes, scratch
.escapes:
andn unescaped, prev_escape, slashes
lea run_starts, [unescaped + unescaped]
andn run_starts, run_starts, unescaped
mov even_starts, EVEN_BITS
and even_starts, run_starts
xor odd_starts, even_starts
add even_carries, unescaped
andn even_ends, unescaped, even_carries
add odd_carries, unescaped
setc escape_carry_8
movzx escape_carry_32, escape_carry_8
andn odd_ends, unescaped, odd_carries
mov parity_bits, ODD_BITS
and even_ends, parity_bits
not parity_bits
and odd_ends, parity_bits
or escaped, odd_ends
or escaped, prev_escape
mov prev_escape, escape_carry
andn quotes, escaped, quotes
.strings:
vmovq vec_quotes_low, quotes
vpclmulqdq vec_quotes_low, vec_quotes_low, vec_all_ones, 0
vmovq in_string, vec_quotes_low
xor in_string, string_carry
mov string_carry, in_string
sar string_carry, 63
mov string_edges, quotes
and string_edges, in_string
mov [out_string_starts], string_edges
andn string_edges, in_string, quotes
mov [out_string_ends], string_edges
or string_mask, quotes
andn words, string_mask, words
.words:
lea words_shifted, [words + words]
or words_shifted, prev_word
mov prev_word, words
shr prev_word, 63
andn word_edges, words_shifted, words
mov [out_word_starts], word_edges
andn word_edges, words, words_shifted
mov [out_word_ends], word_edges
.loop_advance:
add out_word_starts, 8
add out_word_ends, 8
add out_string_starts, 8
add out_string_ends, 8
add source_cursor, 64
cmp source_cursor, source_end
jb .loop
.loop_exit:
vzeroupper
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
ret
section .note.GNU-stack noalloc noexec nowrite progbits
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef float f32;
/* *
* CLASS_QUOTE = ["]
* */
enum CLASSES: u8 {
CLASS_NONE = 0u,
CLASS_SPACE = 1u << 0u,
CLASS_UNDERSCORE = 1u << 1u,
CLASS_CONTROL_SPACE = 1u << 2u,
CLASS_DIGIT = 1u << 3u,
CLASS_LETTER_A_TO_O = 1u << 4u,
CLASS_LETTER_P_TO_Z = 1u << 5u,
CLASS_QUOTE = 1u << 7u,
CLASS_LETTER_A_TO_Z = CLASS_LETTER_A_TO_O | CLASS_LETTER_P_TO_Z,
CLASS_WHITESPACE = CLASS_SPACE | CLASS_CONTROL_SPACE,
CLASS_WORD = CLASS_DIGIT | CLASS_LETTER_A_TO_O | CLASS_LETTER_P_TO_Z | CLASS_UNDERSCORE
};
/* *
* this table cannot follow the same indexing visual logic as the low_nibbles table of 0xHL where low_nibbles[L] is the index.
* because high_nibbles[H] from a 0xHL would be incorrect
* therefore, the high part of the ASCII is the low part of the index:
* Index (low part in bracket []) = 0x0[2] PAIRS 0x[2]2, 0x[2]3, 0x[2]7 and so on (high part in bracket [])
* */
const u8 table_high_class[32] = {
[0x00] = CLASS_CONTROL_SPACE /*[0x[0]8 BACKSPACE, 0x[0]9 TAB SPACE, 0x[0]A LINE FEED, 0x[0]B VERTICAL TAB, 0x[0]D CARRIAGE RETURN]*/,
[0x01] = CLASS_NONE,
[0x02] = CLASS_SPACE /*[0x[2]0 SPACE]*/
| CLASS_QUOTE /*[0x[2]2 '"']*/,
[0x03] = CLASS_DIGIT /*[0x[3]0..0x[3]9 '0'..'9']*/,
[0x04] = CLASS_LETTER_A_TO_O /*[0x[4]1..0x[4]F 'A'..'O']*/,
[0x05] = CLASS_LETTER_P_TO_Z /*[0x[5]0..0x[5]A 'P'..'Z']*/
| CLASS_UNDERSCORE /*[0x[5]F '_']*/,
[0x06] = CLASS_LETTER_A_TO_O /*[0x[6]1..0x[6]F 'a'..'o']*/,
[0x07] = CLASS_LETTER_P_TO_Z /*[0x[7]0..0x[7]A 'p'..'z']*/,
[0x08] = CLASS_NONE,
[0x09] = CLASS_NONE,
[0x0A] = CLASS_NONE,
[0x0B] = CLASS_NONE,
[0x0C] = CLASS_NONE,
[0x0D] = CLASS_NONE,
[0x0E] = CLASS_NONE,
[0x0F] = CLASS_NONE,
[0x10] = CLASS_CONTROL_SPACE /*[0x[0]8 BACKSPACE, 0x[0]9 TAB SPACE, 0x[0]A LINE FEED, 0x[0]B VERTICAL TAB, 0x[0]D CARRIAGE RETURN]*/,
[0x11] = CLASS_NONE,
[0x12] = CLASS_SPACE /*[0x[2]0 SPACE]*/
| CLASS_QUOTE /*[0x[2]2 '"']*/,
[0x13] = CLASS_DIGIT /*[0x[3]0..0x[3]9 '0'..'9']*/,
[0x14] = CLASS_LETTER_A_TO_O /*[0x[4]1..0x[4]F 'A'..'O']*/,
[0x15] = CLASS_LETTER_P_TO_Z /*[0x[5]0..0x[5]A 'P'..'Z']*/
| CLASS_UNDERSCORE /*[0x[5]F '_']*/,
[0x16] = CLASS_LETTER_A_TO_O /*[0x[6]1..0x[6]F 'a'..'o']*/,
[0x17] = CLASS_LETTER_P_TO_Z /*[0x[7]0..0x[7]A 'p'..'z']*/,
[0x18] = CLASS_NONE,
[0x19] = CLASS_NONE,
[0x1A] = CLASS_NONE,
[0x1B] = CLASS_NONE,
[0x1C] = CLASS_NONE,
[0x1D] = CLASS_NONE,
[0x1E] = CLASS_NONE,
[0x1F] = CLASS_NONE,
};
/*this represents the matching low nibble of an ASCII byte indexed in this table*/
/*
* if an ASCII character is of the form 0xN0, that low nibble (0 zero) means it should be at index 0 in this table
* same for any other one. The general form is 0xHL (high/low) where low_nibbles[L] = the combined flags
* for L = 0 the low_nibbles[L] = CLASS_SPACE | CLASS_DIGIT | CLASS_SYMBOL | CLASS_LETTER_P_TO_Z
* that is because: 0x2[0] = Space, 0x3[0] = '0', 0x4[0] = '@', 0x5[0] = 'P' and 0x7[0] = 'p'. All have a low nibble of 0 (zero).
* The other characters that have 0 (zero) at their nibbles (such as 0x10 ) are elided, because they're not characters you would encounter in a text editor.
*/
const u8 table_low_class[32] = {
[0x00] = CLASS_SPACE /*[0x2[0] SPACE]*/
| CLASS_DIGIT /*[0x3[0] '0']*/
| CLASS_LETTER_P_TO_Z /*[0x5[0] 'P', 0x7[0] 'p']*/,
[0x01] = CLASS_DIGIT /*[0x3[1] '1']*/
| CLASS_LETTER_A_TO_Z /*[0x4[1] 'A', 0x6[1] 'a', 0x5[1] 'Q', 0x7[1] 'q']*/,
[0x02] = CLASS_DIGIT /*[0x3[2] '2']*/
| CLASS_LETTER_A_TO_Z /*[0x4[2] 'B', 0x6[2] 'b', 0x5[2] 'R', 0x7[2] 'r']*/
| CLASS_QUOTE /*[0x2[2] '"']*/,
[0x03] = CLASS_DIGIT /*[0x3[3] '3']*/
| CLASS_LETTER_A_TO_Z /*[0x4[3] 'C', 0x6[3] 'c', 0x5[3] 'S', 0x7[3] 's']*/,
[0x04] = CLASS_DIGIT /*[0x3[4] '4']*/
| CLASS_LETTER_A_TO_Z /*[0x4[4] 'D', 0x6[4] 'd', 0x5[4] 'T', 0x7[4] 't']*/,
[0x05] = CLASS_DIGIT /*[0x3[5] '5']*/
| CLASS_LETTER_A_TO_Z /*[0x4[5] 'E', 0x6[5] 'e', 0x5[5] 'U', 0x7[5] 'u']*/,
[0x06] = CLASS_DIGIT /*[0x3[6] '6']*/
| CLASS_LETTER_A_TO_Z /*[0x4[6] 'F', 0x6[6] 'f', 0x5[6] 'V', 0x7[6] 'v']*/,
[0x07] = CLASS_DIGIT /*[0x3[7] '7']*/
| CLASS_LETTER_A_TO_Z /*[0x4[7] 'G', 0x6[7] 'g', 0x5[7] 'W', 0x7[7] 'w']*/,
[0x08] = CLASS_CONTROL_SPACE /*[0x0[8] BACKSPACE]*/
| CLASS_DIGIT /*[0x3[8] '8']*/
| CLASS_LETTER_A_TO_Z /*[0x4[8] 'H', 0x6[8] 'h', 0x5[8] 'X', 0x7[8] 'x']*/,
[0x09] = CLASS_CONTROL_SPACE /*[0x0[9] TAB SPACE]*/
| CLASS_DIGIT /*[0x3[9] '9']*/
| CLASS_LETTER_A_TO_Z /*[0x4[9] 'I', 0x6[9] 'i', 0x5[9] 'Y', 0x7[9] 'y']*/,
[0x0A] = CLASS_CONTROL_SPACE /*[0x0[A] LINE FEED]*/
| CLASS_LETTER_A_TO_Z /*[0x4[A] 'J', 0x6[A] 'j', 0x5[A] 'Z', 0x7[A] 'z']*/,
[0x0B] = CLASS_CONTROL_SPACE /*[0x0[B] VERTICAL TAB]*/
| CLASS_LETTER_A_TO_O /*[0x4[B] 'K', 0x6[B] 'k']*/,
[0x0C] = CLASS_CONTROL_SPACE /*0x0[C] FORM FEED / NEW PAGE*/
| CLASS_LETTER_A_TO_O /*[0x4[C] 'L', 0x6[C] 'l']*/,
[0x0D] = CLASS_CONTROL_SPACE /*[0x0[D] CARRIAGE RETURN]*/
| CLASS_LETTER_A_TO_O /*[0x4[D] 'M', 0x6[D] 'm']*/,
[0x0E] = CLASS_LETTER_A_TO_O /*[0x4[E] 'N', 0x6[E] 'n']*/,
[0x0F] = CLASS_LETTER_A_TO_O /*[0x4[F] 'O', 0x6[F] 'o']*/
| CLASS_UNDERSCORE /*[0x5[F] '_']*/,
[0x10] = CLASS_SPACE /*[0x2[0] SPACE]*/
| CLASS_DIGIT /*[0x3[0] '0']*/
| CLASS_LETTER_P_TO_Z /*[0x5[0] 'P', 0x7[0] 'p']*/,
[0x11] = CLASS_DIGIT /*[0x3[1] '1']*/
| CLASS_LETTER_A_TO_Z /*[0x4[1] 'A', 0x6[1] 'a', 0x5[1] 'Q', 0x7[1] 'q']*/,
[0x12] = CLASS_DIGIT /*[0x3[2] '2']*/
| CLASS_LETTER_A_TO_Z /*[0x4[2] 'B', 0x6[2] 'b', 0x5[2] 'R', 0x7[2] 'r']*/
| CLASS_QUOTE /*[0x2[2] '"']*/,
[0x13] = CLASS_DIGIT /*[0x3[3] '3']*/
| CLASS_LETTER_A_TO_Z /*[0x4[3] 'C', 0x6[3] 'c', 0x5[3] 'S', 0x7[3] 's']*/,
[0x14] = CLASS_DIGIT /*[0x3[4] '4']*/
| CLASS_LETTER_A_TO_Z /*[0x4[4] 'D', 0x6[4] 'd', 0x5[4] 'T', 0x7[4] 't']*/,
[0x15] = CLASS_DIGIT /*[0x3[5] '5']*/
| CLASS_LETTER_A_TO_Z /*[0x4[5] 'E', 0x6[5] 'e', 0x5[5] 'U', 0x7[5] 'u']*/,
[0x16] = CLASS_DIGIT /*[0x3[6] '6']*/
| CLASS_LETTER_A_TO_Z /*[0x4[6] 'F', 0x6[6] 'f', 0x5[6] 'V', 0x7[6] 'v']*/,
[0x17] = CLASS_DIGIT /*[0x3[7] '7']*/
| CLASS_LETTER_A_TO_Z /*[0x4[7] 'G', 0x6[7] 'g', 0x5[7] 'W', 0x7[7] 'w']*/,
[0x18] = CLASS_CONTROL_SPACE /*[0x0[8] BACKSPACE]*/
| CLASS_DIGIT /*[0x3[8] '8']*/
| CLASS_LETTER_A_TO_Z /*[0x4[8] 'H', 0x6[8] 'h', 0x5[8] 'X', 0x7[8] 'x']*/,
[0x19] = CLASS_CONTROL_SPACE /*[0x0[9] TAB SPACE]*/
| CLASS_DIGIT /*[0x3[9] '9']*/
| CLASS_LETTER_A_TO_Z /*[0x4[9] 'I', 0x6[9] 'i', 0x5[9] 'Y', 0x7[9] 'y']*/,
[0x1A] = CLASS_CONTROL_SPACE /*[0x0[A] LINE FEED]*/
| CLASS_LETTER_A_TO_Z /*[0x4[A] 'J', 0x6[A] 'j', 0x5[A] 'Z', 0x7[A] 'z']*/,
[0x1B] = CLASS_CONTROL_SPACE /*[0x0[B] VERTICAL TAB]*/
| CLASS_LETTER_A_TO_O /*[0x4[B] 'K', 0x6[B] 'k']*/,
[0x1C] = CLASS_LETTER_A_TO_O /*[0x4[C] 'L', 0x6[C] 'l']*/
| CLASS_CONTROL_SPACE /*0x0[C] FORM FEED / NEW PAGE*/,
[0x1D] = CLASS_CONTROL_SPACE /*[0x0[D] CARRIAGE RETURN]*/
| CLASS_LETTER_A_TO_O /*[0x4[D] 'M', 0x6[D] 'm']*/,
[0x1E] = CLASS_LETTER_A_TO_O /*[0x4[E] 'N', 0x6[E] 'n']*/,
[0x1F] = CLASS_LETTER_A_TO_O /*[0x4[F] 'O', 0x6[F] 'o']*/
| CLASS_UNDERSCORE /*[0x5[F] '_']*/,
};
_Static_assert(CLASS_QUOTE == 1u << 7u, "_lex_masks reads CLASS_QUOTE as each byte's sign bit with vpmovmskb");
struct lex_masks_params {
const u8 *source;
u64 source_size;
u64 *word_starts;
u64 *word_ends;
u64 *string_starts;
u64 *string_ends;
enum CLASSES word_class;
u8 _pad[7];
};
_Static_assert(sizeof(struct lex_masks_params) == 56, "utils.asm lex_masks_params struc must match");
extern void _lex_masks(struct lex_masks_params params);
#define lex_masks(...) \
_lex_masks((struct lex_masks_params){ \
.word_class = CLASS_WORD, \
__VA_ARGS__ \
})
enum token_kind: u8 {
TOKEN_KIND_NONE = 0,
TOKEN_KIND_IDENTIFIER,
TOKEN_KIND_STRING,
};
static const char *const token_kind_names[] = {
[TOKEN_KIND_NONE] = "none",
[TOKEN_KIND_IDENTIFIER] = "identifier",
[TOKEN_KIND_STRING] = "string",
};
static const enum token_kind token_kind_by_is_word[2] = {
[0] = TOKEN_KIND_STRING,
[1] = TOKEN_KIND_IDENTIFIER,
};
struct tokens {
u32 *start;
u32 *end;
enum token_kind *kind;
u32 count_start;
u32 count_end;
};
enum lex_error {
LEX_ERROR_NONE = 0,
LEX_ERROR_OPEN,
LEX_ERROR_SIZE,
LEX_ERROR_MEMORY,
LEX_ERROR_READ,
LEX_ERROR_UNTERMINATED_STRING,
};
static const char *const lex_error_names[] = {
[LEX_ERROR_NONE] = "none",
[LEX_ERROR_OPEN] = "cannot open the file",
[LEX_ERROR_SIZE] = "the file is larger than u32 positions hold",
[LEX_ERROR_MEMORY] = "out of memory",
[LEX_ERROR_READ] = "the file was not read whole",
[LEX_ERROR_UNTERMINATED_STRING] = "a string is not closed",
};
static inline u64
ctz_u64(u64 value)
{
return __builtin_ctzg(value, 64);
}
static inline u64
select_u64(u64 condition, u64 if_true, u64 if_false)
{
u64 mask = 0 - condition;
return (if_true & mask) | (if_false & ~mask);
}
struct tokens_starts_append_params {
struct tokens *tokens;
u64 words;
u64 strings;
u32 base;
};
#define tokens_starts_append(...) \
_tokens_starts_append((struct tokens_starts_append_params){__VA_ARGS__})
static void
_tokens_starts_append(struct tokens_starts_append_params params)
{
struct tokens *t = params.tokens;
u64 words = params.words;
u64 strings = params.strings;
loop:
if ((words | strings) == 0)
goto loop_exit;
u64 word_at = ctz_u64(words);
u64 string_at = ctz_u64(strings);
u64 is_word = word_at < string_at;
u32 index = t->count_start;
t->kind[index] = token_kind_by_is_word[is_word];
t->start[index] = params.base + (u32)select_u64(is_word, word_at, string_at);
t->count_start = index + 1;
words &= words - is_word;
strings &= strings - (is_word ^ 1);
goto loop;
loop_exit:
return;
}
struct tokens_ends_append_params {
struct tokens *tokens;
u64 words;
u64 strings;
u32 base;
};
#define tokens_ends_append(...) \
_tokens_ends_append((struct tokens_ends_append_params){__VA_ARGS__})
static void
_tokens_ends_append(struct tokens_ends_append_params params)
{
struct tokens *t = params.tokens;
u64 words = params.words;
u64 strings = params.strings;
loop:
if ((words | strings) == 0)
goto loop_exit;
u64 word_at = ctz_u64(words);
u64 string_at = ctz_u64(strings);
u64 is_word = word_at <= string_at;
u32 index = t->count_end;
t->end[index] = params.base + (u32)select_u64(is_word, word_at, string_at + 1);
t->count_end = index + 1;
words &= words - is_word;
strings &= strings - (is_word ^ 1);
goto loop;
loop_exit:
return;
}
int main(int argc, char **argv)
{
enum lex_error error = LEX_ERROR_NONE;
const char *path = argc > 1 ? argv[1] : "file.stc";
u8 *memory = NULL;
int fd = open(path, O_RDONLY);
if (fd < 0) {
error = LEX_ERROR_OPEN;
goto procedure_exit;
}
off_t length = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
if (length < 0 || (u64)length > UINT32_MAX - 64) {
error = LEX_ERROR_SIZE;
goto exit_close;
}
u64 source_size = ((u64)length + 64) & ~(u64)63;
u64 block_count = source_size >> 6;
u64 bytes_masks = block_count * 4 * sizeof(u64);
u64 bytes_positions = source_size * sizeof(u32);
memory = malloc(bytes_masks + 2 * bytes_positions + 2 * source_size);
if (memory == NULL) {
error = LEX_ERROR_MEMORY;
goto exit_close;
}
u64 *word_starts = (u64 *)memory;
u64 *word_ends = word_starts + block_count;
u64 *string_starts = word_ends + block_count;
u64 *string_ends = string_starts + block_count;
struct tokens tokens = {
.start = (u32 *)(memory + bytes_masks),
.end = (u32 *)(memory + bytes_masks + bytes_positions),
.kind = (enum token_kind *)(memory + bytes_masks + 2 * bytes_positions),
};
u8 *source = memory + bytes_masks + 2 * bytes_positions + source_size;
if (read(fd, source, (size_t)length) != length) {
error = LEX_ERROR_READ;
goto exit_free;
}
memset(source + length, 0, source_size - (u64)length);
lex_masks(.source = source,
.source_size = source_size,
.word_starts = word_starts,
.word_ends = word_ends,
.string_starts = string_starts,
.string_ends = string_ends);
for (u64 block = 0; block < block_count; ++block) {
u32 base = (u32)(block << 6);
tokens_starts_append(.tokens = &tokens,
.words = word_starts[block],
.strings = string_starts[block],
.base = base);
tokens_ends_append(.tokens = &tokens,
.words = word_ends[block],
.strings = string_ends[block],
.base = base);
}
if (tokens.count_start != tokens.count_end) {
error = LEX_ERROR_UNTERMINATED_STRING;
goto exit_free;
}
for (u32 index = 0; index < tokens.count_start; ++index) {
u32 start = tokens.start[index];
u32 end = tokens.end[index];
printf("%s : %.*s\n", token_kind_names[tokens.kind[index]],
(int)(end - start), (const char *)source + start);
}
exit_free:
free(memory);
exit_close:
close(fd);
procedure_exit:
if (error != LEX_ERROR_NONE)
fprintf(stderr, "%s: %s\n", path, lex_error_names[error]);
return error;
}
Later, for the AST / syntax checker, token types can be pre-made with this strategy. With ASCII, you get the hex values that ASCII has, but with token types, you give them whatever values, so you don't have to stare and find matching nibbles like in the ASCII table. The stormc tokens and other kinds (declarations / statements) seem to do something like this, but they're more linear, not exactly subgrouped. Not sure if it would help to subgroup For example here
DeclarationKind :: enum(u8) {
NONE = 0x00,
CONSTANT = 0x01,
BUILD = 0x02,
GLOBAL = 0x03,
LANE_LOCAL = 0x04,
STARTUP_BINDING = 0x05,
FUNCTION = 0x06,
STRUCT = 0x10,
PACKED_STRUCT = 0x11,
SOA_STRUCT = 0x12,
RAW_UNION = 0x13,
ENUM = 0x14,
UNION = 0x15,
ERROR_SET = 0x16,
CONFIG = 0x17,
PRIMITIVE = 0x18,
OPAQUE = 0x19,
IF = 0x20,
ELSE_IF = 0x21,
ELSE = 0x22,
ASSERT = 0x23,
INSERT = 0x24,
MODULE = 0x30,
IMPORTS = 0x31,
};
The control flow (if / else if / else) could be separate from insert and only the if and friends are at 0x2N for example, but I am not sure how much that would change anything, other than moving shit around. It seems like as it is it would work anyway with no penalties
Found this useful? Support the writing on Ko-fi.