Class: HeadMusic::Notation::ABC::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/head_music/notation/abc/parser.rb

Overview

Interprets an ABC tune string as a HeadMusic::Content::Composition.

Everything that can be validated up front (blank input, header problems, lexing errors, unsupported features) raises before the composition is constructed, so callers never receive a reference to a partially built composition.

Defined Under Namespace

Classes: PendingNote, VoiceState

Constant Summary collapse

BROKEN_RHYTHM_SCALES =

Broken-rhythm scales: the mark’s side gets the dot (x 3/2) and the other side is halved.

{
  :> => [Rational(3, 2), Rational(1, 2)],
  :< => [Rational(1, 2), Rational(3, 2)]
}.freeze
REPEAT_ENDING_STYLES =

Bar styles that end a repeated section, terminating any volta.

[":|", "::"].freeze
REPEAT_STARTING_STYLES =
["|:", "::"].freeze
SECTION_ENDING_STYLES =
["||", "|]", "[|"].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(abc_string, start_line: 1) ⇒ Parser

start_line offsets reported line numbers, so a tune parsed out of a larger book raises errors with book-relative line numbers.



24
25
26
27
# File 'lib/head_music/notation/abc/parser.rb', line 24

def initialize(abc_string, start_line: 1)
  @abc_string = abc_string
  @start_line = start_line
end

Instance Attribute Details

#duration_resolverObject (readonly, private)

Returns the value of attribute duration_resolver.



35
36
37
# File 'lib/head_music/notation/abc/parser.rb', line 35

def duration_resolver
  @duration_resolver
end

#headerObject (readonly, private)

Returns the value of attribute header.



35
36
37
# File 'lib/head_music/notation/abc/parser.rb', line 35

def header
  @header
end

Instance Method Details

#append_tied(head, tail) ⇒ Object (private)

Attaches tail at the deep end of head’s tied chain, rebuilding each link (RhythmicValue exposes no setter) so a chain like “half tied to eighth” gains a further “tied to quarter”.



389
390
391
392
# File 'lib/head_music/notation/abc/parser.rb', line 389

def append_tied(head, tail)
  inner = head.tied_value ? append_tied(head.tied_value, tail) : tail
  HeadMusic::Rudiment::RhythmicValue.new(head.unit, dots: head.dots, tied_value: inner)
end

#apply_repeat_flags(state, style) ⇒ Object (private)



399
400
401
402
403
404
405
406
407
# File 'lib/head_music/notation/abc/parser.rb', line 399

def apply_repeat_flags(state, style)
  if REPEAT_ENDING_STYLES.include?(style)
    completed = state.completed_bar_number
    bar(completed).ends_repeat_after_num_plays = 2 if completed
  end
  return unless REPEAT_STARTING_STYLES.include?(style)

  bar(state.entered_bar_number).starts_repeat = true
end

#bar(bar_number) ⇒ Object (private)



427
428
429
# File 'lib/head_music/notation/abc/parser.rb', line 427

def bar(bar_number)
  @building.bars(bar_number).last
end

#build_compositionObject (private)



70
71
72
73
74
75
76
77
78
# File 'lib/head_music/notation/abc/parser.rb', line 70

def build_composition
  ensure_input_present
  @header = Header.new(@abc_string, start_line: @start_line)
  reject_content_after_tune
  tokens = BodyLexer.new(header.body, start_line: header.body_start_line).tokens
  reject_unsupported_tokens(tokens)
  @duration_resolver = DurationResolver.new(header.unit_note_length)
  interpret(tokens)
end

#chord_snippet(token) ⇒ Object (private)



209
210
211
212
213
214
# File 'lib/head_music/notation/abc/parser.rb', line 209

def chord_snippet(token)
  inner = token.notes.map do |note|
    "#{note.accidental}#{note.letter}#{note.octave_marks}#{note.length}"
  end.join
  "[#{inner}]"
end

#clear_passes_if_over(state, style) ⇒ Object (private)



420
421
422
423
424
425
# File 'lib/head_music/notation/abc/parser.rb', line 420

def clear_passes_if_over(state, style)
  return unless REPEAT_ENDING_STYLES.include?(style) || SECTION_ENDING_STYLES.include?(style)

  state.active_passes = nil
  state.volta_start_bar = nil
end

#compositionObject



29
30
31
# File 'lib/head_music/notation/abc/parser.rb', line 29

def composition
  @composition ||= build_composition
end

#current_stateObject (private)

Body music before any V: line falls into a default unnamed voice.



149
150
151
# File 'lib/head_music/notation/abc/parser.rb', line 149

def current_state
  @current_state ||= voice_state(nil)
end

#defer_placement(state, pitches, length, inner_scale = Rational(1)) ⇒ Object (private)



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/head_music/notation/abc/parser.rb', line 216

