Class: Mayu::Resources::Transformers::Haml::Transformer

Inherits:
SyntaxTree::Haml::Visitor
  • Object
show all
Defined in:
lib/mayu/resources/transformers/haml.rb

Defined Under Namespace

Classes: Result

Constant Summary collapse

IN_RE =
/\A\s*in\s+/

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Transformer

Returns a new instance of Transformer.



424
425
426
427
428
# File 'lib/mayu/resources/transformers/haml.rb', line 424

def initialize(options)
  @options = options
  @builder = RubyBuilder.new(options)
  @state = {}
end

Instance Method Details

#append_whitespace(children) ⇒ Object



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# File 'lib/mayu/resources/transformers/haml.rb', line 683

def append_whitespace(children)
  [*children, nil].each_cons(2)
    .flat_map do |curr, succ|
      if succ in {
           type: :tag, value: { nuke_inner_whitespace: true }
         }
        if curr in { type: :plain, value: { text: } }
          curr.value = { text: "#{text} " }
        else
          next curr, make_space(curr)
        end
      end

      curr
    end
end

#fix_syntax_by_adding_missing_pairs(source) ⇒ Object



830
831
832
833
834
835
# File 'lib/mayu/resources/transformers/haml.rb', line 830

def fix_syntax_by_adding_missing_pairs(source)
  left_right = SyntaxSuggest::LeftRightLexCount.new
  SyntaxSuggest::LexAll.new(source:).each { left_right.count_lex(_1) }
  left_right.missing
  [source, *left_right.missing].join("\n")
end

#group_condition(type, chunk) ⇒ Object



638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/mayu/resources/transformers/haml.rb', line 638

def group_condition(type, chunk)
  parse_ruby(join_ruby_script_nodes(chunk), fix: true) => [statement]

  visitor = MutationVisitor.new

  chunk.shift if type == :case

  visitor.mutate("Statements") do |node|
    top = chunk.shift

    if node.child_nodes in [SyntaxTree::VoidStmt]
      @builder.Statements(visit_tag_children(top.children))
    else
      unless top.children.empty?
        raise "Line #{top.line} should not have children."
      end

      node
    end
  end

  @builder.ruby_script([statement.accept(visitor)])
end

#group_control_statements(children) ⇒ Object



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/mayu/resources/transformers/haml.rb', line 575

def group_control_statements(children)
  children
    .chunk_while do |a, b|
      case [a, b]
      in [
           { type: :script, value: { keyword: "if" | "elsif" } },
           { type: :script, value: { keyword: "elsif" | "else" } }
         ]
        true
      in [
           { type: :script, value: { keyword: "case" | "when" } },
           { type: :script, value: { keyword: "when" | "else" } }
         ]
        true
      in [
           {
             type: :script,
             value: { keyword: "case" } | { text: IN_RE }
           },
           {
             type: :script,
             value: { keyword: "else" } | { text: IN_RE }
           }
         ]
        true
      in [
           { type: :script, value: { keyword: "begin" } },
           {
             type: :script,
             value: { keyword: "rescue" | "else" | "ensure" }
           }
         ]
        true
      in [
           { type: :script, value: { keyword: "rescue" } },
           { type: :script, value: { keyword: "else" | "ensure" } }
         ]
        true
      in [
           { type: :script, value: { keyword: "else" } },
           { type: :script, value: { keyword: "ensure" } }
         ]
        true
      else
        false
      end
    end
    .map do |chunk|
      case chunk
      in [{ type: :script, value: { keyword: "if" } }, *]
        @builder.compute(group_condition(:if, chunk))
      in [{ type: :script, value: { keyword: "case" } }, *]
        @builder.compute(group_condition(:case, chunk))
      in [{ type: :script, value: { keyword: "begin" } }, *]
        @builder.compute(group_condition(:begin, chunk))
      else
        chunk.map { _1.accept(self) }
      end
    end
    .flatten
    .compact
end

#join_plain_nodes(children) ⇒ Object



551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/mayu/resources/transformers/haml.rb', line 551

def join_plain_nodes(children)
  children
    .chunk_while do |prev, curr|
      (
        (prev in { type: :plain, value: { text: prev_text } }) &&
          (curr in { type: :plain, value: { text: new_text } })
      )
    end
    .map do |chunk|
      case chunk
      in [{ type: :plain } => first, *]
        text = chunk.map { _1.value[:text].to_s.strip }.join(" ")
        first.value[:text] = text
        first
      else
        chunk
      end
    end
    .flatten
    .compact
end

#join_ruby_script_nodes(nodes) ⇒ Object



662
663
664
# File 'lib/mayu/resources/transformers/haml.rb', line 662

