summaryrefslogtreecommitdiffhomepage
path: root/gleam/src/ssp/parse.gleam
blob: dff7118b7a9286f003ba9fd49cb7a4bc1caf7f94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//// Parsing a .ssp.
////
//// Specification section 3: the format is line oriented, and every line
//// is one of eight shapes told apart by its first character. So the
//// parser is a fold over the lines carrying the state the shapes need.

import gleam/dict.{type Dict}
import gleam/int
import gleam/list
import gleam/option
import gleam/string
import ssp/types.{type Document, type Object, type Section, Object, Section}

/// specification section 6.1: the sixteen kinds
pub const kinds = [
  "para", "heading", "toc", "bookindex", "endnote", "code", "bibliography",
  "comment", "verse", "glossary", "quote", "poem", "block", "table", "blurb",
  "group",
]

/// specification section 4: the four preamble blocks
pub const preamble_blocks = ["source", "meta", "make", "doc_has"]

/// specification section 4: the nine sections, in the order they appear
pub const section_names = [
  "head", "toc", "body", "endnotes", "glossary", "bibliography", "bookindex",
  "blurb", "tail",
]

/// specification section 6.3: the 43 properties, in the order emitted
/// (43 since format 2.1, which added ocn_range)
pub const properties = [
  "identifier", "part", "section", "parent", "last_descendant", "ocn_range",
  "children",
  "ancestors", "ancestors_collapsed", "dom_status", "dom_status_collapsed",
  "heading_lev_collapsed", "parent_lev", "dummy", "ocn_off", "is_of_type",
  "attrib", "meta_lang", "meta_syntax", "sha256", "image", "indent", "bullet",
  "lang", "has", "table_cols", "table_widths", "table_aligns", "table_header",
  "code_linenumbers", "stow_link", "segment", "anchor", "segment_prev",
  "segment_next", "heading_lev_anchor", "segment_epub", "segment_html_is",
  "segment_epub_is", "segment_lv4_is", "heading_ancestors_text", "lev4_subtoc",
  "anchor_tag",
]

/// The properties this reader makes use of. The rest are counted and
/// ignored, which is conforming behaviour within a major version
/// (specification section 8.1) so long as it is not done in silence.
const properties_used = [
  "part", "parent", "ancestors", "is_of_type", "identifier",
]

type State {
  State(
    document: Document,
    /// the block currently open, "" when none
    block: String,
    /// the section currently open, "" when in the preamble
    section: String,
    /// objects of the current section, newest first
    objects: List(Object),
    /// the object being read, if any
    current: Result(Object, Nil),
    /// sections completed, newest first
    done: List(Section),
  )
}

pub fn parse(content: String) -> Document {
  let state =
    content
    |> string.split(on: "\n")
    |> list.fold(from: initial_state(), with: line)
  finish(state)
}

fn initial_state() -> State {
  State(
    document: types.new_document(),
    block: "",
    section: "",
    objects: [],
    current: Error(Nil),
    done: [],
  )
}

fn line(state: State, raw: String) -> State {
  case raw {
    "" -> commit_object(state)
    "% SiSU Document Abstraction v" <> version ->
      State(
        ..state,
        document: types.Document(
          ..state.document,
          version: string.trim(version),
        ),
      )
    "% Source: " <> filename ->
      State(
        ..state,
        document: types.Document(
          ..state.document,
          source_filename: string.trim(filename),
        ),
      )
    "%" <> _ -> state
    "@" <> rest -> open_block(state, rest)
    "}" -> close_block(state)
    "  " <> rest -> preamble_pair(state, rest)
    "[" <> rest -> declaration(state, rest)
    "." <> rest -> property(state, rest)
    "| " <> rest -> text_line(state, rest)
    _ ->
      State(
        ..state,
        document: types.Document(
          ..state.document,
          malformed_lines: state.document.malformed_lines + 1,
        ),
      )
  }
}

