Class: HTree::TemplateCompiler

Inherits:
Object
  • Object
show all
Defined in:
lib/htree/template.rb

Overview

:stopdoc:

Defined Under Namespace

Classes: TemplateAttrName, TemplateNode

Constant Summary collapse

IGNORABLE_ELEMENTS =
{
  'span' => true,
  'div' => true,
  '{http://www.w3.org/1999/xhtml}span' => true,
  '{http://www.w3.org/1999/xhtml}div' => true,
}
WhiteSpacePreservingElements =
{
  '{http://www.w3.org/1999/xhtml}pre' => true
}
ID_PAT =
/[a-z][a-z0-9_]*/
NAME_FARGS_PAT =
/(#{ID_PAT})(?:\(\s*(|#{ID_PAT}\s*(?:,\s*#{ID_PAT}\s*)*)\))?/

Instance Method Summary collapse

Constructor Details

#initializeTemplateCompiler

Returns a new instance of TemplateCompiler.



438
439
440
# File 'lib/htree/template.rb', line 438

def initialize
  @gensym_id = 0
end

Instance Method Details

#check_syntax(code) ⇒ Object



704
705
706
707
708
# File 'lib/htree/template.rb', line 704

def check_syntax(code)
  unless valid_syntax?(code)
    raise HTree::Error, "invalid ruby code: #{code}"
  end
end

#compile_body(outvar, contextvar, node, is_toplevel, local_templates = {}) ⇒ Object



609
610
611
612
613
614
615
616
# File 'lib/htree/template.rb', line 609

def compile_body(outvar, contextvar, node, is_toplevel, local_templates={})
  if node.elem? && IGNORABLE_ELEMENTS[node.name] && node.attributes.empty?
    node = TemplateNode.new(node.children)
  else
    node = TemplateNode.new(node)
  end
  generate_logic_node([:content], node, local_templates).generate_xml_output_code(outvar, contextvar)
end

#compile_call(ignore_tag, spec) ⇒ Object



755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'lib/htree/template.rb', line 755

def compile_call(ignore_tag, spec)
  # spec : [recv.]meth[(args)]
  spec = spec.strip
  spec, args = split_args(spec)
  unless /#{ID_PAT}\z/o =~ spec
    raise HTree::Error, "invalid _call: #{spec}"
  end
  meth = $&
  spec = $`
  if /\A\s*\z/ =~ spec
    recv = nil
  elsif /\A\s*(.*)\.\z/ =~ spec
    recv = $1
  else
    raise HTree::Error, "invalid _call: #{spec}"
  end
  if recv
    check_syntax(recv)
    check_syntax("#{recv}.#{meth}(#{args})")
  end
  check_syntax("#{meth}(#{args})")
  [:call, recv, meth, args]
end

#compile_dynamic_text(ignore_tag, expr) ⇒ Object



710
711
712
713
714
715
# File 'lib/htree/template.rb', line 710

def compile_dynamic_text(ignore_tag, expr)
  check_syntax(expr)
  logic = [:text, expr]
  logic = [:tag, logic] unless ignore_tag
  logic
end

#compile_dynamic_tree(ignore_tag, expr) ⇒ Object



717
718
719
720
721
722
# File 'lib/htree/template.rb', line 717

def compile_dynamic_tree(ignore_tag, expr)
  check_syntax(expr)
  logic = [:tree, expr]
  logic = [:tag, logic] unless ignore_tag
  logic
end

#compile_global_template(name_fargs, node) ⇒ Object



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
# File 'lib/htree/template.rb', line 563

def compile_global_template(name_fargs, node)
  unless /\A#{NAME_FARGS_PAT}\z/o =~ name_fargs
    raise HTree::Error, "invalid template declaration: #{name_fargs}"
  end
  name = $1
  fargs = $2 ? $2.scan(ID_PAT) : []

  outvar = gensym('out')
  contextvar = gensym('top_context')
  args2 = [outvar, contextvar, *fargs]

  <<"End"
def #{name}(#{fargs.join(',')})
HTree.parse(_xml_#{name}(#{fargs.join(',')}))
end
def _xml_#{name}(#{fargs.join(',')})
#{outvar} = HTree::Encoder.new(HTree::Encoder.internal_charset)
#{contextvar} = HTree::DefaultContext
_ht_#{name}(#{args2.join(',')})
#{outvar}.finish
end
def _ht_#{name}(#{args2.join(',')})
#{compile_body(outvar, contextvar, node, false)}\
end
public :_ht_#{name}
End
end

#compile_if(ignore_tag, expr, else_call) ⇒ Object



724
725
726
727
728
729
730
731
732
733
734
735
# File 'lib/htree/template.rb', line 724

def compile_if(ignore_tag, expr, else_call)
  check_syntax(expr)
  then_logic = [:content]
  unless ignore_tag
    then_logic = [:tag, then_logic]
  end
  else_logic = nil
  if else_call
    else_logic = compile_call(true, else_call)
  end
  [:if, expr, then_logic, else_logic]
end

#compile_iter(ignore_tag, spec) ⇒ Object



779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/htree/template.rb', line 779

def compile_iter(ignore_tag, spec)
  # spec: <n _iter="expr.meth[(args)]//fargs" >...</n>
  spec = spec.strip
  unless %r{\s*//\s*(#{ID_PAT}\s*(?:,\s*#{ID_PAT}\s*)*)?\z}o =~ spec
    raise HTree::Error, "invalid block arguments for _iter: #{spec}"
  end
  call = $`.strip
  fargs = $1 ? $1.strip : ''
  check_syntax("#{call} {|#{fargs}| }")
  logic = [:content]
  unless ignore_tag
    logic = [:tag, logic]
  end
  [:iter, call, fargs, logic]
end

#compile_iter_content(ignore_tag, spec) ⇒ Object



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/htree/template.rb', line 795

def compile_iter_content(ignore_tag, spec)
  # spec: <n _iter_content="expr.meth[(args)]//fargs" >...</n>
  spec = spec.strip
  unless %r{\s*//\s*(#{ID_PAT}\s*(?:,\s*#{ID_PAT}\s*)*)?\z}o =~ spec
    raise HTree::Error, "invalid block arguments for _iter: #{spec}"
  end
  call = $`.strip
  fargs = $1 ? $1.strip : ''
  check_syntax("#{call} {|#{fargs}| }")
  logic = [:content]
  logic = [:iter, call, fargs, logic]
  unless ignore_tag
    logic = [:tag, logic]
  end
  logic
end

#compile_local_template(name_fargs, node, local_templates) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/htree/template.rb', line 591

def compile_local_template(name_fargs, node, local_templates)
  unless /\A#{NAME_FARGS_PAT}\z/o =~ name_fargs
    raise HTree::Error, "invalid template declaration: #{name_fargs}"
  end
  name = $1
  fargs = $2 ? $2.scan(ID_PAT) : []

  outvar = gensym('out')
  contextvar = gensym('top_context')
  args2 = [outvar, contextvar, *fargs]

  <<"End"
#{name} = lambda {|#{args2.join(',')}|
#{compile_body(outvar, contextvar, node, false, local_templates)}\
}
End
end

#compile_node(node, local_templates) ⇒ Object



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/htree/template.rb', line 618

def compile_node(node, local_templates)
  case node
  when HTree::Doc
    TemplateNode.new(node.children.map {|n| compile_node(n, local_templates) })
  when HTree::Elem
    ht_attrs = node.attributes.find_all {|name, text| template_attribute? name }
    ht_attrs = ht_attrs.sort_by {|htname, text| htname.universal_name }
    ignore_tag = false
    unless ht_attrs.empty?
      attr_mod = {}
      ht_attrs.each {|htname, text|
        attr_mod[htname] = nil
        if /\A_attr_/ =~ htname.local_name
          attr_mod[TemplateAttrName.new(htname.namespace_prefix, htname.namespace_uri, $')] = text
        end
      }
      ht_attrs.reject! {|htname, text| /\A_attr_/ =~ htname.local_name }
      node = node.subst_subnode(attr_mod)
      ignore_tag = IGNORABLE_ELEMENTS[node.name] && node.attributes.empty?
    end
    ht_names = ht_attrs.map {|htname, text| htname.universal_name }
    ht_vals =  ht_attrs.map {|htname, text| text.to_s }
    case ht_names
    when []
      generate_logic_node([:tag, [:content]], node, local_templates)
    when ['_text'] # <n _text="expr" /> or <n _text>expr</n>
      if ht_vals[0] != '_text' # xxx: attribute value is really omitted?
        expr = ht_vals[0]
      else
        children = node.children
        if children.length != 1
          raise HTree::Error, "_text expression has #{children.length} nodes"
        end
        if !children[0].text?
          raise HTree::Error, "_text expression is not text: #{children[0].class}"
        end
        expr = children[0].to_s
      end
      if ignore_tag && /\A\s*'((?:[^'\\]|\\.)*)'\s*\z/m =~ expr
        # if expr is just a constant string literal, use it as a literal text.
        # This saves dynamic evaluation of <span _text="' '"/> 
        # xxx: handle "..." as well if it has no #{}.
        HTree::Text.new($1.gsub(/\\(.)/m, '\1'))
      else
        generate_logic_node(compile_dynamic_text(ignore_tag, expr), node, local_templates)
      end
    when ['_tree'] # <n _tree="expr" /> or <n _tree>expr</n>
      if ht_vals[0] != '_tree' # xxx: attribute value is really omitted?
        expr = ht_vals[0]
      else
        children = node.children
        if children.length != 1
          raise HTree::Error, "_tree expression has #{children.length} nodes"
        end
        if !children[0].text?
          raise HTree::Error, "_tree expression is not text: #{children[0].class}"
        end
        expr = children[0].to_s
      end
      generate_logic_node(compile_dynamic_tree(ignore_tag, expr), node, local_templates)
    when ['_if'] # <n _if="expr" >...</n>
      generate_logic_node(compile_if(ignore_tag, ht_vals[0], nil), node, local_templates)
    when ['_else', '_if'] # <n _if="expr" _else="expr.meth(args)" >...</n>
      generate_logic_node(compile_if(ignore_tag, ht_vals[1], ht_vals[0]), node, local_templates)
    when ['_call'] # <n _call="recv.meth(args)" />
      generate_logic_node(compile_call(ignore_tag, ht_vals[0]), node, local_templates)
    when ['_iter'] # <n _iter="expr.meth(args)//fargs" >...</n>
      generate_logic_node(compile_iter(ignore_tag, ht_vals[0]), node, local_templates)
    when ['_iter_content'] # <n _iter_content="expr.meth(args)//fargs" >...</n>
      generate_logic_node(compile_iter_content(ignore_tag, ht_vals[0]), node, local_templates)
    else
      raise HTree::Error, "unexpected template attributes: #{ht_attrs.inspect}"
    end
  else
    return node
  end
end

#compile_template(src) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/htree/template.rb', line 503

def compile_template(src)
  srcdoc = parse_template(src)
  templates = []
  body = extract_templates(srcdoc, templates, true)
  methods = []
  templates.each {|name_args, node|
    methods << compile_global_template(name_args, node)
  }
  <<"End"
require 'htree/encoder'
require 'htree/context'
Module.new.module_eval <<'EE'
module_function
#{methods.join('').chomp}
self
EE
End
end

#expand_template(template, out, encoding, binding) ⇒ Object



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/htree/template.rb', line 485

def expand_template(template, out, encoding, binding)
  template = parse_template(template)
  is_html = template_is_html(template)
  outvar = gensym('out')
  contextvar = gensym('top_context')
  code = ''
  code << "#{outvar} = HTree::Encoder.new(#{encoding.dump})\n"
  code << "#{outvar}.html_output = true\n" if is_html
  code << "#{contextvar} = #{is_html ? "HTree::HTMLContext" : "HTree::DefaultContext"}\n"
  code << compile_body(outvar, contextvar, template, false)
  code << "[#{outvar}.#{is_html ? "finish" : "finish_with_xmldecl"}, #{outvar}.minimal_charset]\n"
#puts code; STDOUT.flush
  result, minimal_charset = eval(code, binding, "(eval:#{__FILE__}:#{__LINE__})")
  out.charset = minimal_charset if out.respond_to? :charset=
  out << result
  out
end

#extract_templates(node, templates, is_toplevel) ⇒ Object



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
553
554
555
556
557
558
559
# File 'lib/htree/template.rb', line 526

def extract_templates(node, templates, is_toplevel)
  case node
  when HTree::Doc
    subst = {}
    node.children.each_with_index {|n, i|
      subst[i] = extract_templates(n, templates, is_toplevel)
    }
    node.subst_subnode(subst)
  when HTree::Elem
    ht_attrs, rest_attrs = node.attributes.partition {|name, text| template_attribute? name }
    if ht_attrs.empty?
      subst = {}
      node.children.each_with_index {|n, i|
        subst[i] = extract_templates(n, templates, is_toplevel)
      }
      node.subst_subnode(subst)
    else
      ht_attrs.each {|htname, text|
        if htname.universal_name == '_template'
          name_fargs = text.to_s
          templates << [name_fargs, node.subst_subnode('_template' => nil)]
          return nil
        end
      }
      if is_toplevel
        raise HTree::Error, "unexpected template attributes in toplevel: #{ht_attrs.inspect}"
      else
        node
      end
    end
  else
    node
  end
end

#generate_logic_node(logic, node, local_templates) ⇒ Object



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/htree/template.rb', line 812

def generate_logic_node(logic, node, local_templates)
  # logic ::= [:if, expr, then_logic, else_logic]
  #         | [:iter, call, fargs, logic]
  #         | [:tag, logic]
  #         | [:text, expr]
  #         | [:tree, expr]
  #         | [:call, expr, meth, args]
  #         | [:content]
  #         | [:empty]
  case logic.first
  when :empty
    nil
  when :content
    subtemplates = []
    children = []
    node.children.each {|c|
      children << extract_templates(c, subtemplates, false)
    }
    if subtemplates.empty?
      TemplateNode.new(node.children.map {|n|
        compile_node(n, local_templates)
      })
    else
      local_templates = local_templates.dup
      decl = ''
      subtemplates.each {|sub_name_args, sub_node|
        sub_name = sub_name_args[ID_PAT]
        local_templates[sub_name] = sub_name
        decl << "#{sub_name} = "
      }
      decl << "nil\n"
      defs = []
      subtemplates.each {|sub_name_args, sub_node|
        defs << lambda {|out, context|
          out.output_logic_line compile_local_template(sub_name_args, sub_node, local_templates)
        }
      }
      TemplateNode.new(
        lambda {|out, context| out.output_logic_line decl },
        defs,
        children.map {|n| compile_node(n, local_templates) }
      )
    end
  when :text
    _, expr = logic
    TemplateNode.new(lambda {|out, context| out.output_dynamic_text expr })
  when :tree
    _, expr = logic
    TemplateNode.new(lambda {|out, context| out.output_dynamic_tree expr, make_context_expr(out, context) })
  when :tag
    _, rest_logic = logic
    if rest_logic == [:content] && node.empty_element?
      node
    else
      subst = {}
      node.children.each_index {|i| subst[i] = nil }
      subst[0] = TemplateNode.new(generate_logic_node(rest_logic, node, local_templates))
      node.subst_subnode(subst)
    end
  when :if
    _, expr, then_logic, else_logic = logic
    children = [
      lambda {|out, context| out.output_logic_line "if (#{expr})" },
      generate_logic_node(then_logic, node, local_templates)
    ]
    if else_logic
      children.concat [
        lambda {|out, context| out.output_logic_line "else" },
        generate_logic_node(else_logic, node, local_templates)
      ]
    end
    children <<
      lambda {|out, context| out.output_logic_line "end" }
    TemplateNode.new(*children)
  when :iter
    _, call, fargs, rest_logic = logic
    TemplateNode.new(
      lambda {|out, context| out.output_logic_line "#{call} {|#{fargs}|" },
      generate_logic_node(rest_logic, node, local_templates),
      lambda {|out, context| out.output_logic_line "}" }
    )
  when :call
    _, recv, meth, args = logic
    TemplateNode.new(
      lambda {|out, context|
        as = [out.outvar, ", ", make_context_expr(out, context)]
        unless args.empty?
          as << ", " << args
        end
        if recv
          out.output_logic_line "(#{recv})._ht_#{meth}(#{as.join('')})"
        elsif local_templates.include? meth
          out.output_logic_line "#{meth}.call(#{as.join('')})"
        else
          out.output_logic_line "_ht_#{meth}(#{as.join('')})"
        end
      }
    )
  else
    raise Exception, "[bug] invalid logic: #{logic.inspect}"
  end
end

#gensym(suffix = '') ⇒ Object



442
443
444
445
# File 'lib/htree/template.rb', line 442

def gensym(suffix='')
  @gensym_id += 1
  "g#{@gensym_id}#{suffix}"
end

#make_context_expr(out, context) ⇒ Object



915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
# File 'lib/htree/template.rb', line 915

def make_context_expr(out, context)
  ns = context.namespaces.reject {|k, v| HTree::Context::DefaultNamespaces[k] == v }
  if ns.empty?
    result = out.contextvar
  else
    result = "#{out.contextvar}.subst_namespaces("
    sep = ''
    ns.each {|k, v|
      result << sep << (k ? k.dump : "nil") << '=>' << v.dump
      sep = ', '
    }
    result << ")"
  end
  result
end

#parse_template(template) ⇒ Object



447
448
449
# File 'lib/htree/template.rb', line 447

def parse_template(template)
  strip_whitespaces(HTree.parse(template))
end

#split_args(spec) ⇒ Object



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/htree/template.rb', line 737

def split_args(spec)
  return spec, '' if /\)\z/ !~ spec
  i = spec.length - 1
  nest = 0
  begin
    raise HTree::Error, "unmatched paren: #{spec}" if i < 0
    case spec[i]
    when ?\)
      nest += 1
    when ?\(
      nest -= 1
    end
    i -= 1
  end while nest != 0
  i += 1
  return spec[0, i], spec[(i+1)...-1]
end

#strip_whitespaces(template) ⇒ Object



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/htree/template.rb', line 455

def strip_whitespaces(template)
  case template
  when HTree::Doc
    HTree::Doc.new(*template.children.map {|c| strip_whitespaces(c) }.compact)
  when HTree::Elem, HTree::Doc
    return template if WhiteSpacePreservingElements[template.name]
    subst = {}
    template.children.each_with_index {|c, i|
      subst[i] = strip_whitespaces(c)
    }
    template.subst_subnode(subst)
  when HTree::Text
    if /\A[ \t\r\n]*\z/ =~ template.rcdata
      nil
    else
      template
    end
  else
    template
  end
end

#template_attribute?(name) ⇒ Boolean

Returns:

  • (Boolean)


522
523
524
# File 'lib/htree/template.rb', line 522

def template_attribute?(name)
  /\A_/ =~ name.local_name
end

#template_is_html(template) ⇒ Object



477
478
479
480
481
482
483
# File 'lib/htree/template.rb', line 477

def template_is_html(template)
  template.each_child {|c|
    return false if c.xmldecl?
    return true if c.elem? && c.element_name.namespace_uri == 'http://www.w3.org/1999/xhtml'
  }
  false
end

#valid_syntax?(code) ⇒ Boolean

Returns:

  • (Boolean)


696
697
698
699
700
701
702
# File 'lib/htree/template.rb', line 696

def valid_syntax?(code)
  begin
    eval("BEGIN {return true}\n#{code.untaint}")
  rescue SyntaxError
    raise SyntaxError, "invalid code: #{code}"
  end
end