def defer_placement(state, pitches, length, inner_scale = Rational(1))
  scale = (state.awaiting_scale || Rational(1)) * inner_scale
  state.awaiting_scale = nil
  return tie_onto_pending(state, pitches, length, scale) if state.tie_open

  flush_pending_note(state)
  flag = if state.beam_break_pending
    true
  else
    (state.beam_last_was_note ? false : nil)
  end
  state.beam_break_pending = false
  state.beam_last_was_note = true
  state.pending_note = PendingNote.new(pitches: pitches, length: length, scale: scale, beam_break: flag)
end

#ensure_input_presentObject (private)

Raises:



80
81
82
83
84
# File 'lib/head_music/notation/abc/parser.rb', line 80

def ensure_input_present
  return unless @abc_string.to_s.strip.empty?

  raise ParseError, "ABC input is blank"
end

#ensure_not_awaiting_note(token, state: current_state) ⇒ Object (private)

Raises:



361
362
363
364
365
366
367
368
# File 'lib/head_music/notation/abc/parser.rb', line 361

def ensure_not_awaiting_note(token, state: current_state)
  return unless state.awaiting_scale

  raise ParseError.new(
    "Broken rhythm must be followed by a note",
    line_number: token&.line || state.broken_line
  )
end

#ensure_tie_pitches_match(state, pending, pitches) ⇒ Object (private)

Raises:



267
268
269
270
271
272
273
274
# File 'lib/head_music/notation/abc/parser.rb', line 267

def ensure_tie_pitches_match(state, pending, pitches)
  return if pending.pitches.sort == pitches.sort

  raise ParseError.new(
    "A tie must connect two notes of the same pitch",
    line_number: state.tie_line, snippet: "-"
  )
end

#ensure_unique_chord_pitches(pitches, token) ⇒ Object (private)

Raises:



185
186
187
188
189
190
191
192
# File 'lib/head_music/notation/abc/parser.rb', line 185

def ensure_unique_chord_pitches(pitches, token)
  return if pitches.uniq.length == pitches.length

  raise ParseError.new(
    "Chord pitches must be unique",
    line_number: token.line, snippet: chord_snippet(token)
  )
end

#finishObject (private)



352
353
354
355
356
357
358
359
# File 'lib/head_music/notation/abc/parser.rb', line 352

def finish
  @voice_states.each_value do |state|
    ensure_not_awaiting_note(nil, state: state)
    reject_open_tie(state, nil, "A tie must be followed by a note")
    flush_pending_note(state)
    tag_completed_bar(state)
  end
end

#flush_pending_note(state) ⇒ Object (private)



370
371
372
373
374
375
376
377
# File 'lib/head_music/notation/abc/parser.rb', line 370

def flush_pending_note(state)
  pending = state.pending_note
  return unless pending

  state.pending_note = nil
  placement = state.voice.place(state.voice.next_position, pending_rhythmic_value(pending), pending.pitches)
  placement.beam_break_before = pending.beam_break
end

#handle(token) ⇒ Object (private)



153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/head_music/notation/abc/parser.rb', line 153

def handle(token)
  case token.type
  when :note then handle_note(token)
  when :chord then handle_chord(token)
  when :rest then handle_rest(token)
  when :tie then handle_tie(token)
  when :broken_rhythm then handle_broken_rhythm(token)
  when :bar_line then handle_bar_line(token)
  when :volta then handle_volta(token)
  when :voice_change then handle_voice_change(token)
  when :beam_break then handle_beam_break(token)
  end
end

#handle_bar_line(token) ⇒ Object (private)



316
317
318
319
320
321
322
323
324
325
326
# File 'lib/head_music/notation/abc/parser.rb', line 316

def handle_bar_line(token)
  ensure_not_awaiting_note(token)
  state = current_state
  reject_open_tie(state, token.line, "Ties across barlines are not yet supported")
  flush_pending_note(state)
  reset_beam_adjacency(state)
  tag_completed_bar(state)
  apply_repeat_flags(state, token.style)
  clear_passes_if_over(state, token.style)
  state.pitch_builder.start_new_bar
end

#handle_beam_break(_token) ⇒ Object (private)

The lexer only emits :beam_break after a music token, so a voice state already exists; the flag is consumed by the next deferred note.



234
235
236
# File 'lib/head_music/notation/abc/parser.rb', line 234

def handle_beam_break(_token)
  current_state.beam_break_pending = true
end

#handle_broken_rhythm(token) ⇒ Object (private)



301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/head_music/notation/abc/parser.rb', line 301

def handle_broken_rhythm(token)
  state = current_state
  reject_open_tie(state, token.line, "A tie must be followed by a note")
  if state.awaiting_scale || state.pending_note.nil?
    raise ParseError.new(
      "Broken rhythm must appear between two notes",
      line_number: token.line, snippet: token.direction.to_s
    )
  end
  left_scale, right_scale = BROKEN_RHYTHM_SCALES.fetch(token.direction)
  state.pending_note = state.pending_note.with(scale: state.pending_note.scale * left_scale)
  state.awaiting_scale = right_scale
  state.broken_line = token.line