fn open_block(state: State, rest: String) -> State {
  let name = case string.split_once(rest, " {") {
    Ok(#(name, _)) -> name
    Error(_) -> rest
  }
  case list.contains(preamble_blocks, name), list.contains(section_names, name) {
    True, _ -> State(..state, block: name)
    _, True -> State(..state, block: name, section: name, objects: [])
    _, _ ->
      State(
        ..state,
        block: name,
        document: types.Document(
          ..state.document,
          unknown_blocks: bump(state.document.unknown_blocks, name),
        ),
      )
  }
}

fn close_block(state: State) -> State {
  let state = commit_object(state)
  case state.section {
    "" -> State(..state, block: "")
    name ->
      State(
        ..state,
        block: "",
        section: "",
        objects: [],
        done: [Section(name: name, objects: list.reverse(state.objects)), ..state.done],
      )
  }
}

fn preamble_pair(state: State, rest: String) -> State {
  case string.split_once(rest, ": ") {
    Error(_) -> state
    Ok(#(key, value)) -> {
      let document = state.document
      let document = case state.block {
        "source" ->
          types.Document(..document, source: dict.insert(document.source, key, value))
        "meta" ->
          types.Document(..document, meta: dict.insert(document.meta, key, value))
        "make" ->
          types.Document(..document, make: dict.insert(document.make, key, value))
        "doc_has" ->
          types.Document(
            ..document,
            doc_has: dict.insert(document.doc_has, key, value),
          )
        _ -> document
      }
      State(..state, document: document)
    }
  }
}

/// specification section 6.1
///   [<ocn>] <kind>
///   [<ocn>] heading :<level>
///   [<ocn>] heading :<level> <identifier>
fn declaration(state: State, rest: String) -> State {
  let state = commit_object(state)
  case string.split_once(rest, "] ") {
    Error(_) -> state
    Ok(#(ocn_text, tail)) -> {
      let ocn = case int.parse(ocn_text) {
        Ok(n) -> n
        Error(_) -> 0
      }
      let object = case string.split(tail, on: " ") {
        ["heading", level, ..identifier] ->
          Object(
            ..types.new_object(),
            ocn: ocn,
            kind: "heading",
            level: string.drop_start(level, 1),
            identifier: string.join(identifier, " "),
          )
        [kind, ..] -> Object(..types.new_object(), ocn: ocn, kind: kind)
        [] -> types.new_object()
      }
      State(..state, current: Ok(object))
    }
  }
}

fn property(state: State, rest: String) -> State {
  case state.current, string.split_once(rest, ": ") {
    Ok(object), Ok(#(name, value)) -> {
      let object =
        Object(..object, properties: [#(name, value), ..object.properties])
      let object = case name {
        "part" -> Object(..object, part: value)
        "is_of_type" -> Object(..object, is_of_type: value)
        "identifier" -> Object(..object, identifier: value)
        "parent" ->
          Object(..object, parent: case int.parse(value) {
            Ok(n) -> n
            Error(_) -> 0
          })
        "ancestors" -> Object(..object, ancestors: numbers(value))
        _ -> object
      }
      // a property this reader does not use, whether or not the
      // specification names it, is counted rather than passed over: within
      // a major version ignoring it is conforming, doing so in silence is
      // what stops a reader being a check on the specification
      let document = case list.contains(properties_used, name) {
        True -> state.document
        False ->
          types.Document(
            ..state.document,
            unknown_properties: bump(state.document.unknown_properties, name),
          )
      }
      State(..state, current: Ok(object), document: document)
    }
    _, _ -> state
  }
}

fn text_line(state: State, rest: String) -> State {
  case state.current {
    Ok(object) -> State(..state, current: Ok(Object(..object, text: [rest, ..object.text])))
    Error(_) -> state
  }
}

fn commit_object(state: State) -> State {
  case state.current {
    Error(_) -> state
    Ok(object) ->
      State(
        ..state,
        current: Error(Nil),
        objects: [Object(..object, text: list.reverse(object.text),
          properties: list.reverse(object.properties)), ..state.objects],
      )
  }
}

fn finish(state: State) -> Document {
  let state = close_block(commit_object(state))
  types.Document(..state.document, sections: list.reverse(state.done))
}

fn bump(counts: Dict(String, Int), key: String) -> Dict(String, Int) {
  dict.upsert(counts, key, fn(existing) {
    case existing {
      option.Some(n) -> n + 1
      option.None -> 1
    }
  })
}

fn numbers(value: String) -> List(Int) {
  value
  |> string.split(on: " ")
  |> list.filter_map(int.parse)
}