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

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



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

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)



323
324
325
# File 'lib/head_music/notation/abc/parser.rb', line 323

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

#build_compositionObject (private)



63
64
65
66
67
68
69
70
71
# File 'lib/head_music/notation/abc/parser.rb', line 63

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)



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

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)



316
317
318
319
320
321
# File 'lib/head_music/notation/abc/parser.rb', line 316

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.



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

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

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



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

def defer_placement(state, pitches, length, inner_scale = Rational(1))
  scale = (state.awaiting_scale || Rational(1)) * inner_scale
  state.awaiting_scale = nil
  flush_pending_note(state)
  state.pending_note = PendingNote.new(pitches: pitches, length: length, scale: scale)
end

#ensure_input_presentObject (private)

Raises:



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

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:



273
274
275
276
277
278
279
280
# File 'lib/head_music/notation/abc/parser.rb', line 273

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_unique_chord_pitches(pitches, token) ⇒ Object (private)

Raises:



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

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)



265
266
267
268
269
270
271
# File 'lib/head_music/notation/abc/parser.rb', line 265

def finish
  @voice_states.each_value do |state|
    ensure_not_awaiting_note(nil, state: state)
    flush_pending_note(state)
    tag_completed_bar(state)
  end
end

#flush_pending_note(state) ⇒ Object (private)



282
283
284
285
286
287
288
# File 'lib/head_music/notation/abc/parser.rb', line 282

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

  state.pending_note = nil
  place(state, pending.length, pending.pitches, scale: pending.scale)
end

#handle(token) ⇒ Object (private)



146
147
148
149
150
151
152
153
154
155
156
# File 'lib/head_music/notation/abc/parser.rb', line 146

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 :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)
  end
end

#handle_bar_line(token) ⇒ Object (private)



235
236
237
238
239
240
241
242
243
# File 'lib/head_music/notation/abc/parser.rb', line 235

def handle_bar_line(token)
  ensure_not_awaiting_note(token)
  state = current_state
  flush_pending_note(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_broken_rhythm(token) ⇒ Object (private)



221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/head_music/notation/abc/parser.rb', line 221

def handle_broken_rhythm(token)
  state = current_state
  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.



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

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)



158
159
160
161
162
# File 'lib/head_music/notation/abc/parser.rb', line 158

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)



214
215
216
217
218
219
# File 'lib/head_music/notation/abc/parser.rb', line 214

def handle_rest(token)
  ensure_not_awaiting_note(token)
  state = current_state
  flush_pending_note(state)
  place(state, token.length, nil)
end

#handle_voice_change(token) ⇒ Object (private)



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

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)
    flush_pending_note(@current_state)
  end
  @current_state = voice_state(token.voice_id)
end

#handle_volta(token) ⇒ Object (private)



245
246
247
248
249
250
251
252
253
254
# File 'lib/head_music/notation/abc/parser.rb', line 245

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
  flush_pending_note(state)
  state.active_passes = token.passes
  state.volta_start_bar = state.entered_bar_number
end

#interpret(tokens) ⇒ Object (private)



110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/head_music/notation/abc/parser.rb', line 110

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

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



290
291
292
293
# File 'lib/head_music/notation/abc/parser.rb', line 290

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:



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/head_music/notation/abc/parser.rb', line 81

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_unsupported_tokens(tokens) ⇒ Object (private)



100
101
102
103
104
105
106
107
108
# File 'lib/head_music/notation/abc/parser.rb', line 100

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

#setup_voices(tokens) ⇒ Object (private)



125
126
127
128
129
130
131
132
# File 'lib/head_music/notation/abc/parser.rb', line 125

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.



307
308
309
310
311
312
313
314
# File 'lib/head_music/notation/abc/parser.rb', line 307

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

#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:



189
190
191
192
193
194
195
196
197
198
# File 'lib/head_music/notation/abc/parser.rb', line 189

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)



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

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