end

#handle_chord(token) ⇒ Object (private)

Chord pitches resolve in bracket order, so an explicit accidental inside a chord persists for the rest of the bar like any other.



175
176
177
178
179
180
181
182
183
# File 'lib/head_music/notation/abc/parser.rb', line 175

def handle_chord(token)
  state = current_state
  pitches = token.notes.map do |note|
    state.pitch_builder.pitch(note.letter, note.octave_marks, note.accidental)
  end
  ensure_unique_chord_pitches(pitches, token)
  inner_length = uniform_chord_length(token)
  defer_placement(state, pitches, token.length, inner_length)
end

#handle_note(token) ⇒ Object (private)



167
168
169
170
171
# File 'lib/head_music/notation/abc/parser.rb', line 167

def handle_note(token)
  state = current_state
  pitch = state.pitch_builder.pitch(token.letter, token.octave_marks, token.accidental)
  defer_placement(state, [pitch], token.length)
end

#handle_rest(token) ⇒ Object (private)



276
277
278
279
280
281
282
283
# File 'lib/head_music/notation/abc/parser.rb', line 276

def handle_rest(token)
  ensure_not_awaiting_note(token)
  state = current_state
  reject_open_tie(state, token.line, "A tie must be followed by a note")
  flush_pending_note(state)
  reset_beam_adjacency(state)
  place(state, token.length, nil)
end

#handle_tie(token) ⇒ Object (private)

A tie (-) after a note or chord fuses it to the next note of the same pitch. The left note stays pending; the tie is only closed once its right note arrives.



241
242
243
244
245
246
247
248
249
250
# File 'lib/head_music/notation/abc/parser.rb', line 241

def handle_tie(token)
  state = current_state
  if state.awaiting_scale || state.pending_note.nil?
    raise ParseError.new(
      "A tie must follow a note", line_number: token.line, snippet: "-"
    )
  end
  state.tie_open = true
  state.tie_line = token.line
end

#handle_voice_change(token) ⇒ Object (private)



341
342
343
344
345
346
347
348
349
350
# File 'lib/head_music/notation/abc/parser.rb', line 341

def handle_voice_change(token)
  # Guarded so a leading V: line doesn't force a default voice into existence.
  if @current_state
    ensure_not_awaiting_note(token, state: @current_state)
    reject_open_tie(@current_state, token.line, "A tie must be followed by a note")
    flush_pending_note(@current_state)
    reset_beam_adjacency(@current_state)
  end
  @current_state = voice_state(token.voice_id)
end

#handle_volta(token) ⇒ Object (private)



328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/head_music/notation/abc/parser.rb', line 328

def handle_volta(token)
  ensure_not_awaiting_note(token)
  if token.passes.empty?
    raise ParseError.new("Volta has no passes", line_number: token.line)
  end
  state = current_state
  reject_open_tie(state, token.line, "A tie must be followed by a note")
  flush_pending_note(state)
  reset_beam_adjacency(state)
  state.active_passes = token.passes
  state.volta_start_bar = state.entered_bar_number
end

#interpret(tokens) ⇒ Object (private)



117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/head_music/notation/abc/parser.rb', line 117

def interpret(tokens)
  @building = HeadMusic::Content::Composition.new(
    name: header.title,
    key_signature: header.key_signature,
    meter: header.meter,
    composer: header.composer,
    origin: header.origin,
    comments: header.annotations
  )
  setup_voices(tokens)
  tokens.each { |token| handle(token) }
  finish
  @building
end

#pending_rhythmic_value(pending) ⇒ Object (private)

A pending note’s own value, with any tied prefix appended ahead of it so the whole tie chain renders as one sounding note.



381
382
383
384
# File 'lib/head_music/notation/abc/parser.rb', line 381

def pending_rhythmic_value(pending)
  own = duration_resolver.rhythmic_value(pending.length, scale: pending.scale)
  pending.tied_prefix ? append_tied(pending.tied_prefix, own) : own
end

#place(state, length, pitches, scale: Rational(1)) ⇒ Object (private)



394
395
396
397
# File 'lib/head_music/notation/abc/parser.rb', line 394

def place(state, length, pitches, scale: Rational(1))
  rhythmic_value = duration_resolver.rhythmic_value(length, scale: scale)
  state.voice.place(state.voice.next_position, rhythmic_value, pitches)
end

#reject_content_after_tuneObject (private)

The lexer treats a blank line as the end of the tune, so anything after it would be silently dropped — most likely another tune.

Raises:



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/head_music/notation/abc/parser.rb', line 88

