Class: Rhales::HandlebarsParser

Inherits:
Object
  • Object
show all
Defined in:
lib/rhales/parsers/handlebars_parser.rb

Overview

Hand-rolled recursive descent parser for Handlebars template syntax

This parser implements Handlebars parsing rules in Ruby code and produces an Abstract Syntax Tree (AST) for template processing. It handles:

  • Variable expressions: {variable}, {{raw}}
  • Block expressions: {{#if}{else}{/if}, {{#each}{/each}
  • Partials: partial_name}
  • Proper nesting and error reporting
  • Whitespace control (future)

Note: This class is a parser implementation, not a formal grammar definition. A formal grammar would be written in BNF/EBNF notation, while this class contains the actual parsing logic written in Ruby.

AST Node Types: - :template - Root template node - :text - Plain text content - :variable_expression - {variable} or {{variable}} - :if_block - {{#if}…{else}…{/if} - :unless_block - {{#unless}…{/unless} - :each_block - {{#each}…{/each} - :partial_expression - partial}

Defined Under Namespace

Classes: Location, Node, ParseError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ HandlebarsParser

Returns a new instance of HandlebarsParser.



66
67
68
69
70
71
72
# File 'lib/rhales/parsers/handlebars_parser.rb', line 66

def initialize(content)
  @content  = content
  @position = 0
  @line     = 1
  @column   = 1
  @ast      = nil
end

Instance Attribute Details

#astObject (readonly)

Returns the value of attribute ast.



64
65
66
# File 'lib/rhales/parsers/handlebars_parser.rb', line 64

def ast
  @ast
end

#contentObject (readonly)

Returns the value of attribute content.



64
65
66
# File 'lib/rhales/parsers/handlebars_parser.rb', line 64

def content
  @content
end

Instance Method Details

#advanceObject (private)



692
693
694
695
696
697
698
699
700
# File 'lib/rhales/parsers/handlebars_parser.rb', line 692

def advance
  if current_char == "\n"
    @line  += 1
    @column = 1
  else
    @column += 1
  end
  @position += 1
end

#at_end?Boolean (private)

Returns:

  • (Boolean)


702
703
704
# File 'lib/rhales/parsers/handlebars_parser.rb', line 702

def at_end?
  @position >= @content.length
end

#blocksObject



91
92
93
94
95
# File 'lib/rhales/parsers/handlebars_parser.rb', line 91

def blocks
  return [] unless @ast

  collect_blocks(@ast)
end

#collect_blocks(node) ⇒ Object (private)



646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'lib/rhales/parsers/handlebars_parser.rb', line 646

def collect_blocks(node)
  blocks = []

  case node.type
  when :if_block, :unless_block, :each_block
    blocks << node
    # Also collect nested blocks
    if node.type == :if_block
      blocks.concat(node.value[:if_content].flat_map { |child| collect_blocks(child) })
      blocks.concat(node.value[:else_content].flat_map { |child| collect_blocks(child) })
    else
      blocks.concat(node.value[:content].flat_map { |child| collect_blocks(child) })
    end
  else
    blocks.concat(node.children.flat_map { |child| collect_blocks(child) })
  end

  blocks
end

#collect_partials(node) ⇒ Object (private)



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/rhales/parsers/handlebars_parser.rb', line 628

def collect_partials(node)
  partials = []

  case node.type
  when :partial_expression
    partials << node.value[:name]
  when :if_block
    partials.concat(node.value[:if_content].flat_map { |child| collect_partials(child) })
    partials.concat(node.value[:else_content].flat_map { |child| collect_partials(child) })
  when :unless_block, :each_block
    partials.concat(node.value[:content].flat_map { |child| collect_partials(child) })
  else
    partials.concat(node.children.flat_map { |child| collect_partials(child) })
  end

  partials.uniq
end

#collect_variables(node) ⇒ Object (private)



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/rhales/parsers/handlebars_parser.rb', line 605

def collect_variables(node)
  variables = []

  case node.type
  when :variable_expression
    variables << node.value[:name]
  when :if_block
    variables << node.value[:condition]
    variables.concat(node.value[:if_content].flat_map { |child| collect_variables(child) })
    variables.concat(node.value[:else_content].flat_map { |child| collect_variables(child) })
  when :unless_block
    variables << node.value[:condition]
    variables.concat(node.value[:content].flat_map { |child| collect_variables(child) })
  when :each_block
    variables << node.value[:items]
    variables.concat(node.value[:content].flat_map { |child| collect_variables(child) })
  else
    variables.concat(node.children.flat_map { |child| collect_variables(child) })
  end

  variables.uniq
end

#consume(expected) ⇒ Object (private)



683
684
685
686
687
688
689
690
# File 'lib/rhales/parsers/handlebars_parser.rb', line 683

def consume(expected)
  if peek_string?(expected)
    expected.length.times { advance }
    true
  else
    false
  end
end

#create_each_block(items_expression, start_location) ⇒ Object (private)



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/rhales/parsers/handlebars_parser.rb', line 396

def create_each_block(items_expression, start_location)
  # Parse the each block content
  content = []
  depth   = 1

  while !at_end? && depth > 0
    if current_char == '{' && peek_char == '{'
      expr_start = current_position
      consume('{{')

      raw = false
      if current_char == '{'
        raw = true
        advance
      end

      skip_whitespace
      expr_content = parse_expression_content(raw)
      skip_whitespace

      if raw
        consume('}}}') || parse_error("Expected '}}}'")
      else
        consume('}}') || parse_error("Expected '}}'")
      end

      expr_end      = current_position
      expr_location = create_location(expr_start, expr_end)

      case expr_content
      when /^#if\s+(.+)$/, /^#unless\s+(.+)$/, /^#each\s+(.+)$/
        depth += 1
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when %r{^/each$}
        depth -= 1
        break if depth == 0

        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )

      when %r{^/if$}, %r{^/unless$}
        depth -= 1
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when 'else'
        # This else belongs to a nested if block, not this each block
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      else
        content << create_expression_node(expr_content, raw, expr_location)
      end
    else
      text_content = parse_text_until_handlebars
      content << create_text_node(text_content) unless text_content.empty?
    end
  end

  if depth > 0
    parse_error('Missing closing tag for {{#each}}')
  end

  processed_content = post_process_content(content)

  Node.new(:each_block, start_location, value: {
    items: items_expression,
    content: processed_content,
  }
  )
end

#create_expression_node(content, raw, location) ⇒ Object (private)



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/rhales/parsers/handlebars_parser.rb', line 174

def create_expression_node(content, raw, location)
  case content
  when /^#if\s+(.+)$/
    create_if_block(Regexp.last_match(1).strip, location)
  when /^#unless\s+(.+)$/
    create_unless_block(Regexp.last_match(1).strip, location)
  when /^#each\s+(.+)$/
    create_each_block(Regexp.last_match(1).strip, location)
  when /^>\s*(.+)$/
    create_partial_node(Regexp.last_match(1).strip, location)
  when %r{^/(.+)$}
    # This is a closing tag, should be handled by block parsing
    parse_error("Unexpected closing tag: #{content}")
  when 'else'
    # This should be handled by block parsing
    parse_error("Unexpected 'else' outside of block")
  else
    # Variable expression
    create_variable_node(content, raw, location)
  end
end

#create_if_block(condition, start_location) ⇒ Object (private)



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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/rhales/parsers/handlebars_parser.rb', line 196

def create_if_block(condition, start_location)
  # Parse the if block content
  if_content      = []
  else_content    = []
  current_content = if_content
  depth           = 1

  while !at_end? && depth > 0
    if current_char == '{' && peek_char == '{'
      expr_start = current_position
      consume('{{')

      # Check for triple braces
      raw = false
      if current_char == '{'
        raw = true
        advance
      end

      skip_whitespace
      expr_content = parse_expression_content(raw)
      skip_whitespace

      if raw
        consume('}}}') || parse_error("Expected '}}}'")
      else
        consume('}}') || parse_error("Expected '}}'")
      end

      expr_end      = current_position
      expr_location = create_location(expr_start, expr_end)

      case expr_content
      when /^#if\s+(.+)$/
        depth += 1
        # Add as variable expression, will be parsed properly later
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when /^#unless\s+(.+)$/
        depth += 1
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when /^#each\s+(.+)$/
        depth += 1
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when %r{^/if$}
        depth -= 1
        break if depth == 0

        # Found the matching closing tag

        # This is a nested closing tag
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )

      when %r{^/unless$}
        depth -= 1
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when %r{^/each$}
        depth -= 1
        current_content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when 'else'
        if depth == 1
          current_content = else_content
        else
          current_content << Node.new(:variable_expression, expr_location, value: {
            name: expr_content,
            raw: raw,
          }
          )
        end
      else
        current_content << create_expression_node(expr_content, raw, expr_location)
      end
    else
      text_content = parse_text_until_handlebars
      current_content << create_text_node(text_content) unless text_content.empty?
    end
  end

  if depth > 0
    parse_error('Missing closing tag for {{#if}}')
  end

  # Now post-process the content to handle nested blocks
  processed_if_content   = post_process_content(if_content)
  processed_else_content = post_process_content(else_content)

  Node.new(:if_block, start_location, value: {
    condition: condition,
    if_content: processed_if_content,
    else_content: processed_else_content,
  }
  )
end

#create_location(start_pos, end_pos) ⇒ Object (private)



714
715
716
717
718
719
720
721
722
723
# File 'lib/rhales/parsers/handlebars_parser.rb', line 714

def create_location(start_pos, end_pos)
  Location.new(
    start_line: start_pos[:line],
    start_column: start_pos[:column],
    end_line: end_pos[:line],
    end_column: end_pos[:column],
    start_offset: start_pos[:offset],
    end_offset: end_pos[:offset],
  )
end

#create_partial_node(name, location) ⇒ Object (private)



487
488
489
490
491
492
# File 'lib/rhales/parsers/handlebars_parser.rb', line 487

def create_partial_node(name, location)
  Node.new(:partial_expression, location, value: {
    name: name,
  }
  )
end

#create_text_node(text) ⇒ Object (private)



494
495
496
497
498
# File 'lib/rhales/parsers/handlebars_parser.rb', line 494

def create_text_node(text)
  pos      = current_position
  location = create_location(pos, pos)
  Node.new(:text, location, value: text)
end

#create_unless_block(condition, start_location) ⇒ Object (private)



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/rhales/parsers/handlebars_parser.rb', line 313

def create_unless_block(condition, start_location)
  # Parse the unless block content
  content = []
  depth   = 1

  while !at_end? && depth > 0
    if current_char == '{' && peek_char == '{'
      expr_start = current_position
      consume('{{')

      raw = false
      if current_char == '{'
        raw = true
        advance
      end

      skip_whitespace
      expr_content = parse_expression_content(raw)
      skip_whitespace

      if raw
        consume('}}}') || parse_error("Expected '}}}'")
      else
        consume('}}') || parse_error("Expected '}}'")
      end

      expr_end      = current_position
      expr_location = create_location(expr_start, expr_end)

      case expr_content
      when /^#if\s+(.+)$/, /^#unless\s+(.+)$/, /^#each\s+(.+)$/
        depth += 1
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when %r{^/unless$}
        depth -= 1
        break if depth == 0

        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )

      when %r{^/if$}, %r{^/each$}
        depth -= 1
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      when 'else'
        # This else belongs to a nested if block, not this unless block
        content << Node.new(:variable_expression, expr_location, value: {
          name: expr_content,
          raw: raw,
        }
        )
      else
        content << create_expression_node(expr_content, raw, expr_location)
      end
    else
      text_content = parse_text_until_handlebars
      content << create_text_node(text_content) unless text_content.empty?
    end
  end

  if depth > 0
    parse_error('Missing closing tag for {{#unless}}')
  end

  processed_content = post_process_content(content)

  Node.new(:unless_block, start_location, value: {
    condition: condition,
    content: processed_content,
  }
  )