def join_ruby_script_nodes(nodes)
  nodes.map { _1.value[:text] }.join("\n")
end

#make_space(ref_node) ⇒ Object



700
701
702
703
704
705
706
707
708
# File 'lib/mayu/resources/transformers/haml.rb', line 700

def make_space(ref_node)
  ::Haml::Parser::ParseNode.new(
    :plain,
    ref_node.line,
    { text: " " },
    ref_node.parent,
    []
  )
end

#parse_ruby(source, fix: false) ⇒ Object



805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
# File 'lib/mayu/resources/transformers/haml.rb', line 805

def parse_ruby(source, fix: false)
  source = fix_syntax_by_adding_missing_pairs(source) if fix

  SyntaxTree.parse(source).statements.body
rescue SyntaxTree::Parser::ParseError => e
  explain =
    SyntaxSuggest::ExplainSyntax.new(
      code_lines: SyntaxSuggest::CodeLine.from_source(source)
    ).call

  msg = ["Failed parsing Ruby: #{source}"]

  msg.push <<~MSG unless explain.errors.empty?
      Errors:
        #{explain.errors.join("  \n")}
    MSG

  msg.push <<~MSG unless explain.missing.empty?
      Missing:
        #{explain.missing.map { explain.why(_1) }.join("  \n")}
    MSG

  raise ParseError, "\n#{msg.join("\n")}"
end

#prepend_whitespace(children) ⇒ Object



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/mayu/resources/transformers/haml.rb', line 666

def prepend_whitespace(children)
  [nil, *children].each_cons(2)
    .map do |prev, curr|
      if prev in {
           type: :tag, value: { nuke_outer_whitespace: true }
         }
        if curr in { type: :plain, value: { text: } }
          curr.value = { text: " #{text}" }
        else
          next make_space(curr), curr
        end
      end

      curr
    end
end

#string_keys_to_labels_mutation_visitorObject



858
859
860
861
862
863
864
865
866
867
868
869
870
871
# File 'lib/mayu/resources/transformers/haml.rb', line 858

def string_keys_to_labels_mutation_visitor
  visitor = MutationVisitor.new

  visitor.mutate("Assoc[key: StringLiteral]") do |assoc|
    @builder.Assoc(
      @builder.Label(
        assoc.key.parts.map(&:value).join.gsub("-", "_") + ":"
      ),
      assoc.value
    )
  end

  visitor
end

#transform_script_node(node) ⇒ Object



786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'lib/mayu/resources/transformers/haml.rb', line 786

def transform_script_node(node)
  source = node.value.fetch(:text).strip

  if node.children.empty?
    parse_ruby(source, fix: false) => statements
    return @builder.ruby_script(statements)
  end

  parse_ruby(source, fix: true) => [statement]

  visitor = MutationVisitor.new

  visitor.mutate("Statements[body: [VoidStmt]]") do
    @builder.Statements(visit_tag_children(node.children))
  end

  @builder.ruby_script([statement.accept(visitor)])
end

#visit_filter(node) ⇒ Object



710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/mayu/resources/transformers/haml.rb', line 710

def visit_filter(node)
  case node.value
  in { name: "ruby", text: }
    @builder.ruby_script(parse_ruby(text)) if text
  in { name: "css", text: }
    CSS.transform(
      source: text,
      source_path:
        @options.source_path_without_extension + ".haml (inline css)",
      source_line: node.line
    )
  in { name: "plain", text: }
    case text.inspect.each_line.to_a
    in []
      # noop
    in [line]
      @builder.string_literal(text)
    in [*lines]
      @builder.Heredoc(lines.map { @builder.TStringContent(_1) })
    end
  end
end

#visit_haml_comment(node) ⇒ Object



463
464
465
# File 'lib/mayu/resources/transformers/haml.rb', line 463

def visit_haml_comment(node)
  nil
end

#visit_plain(node) ⇒ Object



733
734
735
736
# File 'lib/mayu/resources/transformers/haml.rb', line 733

def visit_plain(node)
  node.value => { text: }
  @builder.string_literal(text)
end

#visit_root(node) ⇒ Object



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
# File 'lib/mayu/resources/transformers/haml.rb', line 430

def visit_root(node)
  setup = []
  styles = []
  render = []

  node.children.each do |child|
    case child
    in { type: :filter, value: { name: "ruby" } }
      if setup.empty? && styles.empty?
        setup.push(child)
      else
        render.push(child)
      end
    in type: :script | :silent_script
      render.push(child)
    in { type: :filter, value: { name: "css" } }
      styles.push(child.accept(self))
    in type: :tag
      render.push(child)
    end
  end

  Result.new(
    program:
      @builder.create_program(
        group_control_statements(setup),
        styles,
        group_control_statements(render)
      ),
    styles:
  )