def reject_content_after_tune
  lines = header.body.lines
  blank_index = lines.find_index { |line| line.strip.empty? }
  return unless blank_index

  extra_lines = lines[(blank_index + 1)..]
  extra_index = extra_lines.find_index do |line|
    stripped = line.strip
    !stripped.empty? && !stripped.start_with?("%")
  end
  return unless extra_index

  raise ParseError.new(
    "Content after the tune body; parse a book of tunes with ABC.parse_book",
    line_number: header.body_start_line + blank_index + 1 + extra_index,
    snippet: extra_lines[extra_index].strip[0, BodyLexer::SNIPPET_LENGTH]
  )
end

#reject_open_tie(state, line, message) ⇒ Object (private)

A tie left open by a non-note terminator can never close, so each terminator rejects it. A bar line gets its own message: an author tie across a barline is a real, but not-yet-supported, request.

Raises:



295
296
297
298
299
# File 'lib/head_music/notation/abc/parser.rb', line 295

def reject_open_tie(state, line, message)
  return unless state&.tie_open

  raise ParseError.new(message, line_number: line || state.tie_line, snippet: "-")
end

#reject_unsupported_tokens(tokens) ⇒ Object (private)



107
108
109
110
111
112
113
114
115
# File 'lib/head_music/notation/abc/parser.rb', line 107

def reject_unsupported_tokens(tokens)
  token = tokens.find { |candidate| candidate.type == :unsupported }
  return unless token

  raise UnsupportedFeatureError.new(
    "Unsupported ABC feature #{token.lexeme.inspect}",
    line_number: token.line, snippet: token.lexeme
  )
end

#reset_beam_adjacency(state) ⇒ Object (private)

After a rest, bar line, volta, or voice change, a following note must not be marked as beamed to whatever preceded the boundary.



287
288
289
290
# File 'lib/head_music/notation/abc/parser.rb', line 287

def reset_beam_adjacency(state)
  state.beam_last_was_note = false
  state.beam_break_pending = false
end

#setup_voices(tokens) ⇒ Object (private)



132
133
134
135
136
137
138
139
# File 'lib/head_music/notation/abc/parser.rb', line 132

def setup_voices(tokens)
  @voice_states = {}
  header.voice_ids.each { |voice_id| voice_state(voice_id) }
  if @voice_states.empty? && tokens.none? { |token| token.type == :voice_change }
    voice_state(nil)
  end
  @current_state = @voice_states.values.first
end

#tag_completed_bar(state) ⇒ Object (private)

A volta covers every bar from its opening bracket through the bar line that ends it, so each completed bar in that span gets tagged.



411
412
413
414
415
416
417
418
# File 'lib/head_music/notation/abc/parser.rb', line 411

def tag_completed_bar(state)
  return unless state.active_passes

  completed = state.completed_bar_number
  return unless completed && completed >= state.volta_start_bar

  bar(completed).plays_on_passes = state.active_passes
end

#tie_onto_pending(state, pitches, length, scale) ⇒ Object (private)

Closes an open tie: the pending note becomes the new note’s tied prefix, so the pair (and any longer chain) resolves to a single placement whose rhythmic value carries the author’s chosen split.



255
256
257
258
259
260
261
262
263
264
265
# File 'lib/head_music/notation/abc/parser.rb', line 255

def tie_onto_pending(state, pitches, length, scale)
  pending = state.pending_note
  ensure_tie_pitches_match(state, pending, pitches)
  prefix = pending_rhythmic_value(pending)
  state.tie_open = false
  state.tie_line = nil
  state.pending_note = PendingNote.new(
    pitches: pitches, length: length, scale: scale, tied_prefix: prefix,
    beam_break: pending.beam_break
  )
end

#uniform_chord_length(token) ⇒ Object (private)

ABC 2.1 sec. 4.17 allows per-note lengths only when they agree; the shared inner length then multiplies with any outer length. Unequal lengths (whose ABC meaning is “the duration of the first note”) would need silent reinterpretation to fit one rhythmic value, so we reject.

Raises:



198
199
200
201
202
203
204
205
206
207
# File 'lib/head_music/notation/abc/parser.rb', line 198

def uniform_chord_length(token)
  fractions = token.notes.map { |note| duration_resolver.length_fraction(note.length) }
  return fractions.first if fractions.uniq.length == 1

  raise ParseError.new(
    'Chord notes must share one length; write it after the bracket ("[CEG]2") ' \
    'or repeat it on every note ("[C2E2G2]")',
    line_number: token.line, snippet: chord_snippet(token)
  )
end

#voice_state(role) ⇒ Object (private)



141
142
143
144
145
146
# File 'lib/head_music/notation/abc/parser.rb', line 141

def voice_state(role)
  @voice_states[role] ||= VoiceState.new(
    @building.add_voice(role: role),
    PitchBuilder.new(header.key_signature)
  )
end