end

#create_variable_node(name, raw, location) ⇒ Object (private)



479
480
481
482
483
484
485
# File 'lib/rhales/parsers/handlebars_parser.rb', line 479

def create_variable_node(name, raw, location)
  Node.new(:variable_expression, location, value: {
    name: name,
    raw: raw,
  }
  )
end

#current_charObject (private)

Utility methods



667
668
669
670
671
# File 'lib/rhales/parsers/handlebars_parser.rb', line 667

def current_char
  return "\0" if at_end?

  @content[@position]
end

#current_positionObject (private)



710
711
712
# File 'lib/rhales/parsers/handlebars_parser.rb', line 710

def current_position
  { line: @line, column: @column, offset: @position }
end

#extract_block_content_from_array(content, start_index, block_type) ⇒ Object (private)



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/rhales/parsers/handlebars_parser.rb', line 554

def extract_block_content_from_array(content, start_index, block_type)
  block_content   = []
  else_content    = []
  current_content = block_content
  depth           = 1
  i               = start_index

  while i < content.length && depth > 0
    node = content[i]

    if node.type == :variable_expression
      case node.value[:name]
      when /^##{block_type}\s+/
        depth += 1
        current_content << node
      when %r{^/#{block_type}$}
        depth -= 1
        return [block_content, else_content, i + 1] if depth == 0

        current_content << node

      when 'else'
        if block_type == 'if' && depth == 1
          current_content = else_content
        else
          current_content << node
        end
      else
        current_content << node
      end
    else
      current_content << node
    end

    i += 1
  end

  [block_content, else_content, i]
end

#parse!Object



74
75
76
77
# File 'lib/rhales/parsers/handlebars_parser.rb', line 74

def parse!
  @ast = parse_template
  self
end

#parse_error(message) ⇒ Object (private)

Raises:



725
726
727
# File 'lib/rhales/parsers/handlebars_parser.rb', line 725

def parse_error(message)
  raise ParseError.new(message, line: @line, column: @column, offset: @position)
end

#parse_expression_content(raw) ⇒ Object (private)



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/rhales/parsers/handlebars_parser.rb', line 149

def parse_expression_content(raw)
  chars          = []
  closing_braces = raw ? '}}}' : '}}'
  brace_count    = 0

  until at_end?
    if current_char == '}' && peek_string?(closing_braces)
      break
    elsif current_char == '{' && peek_char == '{'
      # Handle nested braces in content
      brace_count += 1
    elsif current_char == '}' && peek_char == '}'
      brace_count -= 1
      if brace_count < 0
        break
      end
    end

    chars << current_char
    advance
  end

  chars.join.strip
end

#parse_handlebars_expressionObject (private)



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
# File 'lib/rhales/parsers/handlebars_parser.rb', line 117

def parse_handlebars_expression
  start_pos = current_position

  consume('{{') || parse_error("Expected '{{'")

  # Check for triple braces (raw output)
  raw = false
  if current_char == '{'
    raw = true
    advance
  end

  skip_whitespace

  # Parse expression content
  expression_content = parse_expression_content(raw)
  skip_whitespace

  # Consume closing braces
  if raw
    consume('}}}') || parse_error("Expected '}}}'")
  else
    consume('}}') || parse_error("Expected '}}'")
  end

  end_pos  = current_position
  location = create_location(start_pos, end_pos)

  # Determine expression type and create appropriate node
  create_expression_node(expression_content, raw, location)
end

#parse_templateObject (private)



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/rhales/parsers/handlebars_parser.rb', line 99

def parse_template
  start_pos = current_position
  children  = []

  until at_end?
    if current_char == '{' && peek_char == '{'
      children << parse_handlebars_expression
    else
      text_content = parse_text_until_handlebars
      children << create_text_node(text_content) unless text_content.empty?
    end
  end

  end_pos  = current_position
  location = create_location(start_pos, end_pos)
  Node.new(:template, location, children: children)
end

#parse_text_until_handlebarsObject (private)



594
595
596
597
598
599
600
601
602
603
# File 'lib/rhales/parsers/handlebars_parser.rb', line 594

def parse_text_until_handlebars
  chars = []

  while !at_end? && !(current_char == '{' && peek_char == '{')
    chars << current_char
    advance
  end

  chars.join
end

#partialsObject



85
86
87
88
89
# File 'lib/rhales/parsers/handlebars_parser.rb', line 85

def partials
  return [] unless @ast

  collect_partials(@ast)
end

#peek_charObject (private)



673
674
675
676
677
# File 'lib/rhales/parsers/handlebars_parser.rb', line 673

def peek_char
  return "\0" if @position + 1 >= @content.length

  @content[@position + 1]
end

#peek_string?(string) ⇒ Boolean (private)

Returns:

  • (Boolean)


679
680
681
# File 'lib/rhales/parsers/handlebars_parser.rb', line 679

def peek_string?(string)
  @content[@position, string.length] == string
end

#post_process_content(content) ⇒ Object (private)



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/rhales/parsers/handlebars_parser.rb', line 500

def post_process_content(content)
  # Convert variable expressions that are actually block expressions
  processed = []
  i         = 0

  while i < content.length
    node = content[i]

    if node.type == :variable_expression
      case node.value[:name]
      when /^#if\s+(.+)$/
        condition                           = Regexp.last_match(1).strip
        if_content, else_content, end_index = extract_block_content_from_array(content, i + 1, 'if')
        processed << Node.new(:if_block, node.location, value: {
          condition: condition,
          if_content: post_process_content(if_content),
          else_content: post_process_content(else_content),
        }
        )
        i                                   = end_index
      when /^#unless\s+(.+)$/
        condition                   = Regexp.last_match(1).strip
        block_content, _, end_index = extract_block_content_from_array(content, i + 1, 'unless')
        processed << Node.new(:unless_block, node.location, value: {
          condition: condition,
          content: post_process_content(block_content),
        }
        )
        i                           = end_index
      when /^#each\s+(.+)$/
        items                       = Regexp.last_match(1).strip
        block_content, _, end_index = extract_block_content_from_array(content, i + 1, 'each')
        processed << Node.new(:each_block, node.location, value: {
          items: items,
          content: post_process_content(block_content),
        }
        )
        i                           = end_index
      when %r{^/\w+$}, 'else'
        # Skip closing tags and else - they're handled by block extraction
        i += 1
      else
        processed << node
        i += 1
      end
    else
      processed << node
      i += 1
    end
  end

  processed
end

#skip_whitespaceObject (private)



706
707
708
# File 'lib/rhales/parsers/handlebars_parser.rb', line 706

def skip_whitespace
  advance while !at_end? && current_char.match?(/\s/)
end

#variablesObject



79
80
81
82
83
# File 'lib/rhales/parsers/handlebars_parser.rb', line 79

def variables
  return [] unless @ast

  collect_variables(@ast)
end