The shared Roc library
cookbook/roc/lib/Bytes.roc, 128 lines
## A line's bytes read as Shale's builtins read a string: a place counted
## from 1, cut as `sub` cuts, trimmed as `trim` trims, and a width that is
## the bytes with a tab counting four. A recipe that scans Roc a byte at a
## time (Groups, Stacking) reads its lines through these, so its places and
## widths are its Shale original's.
Bytes := [].{
## A line's width: its bytes, a tab counting four.
width_of : List(U8) -> U64
width_of = |bytes| bytes.len() + 3 * bytes.count_if(|byte| byte == '\t')
## The width of a line given as text.
line_width : Str -> U64
line_width = |text| Bytes.width_of(text.to_utf8())
## Line `number` of the lines, counted from 1, as bytes: empty past the end.
line_of : List(Str), U64 -> List(U8)
line_of = |source_lines, number|
if number == 0 {
[]
} else {
(source_lines.get(number - 1) ?? "").to_utf8()
}
## The byte at `place`, counted from 1, or 0 past either end.
byte_at : List(U8), U64 -> U8
byte_at = |bytes, place|
if place == 0 {
0
} else {
bytes.get(place - 1) ?? 0
}
## Shale's `sub(s, first, last)` of bytes: the places from `first` to
## `last`, counted from 1, cut to the bytes there are.
span : List(U8), U64, U64 -> List(U8)
span = |bytes, first, last| {
start = if first == 0 {
1
} else {
first
}
end = if last < bytes.len() {
last
} else {
bytes.len()
}
if start > end {
[]
} else {
bytes.sublist({ start: start - 1, len: end - start + 1 })
}
}
## Shale's `sub(s, first)`: the bytes from place `first` to the end.
rest_from : List(U8), U64 -> List(U8)
rest_from = |bytes, first| Bytes.span(bytes, first, bytes.len())
## 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 bytes without the blanks at their end, as Shale's `trim_end`.
trimmed_end : List(U8) -> List(U8)
trimmed_end = |bytes|
match bytes.find_last_index(|byte| !(is_blank(byte))) {
Ok(end) => bytes.take_first(end + 1)
Err(_) => []
}
## Whether `byte` is one of `[A-Za-z0-9_]`.
is_word_byte : U8 -> Bool
is_word_byte = |byte| Bytes.is_letter(byte) or Bytes.is_digit(byte) or byte == '_'
## Whether `byte` is an ASCII letter, small or capital.
is_letter : U8 -> Bool
is_letter = |byte| (byte >= 'a' and byte <= 'z') or (byte >= 'A' and byte <= 'Z')
## Whether `byte` is a digit.
is_digit : U8 -> Bool
is_digit = |byte| byte >= '0' and byte <= '9'
## Whether `byte` is a small letter or `_`, which starts a lower name.
starts_lower_name : U8 -> Bool
starts_lower_name = |byte| (byte >= 'a' and byte <= 'z') or byte == '_'
## The last byte before `place` that is not a space, or 0.
byte_before : List(U8), U64 -> U8
byte_before = |bytes, place| {
var $at = place - 1
while $at > 0 and Bytes.byte_at(bytes, $at) == ' ' {
$at = $at - 1
}
Bytes.byte_at(bytes, $at)
}
## The first place at `place` or after it that is no space: the end of ` *`.
spaces_end : List(U8), U64 -> U64
spaces_end = |bytes, place| {
var $end = place
while Bytes.byte_at(bytes, $end) == ' ' {
$end = $end + 1
}
$end
}
## The first place at `place` or after it that is no `[A-Za-z0-9_]`.
word_end : List(U8), U64 -> U64
word_end = |bytes, place| {
var $end = place
while Bytes.is_word_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
$end
}
}
## 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'
cookbook/roc/lib/Declarations.roc, 341 lines
## What a file declares at its top level or as a module type's member, read
## from its tree in file order: its types, its values and the record fields of its
## types and annotations, never a local's. Each carries `place`, its node's
## place in the tree, so the three kinds can be put back in file order.
import Text
import Tree
Declarations := {
types : List(Declarations.TypeDeclared),
values : List(Declarations.ValueDeclared),
fields : List(Declarations.FieldDeclared),
}.{
## A type declaration. `underlying` is the type it is built on as written
## and `shape` the same as a shape (Tree.shape), both `""` when it is
## built on none, as a module's `Cat := [].{ ... }` is not; `is_nominal`
## says it is declared with `:=` or `::`, not as an alias with `:`;
## `is_tag_union` and `is_function_type` say what it is built on.
TypeDeclared : {
path : Str,
place : U64,
line : U64,
name : Str,
owner : Str,
underlying : Str,
shape : Str,
is_nominal : Bool,
is_tag_union : Bool,
is_function_type : Bool,
}
## A value: an annotation, or a definition with no annotation before it
## (`annotated` false, its types `""`). `written_type` is its whole type,
## `result_type` what it gives when it is a function, else the same, and
## `first_type` its first argument's type, `""` when it takes none.
## `has_text` says its definition is a string with something in it.
ValueDeclared : {
path : Str,
place : U64,
line : U64,
name : Str,
owner : Str,
annotated : Bool,
is_function : Bool,
has_text : Bool,
written_type : Str,
result_type : Str,
first_type : Str,
}
## A record field in a type or an annotation, with its type as written.
FieldDeclared : {
path : Str,
place : U64,
line : U64,
name : Str,
owner : Str,
written_type : Str,
}
## A parsed file: its path, the file's nodes (its syntax tree, a node a
## place) and its text cut at each newline.
FileRead : {
path : Str,
nodes : List(Tree.Node),
source_lines : List(Str),
}
## Nothing declared, to add files to.
none_yet : Declarations
none_yet = { types: [], values: [], fields: [] }
## What `earlier` holds, then what `later` does.
concat : Declarations, Declarations -> Declarations
concat = |earlier, later| {
types: earlier.types.concat(later.types),
values: earlier.values.concat(later.values),
fields: earlier.fields.concat(later.fields),
}
## What the file declares at its top level or as a module type's member,
## each kind in file order. A definition of an annotated value sets the
## annotation's `has_text`, and the last definition says.
from_file : Declarations.FileRead -> Declarations
from_file = |file| {
nodes = file.nodes
var $outer_answers = []
var $declaration_lines = []
var $annotation_places = Dict.empty()
var $declared = Declarations.none_yet
var $at = 0
for node in nodes {
$at = $at + 1
at = $at
place = { outer_answers: $outer_answers, parent: node.parent }
is_outer = node.parent == 0 or is_outer_parent(nodes, place)
$outer_answers = $outer_answers.append(is_outer)
kind = node.kind
is_declaration = kind == "s-type-anno" or kind == "s-type-decl"
$declaration_lines = $declaration_lines.append(
if is_outer and is_declaration {
node.line
} else {
0
},
)
if is_outer and kind == "s-type-decl" {
match type_declared(file, at) {
Ok(declared) => {
$declared = { ..$declared, types: $declared.types.append(declared) }
}
Err(Unnamed) => {}
}
}
field_place = { declaration_lines: $declaration_lines, at }
if kind == "anno-record-field" and field_declaration_line(nodes, field_place) != 0 {
field = {
path: file.path,
place: at,
line: node.line,
name: Tree.attribute(node, "name"),
owner: owner_of(nodes, at),
written_type: Tree.written_type(nodes, Tree.first_kid(node)),
}
$declared = { ..$declared, fields: $declared.fields.append(field) }
}
if is_outer and kind == "s-type-anno" {
match annotated_value(file, at) {
Ok(value) => {
value_key = "${value.owner}.${value.name}"
value_place = $declared.values.len()
$annotation_places = $annotation_places.insert(value_key, value_place)
$declared = { ..$declared, values: $declared.values.append(value) }
}
Err(OnlyWhere) => {}
}
}
if is_outer and kind == "s-decl" and Tree.kid_kind(nodes, node, 1) == "p-ident" {
name = Tree.attribute(Tree.node_at(nodes, Tree.first_kid(node)), "raw")
owner = owner_of(nodes, at)
values = match $annotation_places.get("${owner}.${name}") {
Ok(annotation_place) => {
definition = { place: annotation_place, has_text: is_text(nodes, node) }
with_text($declared.values, definition)
}
Err(_) => {
value = {
path: file.path,
place: at,
line: node.line,
name,
owner,
annotated: Bool.False,
is_function: Tree.kid_kind(nodes, node, 2) == "e-lambda",
has_text: Bool.False,
written_type: "",
result_type: "",
first_type: "",
}
$declared.values.append(value)
}
}
$declared = { ..$declared, values }
}
}
$declared
}
}
## Whether a node's `parent` lets it be outer: the parent is outer itself, as
## `outer_answers` holds it so far (a parent comes before its kids), and of a
## kind a definition may sit in and still be top-level or a module type's
## member, the type's `associated` block among them. Inside any other kind,
## such as a lambda's block, a definition is local.
is_outer_parent : List(Tree.Node), { outer_answers : List(Bool), parent : U64 } -> Bool
is_outer_parent = |nodes, place| {
parent_is_outer = match place.outer_answers.get(place.parent - 1) {
Ok(answer) => answer
Err(_) => {
parent = place.parent.to_str()
crash "Declarations: node ${parent} comes after its kid"
}
}
kind = Tree.node_at(nodes, place.parent).kind
parent_is_outer and ["file", "statements", "s-type-decl", "associated"].contains(kind)
}
## The name of the type declaration around node `at`, or "" at the top level.
owner_of : List(Tree.Node), U64 -> Str
owner_of = |nodes, at| {
var $up = Tree.node_at(nodes, at).parent
while $up != 0 {
node = Tree.node_at(nodes, $up)
if node.kind == "s-type-decl" {
return Tree.attribute(Tree.node_at(nodes, Tree.first_kid(node)), "name")
}
$up = node.parent
}
""
}
## The line of the declaration the record field at `at` belongs to, as
## `declaration_lines` holds it so far, or 0 when an expression, a pattern or
## a definition lies between them (the field is then a local's), or the
## declaration is not outer.
field_declaration_line : List(Tree.Node), { declaration_lines : List(U64), at : U64 } -> U64
field_declaration_line = |nodes, field_place| {
var $up = Tree.node_at(nodes, field_place.at).parent
while $up != 0 {
node = Tree.node_at(nodes, $up)
if node.kind.starts_with("e-") or node.kind.starts_with("p-") or node.kind == "s-decl" {
return 0
}
if node.kind == "s-type-anno" or node.kind == "s-type-decl" {
return match field_place.declaration_lines.get($up - 1) {
Ok(line) => line
Err(_) => crash "Declarations: a field's declaration comes after it"
}
}
$up = node.parent
}
0
}
## Whether the definition `node` gives a string with something in it: `""`
## spans two columns.
is_text : List(Tree.Node), Tree.Node -> Bool
is_text = |nodes, node|
match node.kids.get(1) {
Ok(at) => {
given = Tree.node_at(nodes, at)
is_wide = given.end_line > given.line or given.end_column > given.column + 2
given.kind == "e-string" and is_wide
}
Err(_) => Bool.False
}
## A definition of an annotated value: the annotation's place among the
## values, and whether the definition is a string with something in it.
Definition : { place : U64, has_text : Bool }
## The values with the annotation at the definition's place given its
## `has_text`.
with_text : List(Declarations.ValueDeclared), Definition -> List(Declarations.ValueDeclared)
with_text = |values, definition| {
past_end = "Declarations: an annotation's place is past the values"
value = match values.get(definition.place) {
Ok(found) => found
Err(OutOfBounds) => crash past_end
}
match values.set(definition.place, { ..value, has_text: definition.has_text }) {
Ok(changed) => changed
Err(OutOfBounds) => crash past_end
}
}
## The annotation at `at`, unless it is only a `where` clause.
annotated_value : Declarations.FileRead, U64 -> Try(Declarations.ValueDeclared, [OnlyWhere])
annotated_value = |file, at| {
nodes = file.nodes
node = Tree.node_at(nodes, at)
match node.kids.first() {
Err(_) => Err(OnlyWhere)
Ok(type_at) => {
type_node = Tree.node_at(nodes, type_at)
if type_node.kind == "where" {
return Err(OnlyWhere)
}
written_type = Tree.written_type(nodes, type_at)
is_function = type_node.kind == "ty-fn"
result_type = if is_function {
Tree.written_type(nodes, Tree.last_kid(type_node))
} else {
written_type
}
first_type = if is_function and type_node.kids.len() > 1 {
Tree.written_type(nodes, Tree.first_kid(type_node))
} else {
""
}
Ok({
path: file.path,
place: at,
line: node.line,
name: Tree.attribute(node, "name"),
owner: owner_of(nodes, at),
annotated: Bool.True,
is_function,
has_text: Bool.False,
written_type,
result_type,
first_type,
})
}
}
}
## The type declared at `at`, when it has a name. Whether it is nominal is
## read from the text just after its name, where `:=` or `::` stands.
type_declared : Declarations.FileRead, U64 -> Try(Declarations.TypeDeclared, [Unnamed])
type_declared = |file, at| {
nodes = file.nodes
node = Tree.node_at(nodes, at)
name_node = Tree.node_at(nodes, Tree.first_kid(node))
name = Tree.attribute(name_node, "name")
if name == "" {
return Err(Unnamed)
}
declared = {
path: file.path,
place: at,
line: node.line,
name,
owner: owner_of(nodes, at),
underlying: "",
shape: "",
is_nominal: Bool.False,
is_tag_union: Bool.False,
is_function_type: Bool.False,
}
match node.kids.get(1) {
Ok(built_at) => {
built_on = Tree.node_at(nodes, built_at)
if built_on.kind == "associated" {
Ok(declared)
} else {
name_line = Text.line_at(file.source_lines, name_node.end_line)
after_name = Text.bytes_of(name_line, { start: name_node.end_column - 1, count: 4 })
Ok({
..declared,
underlying: Tree.written_type(nodes, built_at),
shape: Tree.shape(nodes, built_at),
is_nominal: after_name.contains(":=") or after_name.contains("::"),
is_tag_union: built_on.kind == "ty-tag-union",
is_function_type: built_on.kind == "ty-fn",
})
}
}
Err(_) => Ok(declared)
}
}
cookbook/roc/lib/Finding.roc, 42 lines
## A finding of one of a recipe's checks: the file, the line, the check and
## what is wrong there, ordered as the Shale originals sorted their reports
## and printed as their lines.
import Text
Finding := {
path : Str,
line : U64,
check : Str,
what : Str,
}.{
## By path, then line, then what is said, each path and saying bytewise.
order : Finding, Finding -> [Before, Same, After]
order = |first, second|
match Text.byte_order(first.path, second.path) {
Same =>
if first.line < second.line {
Before
} else if first.line > second.line {
After
} else {
Text.byte_order(first.what, second.what)
}
other => other
}
## The finding as its line: `path:line: check: what`.
line_of : Finding -> Str
line_of = |finding| {
place = "${finding.path}:${finding.line.to_str()}"
"${place}: ${finding.check}: ${finding.what}"
}
## How many of the findings each check made, in the order of `checks`, as
## a summary counts them: `family 2, twin_name 0`.
counts_of : List(Finding), List(Str) -> Str
counts_of = |findings, checks| {
count_of = |check| findings.count_if(|finding| finding.check == check).to_str()
Str.join_with(checks.map(|check| "${check} ${count_of(check)}"), ", ")
}
}
cookbook/roc/lib/Forest.roc, 124 lines
## Every parsed file's tree joined into one list of nodes, as the Shale
## originals of check_how_failure_is_reported and find_functions_and_parameters_that_dont_earn_their_keep join them: each node's
## `parent` and `kids` are places in the joined list, counted from 1, a
## file's root's parent 0, and each node keeps its file's path. Nodes are in source order, each before its kids, so a
## subtree runs from its root to its last descendant, and a node with no line
## of its own takes the next line in the list, across a file's end.
import Tree
Forest := {
nodes : List(Tree.Node),
paths : List(Str),
}.{
## The files' trees joined, in the files' order.
join : List({ path : Str, nodes : List(Tree.Node) }) -> Forest
join = |files| {
var $nodes = []
var $paths = []
for file in files {
offset = $nodes.len()
for file_node in file.nodes {
moved_parent = if file_node.parent > 0 {
file_node.parent + offset
} else {
0
}
moved = { ..file_node, kids: file_node.kids.map(|kid_at| kid_at + offset), parent: moved_parent }
$nodes = $nodes.append(moved)
$paths = $paths.append(file.path)
}
}
{ nodes: $nodes, paths: $paths }
}
## How many nodes there are.
count : Forest -> U64
count = |forest| forest.nodes.len()
## The node at a place.
node : Forest, U64 -> Tree.Node
node = |forest, at| Tree.node_at(forest.nodes, at)
## The path of the file the node at a place is in.
path : Forest, U64 -> Str
path = |forest, at|
match forest.paths.get(at - 1) {
Ok(found) => found
Err(_) => crash "Forest.path: no node ${at.to_str()}"
}
kind : Forest, U64 -> Str
kind = |forest, at| Forest.node(forest, at).kind
kids : Forest, U64 -> List(U64)
kids = |forest, at| Forest.node(forest, at).kids
parent : Forest, U64 -> U64
parent = |forest, at| Forest.node(forest, at).parent
## A node's attribute, `""` where it has none.
attribute : Forest, U64, Str -> Str
attribute = |forest, at, attribute_name| Tree.attribute(Forest.node(forest, at), attribute_name)
name : Forest, U64 -> Str
name = |forest, at| Forest.attribute(forest, at, "name")
raw : Forest, U64 -> Str
raw = |forest, at| Forest.attribute(forest, at, "raw")
## The place of a node's kid, the kids counted from 1, 0 when it has no
## such kid.
kid : Forest, U64, U64 -> U64
kid = |forest, at, number| Forest.kids(forest, at).get(number - 1) ?? 0
## The kind of the node at a place, `""` for place 0, no node.
kind_or_none : Forest, U64 -> Str
kind_or_none = |forest, at|
if at == 0 {
""
} else {
Forest.kind(forest, at)
}
## The last node of the subtree at a place.
last_descendant : Forest, U64 -> U64
last_descendant = |forest, at| {
var $last = at
while !(Forest.kids(forest, $last).is_empty()) {
$last = Forest.kids(forest, $last).last() ?? $last
}
$last
}
## The line a node is reported at: its own, else the next node's that has
## one, 0 when no node after it has one (a finding prints that as `?`).
line_number : Forest, U64 -> U64
line_number = |forest, at| {
var $place = at
while $place <= Forest.count(forest) and Forest.node(forest, $place).line == 0 {
$place = $place + 1
}
if $place <= Forest.count(forest) {
Forest.node(forest, $place).line
} else {
0
}
}
## Each tag of the tag union at a place, as a whole node (`Some(U64)`).
union_tags : Forest, U64 -> List(U64)
union_tags = |forest, at|
Forest.kids(forest, at)
.keep_if(|tags| Forest.kind(forest, tags) == "tags")
.join_map(|tags| Forest.kids(forest, tags))
## The name of a tag node: `Some` for `Some(U64)`.
tag_name : Forest, U64 -> Str
tag_name = |forest, at|
if Forest.kind(forest, at) == "ty-apply" {
Forest.name(forest, Forest.kid(forest, at, 1))
} else {
Forest.name(forest, at)
}
}
cookbook/roc/lib/Groups.roc, 472 lines
## Roc's bracket groups read from a file's lines, for check_and_fix_group_stacking and
## wrap_long_lines_with_trailing_commas (ported from the Shale groups.shale): each pair of
## brackets or a lambda's `|...|`, where it opens and closes, its items counted by the
## commas at its own depth and its tokens. A token is a name (a dotted path
## like `Angle.Bearing` is one), a number, a string or a character;
## punctuation and operators are none. The rule the groups are judged by is
## Stacking's. A place in a line is counted from 1 and in bytes, as Shale's
## `sub` counts, so a line's width is its bytes with a tab counting four.
import Bytes
Groups := [].{
## A group of the lines read: the line and column it opens at, the line
## and column it closes at, its items, its tokens, whether a comment or a
## `\\` string lies inside it (`fixed`), whether its last item ends in a
## comma (`trailing`), how many groups are open around it, the group
## around it and whether it is a function type's arguments, `(A, B -> C)`,
## which can't take a trailing comma.
Group : {
line : U64,
open : U64,
close_line : U64,
close : U64,
items : U64,
tokens : U64,
fixed : Bool,
trailing : Bool,
depth : U64,
parent : Groups.Parent,
fn_type : Bool,
}
## The group around a group: the byte that closes it (0 for none), the
## line it opens on (0 for none) and whether its last item ends in a
## comma, which is known once it closes.
Parent : {
closer : U8,
line : U64,
trailing : Bool,
}
## The byte that closes a group `byte` opens, or 0 when it opens none.
closer_of : U8 -> U8
closer_of = |byte|
if byte == '(' {
')'
} else if byte == '{' {
'}'
} else if byte == '[' {
']'
} else {
0
}
## Whether `byte` closes a pair of brackets.
is_closer : U8 -> Bool
is_closer = |byte| byte == ')' or byte == '}' or byte == ']'
## The groups of `source_lines`, by where they close. A group that never
## closes in them is left out.
groups_in_lines : List(Str) -> List(Groups.Group)
groups_in_lines = |source_lines| {
var $scan = {
open: [],
closed: [],
trailing_by_id: [],
tokens: 0,
fixed: 0,
last_code: 0,
}
$number : U64
var $number = 0
for text in source_lines {
$number = $number + 1
$scan = scanned_line($scan, { bytes: text.to_utf8(), number: $number })
}
trailing_by_id = $scan.trailing_by_id
$scan.closed.map(
|(group, parent_id)|
if parent_id == 0 {
group
} else {
parent = group.parent
{
..group,
parent: {
..parent,
trailing: trailing_by_id.get(parent_id - 1) ?? Bool.False,
},
}
},
)
}
## The groups that open and close on one line.
groups_on_line : Str -> List(Groups.Group)
groups_on_line = |text| Groups.groups_in_lines([text])
}
## A group still open: where it opened, the byte that closes it, its commas
## so far and the place of the last one, whether an arrow stands at its own
## depth, whether it is a `where` clause's brackets, and the running counts
## when it opened.
Opened : {
id : U64,
line : U64,
at : U64,
closer : U8,
commas : U64,
last : U64,
has_arrow : Bool,
is_where : Bool,
tokens_before : U64,
fixed_before : U64,
}
## The scan so far: the groups open (innermost last), those closed with the
## id of the group around each (0 for none), each group's `trailing` by its
## id once it closes, the running counts of tokens and of comments and `\\`
## strings, and the last byte of code seen (0 for none).
Scan : {
open : List(Opened),
closed : List((Groups.Group, U64)),
trailing_by_id : List(Bool),
tokens : U64,
fixed : U64,
last_code : U8,
}
## The scan after one more line.
scanned_line : Scan, { bytes : List(U8), number : U64 } -> Scan
scanned_line = |before, source| {
l = source.bytes
line = source.number
var $scan = before
var $count = l.len()
if Bytes.trimmed(l).starts_with(['\\', '\\']) {
$scan = {
..$scan,
fixed: $scan.fixed + 1,
tokens: $scan.tokens + 1,
last_code: '\\',
}
$count = 0
}
$i : U64
var $i = 1
while $i <= $count {
c = Bytes.byte_at(l, $i)
var $code = c
if c == ' ' {
# A space only separates, and spaces are the most common byte.
$code = ' '
} else if Bytes.is_word_byte(c) {
# A name right after a dot continues a path, as in `f(x).name`.
continues = Bytes.byte_at(
l,
$i - 1,
) == '.' and !($i >= 2 and Bytes.byte_at(l, $i - 2) == '.')
if !(continues) {
$scan = { ..$scan, tokens: $scan.tokens + 1 }
}
$i = path_end(l, $i) - 1
} else if c == '"' or c == '\'' {
$scan = { ..$scan, tokens: $scan.tokens + 1 }
$i = $i + 1
while $i <= $count and Bytes.byte_at(l, $i) != c {
if Bytes.byte_at(l, $i) == '\\' {
$i = $i + 1
}
$i = $i + 1
}
} else if c == '#' {
$scan = { ..$scan, fixed: $scan.fixed + 1 }
$code = ' '
$count = 0
} else if Groups.closer_of(c) != 0 {
is_where = c == '[' and follows_where(l, $i)
$scan = opened(
$scan,
{
line,
at: $i,
closer: Groups.closer_of(c),
is_where,
},
)
} else if (c == '-' or c == '=') and Bytes.byte_at(
l,
$i + 1,
) == '>' and Bytes.byte_at(l, $i - 1) == ' ' and !($scan.open.is_empty()) {
$scan = with_top($scan, |group| { ..group, has_arrow: Bool.True })
$i = $i + 1
} else if c == '|' and Bytes.byte_at(
l,
$i + 1,
) != '>' and Bytes.byte_at(l, $i + 1) != '|' and Bytes.byte_at(l, $i - 1) != '|' {
if top_closer($scan.open) == '|' {
$scan = closed($scan, { bytes: l, line, close: $i })
} else {
# A `|` opens a lambda only where an expression can start.
b = Bytes.byte_before(l, $i)
if b == 0 or b == '=' or b == '(' or b == ',' or b == '[' or b == '{' or b == ':' {
$scan = opened(
$scan,
{
line,
at: $i,
closer: '|',
is_where: Bool.False,
},
)
}
}
} else if Groups.is_closer(c) {
# Pop down to the group this byte closes. A `|` that turned out to
# be no lambda is dropped on the way.
var $open = $scan.open
while !($open.is_empty()) and top_closer($open) != c {
$open = $open.drop_last(1)
}
$scan = { ..$scan, open: $open }
if !($open.is_empty()) {
$scan = closed($scan, { bytes: l, line, close: $i })
}
} else if c == ',' and !($scan.open.is_empty()) {
rest = Bytes.rest_from(l, $i + 1)
in_where = match $scan.open.last() {
Ok(group) => group.is_where
Err(_) => Bool.False
}
# In a `where` clause's brackets, only a comma before a method
# constraint, or at its line's end, separates items.
if !(in_where) or Bytes.trimmed(rest).is_empty() or starts_constraint(rest) {
comma_at = $i
$scan = with_top($scan, |group| with_comma(group, comma_at))
}
}
if $code != ' ' and $code != '\t' {
$scan = { ..$scan, last_code: $code }
}
$i = $i + 1
}
$scan
}
## The byte that closes the innermost of the open groups, or 0 for none.
top_closer : List(Opened) -> U8
top_closer = |open|
match open.last() {
Ok(group) => group.closer
Err(_) => 0
}
## An open group with one more comma, the last at `place`.
with_comma : Opened, U64 -> Opened
with_comma = |group, place| {
..group,
commas: group.commas + 1,
last: place,
}
## The scan with a group opened.
opened : Scan,
{
line : U64,
at : U64,
closer : U8,
is_where : Bool,
} -> Scan
opened = |scan, place| {
id = scan.trailing_by_id.len() + 1
group = {
id,
line: place.line,
at: place.at,
closer: place.closer,
commas: 0,
last: place.at,
has_arrow: Bool.False,
is_where: place.is_where,
tokens_before: scan.tokens,
fixed_before: scan.fixed,
}
{
..scan,
open: scan.open.append(group),
trailing_by_id: scan.trailing_by_id.append(Bool.False),
}
}
## The scan with its innermost open group changed.
with_top : Scan, (Opened -> Opened) -> Scan
with_top = |scan, change|
match scan.open.last() {
Ok(group) => {
..scan,
open: scan.open.set(
scan.open.len() - 1,
change(group),
) ?? crash "Groups: no open group to change",
}
Err(_) => scan
}
## The scan with its innermost open group closed at column `close` of line
## `line`: its items counted from the commas at its own depth, a last item
## that is a rest pattern (`{ a, b, .. }`, `[x, .. as more]`) not counted.
closed : Scan,
{
bytes : List(U8),
line : U64,
close : U64,
} -> Scan
closed = |scan, at|
match scan.open.last() {
Err(_) => scan
Ok(g) => {
l = at.bytes
trailing = scan.last_code == ','
var $items = if trailing {
g.commas
} else {
g.commas + 1
}
if g.line == at.line {
if Bytes.trimmed(Bytes.span(l, g.at + 1, at.close - 1)).is_empty() {
$items = 0
}
last = Bytes.trimmed(Bytes.span(l, g.last + 1, at.close - 1))
if !(trailing) and g.commas > 0 and (
last == [
'.',
'.',
] or last.starts_with(".. as ".to_utf8())
) {
$items = $items - 1
}
}
depth = scan.open.len() - 1
around = if depth > 0 {
scan.open.get(depth - 1)
} else {
Err(OutOfBounds)
}
(parent, parent_id) = match around {
Ok(outer) => (
{
closer: outer.closer,
line: outer.line,
trailing: Bool.False,
},
outer.id,
)
Err(_) => (
{
closer: 0,
line: 0,
trailing: Bool.False,
},
0,
)
}
group = {
line: g.line,
open: g.at,
close_line: at.line,
close: at.close,
items: $items,
tokens: scan.tokens - g.tokens_before,
fixed: scan.fixed > g.fixed_before,
trailing,
depth,
parent,
fn_type: g.has_arrow and g.closer == ')',
}
{
..scan,
open: scan.open.drop_last(1),
closed: scan.closed.append((group, parent_id)),
trailing_by_id: scan.trailing_by_id.set(
g.id - 1,
trailing,
) ?? crash "Groups: a group with no id",
}
}
}
## Where a name or a dotted path that starts at `place` ends, one past its last byte:
## `[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*`.
path_end : List(U8), U64 -> U64
path_end = |bytes, place| {
var $end = place
while Bytes.is_word_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
while Bytes.byte_at(bytes, $end) == '.' and Bytes.is_word_byte(Bytes.byte_at(bytes, $end + 1)) {
$end = $end + 1
while Bytes.is_word_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
}
$end
}
## Whether the code before column `place` ends in the keyword `where`, so
## that a `[` there opens a `where` clause.
follows_where : List(U8), U64 -> Bool
follows_where = |bytes, place| {
var $j = place - 1
while $j > 0 and (Bytes.byte_at(bytes, $j) == ' ' or Bytes.byte_at(bytes, $j) == '\t') {
$j = $j - 1
}
if $j < 5 or Bytes.span(bytes, $j - 4, $j) != "where".to_utf8() {
Bool.False
} else if $j == 5 {
Bool.True
} else {
b = Bytes.byte_at(bytes, $j - 5)
b == ' ' or (b == '\t' and Bytes.trimmed(Bytes.span(bytes, 1, $j - 5)).is_empty())
}
}
## Whether the bytes start a method constraint, `k.is_eq :`:
## `^ *[a-z_][A-Za-z0-9_]*\.[a-z_][A-Za-z0-9_]*!? *:`. In a `where` clause's
## brackets, only a comma followed by one, or ending its line, separates
## items.
starts_constraint : List(U8) -> Bool
starts_constraint = |bytes| {
var $at = 1
while Bytes.byte_at(bytes, $at) == ' ' {
$at = $at + 1
}
match name_end(bytes, $at) {
Err(_) => Bool.False
Ok(after_type) =>
if Bytes.byte_at(bytes, after_type) != '.' {
Bool.False
} else {
match name_end(bytes, after_type + 1) {
Err(_) => Bool.False
Ok(after_method) => {
var $end = after_method
if Bytes.byte_at(bytes, $end) == '!' {
$end = $end + 1
}
while Bytes.byte_at(bytes, $end) == ' ' {
$end = $end + 1
}
Bytes.byte_at(bytes, $end) == ':'
}
}
}
}
}
## Where a lower name `[a-z_][A-Za-z0-9_]*` that starts at `place` ends, one
## past its last byte.
name_end : List(U8), U64 -> Try(U64, [NoName])
name_end = |bytes, place| {
first = Bytes.byte_at(bytes, place)
if (first >= 'a' and first <= 'z') or first == '_' {
var $end = place + 1
while Bytes.is_word_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
Ok($end)
} else {
Err(NoName)
}
}
cookbook/roc/lib/Headers.roc, 130 lines
## What a Roc file's header says about who chooses its names: a name an app's platform asks for, a
## hook a platform hands its host and a method Roc calls by name were chosen
## somewhere else, so the recipes judge them differently from the names a
## program picks for itself; and which modules a package keeps to itself.
import Bytes
import Text
import Tree
Headers := [].{
## The methods Roc calls by name, from Roc's docs/langref/static-dispatch.md
## and operators.md, with the encoders' `encode` and `decode`: a module
## that declares one has it because Roc asks, not as a name of its own.
language_fixed_names : Set(Str)
language_fixed_names = Set.from_list([
"to_inspect",
"is_eq",
"to_hash",
"plus",
"minus",
"times",
"div_by",
"div_trunc_by",
"rem_by",
"is_lt",
"is_lte",
"is_gt",
"is_gte",
"range_exclusive_to",
"range_inclusive_to",
"range_exclusive_from",
"range_inclusive_from",
"range_iter",
"range_len_if_known",
"negate",
"not",
"from_numeral",
"from_quote",
"from_interpolation",
"iter",
"next",
"parser_for",
"encoder_for",
"map",
"map!",
"subscript",
"encode",
"decode",
])
## What a folder's `main.roc` exposes, from the file's text (reading the
## file is the recipe's): `is_package` when its header is `package` or `platform`, and
## the modules it exposes.
exposed_by : Str -> { is_package : Bool, modules : List(Str) }
exposed_by = |text| {
code = code_of(text)
word = Headers.header_word(code)
if word == "package" {
{ is_package: Bool.True, modules: bracketed_names(code) }
} else if word == "platform" {
listed = Text.between(code, "exposes", "]") ?? ""
{ is_package: Bool.True, modules: bracketed_names("${listed}]") }
} else {
{ is_package: Bool.False, modules: [] }
}
}
## The first word of a file's code, its comment lines left out: `app`,
## `package`, `platform`, `module`, `hosted`, or for a type module the
## type's name; `""` when it has none.
header_word : Str -> Str
header_word = |text| {
bytes = code_of(text).to_utf8()
is_word = |byte| Bytes.is_letter(byte) or byte == '_'
match bytes.find_first_index(is_word) {
Ok(start) => {
after = bytes.drop_first(start)
length = after.find_first_index(|byte| !(is_word(byte))) ?? after.len()
Str.from_utf8_lossy(after.take_first(length))
}
Err(_) => ""
}
}
## The value names a file's tree's header speaks for, in the tree's order:
## `dictated`, what an app provides,
## what a platform requires of its app and what it provides to its host;
## `exposed`, what a `module` or `hosted` header exposes.
header_names : List(Tree.Node) -> { dictated : List(Str), exposed : List(Str) }
header_names = |nodes| {
var $dictated = []
var $exposed = []
var $place = 2
while $place <= nodes.len() and Tree.node_at(nodes, $place).kind != "statements" {
node = Tree.node_at(nodes, $place)
if node.kind == "entrypoint" {
$dictated = $dictated.append(Tree.attribute(node, "value"))
}
if node.kind == "symbol-map-entry" {
$dictated = $dictated.append(Tree.attribute(node, "func"))
}
if node.kind == "text" and node.parent > 0 {
parent = Tree.node_at(nodes, node.parent)
match Tree.find_attribute(node, "value") {
Ok(value) if parent.kind == "exposed-lower-ident" =>
if parent.parent > 0 and Tree.node_at(
nodes,
parent.parent,
).kind == "provides" {
$dictated = $dictated.append(value)
} else {
$exposed = $exposed.append(value)
}
_ => {}
}
}
$place = $place + 1
}
{ dictated: $dictated, exposed: $exposed }
}
}
## A file's text with its comment lines left out.
code_of : Str -> Str
code_of = |text| Str.join_with(Text.lines(text).drop_if(|line| Text.trim(line).starts_with("#")), "\n")
## The names in the list between the first `[` and the next `]` of `text`.
bracketed_names : Str -> List(Str)
bracketed_names = |text|
(Text.between(text, "[", "]") ?? "").split_on(",").map(Text.trim).keep_if(|name| name != "")
cookbook/roc/lib/Imports.roc, 209 lines
## A Roc file's imports, read from Roc's own tree of it, and the ones the file
## never uses: find_unused_imports' rule, `unused_import`, in its one home
## (cookbook/roc/find_unused_imports.shale's header says what counts as a
## use). rewrite_module_calls_as_method_calls asks it too, of a file before and after its
## rewrite, to name each import the rewrite left unused.
import Tree
Imports := [].{
## An import line no name of the file uses: its line and how a finding
## names it.
UnusedImport : { line : U64, label : Str }
## Each import of the file whose names it never uses, from its tree and
## its source lines, which hold the qualifier of a pattern's tag that the
## tree drops.
unused_imports : List(Tree.Node), List(Str) -> List(Imports.UnusedImport)
unused_imports = |nodes, source_lines| {
used = heads_used(nodes, source_lines)
imports_of(nodes)
.drop_if(|line_import| line_import.names.any(|name| used.contains(name)))
.map(|line_import| { line: line_import.line, label: line_import.label })
}
}
## An import line: its line, how a finding names it, and the names a use of
## it may start with.
Import : {
line : U64,
label : Str,
names : List(Str),
}
## The kids of a node, as nodes.
kid_nodes : List(Tree.Node), Tree.Node -> List(Tree.Node)
kid_nodes = |nodes, node|
node.kids.map(|at| Tree.node_at(nodes, at))
# โโ The imports
## Each import of the file, in order: `import pkg.Mod`, its alias and what it
## exposes, and each file import, `import "page.html" as page : Str`.
imports_of : List(Tree.Node) -> List(Import)
imports_of = |nodes|
nodes.join_map(
|node|
if node.kind == "s-import" {
[module_import(nodes, node)]
} else if node.kind == "s-file-import" {
file_imports(nodes, node)
} else {
[]
},
)
## A module's import. Its name is the alias of `import pkg.Mod as M`, else
## the last part of the module's path; a name it exposes is one too.
module_import : List(Tree.Node), Tree.Node -> Import
module_import = |nodes, node| {
path = Tree.attribute(node, "raw")
alias = Tree.attribute(node, "alias")
name = if alias == "" {
path.split_on(".").last() ?? path
} else {
alias
}
label = if alias == "" {
"`${path}`"
} else {
"`${path}` as `${alias}`"
}
exposing_lists = kid_nodes(nodes, node).keep_if(|kid| kid.kind == "exposing")
exposed = exposing_lists.join_map(|list| exposed_names(nodes, list))
{
line: node.line,
label,
names: exposed.prepend(name),
}
}
## The names an `exposing [...]` list names: a type's `text`, and each
## value's name, held by the value's own kids.
exposed_names : List(Tree.Node), Tree.Node -> List(Str)
exposed_names = |nodes, list|
kid_nodes(nodes, list).join_map(
|entry|
if entry.kind == "exposed-upper-ident" {
[Tree.attribute(entry, "text")]
} else if entry.kind == "exposed-lower-ident" {
kid_nodes(nodes, entry).map(|name| Tree.attribute(name, "value"))
} else {
[]
},
)
## A file import's name, used when the file refers to it.
file_imports : List(Tree.Node), Tree.Node -> List(Import)
file_imports = |nodes, node|
kid_nodes(nodes, node)
.keep_if(|kid| kid.kind == "name")
.map(
|kid| {
name = Tree.attribute(kid, "value")
{
line: node.line,
label: "the file import `${name}`",
names: [name],
}
},
)
# โโ The uses
## The first part of every value, tag and type name the file uses. A bare
## tag (`Other`, in an expression, a pattern or a tag union type) names no
## module, so only a qualified one counts, or one that is a nominal type's
## name (`Point.{ x: 0 }`). A platform header's `hosted { "sym": Host.f! }`
## entry uses its module.
heads_used : List(Tree.Node), List(Str) -> Set(Str)
heads_used = |nodes, source_lines| {
union_tags = kids_of_kind(nodes, "tags")
nominal_names = kids_of_kind(nodes, "mapper")
names = nodes.map_with_index(
|node, index| {
at = index + 1
if node.kind == "e-ident" {
Tree.attribute(node, "raw")
} else if node.kind == "e-tag" {
tag_use(node, nominal_names.contains(at))
} else if node.kind == "ty" and !(union_tags.contains(at)) {
Tree.attribute(node, "name")
} else if node.kind == "symbol-map-entry" {
Tree.attribute(node, "module")
} else if node.kind == "p-tag" {
pattern_tag_use(node, source_lines)
} else {
""
}
},
)
Set.from_list(names.drop_if(Str.is_empty).map(head_of))
}
## An expression's tag, when it names a module: qualified, or a nominal
## type's name.
tag_use : Tree.Node, Bool -> Str
tag_use = |node, names_nominal| {
raw = Tree.attribute(node, "raw")
if raw.contains(".") or names_nominal {
raw
} else {
""
}
}
## A pattern's tag, when it is qualified. roc-ast drops a pattern tag's
## qualifier (`Color.Red =>` comes as `.Red`), so the tag is read from the
## source at the pattern's column.
pattern_tag_use : Tree.Node, List(Str) -> Str
pattern_tag_use = |node, source_lines| {
raw = Tree.attribute(node, "raw")
written = if raw.starts_with(".") {
source_line = match source_lines.get(node.line - 1) {
Ok(text) => text
Err(_) => crash "find_unused_imports: a pattern's tag past the file's end"
}
written_name(source_line.to_utf8().drop_first(node.column - 1))
} else {
raw
}
if written.contains(".") {
written
} else {
""
}
}
## The dotted name the bytes start with: a letter or `_`, then letters,
## digits, `_` and `.`; `""` when they start with none.
written_name : List(U8) -> Str
written_name = |bytes|
match bytes.first() {
Ok(first) if is_letter(first) or first == '_' => {
length = bytes.find_first_index(|byte| !(is_name_byte(byte))) ?? bytes.len()
match Str.from_utf8(bytes.take_first(length)) {
Ok(name) => name
Err(_) => crash "find_unused_imports: a name of ASCII bytes is UTF-8"
}
}
_ => ""
}
is_letter : U8 -> Bool
is_letter = |byte|
(byte >= 'a' and byte <= 'z') or (byte >= 'A' and byte <= 'Z')
is_name_byte : U8 -> Bool
is_name_byte = |byte|
is_letter(byte) or (byte >= '0' and byte <= '9') or byte == '_' or byte == '.'
## The first part of a dotted name: `Mod` of `Mod.Type.name`.
head_of : Str -> Str
head_of = |name|
name.split_on(".").first() ?? name
## The places of the nodes that are kids of a node of the kind.
kids_of_kind : List(Tree.Node), Str -> Set(U64)
kids_of_kind = |nodes, kind|
Set.from_list(nodes.keep_if(|node| node.kind == kind).join_map(|node| node.kids))
cookbook/roc/lib/Packed.roc, 277 lines
## The groups that stay packed whatever the stacking rule says, as the Shale
## groups.shale read them: a row of literals, read at a glance,
## and numeric data, such as a polygon's points. A number is a literal or a
## negative written `(0.0 - 0.5)`; a flat number record is a record of
## numbers, `{ x: 0.5, y: (0.0 - 0.25) }`; and a number list is a list of two
## or more numbers or flat number records. The original's regular
## expressions are matched here by hand, a byte at a time, as a backtracker
## would match them.
import Bytes
import Groups
Packed := [].{
## Whether a group on its line is a row of literals, read at a glance: a list,
## or a tuple (a `(` not right after a name, `)` or `!`, so not a call's
## arguments), whose items are all numbers, strings with nothing interpolated,
## characters or bare tags, on a line within `width`.
is_literal_row : { bytes : List(U8), group : Groups.Group }, U64 -> Bool
is_literal_row = |at, width| {
bytes = at.bytes
group = at.group
if bytes.len() > width or Bytes.width_of(bytes) > width {
return Bool.False
}
opening = Bytes.byte_at(bytes, group.open)
if opening == '(' {
b = Bytes.byte_before(bytes, group.open)
if group.open > 1 and Bytes.byte_at(
bytes,
group.open - 1,
) != ' ' and (Bytes.is_word_byte(b) or b == ')' or b == '!') {
return Bool.False
}
} else if opening != '[' {
return Bool.False
}
inside = Bytes.trimmed(Bytes.span(bytes, group.open + 1, group.close - 1))
pieces_of(inside, ',').all(
|piece| {
item = Bytes.trimmed(piece)
item.is_empty() or is_literal_item(item)
},
)
}
## Whether the bytes hold a number list.
holds_number_list : List(U8) -> Bool
holds_number_list = |bytes| {
zeroed = numbers_as_zero(bytes)
var $at = 1
while $at <= zeroed.len() {
if Bytes.byte_at(zeroed, $at) == '[' and number_list_end(zeroed, $at) != Err(NoMatch) {
return Bool.True
}
$at = $at + 1
}
Bool.False
}
## Whether a group on its line is numeric data: a number list, or a flat
## number record on a line that holds a number list, as a point among a
## polygon's points is.
is_number_data : List(U8), Groups.Group -> Bool
is_number_data = |bytes, group| {
text = numbers_as_zero(Bytes.span(bytes, group.open, group.close))
if number_list_end(text, 1) == Ok(text.len() + 1) {
Bool.True
} else {
text == ['0'] and Packed.holds_number_list(bytes)
}
}
}
## The bytes split at each `separator`, as Shale's `split`: an empty text is
## one empty piece.
pieces_of : List(U8), U8 -> List(List(U8))
pieces_of = |bytes, separator| {
var $pieces = []
var $piece = []
for byte in bytes {
if byte == separator {
$pieces = $pieces.append($piece)
$piece = []
} else {
$piece = $piece.append(byte)
}
}
$pieces.append($piece)
}
## Whether an item is a literal: `-?[0-9][0-9A-Za-z_.]*`, `"[^"\\$]*"`,
## `'[^']+'` or a bare tag `[A-Z][A-Za-z0-9]*`.
is_literal_item : List(U8) -> Bool
is_literal_item = |item| {
count = item.len()
first = Bytes.byte_at(item, 1)
last = Bytes.byte_at(item, count)
middle = Bytes.span(item, 2, count - 1)
if number_end(item, 1) == Ok(count + 1) {
Bool.True
} else if first == '"' {
is_kept_out = |byte| byte == '"' or byte == '\\' or byte == '$'
count >= 2 and last == '"' and !(middle.any(is_kept_out))
} else if first == '\'' {
count >= 3 and last == '\'' and !(middle.contains('\''))
} else {
is_tag_byte = |byte| Bytes.is_letter(byte) or Bytes.is_digit(byte)
first >= 'A' and first <= 'Z' and item.drop_first(1).all(is_tag_byte)
}
}
## Whether a byte may follow a number's first digit: `[0-9A-Za-z_.]`.
is_number_byte : U8 -> Bool
is_number_byte = |byte| Bytes.is_word_byte(byte) or byte == '.'
## Where a number `-?[0-9][0-9A-Za-z_.]*` at `place` ends, one past it.
number_end : List(U8), U64 -> Try(U64, [NoMatch])
number_end = |bytes, place| {
start = if Bytes.byte_at(bytes, place) == '-' {
place + 1
} else {
place
}
unsigned_end(bytes, start)
}
## Where a number with no sign, `[0-9][0-9A-Za-z_.]*`, at `place` ends.
unsigned_end : List(U8), U64 -> Try(U64, [NoMatch])
unsigned_end = |bytes, place|
if Bytes.is_digit(Bytes.byte_at(bytes, place)) {
var $end = place + 1
while is_number_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
Ok($end)
} else {
Err(NoMatch)
}
## Where a negative written `(0.0 - 0.5)` at `place` ends:
## `\(-?[0-9][0-9A-Za-z_.]* - [0-9][0-9A-Za-z_.]*\)`.
negative_end : List(U8), U64 -> Try(U64, [NoMatch])
negative_end = |bytes, place| {
if Bytes.byte_at(bytes, place) != '(' {
return Err(NoMatch)
}
first = number_end(bytes, place + 1)?
if Bytes.span(bytes, first, first + 2) != [' ', '-', ' '] {
return Err(NoMatch)
}
second = unsigned_end(bytes, first + 3)?
if Bytes.byte_at(bytes, second) == ')' {
Ok(second + 1)
} else {
Err(NoMatch)
}
}
## Where a field and its number, `[a-z_][A-Za-z0-9_]*: *-?[0-9]...`, at
## `place` end.
number_field_end : List(U8), U64 -> Try(U64, [NoMatch])
number_field_end = |bytes, place| {
first = Bytes.byte_at(bytes, place)
if !(Bytes.starts_lower_name(first)) {
return Err(NoMatch)
}
end = Bytes.word_end(bytes, place + 1)
if Bytes.byte_at(bytes, end) != ':' {
return Err(NoMatch)
}
number_end(bytes, Bytes.spaces_end(bytes, end + 1))
}
## The items a list of numbers or a record of them holds.
ItemKind : [Number, NumberField]
## Where a run of ` *, *` and an item of the kind given, from place `from`,
## ends.
next_item_end : List(U8), { from : U64, kind : ItemKind } -> Try(U64, [NoMatch])
next_item_end = |bytes, at| {
comma = Bytes.spaces_end(bytes, at.from)
if Bytes.byte_at(bytes, comma) != ',' {
return Err(NoMatch)
}
item_start = Bytes.spaces_end(bytes, comma + 1)
match at.kind {
Number => number_end(bytes, item_start)
NumberField => number_field_end(bytes, item_start)
}
}
## Where a group's end, ` *,? *` and its closing bracket, from place `from`,
## ends.
group_close_end : List(U8), { from : U64, closer : U8 } -> Try(U64, [NoMatch])
group_close_end = |bytes, at| {
var $end = Bytes.spaces_end(bytes, at.from)
if Bytes.byte_at(bytes, $end) == ',' {
$end = Bytes.spaces_end(bytes, $end + 1)
}
if Bytes.byte_at(bytes, $end) == at.closer {
Ok($end + 1)
} else {
Err(NoMatch)
}
}
## Where a flat number record, `{ x: 0.5, y: 0 }`, at `place` ends.
number_record_end : List(U8), U64 -> Try(U64, [NoMatch])
number_record_end = |bytes, place| {
if Bytes.byte_at(bytes, place) != '{' {
return Err(NoMatch)
}
var $end = number_field_end(bytes, Bytes.spaces_end(bytes, place + 1))?
var $more = Bool.True
while $more {
match next_item_end(bytes, { from: $end, kind: NumberField }) {
Ok(end) => {
$end = end
}
Err(_) => {
$more = Bool.False
}
}
}
group_close_end(bytes, { from: $end, closer: '}' })
}
## Where a number list, `[` two or more numbers `]`, at `place` ends.
number_list_end : List(U8), U64 -> Try(U64, [NoMatch])
number_list_end = |bytes, place| {
if Bytes.byte_at(bytes, place) != '[' {
return Err(NoMatch)
}
first = number_end(bytes, Bytes.spaces_end(bytes, place + 1))?
var $end = next_item_end(bytes, { from: first, kind: Number })?
var $more = Bool.True
while $more {
match next_item_end(bytes, { from: $end, kind: Number }) {
Ok(end) => {
$end = end
}
Err(_) => {
$more = Bool.False
}
}
}
group_close_end(bytes, { from: $end, closer: ']' })
}
## The bytes with each match of `pattern_end` replaced by `0`, leftmost
## first, as Shale's `re_replace` replaces.
with_matches_zeroed : List(U8), (List(U8), U64 -> Try(U64, [NoMatch])) -> List(U8)
with_matches_zeroed = |bytes, pattern_end| {
var $out = []
var $at = 1
while $at <= bytes.len() {
match pattern_end(bytes, $at) {
Ok(end) => {
$out = $out.append('0')
$at = end
}
Err(_) => {
$out = $out.append(Bytes.byte_at(bytes, $at))
$at = $at + 1
}
}
}
$out
}
## The bytes with each negative number and each flat number record read as
## the number 0, so that a list of them reads as a list of numbers.
numbers_as_zero : List(U8) -> List(U8)
numbers_as_zero = |bytes| with_matches_zeroed(
with_matches_zeroed(bytes, negative_end),
number_record_end,
)
cookbook/roc/lib/RocTypes.roc, 355 lines
## roc-types' output read: the type Roc's own checker gives each expression
## and pattern of an app's modules, by region, in version 1 of the format
## (https://github.com/showell/roc-types, its FORMAT.md), refusals worded as
## the Shale libraries worded them; the types of several apps joined, and a
## node's type found; and the paths of the Roc and the roc-types a pin names.
## Running roc-types, and holding its pin to the tree's Roc, are effects, so
## they stay in the recipe that asks: a small Types.roc in each of
## check_how_failure_is_reported, find_awkward_names and find_functions_and_parameters_that_dont_earn_their_keep, the same file in all three.
import Text
import Tree
RocTypes := [].{
## A type record of a module: `kind` is `expr` or `pat`, `tag` the
## checker's name for the node, `span` its region as
## `line:col:end_line:end_col` (RocTypes.span_of), and `written` the type
## as the checker writes it, its escapes undone.
Record : {
kind : Str,
tag : Str,
span : Str,
written : Str,
}
## The modules of an output: each module's real, absolute path in the
## checker's order, its records in the checker's pre-order (where nodes
## share a region, the outermost first), and the lines printed before the
## first module.
Modules : {
paths : List(Str),
records : Dict(Str, List(RocTypes.Record)),
warnings : List(Str),
}
## How to install roc-types, for the refusals that find it missing or
## another version.
install_hint : Str
install_hint = "`shale install.shale` in a checkout of https://github.com/showell/roc-types installs it"
## The pin of the Roc roc-types was built from, out of the output's first
## line, `roc-types 1 <pin>`, or why that line is not one. `root` is the
## app the output is of, named in the refusal.
pin_of : List(Str), Str -> Try(Str, Str)
pin_of = |output_lines, root| {
head = output_lines.first() ?? ""
said = Text.words(head)
if !(head.starts_with("roc-types ")) {
Err("`roc_types`: no `roc-types ${format}` header (${root}, the first line `${head}`): an older roc-types, or not roc-types; ${RocTypes.install_hint}")
} else if said.len() < 2 or (said.get(1) ?? "") != format {
Err("`roc_types`: roc-types' header is `${head}`, not format ${format}'s, the one this reads; ${RocTypes.install_hint}")
} else if said.len() != 3 {
Err("`roc_types`: a header that is not `roc-types <N> <pin>`: ${head}")
} else {
Ok(said.get(2) ?? "")
}
}
## What roc-types said when it failed: its lines after the header, the
## first 60 of them and a count of the rest.
said_on_failure : List(Str) -> Str
said_on_failure = |output_lines| {
after_head = output_lines.drop_first(1)
shown = after_head.take_first(60)
left = after_head.len() - shown.len()
if left > 0 {
Str.join_with(shown.append("(${left.to_str()} lines more)"), "\n")
} else {
Str.join_with(shown, "\n")
}
}
## The modules of an output whose header was read, or why a line after it
## is not of the format.
modules_of : List(Str) -> Try(RocTypes.Modules, Str)
modules_of = |output_lines| {
var $paths = []
var $warnings = []
var $records = Dict.empty()
var $current = []
var $path = ""
$number : U64
var $number = 1
for output_line in output_lines.drop_first(1) {
$number = $number + 1
if output_line.starts_with("== ") {
if $path != "" {
$records = $records.insert($path, $current)
}
$current = []
$path = output_line.drop_prefix("== ")
at = "line ${$number.to_str()}"
if !($path.starts_with("/")) {
return Err("`roc_types`: ${at}, a module path that is not absolute: ${$path}")
}
if $records.contains($path) {
return Err("`roc_types`: ${at}, module ${$path} twice")
}
$records = $records.insert($path, [])
$paths = $paths.append($path)
} else if $path == "" {
$warnings = $warnings.append(output_line)
} else if output_line.starts_with("t\t") {
$current = $current.append(record_of(output_line, $number)?)
} else {
return Err("`roc_types`: line ${$number.to_str()} is no record of roc-types' format: ${output_line}")
}
}
if $path != "" {
$records = $records.insert($path, $current)
}
Ok({ paths: $paths, records: $records, warnings: $warnings })
}
## A region as the records' `span` writes it, `line:col:end_line:end_col`,
## for finding a node's type by the node's own region.
span_of : { line : U64, column : U64, end_line : U64, end_column : U64 } -> Str
span_of = |region| {
starts = "${region.line.to_str()}:${region.column.to_str()}"
"${starts}:${region.end_line.to_str()}:${region.end_column.to_str()}"
}
## The app paths of a recipe's `root=`, which may name several
## (`root=a.roc,b.roc`), or why it names none. `who` names the recipe.
root_apps : Str, Str -> Try(List(Str), Str)
root_apps = |who, root| {
apps = root.split_on(",").map(Text.trim).keep_if(|named| named != "")
if apps.is_empty() {
Err("${who}: types=1 needs root=, an app (or several, `root=a.roc,b.roc`) importing the files of the glob: roc-types reads an app, and a type module only through one")
} else {
Ok(apps)
}
}
## The modules of an output whose pin was read, from a run of roc-types
## on the app `root` that ended with `code`, or why they can't be had:
## roc-types failed, or a line is not of the format.
modules_ran : List(Str), I64, Str -> Try(RocTypes.Modules, Str)
modules_ran = |output_lines, code, root|
if code == 0 {
modules_of(output_lines)
} else {
ended = if code < 0 {
"did not exit"
} else {
"exited ${code.to_str()}"
}
Err("`roc_types`: roc-types ${root} ${ended}, what it said:\n${said_on_failure(output_lines)}")
}
## The refusal of a roc-types built from Roc `pin`, run on the app `root`
## of a tree built with the Roc at `roc`.
another_compiler : Str, Str, Str -> Str
another_compiler = |pin, root, roc| {
another = "its types would be another compiler's. Install the roc-types of the tree's pin (https://github.com/showell/roc-types), or move the tree to ${pin}"
"`roc_types`: roc-types reads Roc ${pin}, and ${root}'s tree is built with ${roc}: ${another}"
}
## The types a run keeps: each file's real path, by the path the run
## names it by, for the files some app reached; and the checker's type of
## each node of the kind asked for, by its module's real path, then by its
## region (RocTypes.span_of).
Typing : {
real : Dict(Str, Str),
by_module : Dict(Str, Dict(Str, Str)),
}
## The nodes whose types a run keeps: the expressions (check_how_failure_is_reported'), or
## the patterns, whose type is a definition's or a parameter's.
Kind : [Expressions, Patterns]
## No types, for a run without them.
no_types : RocTypes.Typing
no_types = { real: Dict.empty(), by_module: Dict.empty() }
## The types of an app's modules added to those of the apps before it: a
## module an earlier app reached keeps that app's types, and where nodes
## share a region, the outermost's type is kept.
joined : Dict(Str, Dict(Str, Str)), RocTypes.Modules, RocTypes.Kind -> Dict(Str, Dict(Str, Str))
joined = |by_module, modules, kind| {
wanted = match kind {
Expressions => "expr"
Patterns => "pat"
}
var $by_module = by_module
for path in modules.paths {
if !($by_module.contains(path)) {
var $by_span = Dict.empty()
for record in modules.records.get(path) ?? [] {
if record.kind == wanted and !($by_span.contains(record.span)) {
$by_span = $by_span.insert(record.span, record.written)
}
}
$by_module = $by_module.insert(path, $by_span)
}
}
$by_module
}
## The typing of the files a run names, each with its real path, from the
## types the apps `roots` reached; and a line for each file no app
## reached, except those in `exempt`.
typing_of : { by_module : Dict(Str, Dict(Str, Str)), named : List({ path : Str, real : Str }), exempt : Set(Str), roots : List(Str) } -> { typing : RocTypes.Typing, unreached : List(Str) }
typing_of = |gathered| {
var $real = Dict.empty()
var $unreached = []
for file in gathered.named {
if gathered.by_module.contains(file.real) {
$real = $real.insert(file.path, file.real)
} else if !(gathered.exempt.contains(file.path)) {
$unreached = $unreached.append("not reached by ${Str.join_with(gathered.roots, ",")}: ${file.path}")
}
}
{ typing: { real: $real, by_module: gathered.by_module }, unreached: $unreached }
}
## The checker's type of the node `node` of the file the run names
## `path`, when an app reached the file and the checker typed that
## region.
type_at : RocTypes.Typing, Str, Tree.Node -> Try(Str, [NoType])
type_at = |typing, path, node| {
span = span_of({ line: node.line, column: node.column, end_line: node.end_line, end_column: node.end_column })
match typing.real.get(path) {
Ok(real) => {
by_span = typing.by_module.get(real) ?? Dict.empty()
match by_span.get(span) {
Ok(written) => Ok(written)
Err(_) => Err(NoType)
}
}
Err(_) => Err(NoType)
}
}
## The pin every recipe's self-test runs, out of the text of
## cookbook/roc/pinned.shale, its `SELF_TEST_PIN` and the one home of it.
self_test_pin : Str -> Try(Str, [NoPin])
self_test_pin = |pinned| {
for after in pinned.split_on("\nconst SELF_TEST_PIN = \"").drop_first(1) {
quoted = after.split_on("\"")
pin = quoted.first() ?? ""
if quoted.len() > 1 and pin != "" {
return Ok(pin)
}
}
Err(NoPin)
}
## The Roc a pin names, as installed under the `tools` mount.
roc_of_pin : Str -> Str
roc_of_pin = |pin| "tools:roc-${pin}/roc"
## The roc-types run when none is installed for the tree's pin.
default_checker : Str
default_checker = "tools:roc-types/bin/roc-types"
## The roc-types installed for the pin of the Roc at the OS path `roc`
## (`.../roc-<pin>/roc`), as compilers sit side by side, when that path
## names a pin.
pinned_checker : Str -> Try(Str, [NoPin])
pinned_checker = |roc| {
folders = roc.drop_suffix("/roc").split_on("/")
folder = folders.last() ?? ""
pin = folder.drop_prefix("roc-")
if roc.ends_with("/roc") and folders.len() > 1 and folder.starts_with("roc-") and pin != "" {
Ok("tools:roc-types-${pin}/bin/roc-types")
} else {
Err(NoPin)
}
}
}
## The version of the format this reads.
format : Str
format = "1"
## The record a `t` line holds, `t`, the kind, the tag, the span's four
## numbers and the type, tab-separated, or why it is not one. `number` is the
## line's, named in a refusal.
record_of : Str, U64 -> Try(RocTypes.Record, Str)
record_of = |output_line, number| {
at = |{}| "line ${number.to_str()}"
fields = output_line.split_on("\t")
field = |place| fields.get(place - 1) ?? ""
kind = field(2)
if fields.len() != 8 {
Err("`roc_types`: ${at({})}, a record of ${fields.len().to_str()} fields, not 8: ${output_line}")
} else if kind != "expr" and kind != "pat" {
Err("`roc_types`: ${at({})}, a record of kind `${kind}`")
} else {
var $span = ""
for number_text in fields.sublist({ start: 3, len: 4 }) {
match I64.from_str(number_text) {
Ok(parsed) => {
$span = if $span == "" {
parsed.to_str()
} else {
"${$span}:${parsed.to_str()}"
}
}
Err(_) => {
return Err("`roc_types`: ${at({})}, a span's number `${number_text}`")
}
}
}
written = if field(8).contains("\\") {
unescaped(field(8))?
} else {
field(8)
}
Ok({ kind, tag: field(3), span: $span, written })
}
}
## A type's text with roc-types' escapes of `\`, tab, newline and carriage
## return undone, or why it holds a bad one.
unescaped : Str -> Try(Str, Str)
unescaped = |text| {
bytes = text.to_utf8()
var $out = []
$at : U64
var $at = 0
while $at < bytes.len() {
byte = bytes.get($at) ?? 0
if byte == '\\' and $at + 1 < bytes.len() {
escaped = bytes.get($at + 1) ?? 0
plain = if escaped == 't' {
Ok('\t')
} else if escaped == 'n' {
Ok('\n')
} else if escaped == 'r' {
Ok('\r')
} else if escaped == '\\' {
Ok('\\')
} else {
Err(BadEscape)
}
match plain {
Ok(kept) => {
$out = $out.append(kept)
}
Err(BadEscape) => {
shown = Str.from_utf8_lossy([escaped])
return Err("`roc_types`: a type with a bad escape, `\\${shown}`: ${text}")
}
}
$at = $at + 2
} else if byte == '\\' {
return Err("`roc_types`: a type ending in a lone `\\`: ${text}")
} else {
$out = $out.append(byte)
$at = $at + 1
}
}
Ok(Str.from_utf8_lossy($out))
}
cookbook/roc/lib/Stacking.roc, 450 lines
## The stacking rule's one home, over Groups' groups (ported from the Shale
## groups.shale, since retired): a group of three or more items and `tokens`
## or more tokens stacks, one item a line, and any other group sits on one
## line while that line fits `width`.
## A function type's arguments can't take a trailing comma, and a row of
## literals or a line of numeric data stays packed. The rewrite's own pieces
## are here too: the group a line's rewrite gives a trailing comma, the
## stacked groups whose comma it takes away, the `targets:` section no
## rewrite reaches, and the columns a line's strings take up, which no
## trailing comma can shorten.
import Bytes
import Groups
import Packed
import Tree
Stacking := [].{
## The rule's two numbers: the tokens from which a group of three or more
## items stacks, and the widest a line may be.
Rule : { tokens : U64, width : U64 }
## A group with the line it is on.
Placed : { line : Str, group : Groups.Group }
## A stacked group that should sit on one line, with the line and column
## of its trailing comma.
Unstacked : {
group : Groups.Group,
comma_line : U64,
comma : U64,
}
## The items from which a group stacks.
stack_items : U64
stack_items = 3
## The tokens from which a group stacks, unless a run says otherwise.
stack_tokens : U64
stack_tokens = 6
## Whether a line is a line of data: wider than `width`, with a number
## list on it. No group on it stacks, since stacking any group around the
## data, or beside it, makes `roc fmt` open every group around that one.
is_data_line : Str, U64 -> Bool
is_data_line = |text, width| {
bytes = text.to_utf8()
Bytes.width_of(bytes) > width and Packed.holds_number_list(bytes)
}
## Whether a group holds enough to read better stacked.
is_big : Groups.Group, U64 -> Bool
is_big = |group, tokens| group.items >= Stacking.stack_items and group.tokens >= tokens
## Whether a group on its line should stack: big, no trailing comma yet,
## not a function type's arguments, not a row of literals and not numeric
## data. The caller asks is_data_line first, once a line.
should_stack : Stacking.Placed, Stacking.Rule -> Bool
should_stack = |placed, rule| {
group = placed.group
bytes = placed.line.to_utf8()
if !(Stacking.is_big(group, rule.tokens)) or group.trailing or group.fn_type {
Bool.False
} else {
is_row = Packed.is_literal_row({ bytes, group }, rule.width)
!(is_row) and !(Packed.is_number_data(bytes, group))
}
}
## The group on a line that the rewrite gives a trailing comma: the
## outermost, then widest, group that should stack; or else, on a line
## wider than `width`, the widest group of two or more items whose
## stacking brings the line within `width`. None on a line of data.
group_to_stack : Str, Stacking.Rule -> Try(Groups.Group, [NoGroup])
group_to_stack = |text, rule|
if Stacking.is_data_line(text, rule.width) {
Err(NoGroup)
} else {
groups = Groups.groups_on_line(text)
var $best = Err(NoGroup)
if rule.tokens > 0 {
for group in groups {
if Stacking.should_stack({ line: text, group }, rule) {
$best = match $best {
Err(_) => Ok(group)
Ok(best) =>
if is_outer_or_wider(group, best) {
Ok(group)
} else {
Ok(best)
}
}
}
}
}
if $best != Err(NoGroup) or Bytes.line_width(text) <= rule.width {
$best
} else {
group_to_wrap(text.to_utf8(), { width: rule.width, groups })
}
}
## The line with a comma after the last item of its group, before any
## spaces that come ahead of the group's closing bracket.
with_trailing_comma : Stacking.Placed -> Str
with_trailing_comma = |placed| {
bytes = placed.line.to_utf8()
group = placed.group
var $j = group.close - 1
while $j > group.open and Bytes.byte_at(bytes, $j) == ' ' {
$j = $j - 1
}
Str.from_utf8_lossy(
Bytes.span(bytes, 1, $j).append(',').concat(Bytes.rest_from(bytes, $j + 1)),
)
}
## The line a stacked group of the lines would be on one line, spaced as
## `roc fmt` spaces it, or `Kept` when a line break inside it does more
## than separate items: a blank line, or a block's statements.
group_on_one_line : List(Str), Groups.Group -> Try(Str, [Kept])
group_on_one_line = |source_lines, group| {
var $joined = text_up_to_group(source_lines, group)
var $i = group.line + 1
while $i <= group.close_line {
piece = Bytes.trimmed(Bytes.line_of(source_lines, $i))
before = $joined.last() ?? 0
first = Bytes.byte_at(piece, 1)
closes = Groups.is_closer(first) or ($i == group.close_line and first == '|')
if piece.is_empty() {
return Err(Kept)
}
after_bar = before == '|' and $i == group.line + 1
separates = before == ',' or Groups.closer_of(before) != 0 or after_bar
if !(separates) {
return Err(Kept)
}
if closes and before == ',' {
$joined = $joined.drop_last(1)
}
if before == '{' or first == '}' or (before == ',' and !(closes)) {
$joined = $joined.append(' ')
}
$joined = $joined.concat(piece)
$i = $i + 1
}
Ok(Str.from_utf8_lossy(with_annotation_rest(source_lines, { group, joined: $joined })))
}
## The stacked groups of the lines that should sit on one line, by where
## they close. A group around one that stays on several lines can't be one
## line itself: `roc fmt` would give it its comma back. A group whose line
## doesn't end in its trailing comma is refused, with that line.
groups_to_unstack : List(Str), Stacking.Rule -> Try(List(Stacking.Unstacked), [NoComma(U64)])
groups_to_unstack = |source_lines, rule| {
var $out = []
var $last_kept = Err(NoGroup)
for group in Groups.groups_in_lines(Stacking.without_targets_section(source_lines)) {
if group.line != group.close_line {
holds_kept = match $last_kept {
Ok(kept) => is_inside(kept, group)
Err(_) => Bool.False
}
if holds_kept or !(should_unstack(source_lines, { group, rule })) {
$last_kept = Ok(group)
} else {
close_bytes = Bytes.line_of(source_lines, group.close_line)
comma_line = if Bytes.trimmed(
Bytes.span(close_bytes, 1, group.close - 1),
).is_empty() {
group.close_line - 1
} else {
group.close_line
}
comma = Bytes.trimmed_end(Bytes.line_of(source_lines, comma_line)).len()
if Bytes.byte_at(Bytes.line_of(source_lines, comma_line), comma) != ',' {
return Err(NoComma(comma_line))
}
$out = $out.append({ group, comma_line, comma })
}
}
}
Ok($out)
}
## The lines with the trailing comma of each of the groups taken out,
## which `roc fmt` reads as asking for one line.
without_trailing_commas : List(Str), List(Stacking.Unstacked) -> List(Str)
without_trailing_commas = |source_lines, unstacked| {
var $out = source_lines
for found in unstacked {
bytes = Bytes.line_of($out, found.comma_line)
cut = Str.from_utf8_lossy(Bytes.span(bytes, 1, found.comma - 1))
$out = $out.set(
found.comma_line - 1,
cut,
) ?? crash "Stacking: a comma past the lines' end"
}
$out
}
## The lines with a platform header's `targets:` section blanked, for
## reading groups: `roc fmt` lays that section out by itself, so a
## rewrite that tried would never end.
without_targets_section : List(Str) -> List(Str)
without_targets_section = |source_lines|
if !(source_lines.any(|text| text.contains("targets:"))) {
source_lines
} else {
found = Groups.groups_in_lines(source_lines).find_first(
|group| ends_in_targets(
Bytes.span(
Bytes.line_of(source_lines, group.line),
1,
group.open - 1,
),
),
)
match found {
Ok(group) =>
source_lines.map_with_index(
|text, index|
if index + 1 >= group.line and index + 1 <= group.close_line {
""
} else {
text
},
)
Err(_) => source_lines
}
}
## The columns that strings' text takes up on each line of a file, from
## its tree and its lines, by line number. A run of string text that
## crosses a line is refused, with its line.
string_columns_on_lines : List(Tree.Node), List(Str) -> Try(Dict(U64, U64), [CrossesLine(U64)])
string_columns_on_lines = |nodes, source_lines| {
var $by_line = Dict.empty()
for node in nodes {
if node.kind == "e-string-part" or node.kind == "p-string-text" {
if node.line != node.end_line {
return Err(CrossesLine(node.line))
}
bytes = Bytes.line_of(source_lines, node.line)
text = if node.end_column == 0 {
Bytes.rest_from(bytes, node.column)
} else {
Bytes.span(bytes, node.column, node.end_column - 1)
}
so_far = $by_line.get(node.line) ?? 0
$by_line = $by_line.insert(node.line, so_far + Bytes.width_of(text))
}
}
Ok($by_line)
}
}
## Whether the text before a group ends in `targets:` and spaces, the word
## standing alone (`\btargets: *$`).
ends_in_targets : List(U8) -> Bool
ends_in_targets = |bytes| {
var $end = bytes.len()
while $end > 0 and Bytes.byte_at(bytes, $end) == ' ' {
$end = $end - 1
}
word = "targets:".to_utf8()
if $end < word.len() {
Bool.False
} else {
start = $end - word.len() + 1
Bytes.span(
bytes,
start,
$end,
) == word and !(Bytes.is_word_byte(Bytes.byte_at(bytes, start - 1)))
}
}
## Whether stacked group `group` should sit on one line: not big, nothing a
## rewrite can't join, and a joined line within the width.
should_unstack : List(Str), { group : Groups.Group, rule : Stacking.Rule } -> Bool
should_unstack = |source_lines, judged| {
group = judged.group
rule = judged.rule
kept = group.fixed or holds_parentheses_open(group) or Stacking.is_big(group, rule.tokens)
if !(group.trailing) or kept {
Bool.False
} else {
match Stacking.group_on_one_line(source_lines, group) {
Ok(joined) => Bytes.line_width(joined) <= rule.width
Err(_) => Bool.False
}
}
}
## Whether a group to stack is a better one than `best`: outer to it, or as
## deep and wider.
is_outer_or_wider : Groups.Group, Groups.Group -> Bool
is_outer_or_wider = |group, best| {
wider = group.close - group.open > best.close - best.open
group.depth < best.depth or (group.depth == best.depth and wider)
}
## Whether a group is what keeps the parentheses around it on several lines.
## They would join its line, past what group_on_one_line measures.
holds_parentheses_open : Groups.Group -> Bool
holds_parentheses_open = |group|
group.parent.closer == ')' and group.parent.line < group.line and !(group.parent.trailing)
## Whether group `inner`, which closes before `outer`, lies inside it.
is_inside : Groups.Group, Groups.Group -> Bool
is_inside = |inner, outer|
inner.line > outer.line or (inner.line == outer.line and inner.open > outer.open)
## The text before a group once it sits on one line. A stacked group among an
## annotation's arguments moves its line down from the annotation's, and `roc
## fmt` brings it back up with the group on one line.
text_up_to_group : List(Str), Groups.Group -> List(U8)
text_up_to_group = |source_lines, group| {
up_to = Bytes.span(Bytes.line_of(source_lines, group.line), 1, group.open)
above = Bytes.line_of(source_lines, group.line - 1)
if group.line > 1 and is_annotation_line(Bytes.trimmed(above)) {
above.append(' ').concat(Bytes.trimmed(up_to))
} else {
up_to
}
}
## `joined`, the line a group would be on, with the rest of its annotation
## when the group is among an annotation's arguments: stacking such a group
## puts the arguments after it on lines of their own, and `roc fmt` brings
## them back up with it. The rest runs to the line with the annotation's
## arrow; without one, `joined` is the whole line.
with_annotation_rest : List(Str), { group : Groups.Group, joined : List(U8) } -> List(U8)
with_annotation_rest = |source_lines, at| {
group = at.group
opens = annotation_opens(Bytes.trimmed(Bytes.line_of(source_lines, group.line)))
follows = group.line > 1 and is_annotation_line(
Bytes.trimmed(Bytes.line_of(source_lines, group.line - 1)),
)
if !(opens) and !(follows) {
return at.joined
}
var $rest = at.joined
var $i = group.close_line + 1
while $rest.last() == Ok(',') and $i <= source_lines.len() {
piece = Bytes.trimmed(Bytes.line_of(source_lines, $i))
if piece.is_empty() {
return at.joined
}
$rest = $rest.append(' ').concat(piece)
if holds_arrow(piece) {
return $rest
}
$i = $i + 1
}
at.joined
}
## Whether the bytes hold `->` or `=>`.
holds_arrow : List(U8) -> Bool
holds_arrow = |bytes| {
var $at = 1
while $at < bytes.len() {
byte = Bytes.byte_at(bytes, $at)
if (byte == '-' or byte == '=') and Bytes.byte_at(bytes, $at + 1) == '>' {
return Bool.True
}
$at = $at + 1
}
Bool.False
}
## Where an annotation's name and its `!` end on a trimmed line, one past
## them: `^[a-z_][A-Za-z0-9_]*!?`.
annotated_name_end : List(U8) -> Try(U64, [NoName])
annotated_name_end = |bytes| {
first = Bytes.byte_at(bytes, 1)
if (first >= 'a' and first <= 'z') or first == '_' {
var $end = 2
while Bytes.is_word_byte(Bytes.byte_at(bytes, $end)) {
$end = $end + 1
}
if Bytes.byte_at(bytes, $end) == '!' {
$end = $end + 1
}
Ok($end)
} else {
Err(NoName)
}
}
## Whether a trimmed line starts a function's annotation whose bare
## arguments go on past it: `^[a-z_][A-Za-z0-9_]*!? : .*,$`.
is_annotation_line : List(U8) -> Bool
is_annotation_line = |bytes|
match annotated_name_end(bytes) {
Ok(end) => Bytes.span(
bytes,
end,
end + 2,
) == [' ', ':', ' '] and bytes.len() >= end + 3 and bytes.last() == Ok(',')
Err(_) => Bool.False
}
## Whether a trimmed line opens with a function's annotation:
## `^[a-z_][A-Za-z0-9_]*!? : `.
annotation_opens : List(U8) -> Bool
annotation_opens = |bytes|
match annotated_name_end(bytes) {
Ok(end) => Bytes.span(bytes, end, end + 2) == [' ', ':', ' ']
Err(_) => Bool.False
}
## The group on a line wider than the width that the rewrite stacks for its
## width alone: the widest group of two or more items, not a function type's
## arguments, whose stacking brings the line within the width.
group_to_wrap : List(U8),
{
width : U64,
groups : List(Groups.Group),
} -> Try(Groups.Group, [NoGroup])
group_to_wrap = |bytes, given| {
var $best = Err(NoGroup)
for group in given.groups {
if group.items >= 2 and !(group.trailing) and !(group.fn_type) and stacking_fits(
{ bytes, group },
given.width,
) {
$best = match $best {
Ok(best) if group.close - group.open <= best.close - best.open => Ok(best)
_ => Ok(group)
}
}
}
$best
}
## Whether stacking a group brings its line within `width`, as far as the
## line itself goes: the text up to its opening bracket is one line, and its
## closing bracket and what follows it, at the line's indent, another.
stacking_fits : { bytes : List(U8), group : Groups.Group }, U64 -> Bool
stacking_fits = |at, width|
if Bytes.width_of(Bytes.span(at.bytes, 1, at.group.open)) > width {
Bool.False
} else {
is_indent = |byte| byte == ' ' or byte == '\t'
indent_end = at.bytes.find_first_index(|byte| !(is_indent(byte))) ?? at.bytes.len()
indent = at.bytes.take_first(indent_end)
Bytes.width_of(indent.concat(Bytes.rest_from(at.bytes, at.group.close))) <= width
}
cookbook/roc/lib/Text.roc, 215 lines
## Text cut, trimmed, lowered and ordered as Shale's builtins and preludes do
## it (`lines`, `words`, `trim`, `lower`, `sub`, `split`, `between`,
## `basename`, `dirname`, `path_under`, `sort`), and a name's words, so a
## recipe's output is its
## Shale original's, byte for byte.
Text := [].{
## A text's lines, as Shale's `lines` splits it: a last newline ends a
## line, and an empty text has none.
lines : Str -> List(Str)
lines = |text| {
parts = text.split_on("\n")
if text.ends_with("\n") or text == "" {
parts.drop_last(1)
} else {
parts
}
}
## Line `number` of `source_lines`, counted from 1. A line the file lacks
## stops the run, as Shale's index past a list's end does.
line_at : List(Str), U64 -> Str
line_at = |source_lines, number|
match source_lines.get(number - 1) {
Ok(line) => line
Err(_) => crash "Text.line_at: the file has no line ${number.to_str()}"
}
## The bytes of `text` from place `start` (counted from 0), `count` of them
## or as many as there are, as text.
bytes_of : Str, { start : U64, count : U64 } -> Str
bytes_of = |text, span| {
bytes = text.to_utf8().sublist({ start: span.start, len: span.count })
Str.from_utf8_lossy(bytes)
}
## The text without the spaces, tabs, carriage returns and newlines at its
## ends, as Shale's `trim` takes them.
trim : Str -> Str
trim = |text| {
bytes = text.to_utf8()
is_kept = |byte| !(byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n')
match bytes.find_first_index(is_kept) {
Ok(start) => {
end = bytes.find_last_index(is_kept) ?? start
Str.from_utf8_lossy(bytes.sublist({ start, len: end + 1 - start }))
}
Err(_) => ""
}
}
## The text with its ASCII capitals made small, as Shale's `lower` does.
lower : Str -> Str
lower = |text| Str.from_utf8_lossy(text.to_utf8().map(lower_byte))
is_capital : U8 -> Bool
is_capital = |byte| byte >= 'A' and byte <= 'Z'
is_small_letter : U8 -> Bool
is_small_letter = |byte| byte >= 'a' and byte <= 'z'
is_digit : U8 -> Bool
is_digit = |byte| byte >= '0' and byte <= '9'
## The text before the first `separator`, or all of it (Shale's
## `split(s, separator)[1]`).
before_first : Str, Str -> Str
before_first = |text, separator|
match text.split_first(separator) {
Ok(parts) => parts.before
Err(_) => text
}
## The text after the last `separator`, or all of it.
after_last : Str, Str -> Str
after_last = |text, separator|
match text.split_last(separator) {
Ok(parts) => parts.after
Err(_) => text
}
## Shale's `between(text, opening, closing)`: after the first `opening`,
## before the next `closing`.
between : Str, Str, Str -> Try(Str, [NotFound])
between = |text, opening, closing| {
after_opening = text.split_first(opening)?
inside = after_opening.after.split_first(closing)?
Ok(inside.before)
}
## Shale's `basename`: the path after its last `/`.
basename : Str -> Str
basename = |path| Text.after_last(path, "/")
## Shale's `dirname`: the path before its last `/`, `""` (the root) when
## it has none.
dirname : Str -> Str
dirname = |path|
match path.split_last("/") {
Ok(parts) => parts.before
Err(_) => ""
}
## Shale's `path_under`: a name below a folder, spelled as every call takes
## it: in the root (`""`, `"."`) the name, in a mount's folder (`m:`,
## `m:.`) `m:name`, else `dir/name`.
path_under : Str, Str -> Str
path_under = |folder, name|
if folder == "" or folder == "." {
name
} else if folder.ends_with(":") {
"${folder}${name}"
} else if folder.ends_with(":.") {
"${folder.drop_suffix(".")}${name}"
} else {
"${folder}/${name}"
}
## A name's words, lowercased: split at its underscores and before each
## capital that follows a letter or digit, so `TiltStep` and `tilt_step`
## both give `tilt` and `step` (cookbook/roc/declared.shale's
## `name_words`).
name_words : Str -> List(Str)
name_words = |name| {
var $words = []
var $word = []
for byte in name.to_utf8() {
if byte == '_' {
$words = with_word($words, $word)
$word = []
} else if Text.is_capital(byte) and !($word.is_empty()) {
$words = with_word($words, $word)
$word = [byte]
} else {
$word = $word.append(byte)
}
}
with_word($words, $word)
}
## A text's words, as Shale's `words` splits it: the runs between spaces,
## tabs, carriage returns and newlines, none empty.
words : Str -> List(Str)
words = |text| {
var $said = []
var $word = []
for byte in text.to_utf8() {
if byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n' {
$said = with_raw_word($said, $word)
$word = []
} else {
$word = $word.append(byte)
}
}
with_raw_word($said, $word)
}
## The texts put in Shale's `sort` order, bytewise.
sort_bytewise : List(Str) -> List(Str)
sort_bytewise = |texts| texts.sort_with(Text.byte_order)
## Two texts in the order of their bytes, a text before every longer one
## it starts, as Shale's `sort` puts strings. Its one copy is
## cookbook/c/items' `Words.byte_order`, which says why.
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
}
}
}
}
lower_byte : U8 -> U8
lower_byte = |byte|
if Text.is_capital(byte) {
byte + 32
} else {
byte
}
## `said` with `bytes` after it as a word, as they are, when there are any.
with_raw_word : List(Str), List(U8) -> List(Str)
with_raw_word = |said, bytes|
if bytes.is_empty() {
said
} else {
said.append(Str.from_utf8_lossy(bytes))
}
## `words` with `bytes` after them as a lowercased word, when there are any.
with_word : List(Str), List(U8) -> List(Str)
with_word = |words, bytes|
if bytes.is_empty() {
words
} else {
words.append(Text.lower(Str.from_utf8_lossy(bytes)))
}
cookbook/roc/lib/Tree.roc, 168 lines
## Roc's tree of a file, as `Shale.roc_tree!` gives it, read: a node by its
## place, its attributes and kids, a type written back as Roc writes it or as
## a shape, the module a file holds, and whether the file is an app.
import Text
Tree := [].{
## A node of Roc's tree, its fields named by the platform: `parent` and
## `kids` are places in the tree counted from 1, the root's parent 0;
## `depth` is how far below the root it is, and `line` is 0 for a node
## with no span.
Node : {
kind : Str,
depth : U64,
parent : U64,
kids : List(U64),
line : U64,
column : U64,
end_line : U64,
end_column : U64,
attributes : List({ name : Str, value : Str }),
}
## The node at a place counted from 1, which the tree's own `parent` and
## `kids` always name.
node_at : List(Tree.Node), U64 -> Tree.Node
node_at = |nodes, place|
if place == 0 {
crash "Tree.node_at: the tree has no node 0"
} else {
match nodes.get(place - 1) {
Ok(node) => node
Err(_) => crash "Tree.node_at: the tree has no node ${place.to_str()}"
}
}
## A node's attribute, by its name, when the tree gives it one.
find_attribute : Tree.Node, Str -> Try(Str, [NoSuchAttribute])
find_attribute = |node, name|
match node.attributes.find_first(|attribute_entry| attribute_entry.name == name) {
Ok(attribute_entry) => Ok(attribute_entry.value)
Err(_) => Err(NoSuchAttribute)
}
## A node's attribute, `""` where the tree gives it none.
attribute : Tree.Node, Str -> Str
attribute = |node, name| Tree.find_attribute(node, name) ?? ""
## The place of a node's kid, the kids counted from 1.
kid_at : Tree.Node, U64 -> U64
kid_at = |node, number|
match node.kids.get(number - 1) {
Ok(kid) => kid
Err(_) => crash "Tree.kid_at: a ${node.kind} with no kid ${number.to_str()}"
}
## The place of a node's first kid: an apply's function, a receiver's
## value.
first_kid : Tree.Node -> U64
first_kid = |node|
match node.kids.first() {
Ok(kid) => kid
Err(_) => crash "Tree.first_kid: a ${node.kind} with no kids"
}
## The place of a node's last kid.
last_kid : Tree.Node -> U64
last_kid = |node|
match node.kids.last() {
Ok(kid) => kid
Err(_) => crash "Tree.last_kid: a ${node.kind} with no kids"
}
## The kind of a node's kid, the kids counted from 1, `""` when it has no
## such kid.
kid_kind : List(Tree.Node), Tree.Node, U64 -> Str
kid_kind = |nodes, node, number|
if number == 0 {
""
} else {
match node.kids.get(number - 1) {
Ok(kid) => Tree.node_at(nodes, kid).kind
Err(_) => ""
}
}
## A dotted name's last part: `Geom.Pose` gives `Pose`.
last_part : Str -> Str
last_part = |name| Text.after_last(name, ".")
## The type at `at`, as Roc writes it: `List(U8)`, `{ id : U8 }`, `[A, B]`, `(U8 -> Bool)`. The
## tree does not say which arrow a function type has, so both come out as
## `->`.
written_type : List(Tree.Node), U64 -> Str
written_type = |nodes, at| type_text(nodes, at, AsWritten)
## The type at `at` as a shape: written as Roc writes it, each name cut to
## its last part and a record's fields and a union's tags sorted, so two
## copies of one type read alike.
shape : List(Tree.Node), U64 -> Str
shape = |nodes, at| type_text(nodes, at, AsShape)
## The module a .roc file holds, by its file name: the name without its
## last four bytes, `.roc`.
module_name : Str -> Str
module_name = |path| {
bytes = Text.basename(path).to_utf8()
if bytes.len() > 4 {
Str.from_utf8_lossy(bytes.take_first(bytes.len() - 4))
} else {
""
}
}
## Whether the file is an app, with an `app` header.
is_app : List(Tree.Node) -> Bool
is_app = |nodes| nodes.any(|node| node.kind == "app")
}
## How a type is written: as the code writes it, or as a shape, its names cut
## to their last parts and its fields and tags sorted.
TypeStyle : [AsWritten, AsShape]
## The type at `at`, written in `style`.
type_text : List(Tree.Node), U64, TypeStyle -> Str
type_text = |nodes, at, style| {
node = Tree.node_at(nodes, at)
kind = node.kind
name = Tree.attribute(node, "name")
texts_of = |kids| kids.map(|kid| type_text(nodes, kid, style))
joined = |kids| Str.join_with(texts_of(kids), ", ")
members_joined = |kids|
match style {
AsWritten => joined(kids)
AsShape => Str.join_with(Text.sort_bytewise(texts_of(kids)), ", ")
}
first = |{}| type_text(nodes, Tree.first_kid(node), style)
if kind == "ty-apply" {
"${first({})}(${joined(node.kids.drop_first(1))})"
} else if kind == "ty-fn" {
result = type_text(nodes, Tree.last_kid(node), style)
"(${joined(node.kids.drop_last(1))} -> ${result})"
} else if kind == "ty-record" {
"{ ${members_joined(node.kids)} }"
} else if kind == "ty-tuple" {
"(${joined(node.kids)})"
} else if kind == "tags" {
members_joined(node.kids)
} else if kind == "ty-tag-union" {
"[${first({})}]"
} else if kind == "anno-record-field" {
"${name} : ${first({})}"
} else if name != "" {
match style {
AsWritten => name
AsShape => Tree.last_part(name)
}
} else if kind == "_" {
"_"
} else {
raw = Tree.attribute(node, "raw")
if raw != "" {
raw
} else {
"(${kind})"
}
}
}
cookbook/roc/lib/main.roc, 13 lines
## The modules the cookbook's Roc recipes share, a package each recipe's app
## names by a relative path (`lib: "../lib/main.roc"`, then `import lib.Tree`):
## Roc's tree of a file read (Tree), several files' trees joined (Forest),
## what a file declares (Declarations), what its header dictates (Headers),
## the imports it never uses (Imports, find_unused_imports' rule), text cut
## and ordered as Shale's builtins do it (Text) and a line's bytes as they
## read it (Bytes), a check's finding (Finding), roc-types' output read
## (RocTypes), and a file's bracket groups (Groups) judged by the stacking
## rule (Stacking), the packed ones apart (Packed). None reaches an
## effect: a recipe's own modules
## do that, through `import pf.Shale` (roc_platform/README.md, "A script may
## be several files").
package [Bytes, Declarations, Finding, Forest, Groups, Headers, Imports, Packed, RocTypes, Stacking, Text, Tree] {}