// Part of the inventory program (see main.nika): reading the stock list.
grammar Stock {
rule FIELD -> String = s:until(";" | frame_end) -> { s }
rule COUNT -> i64 = n:dec[i64](digit+) -> { n }
@frame(boundary: "\n")
rule ENTRY -> Entry =
category:FIELD ";" => item:FIELD ";" count:COUNT frame_end
-> { Entry { category, item, count } }
entry rule file -> Vec[Entry] = entries:ENTRY* -> { entries }
}
pub struct Entry {
pub category: String,
pub item: String,
pub count: int,
}
// A grammar is only visible in the file that declares it, so `main.nika`
// cannot call `Stock::file` and calls this instead.
pub fn read(data: String) -> Vec[Entry] throws {
return Stock::file(data)
}
// Not `pub`: the other files of this package can call it, but nothing outside.
fn weight(entry: ref Entry) -> int {
return entry.count
}
pub fn total(entries: ref Vec[Entry]) -> int {
let mut sum = 0
for e in entries { sum += weight(e) }
return sum
}
The file itself · all the examples