The C splitter
cookbook/c/items/Guard.roc, 81 lines
## A header's guard, framed: Split.items gives a header's items to
## Guard.framed, which makes its `#ifndef` and `#define` one item and its
## `#endif` another.
import Item
Guard := [].{
## A header's items with its guard framed: its `#ifndef SHALE_<NAME>_H` and
## the `#define` after it made one item, and the `#endif` that ends the file
## another, each of kind `Guard`, named for the guard. A header without that
## framing is an error.
framed : Str, List(Item) -> Try(List(Item), Str)
framed = |path, items| {
name = file_name(path)
stem = Str.from_utf8_lossy(name.to_utf8().drop_last(2))
guard = "SHALE_${upper(stem)}_H"
opening = "ifndef ${guard}"
var $out = []
var $is_framed = Bool.False
var $at = 0
while $at < items.len() {
item = items.get($at) ?? Item.new(Directive, "", { first: 0, last: 0 })
if !($is_framed) and item.kind == Directive and item.name == opening {
match items.get($at + 1) {
Ok(define) if define.kind == Macro and define.name == guard => {
guard_item = { ..Item.new(Guard, guard, { first: item.first, last: define.last }), comment_first: item.comment_first, comment_last: item.comment_last }
$out = $out.append(guard_item)
$is_framed = Bool.True
$at = $at + 2
}
_ => {
why = "a guard's `#ifndef` with no `#define ${guard}` after it"
return Err(unaccounted(path, item.first, why, "#ifndef ${guard}"))
}
}
} else {
$out = $out.append(item)
$at = $at + 1
}
}
if !($is_framed) {
return Err(unaccounted(path, 1, "a header with no `#ifndef ${guard}`", name))
}
match $out.last() {
Ok(tail) if tail.kind == Directive and tail.name == "endif" =>
Ok($out.drop_last(1).append({ ..tail, kind: Guard, name: guard }))
Ok(tail) => Err(unaccounted(path, tail.first, "a header whose last item is not its guard's `#endif`", tail.name))
Err(_) => Err(unaccounted(path, 1, "a header with no `#ifndef ${guard}`", name))
}
}
}
## The path's last part, after its last `/`.
file_name : Str -> Str
file_name = |path| {
bytes = path.to_utf8()
match bytes.find_last_index(|byte| byte == '/') {
Ok(slash) => Str.from_utf8_lossy(bytes.drop_first(slash + 1))
Err(_) => path
}
}
## The text with its ASCII letters made capitals, as Shale's `upper` does.
upper : Str -> Str
upper = |text|
Str.from_utf8_lossy(
text.to_utf8().map(
|byte|
if byte >= 'a' and byte <= 'z' {
byte - 32
} else {
byte
},
),
)
## The error for line `number` of the file at `path`: its place and why
## first, then what the line shows.
unaccounted : Str, U64, Str, Str -> Str
unaccounted = |path, number, why, shown|
"${path}:${number.to_str()}: ${why}: ${shown}"
cookbook/c/items/Head.roc, 365 lines
## The readers of an item's opening line or head, each over masked bytes
## (Mask.masked), each the regular expression of the Shale original
## (c/build/c_items.shale, the fast tier's copy of this splitter), done by
## hand: the one match a backtracking search would find, with its groups.
import Mask
Head := [].{
## A head read as a function's, its return type and its name, or
## `NoFunction` when it declares none (a variable, a function pointer, a
## value whose `=` comes before its first `(`). Its storage and
## `STATUS_MUST_USE` go first, then a leading `__attribute__((...))`; the
## type is what is left before the name, `void` among them.
function_head : List(U8) -> Try({ return_type : Str, name : Str }, [NoFunction])
function_head = |code| {
after_storage = code.drop_first(storage_end(code))
head = after_storage.drop_first(attribute_end(after_storage))
match Mask.byte_from(head, '(', 0) {
Err(_) => Err(NoFunction)
Ok(open) => {
is_value = match Mask.byte_from(head, '=', 0) {
Ok(equals) => equals < open
Err(_) => Bool.False
}
before = Mask.trimmed(head.take_first(open))
# `^(.*[\s*])([A-Za-z_]\w*)$`: the name is what follows the last
# space or `*`.
match before.find_last_index(|byte| Mask.is_space(byte) or byte == '*') {
Ok(cut) if !(is_value) => {
name = before.drop_first(cut + 1)
return_type = Mask.trimmed(before.take_first(cut + 1))
if is_name(name) and !(return_type.is_empty()) {
Ok({ return_type: Mask.text(return_type), name: Mask.text(name) })
} else {
Err(NoFunction)
}
}
_ => Err(NoFunction)
}
}
}
}
## A `VEC_DEFINE(`, `MAP_DEFINE(` or `SLICE_TYPE(` line read as its macro,
## the name it makes and the type it holds, or `NoGenerator` when it is
## none or its arguments are not a name and a type:
## `^(VEC_DEFINE|MAP_DEFINE|SLICE_TYPE)\(\s*(\w+)\s*,\s*([^)]*\S)\s*\)`.
generator : List(U8) -> Try({ macro : Str, name : Str, held_type : Str }, [NoGenerator])
generator = |code| {
macros = ["VEC_DEFINE", "MAP_DEFINE", "SLICE_TYPE"]
match macros.find_first(|macro| Mask.holds_at(code, 0, "${macro}(")) {
Err(_) => Err(NoGenerator)
Ok(macro) => {
name_start = Mask.spaces_end(code, macro.count_utf8_bytes() + 1)
name_end = Mask.word_end(code, name_start)
comma = Mask.spaces_end(code, name_end)
if name_end == name_start or code.get(comma) != Ok(',') {
Err(NoGenerator)
} else {
held_start = Mask.spaces_end(code, comma + 1)
match held_type_end(code, held_start) {
Ok(held_end) => {
name = Mask.text(code.sublist({ start: name_start, len: name_end - name_start }))
held_type = Mask.text(code.sublist({ start: held_start, len: held_end + 1 - held_start }))
Ok({ macro, name, held_type })
}
Err(_) => Err(NoGenerator)
}
}
}
}
}
## The name a data item's head declares: a function pointer's `(*name)`,
## else the last word before its `=`, `[`, `;` or `{`, or "" for none.
data_name : List(U8) -> Str
data_name = |code|
match Head.pointer_name(code, WithConst) {
Ok(name) => name
Err(_) => {
is_stop = |byte| byte == '=' or byte == '[' or byte == ';' or byte == '{'
head = match code.find_first_index(is_stop) {
Ok(stop) => code.take_first(stop)
Err(_) => code
}
trailing_word(Mask.trimmed(head))
}
}
## The first function pointer's name in the text, `(*name)`, a `const`
## before the name allowed when asked: `\(\s*\*\s*(const\s+)?(\w+)\s*\)`.
pointer_name : List(U8), [WithConst, WithoutConst] -> Try(Str, [NoPointer])
pointer_name = |code, consts| {
var $at = 0
while $at < code.len() {
if code.get($at) == Ok('(') {
star = Mask.spaces_end(code, $at + 1)
if code.get(star) == Ok('*') {
after = Mask.spaces_end(code, star + 1)
is_const = consts == WithConst and Mask.holds_at(code, after, "const") and Mask.is_space_at(code, after + 5)
with_const = if is_const {
closed_word(code, Mask.spaces_end(code, after + 5))
} else {
Err(NoPointer)
}
match with_const {
Ok(name) => return Ok(name)
Err(_) =>
match closed_word(code, after) {
Ok(name) => return Ok(name)
Err(_) => {}
}
}
}
}
$at = $at + 1
}
Err(NoPointer)
}
## The type keyword a `typedef` or `enum` line opens with, after any
## `typedef`: `^(typedef\s+)?(struct|enum|union)\b`.
type_keyword : List(U8) -> [Struct, Enum, Union, NoKeyword]
type_keyword = |code| {
at = if Mask.holds_at(code, 0, "typedef") and Mask.is_space_at(code, 7) {
Mask.spaces_end(code, 7)
} else {
0
}
is_keyword = |word| Mask.holds_at(code, at, word) and !(Mask.is_word_at(code, at + word.count_utf8_bytes()))
if is_keyword("struct") {
Struct
} else if is_keyword("enum") {
Enum
} else if is_keyword("union") {
Union
} else {
NoKeyword
}
}
## The name a type's masked text declares last, before its closing `;`:
## `(\w+)\s*(\[[^\]]*\])?\s*;\s*$`.
declared_name : List(U8) -> Try(Str, [NoName])
declared_name = |text| {
match text.find_last_index(|byte| !(Mask.is_space(byte))) {
Ok(semicolon) if text.get(semicolon) == Ok(';') =>
match last_unspaced(text, semicolon) {
Ok(before) if text.get(before) == Ok(']') => bracketed_name(text, before)
Ok(before) if Mask.is_word_at(text, before) => Ok(word_ending_at(text, before))
_ => Err(NoName)
}
_ => Err(NoName)
}
}
## A named `enum`'s tag: `^enum\s+(\w+)`.
enum_tag : List(U8) -> Try(Str, [NoTag])
enum_tag = |code| {
start = Mask.spaces_end(code, 4)
end = Mask.word_end(code, start)
if Mask.holds_at(code, 0, "enum") and Mask.is_space_at(code, 4) and end > start {
Ok(Mask.text(code.sublist({ start, len: end - start })))
} else {
Err(NoTag)
}
}
## A `#` line's directive and its first argument, "" for none:
## `^#\s*(\w+)\s*(\w*)`.
directive : List(U8) -> Try({ word : Str, argument : Str }, [NoDirective])
directive = |code| {
word_start = Mask.spaces_end(code, 1)
word_end = Mask.word_end(code, word_start)
argument_start = Mask.spaces_end(code, word_end)
argument_end = Mask.word_end(code, argument_start)
if code.get(0) == Ok('#') and word_end > word_start {
word = Mask.text(code.sublist({ start: word_start, len: word_end - word_start }))
argument = Mask.text(code.sublist({ start: argument_start, len: argument_end - argument_start }))
Ok({ word, argument })
} else {
Err(NoDirective)
}
}
## An `#include` line's path, from the raw line: `^#\s*include\s*["<]([^">]+)[">]`.
include_path : List(U8) -> Try(Str, [NoPath])
include_path = |raw| {
keyword = Mask.spaces_end(raw, 1)
open = Mask.spaces_end(raw, keyword + 7)
is_open = raw.get(open) == Ok('"') or raw.get(open) == Ok('<')
is_close = |byte| byte == '"' or byte == '>'
is_framed = raw.get(0) == Ok('#') and Mask.holds_at(raw, keyword, "include") and is_open
match raw.drop_first(open + 1).find_first_index(is_close) {
Ok(length) if is_framed and length > 0 => Ok(Mask.text(raw.sublist({ start: open + 1, len: length })))
_ => Err(NoPath)
}
}
## A `TEST(name) {` line's name: `^TEST\(\s*(\w+)\s*\)\s*\{\s*$`.
test_name : List(U8) -> Try(Str, [NoTest])
test_name = |code| {
start = Mask.spaces_end(code, 5)
end = Mask.word_end(code, start)
close = Mask.spaces_end(code, end)
brace = Mask.spaces_end(code, close + 1)
is_test =
Mask.holds_at(code, 0, "TEST(")
and end > start
and code.get(close) == Ok(')')
and code.get(brace) == Ok('{')
and Mask.spaces_end(code, brace + 1) == code.len()
if is_test {
Ok(Mask.text(code.sublist({ start, len: end - start })))
} else {
Err(NoTest)
}
}
## A test list's macro and its first argument, "" for none:
## `^(\w+)\(\s*(\w*)`, of a line that starts with the macro and `(`.
test_list : List(U8) -> { macro : Str, argument : Str }
test_list = |code| {
macro_end = Mask.word_end(code, 0)
argument_start = Mask.spaces_end(code, macro_end + 1)
argument_end = Mask.word_end(code, argument_start)
{
macro: Mask.text(code.take_first(macro_end)),
argument: Mask.text(code.sublist({ start: argument_start, len: argument_end - argument_start })),
}
}
}
## Where `^static\s+(inline\s+)?(STATUS_MUST_USE\s+)?` ends, or 0.
storage_end : List(U8) -> U64
storage_end = |code|
if Mask.holds_at(code, 0, "static") and Mask.is_space_at(code, 6) {
after_static = Mask.spaces_end(code, 6)
after_inline = word_and_spaces_end(code, after_static, "inline")
word_and_spaces_end(code, after_inline, "STATUS_MUST_USE")
} else {
0
}
## Past `word\s+` at `at`, or `at` when it is not there.
word_and_spaces_end : List(U8), U64, Str -> U64
word_and_spaces_end = |code, at, word| {
after = at + word.count_utf8_bytes()
if Mask.holds_at(code, at, word) and Mask.is_space_at(code, after) {
Mask.spaces_end(code, after)
} else {
at
}
}
## Where `^__attribute__\(\([\w\s,]*\)\)\s+` ends, or 0.
attribute_end : List(U8) -> U64
attribute_end = |code| {
is_inside = |byte| Mask.is_word(byte) or Mask.is_space(byte) or byte == ','
inside_start = 15
inside_end = match code.drop_first(inside_start).find_first_index(|byte| !(is_inside(byte))) {
Ok(length) => inside_start + length
Err(_) => code.len()
}
is_attribute =
Mask.holds_at(code, 0, "__attribute__((")
and Mask.holds_at(code, inside_end, "))")
and Mask.is_space_at(code, inside_end + 2)
if is_attribute {
Mask.spaces_end(code, inside_end + 2)
} else {
0
}
}
## Whether the bytes are a C name: `[A-Za-z_]\w*`, whole.
is_name : List(U8) -> Bool
is_name = |bytes|
match bytes.first() {
Ok(first) => Mask.is_name_start(first) and bytes.all(Mask.is_word)
Err(_) => Bool.False
}
## The last byte of a generator's held type, from `start`: `([^)]*\S)\s*\)`,
## the longest run of no `)` whose last byte is no space and after which a
## `)` follows, past any spaces.
held_type_end : List(U8), U64 -> Try(U64, [NoType])
held_type_end = |code, start|
match Mask.byte_from(code, ')', start) {
Err(_) => Err(NoType)
Ok(first_close) => {
var $end = first_close
while $end >= start {
closes = code.get(Mask.spaces_end(code, $end + 1)) == Ok(')')
if !(Mask.is_space_at(code, $end)) and closes {
return Ok($end)
}
if $end == 0 {
return Err(NoType)
}
$end = $end - 1
}
Err(NoType)
}
}
## The word at `at`, when a `)` follows it past any spaces: `(\w+)\s*\)`.
closed_word : List(U8), U64 -> Try(Str, [NoPointer])
closed_word = |code, at| {
end = Mask.word_end(code, at)
if end > at and code.get(Mask.spaces_end(code, end)) == Ok(')') {
Ok(Mask.text(code.sublist({ start: at, len: end - at })))
} else {
Err(NoPointer)
}
}
## The `\w` run that ends the bytes, "" for none: `(\w+)$`.
trailing_word : List(U8) -> Str
trailing_word = |bytes|
match bytes.find_last_index(|byte| !(Mask.is_word(byte))) {
Ok(last_other) => Mask.text(bytes.drop_first(last_other + 1))
Err(_) => Mask.text(bytes)
}
## The last place before `end` that is no `\s`.
last_unspaced : List(U8), U64 -> Try(U64, [Missing])
last_unspaced = |bytes, end|
match bytes.take_first(end).find_last_index(|byte| !(Mask.is_space(byte))) {
Ok(at) => Ok(at)
Err(_) => Err(Missing)
}
## The `\w` run that ends at `last`, whole.
word_ending_at : List(U8), U64 -> Str
word_ending_at = |bytes, last| {
before = bytes.take_first(last + 1)
trailing_word(before)
}
## The name before a `[...]` that closes at `close`: the leftmost `[` of the
## brackets (no `]` between it and `close`) with a word before it, past any
## spaces, is the match a leftmost search finds.
bracketed_name : List(U8), U64 -> Try(Str, [NoName])
bracketed_name = |text, close| {
var $opens = []
var $at = close
var $is_open = Bool.True
while $is_open and $at > 0 {
$at = $at - 1
byte = text.get($at) ?? 0
if byte == ']' {
$is_open = Bool.False
} else if byte == '[' {
$opens = $opens.prepend($at)
}
}
for open in $opens {
match last_unspaced(text, open) {
Ok(before) if Mask.is_word_at(text, before) => return Ok(word_ending_at(text, before))
_ => {}
}
}
Err(NoName)
}
cookbook/c/items/Item.roc, 112 lines
## A top-level item of a file of Shale's C, as Split.items gives it: its
## kind, the name it declares, and its lines. Every field is set, so none is
## missing: a line field is 0 and a text field "" where the item has none.
##
## kind what it is (Item.Kind; Item.kind_name prints it);
## name the name it declares: a function's, a type's, a macro's,
## an include's path, a generator's type, a test's; a
## directive's word and first argument (`if defined`); an
## anonymous `enum`'s first enumerator;
## first, last its lines, from its opening line to its closing one;
## comment_first, comment_last
## the `//` lines directly above it, no blank between;
## sig_first, sig_last
## its head: a function's or a test's lines up to the one
## its body's `{` ends, a wrapped prototype's lines; else its
## first line alone;
## body_first, body_last
## a function's or a test's body (both its line, when the
## body shares the head's line), a braced item's inside;
## storage `static inline`, `static` or "";
## return_type a function's or a prototype's return type, as written;
## macro, held_type
## a generator's macro (`VEC_DEFINE`) and the type it holds;
## makes a generator macro's own functions, its `Name##_<x>(`
## suffixes (`make`, `push`);
## enumerators an enum's constants, in order;
## uses when asked for, the identifiers a function's, a test's or
## a test list's body names, sorted, each once.
Item := {
kind : Item.Kind,
name : Str,
first : U64,
last : U64,
comment_first : U64,
comment_last : U64,
sig_first : U64,
sig_last : U64,
body_first : U64,
body_last : U64,
storage : Str,
return_type : Str,
macro : Str,
held_type : Str,
makes : List(Str),
enumerators : List(Str),
uses : List(Str),
}.{
## The kinds of item the dialect has.
Kind : [
Function,
Prototype,
Data,
Struct,
Enum,
Union,
Typedef,
Macro,
Guard,
Include,
Directive,
Generator,
Test,
TestList,
StaticAssert,
]
## An item of a kind and a name over its lines, every other field empty:
## the caller sets what its kind has.
new : Item.Kind, Str, { first : U64, last : U64 } -> Item
new = |kind, name, { first, last }| {
kind,
name,
first,
last,
comment_first: 0,
comment_last: 0,
sig_first: first,
sig_last: first,
body_first: 0,
body_last: 0,
storage: "",
return_type: "",
macro: "",
held_type: "",
makes: [],
enumerators: [],
uses: [],
}
## A kind's name as the Shale original printed it: `function`,
## `test_list`, `static_assert`.
kind_name : Item.Kind -> Str
kind_name = |kind|
match kind {
Function => "function"
Prototype => "prototype"
Data => "data"
Struct => "struct"
Enum => "enum"
Union => "union"
Typedef => "typedef"
Macro => "macro"
Guard => "guard"
Include => "include"
Directive => "directive"
Generator => "generator"
Test => "test"
TestList => "test_list"
StaticAssert => "static_assert"
}
}
cookbook/c/items/Mask.roc, 229 lines
## The masker the splitter reads Shale's C with, and the byte classes it
## reads by. A line is its bytes, as Shale's strings are, so a column is a
## byte's place. The classes are the regular expressions' and the builtins'
## of c/build/c_items.shale, the Shale original: `\s` is a space, a tab, a
## newline, a carriage return, a vertical tab or a form feed; `\w` an ASCII
## letter, a digit or `_`; `trim` takes a space, a tab, a carriage return
## and a newline.
Mask := [].{
## The line with its strings, character literals and comments blanked,
## each to spaces between its quotes (a comment wholly to spaces), so every
## column stays where it was. The quotes go first, leftmost first, so a
## `"` in `'"'` is the literal's and a `//` or a `/*` left after them is a
## comment's; a quote that nothing closes is left as it is.
masked : List(U8) -> List(U8)
masked = |line|
if line.contains('"') or line.contains('\'') or line.contains('/') {
masked_slowly(line)
} else {
line
}
## A regular expression's `\s`.
is_space : U8 -> Bool
is_space = |byte|
byte == ' ' or byte == '\t' or byte == '\n' or byte == '\r' or byte == 0x0b or byte == 0x0c
## A regular expression's `\w`: an ASCII letter, a digit or `_`.
is_word : U8 -> Bool
is_word = |byte|
Mask.is_name_start(byte) or (byte >= '0' and byte <= '9')
## The first byte of a C name: an ASCII letter or `_`.
is_name_start : U8 -> Bool
is_name_start = |byte|
(byte >= 'a' and byte <= 'z') or (byte >= 'A' and byte <= 'Z') or byte == '_'
## Whether the byte at `at` is a `\w`, past the end being none.
is_word_at : List(U8), U64 -> Bool
is_word_at = |bytes, at|
match bytes.get(at) {
Ok(byte) => Mask.is_word(byte)
Err(_) => Bool.False
}
## Whether the byte at `at` is a `\s`, past the end being none.
is_space_at : List(U8), U64 -> Bool
is_space_at = |bytes, at|
match bytes.get(at) {
Ok(byte) => Mask.is_space(byte)
Err(_) => Bool.False
}
## The bytes without the spaces, tabs, carriage returns and newlines at
## their ends, as Shale's `trim` takes them.
trimmed : List(U8) -> List(U8)
trimmed = |bytes|
match bytes.find_first_index(|byte| !(is_blank(byte))) {
Ok(start) => {
end = bytes.find_last_index(|byte| !(is_blank(byte))) ?? start
bytes.sublist({ start, len: end + 1 - start })
}
Err(_) => []
}
## The first place at `at` or after it that is no `\s`: the end of `\s*`.
spaces_end : List(U8), U64 -> U64
spaces_end = |bytes, at| {
var $end = at
while Mask.is_space_at(bytes, $end) {
$end = $end + 1
}
$end
}
## The first place at `at` or after it that is no `\w`: the end of `\w*`.
word_end : List(U8), U64 -> U64
word_end = |bytes, at| {
var $end = at
while Mask.is_word_at(bytes, $end) {
$end = $end + 1
}
$end
}
## Whether the bytes hold the text at `at`.
holds_at : List(U8), U64, Str -> Bool
holds_at = |bytes, at, wanted_text| {
wanted = wanted_text.to_utf8()
bytes.sublist({ start: at, len: wanted.len() }) == wanted
}
## The place of the first two bytes `pair` at `from` or after it.
pair_from : List(U8), (U8, U8), U64 -> Try(U64, [Missing])
pair_from = |bytes, (first, second), from| {
var $at = from
while $at + 1 < bytes.len() {
match Mask.byte_from(bytes, first, $at) {
Ok(found) if bytes.get(found + 1) == Ok(second) => return Ok(found)
Ok(found) => {
$at = found + 1
}
Err(_) => return Err(Missing)
}
}
Err(Missing)
}
## The place of the first `byte` at `from` or after it.
byte_from : List(U8), U8, U64 -> Try(U64, [Missing])
byte_from = |bytes, byte, from|
match bytes.drop_first(from).find_first_index(|each| each == byte) {
Ok(offset) => Ok(from + offset)
Err(_) => Err(Missing)
}
## The bytes as text: Shale's C is UTF-8, and a mask cuts only at ASCII.
text : List(U8) -> Str
text = |bytes| Str.from_utf8_lossy(bytes)
}
## The masker's work on a line that holds a quote or a `/`.
masked_slowly : List(U8) -> List(U8)
masked_slowly = |line| {
has_double = line.contains('"')
has_single = line.contains('\'')
quotes_blanked =
if has_double or has_single {
blank_quotes(line, { double: has_double, single: has_single })
} else {
line
}
comments_blanked =
if Mask.pair_from(quotes_blanked, ('/', '*'), 0) != Err(Missing) {
blank_block_comments(quotes_blanked)
} else {
quotes_blanked
}
match Mask.pair_from(comments_blanked, ('/', '/'), 0) {
Ok(cut) => comments_blanked.take_first(cut).concat(List.repeat(' ', comments_blanked.len() - cut))
Err(_) => comments_blanked
}
}
## A byte Shale's `trim` takes off a text's ends.
is_blank : U8 -> Bool
is_blank = |byte| byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n'
## The line with each string (`double`) or character literal (`single`)
## blanked between its quotes, leftmost first: a quote opens one, `\` and the
## byte after it are inside it, and the same quote closes it. One that the
## line does not close is no literal, and the search goes on after its quote.
blank_quotes : List(U8), { double : Bool, single : Bool } -> List(U8)
blank_quotes = |line, kinds| {
count = line.len()
var $out = line
var $at = 0
while $at < count {
byte = line.get($at) ?? 0
is_open = (byte == '"' and kinds.double) or (byte == '\'' and kinds.single)
closed = if is_open {
quote_close(line, $at, byte)
} else {
Err(Unclosed)
}
match closed {
Ok(close) => {
$out = blanked($out, { start: $at + 1, end: close })
$at = close + 1
}
Err(_) => {
$at = $at + 1
}
}
}
$out
}
## Where the literal opened by `quote` at `open` closes: `[^"\\]*(?:\\.[^"\\]*)*"`.
quote_close : List(U8), U64, U8 -> Try(U64, [Unclosed])
quote_close = |line, open, quote| {
count = line.len()
var $at = open + 1
while $at < count {
byte = line.get($at) ?? 0
if byte == quote {
return Ok($at)
}
if byte == '\\' {
# `\\.`: the escape takes any byte but a newline after it.
if $at + 1 >= count or line.get($at + 1) == Ok('\n') {
return Err(Unclosed)
}
$at = $at + 2
} else {
$at = $at + 1
}
}
Err(Unclosed)
}
## The line with each `/* */` comment wholly spaces: `/\*[^*]*\*/`, so a
## comment that holds a `*` of its own is none.
blank_block_comments : List(U8) -> List(U8)
blank_block_comments = |line| {
var $out = line
var $at = 0
while $at + 1 < line.len() {
if line.get($at) == Ok('/') and line.get($at + 1) == Ok('*') {
match Mask.byte_from(line, '*', $at + 2) {
Ok(star) if line.get(star + 1) == Ok('/') => {
$out = blanked($out, { start: $at, end: star + 2 })
$at = star + 2
}
_ => {
$at = $at + 1
}
}
} else {
$at = $at + 1
}
}
$out
}
## The bytes with those from `start` up to `end` made spaces.
blanked : List(U8), { start : U64, end : U64 } -> List(U8)
blanked = |bytes, { start, end }|
bytes.take_first(start).concat(List.repeat(' ', end - start)).concat(bytes.drop_first(end))
cookbook/c/items/Paths.roc, 23 lines
## How the C recipes read a file's path below the folder they walk: whether
## it is the tests', and whether it is under a folder named `out`, the
## build's output, which no recipe reads.
Paths := [].{
## Whether `path`, below the folder, is the tests': in a `tests` folder,
## or a file whose name starts with `test` (c/foundation/test.h, the
## tests' runner).
is_test_path : Str, Str -> Bool
is_test_path = |folder, path| {
below = Str.from_utf8_lossy(path.to_utf8().drop_first(folder.count_utf8_bytes() + 1))
file_name = match below.split_on("/").last() {
Ok(last) => last
Err(_) => below
}
below.starts_with("tests/") or below.contains("/tests/") or file_name.starts_with("test")
}
## Whether a folder below `folder` on the way to `path` is named `out`.
is_in_out_folder : Str, Str -> Bool
is_in_out_folder = |folder, path|
path.drop_prefix("${folder}/").split_on("/").drop_last(1).contains("out")
}
cookbook/c/items/Split.roc, 441 lines
## The splitter: a file of Shale's C split into its top-level items, in
## order. There is no C parser on the box, and none is wanted:
## c/check_discipline.shale holds the C to a shape a line reader can trust,
## and the build fails when a file breaks it, so the dialect is this
## reader's contract (c/docs/style.md, "The top level"):
##
## - every line at column 0 opens a top-level item or closes one, and
## everything inside an item is indented;
## - every function starts at column 0 with `static` (or is `int main(`);
## - an opening brace ends its line, and a declaration is one a line;
## - comments are `//`, `/* */` only inside a macro; there are no tabs;
## - a header is framed by `// <name>: ...`, its guard and `#endif`.
##
## Every line of the file is in exactly one item, or is blank, or is a `//`
## comment line between items. A line that is none of these is an error
## naming the file and its line, never a guess. It is c/build/c_items.shale's
## `c_items`, the Shale original, a second copy of this logic, which the fast
## tier's discipline block splits every C file with, since it builds no Roc.
import Guard
import Head
import Item
import Mask
import Words
Split := [].{
## The text's lines as Shale's `lines` splits them: at each newline, with
## no empty last line after a final one.
lines : Str -> List(List(U8))
lines = |text| {
bytes = text.to_utf8()
if bytes.is_empty() {
[]
} else if bytes.last() == Ok('\n') {
bytes.split_on('\n').drop_last(1)
} else {
bytes.split_on('\n')
}
}
## The items of the C file at `path`, its text `text`, in order (Item has
## their fields); `uses` fills each function's, test's and test list's
## uses. A line the dialect does not account for is an error, the stop's
## words: `<path>:<line>: <why>: <the line>`.
items : { path : Str, text : Str, uses : Bool } -> Try(List(Item), Str)
items = |{ path, text, uses }| {
file = { path, lines: Split.lines(text) }
count = file.lines.len()
var $items = []
var $comment_first = 0
var $comment_last = 0
var $at = 1
while $at <= count {
raw = line_at(file, $at)
if raw.is_empty() {
$comment_first = 0
$at = $at + 1
} else if raw.starts_with(['/', '/']) {
if $comment_first == 0 {
$comment_first = $at
}
$comment_last = $at
$at = $at + 1
} else if raw.starts_with([' ']) {
return Err(unaccounted(file, $at, "an indented line outside every item"))
} else {
opened = item_at(file, $at, Mask.masked(raw))?
commented =
if $comment_first == 0 {
opened
} else {
{ ..opened, comment_first: $comment_first, comment_last: $comment_last }
}
$items = $items.append(with_uses(file, commented, uses))
$comment_first = 0
$at = commented.last + 1
}
}
if path.ends_with(".h") {
Guard.framed(path, $items)
} else {
Ok($items)
}
}
## The masked text of the file's lines from `first` to `last`, counted from
## 1, joined by newlines: Shale's `c_masked_text`.
masked_text : List(List(U8)), { first : U64, last : U64 } -> List(U8)
masked_text = |file_lines, { first, last }| {
var $text = []
var $at = first
while $at <= last {
if $at > first {
$text = $text.append('\n')
}
$text = $text.concat(Mask.masked(file_lines.get($at - 1) ?? []))
$at = $at + 1
}
$text
}
}
## A file being split: its path, for the errors, and its lines.
CFile : { path : Str, lines : List(List(U8)) }
## Line `number` of the file, counted from 1.
line_at : CFile, U64 -> List(U8)
line_at = |file, number| file.lines.get(number - 1) ?? []
## The error for line `number`, which the dialect does not account for: its
## place and why first, then the line.
unaccounted : CFile, U64, Str -> Str
unaccounted = |file, number, why|
unaccounted_text(file, number, why, Mask.text(line_at(file, number)))
## The error for line `number`, with `shown` in place of the line.
unaccounted_text : CFile, U64, Str, Str -> Str
unaccounted_text = |file, number, why, shown|
"${file.path}:${number.to_str()}: ${why}: ${shown}"
## The item's uses, when asked for and it is a function, a test or a test
## list with a body. A body on its head's line is what follows its `{`.
with_uses : CFile, Item, Bool -> Item
with_uses = |file, item, wanted| {
has_body = item.body_first != 0
is_code = item.kind == Function or item.kind == Test or item.kind == TestList
if wanted and has_body and is_code {
text = Split.masked_text(file.lines, { first: item.body_first, last: item.body_last })
body =
if item.body_first == item.sig_last and item.kind != TestList {
match Mask.byte_from(text, '{', 0) {
Ok(brace) => text.drop_first(brace)
Err(_) => text
}
} else {
text
}
{ ..item, uses: Words.uses(body) }
} else {
item
}
}
## The line that closes the braced item opened at line `from`: the first
## line after it at column 0, which must start with `}`. A blank line, an
## indented one or a `#` directive (which C writes at column 0, as an
## `#ifdef` in a body is) is inside; anything else at column 0 is an error.
brace_close : CFile, U64, Str -> Try(U64, Str)
brace_close = |file, from, what| {
count = file.lines.len()
var $at = from + 1
while $at <= count {
match line_at(file, $at).first() {
Ok('}') => return Ok($at)
Ok(byte) if byte != ' ' and byte != '#' => {
why = "a line at column 0 inside ${what} opened at line ${from.to_str()}, which only a `}` may close"
return Err(unaccounted(file, $at, why))
}
_ => {}
}
$at = $at + 1
}
Err(unaccounted(file, from, "${what} that no `}` at column 0 closes"))
}
## The last line of the parenthesized item that opens at line `from`: where
## its masked parentheses balance. A line after the first is indented, or
## starts with the closing `)` at column 0.
paren_close : CFile, U64 -> Try(U64, Str)
paren_close = |file, from| {
count = file.lines.len()
var $depth = 0
var $at = from
while $at <= count {
raw = line_at(file, $at)
if $at > from and !(raw.starts_with([' '])) and !(raw.starts_with([')'])) {
return Err(unaccounted(file, $at, "a line at column 0 inside the parentheses opened at line ${from.to_str()}"))
}
code = Mask.masked(raw)
opens = code.count_if(|byte| byte == '(').to_i64_wrap()
closes = code.count_if(|byte| byte == ')').to_i64_wrap()
$depth = $depth + opens - closes
if $depth <= 0 {
return Ok($at)
}
$at = $at + 1
}
Err(unaccounted(file, from, "parentheses that never close"))
}
## The last line of a head that opens at line `from`: the first whose masked
## code ends with `{`, `;` or `}`. A line after the first is indented.
head_close : CFile, U64 -> Try(U64, Str)
head_close = |file, from| {
count = file.lines.len()
var $at = from
while $at <= count {
raw = line_at(file, $at)
if $at > from and !(raw.starts_with([' '])) {
return Err(unaccounted(file, $at, "a line at column 0 inside the head opened at line ${from.to_str()}"))
}
match last_code_byte(raw) {
Ok(byte) if byte == '{' or byte == ';' or byte == '}' => return Ok($at)
_ => {}
}
$at = $at + 1
}
Err(unaccounted(file, from, "a head that no `{` or `;` ends"))
}
## The last byte of a line's masked code, trimmed.
last_code_byte : List(U8) -> Try(U8, [ListWasEmpty])
last_code_byte = |raw| Mask.trimmed(Mask.masked(raw)).last()
## The item that line `at` opens, its masked code `code`.
item_at : CFile, U64, List(U8) -> Try(Item, Str)
item_at = |file, at, code| {
raw = line_at(file, at)
opens = |text| raw.starts_with(text.to_utf8())
if opens("#") {
hash_item(file, at, code)
} else if opens("static inline ") {
static_item(file, at, "static inline")
} else if opens("static ") {
static_item(file, at, "static")
} else if opens("typedef ") or opens("enum ") {
type_item(file, at, code)
} else if opens("SLICE_TYPE(") or opens("VEC_DEFINE(") or opens("MAP_DEFINE(") {
generator_item(file, at, code)
} else if opens("TEST(") {
test_item(file, at, code)
} else if opens("TEST_MAIN(") or opens("TEST_PART(") or opens("TEST_PARTS_MAIN(") {
test_list_item(file, at, code)
} else if opens("_Static_assert(") {
static_assert_item(file, at)
} else if opens("int main(") {
main_item(file, at)
} else {
Err(unaccounted(file, at, "a line at column 0 that opens no item the dialect knows"))
}
}
## The `static` or `static inline` item at line `at`: a function, a
## prototype or data.
static_item : CFile, U64, Str -> Try(Item, Str)
static_item = |file, at, storage| {
last = head_close(file, at)?
flat = spaces_made_one(Split.masked_text(file.lines, { first: at, last }))
ending = last_code_byte(line_at(file, last))
match Head.function_head(flat) {
Ok({ return_type, name }) => {
head = { ..Item.new(Prototype, name, { first: at, last }), storage, return_type, sig_last: last }
match ending {
Ok(';') => Ok(head)
Ok('}') => Ok({ ..head, kind: Function, body_first: last, body_last: last })
_ => {
close = brace_close(file, last, "the function `${name}`")?
function = { ..head, kind: Function, last: close }
if close > last + 1 {
Ok({ ..function, body_first: last + 1, body_last: close - 1 })
} else {
Ok(function)
}
}
}
}
Err(_) => {
name = Head.data_name(flat)
data = { ..Item.new(Data, name, { first: at, last }), storage, sig_last: last }
if ending == Ok('{') {
close = brace_close(file, last, "the data `${name}`")?
Ok({ ..data, last: close, body_first: last + 1, body_last: close - 1 })
} else {
Ok(data)
}
}
}
}
## The text with each run of `\s` made one space.
spaces_made_one : List(U8) -> List(U8)
spaces_made_one = |text|
text.fold(
[],
|out, byte|
if !(Mask.is_space(byte)) {
out.append(byte)
} else if out.last() == Ok(' ') {
# A space is `\s`, so one that ends `out` is a run's already.
out
} else {
out.append(' ')
},
)
## The `typedef` or `enum` item at line `at`.
type_item : CFile, U64, List(U8) -> Try(Item, Str)
type_item = |file, at, code| {
kind = match Head.type_keyword(code) {
Struct => Struct
Enum => Enum
Union => Union
NoKeyword => Typedef
}
last = head_close(file, at)?
headed = { ..Item.new(kind, "", { first: at, last }), sig_last: last }
braced =
if last_code_byte(line_at(file, last)) == Ok('{') {
close = brace_close(file, last, "the ${Item.kind_name(kind)}")?
{ ..headed, last: close, body_first: last + 1, body_last: close - 1 }
} else {
headed
}
text = Split.masked_text(file.lines, { first: at, last: braced.last })
declared =
if code.starts_with("typedef".to_utf8()) {
match (kind, Head.pointer_name(text, WithoutConst), Head.declared_name(text)) {
(Typedef, Ok(pointer), _) => pointer
(_, _, Ok(name)) => name
_ => ""
}
} else {
Head.enum_tag(code) ?? ""
}
enumerators = if kind == Enum {
Words.enumerators(text)
} else {
[]
}
name =
match enumerators.first() {
Ok(first) if declared == "" => first
_ => declared
}
if name == "" {
Err(unaccounted(file, at, "a ${Item.kind_name(kind)} whose name this reader can't find"))
} else {
Ok({ ..braced, name, enumerators })
}
}
## The `#` item at line `at`: an include, a macro (to its last `\` line),
## the header's guard (Split.items frames it), or another directive.
hash_item : CFile, U64, List(U8) -> Try(Item, Str)
hash_item = |file, at, code| {
count = file.lines.len()
var $last = at
while line_at(file, $last).last() == Ok('\\') and $last < count {
$last = $last + 1
}
last = $last
match Head.directive(code) {
Err(_) => Err(unaccounted(file, at, "a `#` line with no directive"))
Ok({ word, argument: _ }) if word == "include" =>
match Head.include_path(line_at(file, at)) {
Ok(path) => Ok(Item.new(Include, path, { first: at, last }))
Err(_) => Err(unaccounted(file, at, "an `#include` with no path"))
}
Ok({ word, argument }) if word == "define" => {
defined = Item.new(Macro, argument, { first: at, last })
if last > at {
makes = Words.suffixes(Split.masked_text(file.lines, { first: at, last }))
Ok({ ..defined, body_first: at + 1, body_last: last, makes })
} else {
Ok(defined)
}
}
Ok({ word, argument }) => {
name = if argument == "" {
word
} else {
"${word} ${argument}"
}
Ok(Item.new(Directive, name, { first: at, last }))
}
}
}
## The `VEC_DEFINE(`, `MAP_DEFINE(` or `SLICE_TYPE(` item at line `at`.
generator_item : CFile, U64, List(U8) -> Try(Item, Str)
generator_item = |file, at, code|
match Head.generator(code) {
Err(_) => Err(unaccounted(file, at, "a generator line whose name and type this reader can't find"))
Ok({ macro, name, held_type }) => {
close = paren_close(file, at)?
Ok({ ..Item.new(Generator, name, { first: at, last: close }), macro, held_type })
}
}
## The `TEST(name) {` item at line `at`.
test_item : CFile, U64, List(U8) -> Try(Item, Str)
test_item = |file, at, code|
match Head.test_name(code) {
Err(_) => Err(unaccounted(file, at, "a `TEST(` line that is not `TEST(name) {`"))
Ok(name) => {
close = brace_close(file, at, "the test `${name}`")?
test = Item.new(Test, name, { first: at, last: close })
if close > at + 1 {
Ok({ ..test, body_first: at + 1, body_last: close - 1 })
} else {
Ok(test)
}
}
}
## The `TEST_MAIN(`, `TEST_PART(` or `TEST_PARTS_MAIN(` item at line `at`,
## named for its macro, or a `TEST_PART(` for its part.
test_list_item : CFile, U64, List(U8) -> Try(Item, Str)
test_list_item = |file, at, code| {
head = Head.test_list(code)
close = paren_close(file, at)?
name = if head.macro == "TEST_PART" and head.argument != "" {
head.argument
} else {
head.macro
}
Ok({ ..Item.new(TestList, name, { first: at, last: close }), body_first: at, body_last: close })
}
## The `_Static_assert(` item at line `at`, named for its first name that is
## not `_Static_assert` or `sizeof`.
static_assert_item : CFile, U64 -> Try(Item, Str)
static_assert_item = |file, at| {
close = paren_close(file, at)?
names = Words.names(Split.masked_text(file.lines, { first: at, last: close }))
name = names.find_first(|each| each != "_Static_assert" and each != "sizeof") ?? ""
Ok(Item.new(StaticAssert, name, { first: at, last: close }))
}
## The `int main(` function at line `at`.
main_item : CFile, U64 -> Try(Item, Str)
main_item = |file, at| {
last = head_close(file, at)?
close = brace_close(file, last, "the function `main`")?
main = { ..Item.new(Function, "main", { first: at, last: close }), return_type: "int", sig_last: last }
if close > last + 1 {
Ok({ ..main, body_first: last + 1, body_last: close - 1 })
} else {
Ok(main)
}
}
cookbook/c/items/Words.roc, 299 lines
## The words of an item's masked text: its names, the names its body uses,
## an enum's constants and a generator macro's own functions, each the
## regular expression of the Shale original, done by hand: for the names,
## c/build/c_items.shale's; for a body's uses, the `c_words_used` of
## cookbook/c/items.shale, retired (git history), which the fast tier's
## copy left out, since it wants no uses.
import Mask
Words := [].{
## The names in the text, in order, each as often as it is there:
## `\b[A-Za-z_]\w*`, a `\w` run that starts with a letter or `_`.
names : List(U8) -> List(Str)
names = |text| {
var $names = []
var $at = 0
while $at < text.len() {
end = Mask.word_end(text, $at)
if end > $at {
if Mask.is_name_start(text.get($at) ?? 0) {
$names = $names.append(Mask.text(text.sublist({ start: $at, len: end - $at })))
}
$at = end
} else {
$at = $at + 1
}
}
$names
}
## The identifiers the text names, sorted, each once: no keyword, no
## number, no member after `.` or `->`, and no directive's own word
## (`ifdef`), though the names a directive tests are uses.
uses : List(U8) -> List(Str)
uses = |text| {
bare = without_directive_words(without_members(text))
sorted = Words.names(bare)
.keep_if(|name| !(keywords.contains(name)))
.sort_with(Words.byte_order)
sorted.fold(
[],
|once, name|
if once.last() == Ok(name) {
once
} else {
once.append(name)
},
)
}
## An enum's constants, from its masked text: each name that starts an
## item of its braces, `^\s*([A-Za-z_]\w*)` in each part between commas.
enumerators : List(U8) -> List(Str)
enumerators = |text|
match Mask.byte_from(text, '{', 0) {
Err(_) => []
Ok(open) =>
match Mask.byte_from(text, '}', open + 1) {
Err(_) => []
Ok(close) => {
inside = text.sublist({ start: open + 1, len: close - open - 1 })
inside.split_on(',').fold(
[],
|found, part|
match leading_name(part) {
Ok(name) => found.append(name)
Err(_) => found
},
)
}
}
}
## A generator macro's own functions, its `Name##_<x>(` suffixes, from its
## definition's masked text, each once, in order: each match of
## `static\s[^(]*##_(\w+)\s*\(`.
suffixes : List(U8) -> List(Str)
suffixes = |text| {
var $found = []
var $at = 0
while $at < text.len() {
match suffix_at(text, $at) {
Ok({ suffix, open }) => {
if !($found.contains(suffix)) {
$found = $found.append(suffix)
}
$at = open + 1
}
Err(_) => {
$at = $at + 1
}
}
}
$found
}
## Two texts in the order of their bytes, a text before every longer one
## it starts, as Shale's `sort` puts strings. A copy of the cookbook lib's
## `Text.byte_order`, the home of the rule, kept because `uses` (so
## Split.items) sorts with it and this package may not import lib: a
## script's package imports no package of its own (roc_platform/run.shale
## refuses one). The C recipes sort with this copy, so items stays their
## only package.
byte_order : Str, Str -> [Before, Same, After]
byte_order = |first, second| {
pairs = List.map2(first.to_utf8(), second.to_utf8(), |x, y| (x, y))
match pairs.find_first(|(x, y)| x != y) {
Ok((x, y)) =>
if x < y {
Before
} else {
After
}
Err(_) =>
if first.count_utf8_bytes() < second.count_utf8_bytes() {
Before
} else if first.count_utf8_bytes() > second.count_utf8_bytes() {
After
} else {
Same
}
}
}
}
## C's keywords and the words of its types and storage, which are no use of
## a name.
keywords : List(Str)
keywords = [
"auto",
"break",
"case",
"char",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extern",
"float",
"for",
"goto",
"if",
"inline",
"int",
"long",
"register",
"restrict",
"return",
"short",
"signed",
"sizeof",
"static",
"struct",
"switch",
"typedef",
"union",
"unsigned",
"void",
"volatile",
"while",
"_Alignof",
"_Bool",
"_Static_assert",
"bool",
"true",
"false",
"NULL",
]
## The text with each member after `.` or `->` made one space:
## `(\.|->)\s*[A-Za-z_]\w*`.
without_members : List(U8) -> List(U8)
without_members = |text| {
var $out = []
var $at = 0
while $at < text.len() {
byte = text.get($at) ?? 0
after = if byte == '.' {
$at + 1
} else if byte == '-' and text.get($at + 1) == Ok('>') {
$at + 2
} else {
0
}
start = Mask.spaces_end(text, after)
if after > 0 and Mask.is_name_start(text.get(start) ?? 0) {
$out = $out.append(' ')
$at = Mask.word_end(text, start)
} else {
$out = $out.append(byte)
$at = $at + 1
}
}
$out
}
## The text with each directive's `#` and word gone, at the start or after a
## newline, the newline kept: `(^|\n)#\s*\w+`.
without_directive_words : List(U8) -> List(U8)
without_directive_words = |text| {
var $out = []
var $at = 0
while $at < text.len() {
byte = text.get($at) ?? 0
match directive_word_end(text, $at) {
Ok(end) => {
$at = end
}
Err(_) =>
if byte == '\n' {
match directive_word_end(text, $at + 1) {
Ok(end) => {
$out = $out.append('\n')
$at = end
}
Err(_) => {
$out = $out.append(byte)
$at = $at + 1
}
}
} else {
$out = $out.append(byte)
$at = $at + 1
}
}
}
$out
}
## Where `#\s*\w+` at `at` ends, at the text's start or after a newline; the
## start alone is asked of at 0.
directive_word_end : List(U8), U64 -> Try(U64, [NoDirective])
directive_word_end = |text, at| {
is_line_start = at == 0 or text.get(at - 1) == Ok('\n')
word_start = Mask.spaces_end(text, at + 1)
word_end = Mask.word_end(text, word_start)
if is_line_start and text.get(at) == Ok('#') and word_end > word_start {
Ok(word_end)
} else {
Err(NoDirective)
}
}
## The name an enum's part starts with, past any spaces.
leading_name : List(U8) -> Try(Str, [NoName])
leading_name = |part| {
start = Mask.spaces_end(part, 0)
end = Mask.word_end(part, start)
if end > start and Mask.is_name_start(part.get(start) ?? 0) {
Ok(Mask.text(part.sublist({ start, len: end - start })))
} else {
Err(NoName)
}
}
## The suffix of `static\s[^(]*##_(\w+)\s*\(` at `at`, and its `(`: the last
## `##_` before the first `(` after `static`, which only a name and spaces
## may follow up to that `(`.
suffix_at : List(U8), U64 -> Try({ suffix : Str, open : U64 }, [NoSuffix])
suffix_at = |text, at| {
after = at + 7
if !(Mask.holds_at(text, at, "static")) or !(Mask.is_space_at(text, at + 6)) {
return Err(NoSuffix)
}
match Mask.byte_from(text, '(', after) {
Err(_) => Err(NoSuffix)
Ok(open) => {
span = text.sublist({ start: after, len: open - after })
match last_paste(span) {
Err(_) => Err(NoSuffix)
Ok(paste) => {
start = after + paste + 3
end = Mask.word_end(text, start)
if end > start and Mask.spaces_end(text, end) == open {
Ok({ suffix: Mask.text(text.sublist({ start, len: end - start })), open })
} else {
Err(NoSuffix)
}
}
}
}
}
}
## The place of the last `##_` in the bytes.
last_paste : List(U8) -> Try(U64, [Missing])
last_paste = |bytes| {
var $at = bytes.len()
while $at >= 3 {
$at = $at - 1
if Mask.holds_at(bytes, $at - 2, "##_") {
return Ok($at - 2)
}
}
Err(Missing)
}
cookbook/c/items/main.roc, 14 lines
## The splitter the recipes that read Shale's C share: a file of Shale's C
## split into its top-level items, from the dialect c/check_discipline.shale
## holds. A recipe names it by a relative path in its app's header (`items:
## "../items/main.roc"`, then `import items.Split`). It reaches no effect:
## a recipe reads the file and hands Split.items its text.
##
## Split the splitter, Shale's `lines` and an item's masked text
## Guard a header's guard, framed
## Item an item and its kinds
## Mask the masker, and the byte classes the readers read by
## Head the readers of an item's opening line or head
## Words the names in an item's text: its uses, an enum's constants
## Paths a file's path read: the tests', or under a folder named `out`
package [Guard, Head, Item, Mask, Paths, Split, Words] {}