end

#visit_script(node) ⇒ Object



738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
# File 'lib/mayu/resources/transformers/haml.rb', line 738

def visit_script(node)
  case node.value[:text].strip
  when /\Areturn\s+(?<type>if|unless)\s+(?<condition_source>.+)/
    $~ => { type:, condition_source: }

    parse_ruby(condition_source, fix: true) => [condition]

    statements =
      @builder.Statements(
        [
          @builder.ReturnNode(
            @builder.Args(visit_tag_children(node.children))
          )
        ]
      )

    case type
    in "if"
      @builder.IfNode(condition, statements, nil)
    in "unless"
      @builder.UnlessNode(condition, statements, nil)
    end
  when /\Areturn/
    @builder.ReturnNode(
      @builder.Args(visit_tag_children(node.children))
    )
  else
    @builder.compute(transform_script_node(node))
  end
end

#visit_silent_script(node) ⇒ Object



776
777
778
779
780
781
782
783
784
# File 'lib/mayu/resources/transformers/haml.rb', line 776

def visit_silent_script(node)
  with_state(:is_silent, true) do |was_silent|
    if was_silent
      visit_script(node)
    else
      @builder.silent(visit_script(node))
    end
  end
end

#visit_slot_tag(node) ⇒ Object



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/mayu/resources/transformers/haml.rb', line 467

def visit_slot_tag(node)
  node.value => { attributes:, dynamic_attributes: }

  name = nil

  if new = dynamic_attributes.new
    parse_ruby(dynamic_attributes.new) => [parsed_attributes]
    hash = parsed_attributes.accept(HashKeyExtractorVisitor.new)

    name = hash[:name] || hash["name"]
  end

  if attr = attributes["name"]
    name ||= @builder.string_literal(attr)
  end

  return(
    @builder.slot(
      name,
      fallback: node.children.map { _1.accept(self) }
    )
  )
end

#visit_tag(node) ⇒ Object



491
492
493
494
495
496
497
498
499
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
# File 'lib/mayu/resources/transformers/haml.rb', line 491

def visit_tag(node)
  node.value => {
    name:, attributes:, dynamic_attributes:, self_closing:, value:
  }

  return visit_slot_tag(node) if name == "slot"

  attrs = []

  if @options.transform_elements_to_classes
    attrs.push(@builder.props_hash(class: :"__#{name}"))
  end

  attrs.push(@builder.props_hash(attributes)) unless attributes.empty?

  if old = dynamic_attributes.old
    attrs.push(*parse_ruby(old))
  end

  if new = dynamic_attributes.new
    attrs.push(
      *parse_ruby(new)
        .map { _1.accept(string_keys_to_labels_mutation_visitor) }
        .map { _1.accept(wrap_handler_mutation_visitor) }
    )
  end

  if object_ref = node.value[:object_ref]
    unless object_ref == :nil
      parse_ruby(object_ref) => [key]
      attrs.push(@builder.props_hash(key:))
    end
  end

  @builder.tag(
    name,
    if value
      if node.value[:parse]
        parse_ruby(value, fix: false) => statements
        @builder.ruby_script(statements)
      elsif !value.empty?
        @builder.string_literal(value.to_s)
      end
    else
      visit_tag_children(node.children)
    end,
    attrs
  )
end

#visit_tag_children(children) ⇒ Object



541
542
543
544
545
546
547
548
549
# File 'lib/mayu/resources/transformers/haml.rb', line 541

def visit_tag_children(children)
  children
    .reject { _1 in { type: :plain, value: { text: "" } } }
    .then { join_plain_nodes(_1) }
    .then { prepend_whitespace(_1) }
    .then { append_whitespace(_1) }
    .then { group_control_statements(_1) }
    .flatten
end

#with_state(name, value, &block) ⇒ Object



769
770
771
772
773
774
# File 'lib/mayu/resources/transformers/haml.rb', line 769

def with_state(name, value, &block)
  @state[name], prev = value, @state[name]
  yield prev
ensure
  @state[name] = prev
end

#wrap_handler_mutation_visitorObject



837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# File 'lib/mayu/resources/transformers/haml.rb', line 837

def wrap_handler_mutation_visitor
  visitor = MutationVisitor.new

  visitor.mutate(
    "Assoc[key: Label, value: VCall[value: Ident]]"
  ) do |assoc|
    if assoc.key.value.start_with?("on")
      handler_name = @builder.SymbolLiteral(assoc.value.value)

      @builder.Assoc(
        assoc.key,
        @builder.call_helpers(:handler, [handler_name])
      )
    else
      assoc
    end
  end

  visitor
end