Class: Herb::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/herb/engine.rb,
lib/herb/engine/compiler.rb,
lib/herb/engine/validator.rb,
lib/herb/engine/debug_visitor.rb,
lib/herb/engine/error_formatter.rb,
lib/herb/engine/validation_errors.rb,
lib/herb/engine/parser_error_overlay.rb,
lib/herb/engine/validation_error_overlay.rb,
lib/herb/engine/validators/render_validator.rb,
lib/herb/engine/validators/nesting_validator.rb,
lib/herb/engine/validators/security_validator.rb,
lib/herb/engine/validators/accessibility_validator.rb

Defined Under Namespace

Modules: ValidationErrors, Validators Classes: CompilationError, Compiler, DebugVisitor, ErrorFormatter, GeneratorTemplateError, InvalidRubyError, ParserErrorOverlay, SecurityError, ValidationErrorOverlay, Validator

Constant Summary collapse

ESCAPE_TABLE =
{
  "&" => "&",
  "<" => "&lt;",
  ">" => "&gt;",
  '"' => "&quot;",
  "'" => "&#39;",
}.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, properties = {}) ⇒ Engine

Returns a new instance of Engine.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/herb/engine.rb', line 58

def initialize(input, properties = {})
  @filename = properties[:filename] ? ::Pathname.new(properties[:filename]) : nil
  @project_path = ::Pathname.new(properties[:project_path] || Dir.pwd)

  if @filename
    absolute_filename = @filename.absolute? ? @filename : @project_path + @filename
    @relative_file_path = absolute_filename.relative_path_from(@project_path).to_s
  else
    @relative_file_path = "unknown"
  end

  @bufvar = properties[:bufvar] || properties[:outvar] || "_buf"
  @escape = properties.fetch(:escape) { properties.fetch(:escape_html, false) }
  @escapefunc = properties.fetch(:escapefunc, @escape ? "__herb.h" : "::Herb::Engine.h")
  @attrfunc = properties.fetch(:attrfunc, @escape ? "__herb.attr" : "::Herb::Engine.attr")
  @jsfunc = properties.fetch(:jsfunc, @escape ? "__herb.js" : "::Herb::Engine.js")
  @cssfunc = properties.fetch(:cssfunc, @escape ? "__herb.css" : "::Herb::Engine.css")
  @src = properties[:src] || String.new
  @chain_appends = properties[:chain_appends]
  @buffer_on_stack = false
  @debug = properties.fetch(:debug, Herb.configuration.engine_option("debug", false))
  @content_for_head = properties[:content_for_head]
  @validation_error_template = nil
  @validation_mode = properties.fetch(:validation_mode, :raise)
  @enabled_validators = Herb.configuration.enabled_validators(properties[:validators] || {})
  @optimize = properties.fetch(:optimize, Herb.configuration.engine_option("optimize", false))
  @parser_options = properties.fetch(:parser_options, default_parser_options).transform_keys(&:to_sym)

  if @optimize && !self.class.optimize_warning_issued
    self.class.optimize_warning_issued = true

    warn "[Herb] Compile-time optimizations are experimental. Output may differ from standard ActionView rendering."
  end

  @visitors = properties.fetch(:visitors, default_visitors)

  if @debug && @visitors.empty?
    debug_visitor = DebugVisitor.new(
      file_path: @filename,
      project_path: @project_path
    )

    @visitors << debug_visitor
  end

  unless [:raise, :overlay, :none].include?(@validation_mode)
    raise ArgumentError,
          "validation_mode must be one of :raise, :overlay, or :none, got #{@validation_mode.inspect}"
  end

  @freeze = properties[:freeze]
  @freeze_template_literals = properties.fetch(:freeze_template_literals, true)
  @text_end = @freeze_template_literals ? "'.freeze" : "'"

  bufval = properties[:bufval] || "::String.new"
  preamble = properties[:preamble] || "#{@bufvar} = #{bufval};"
  postamble = properties[:postamble] || "#{@bufvar}.to_s\n"

  preamble = "#{preamble}; " unless preamble.empty? || preamble.end_with?(";", " ", "\n")

  @src << "# frozen_string_literal: true\n" if @freeze

  if properties[:ensure]
    @src << "begin; __original_outvar = #{@bufvar}"
    @src << if /\A@[^@]/ =~ @bufvar
              "; "
            else
              " if defined?(#{@bufvar}); "
            end
  end

  @src << "__herb = ::Herb::Engine; " if @escape && @escapefunc == "__herb.h"
  @src << preamble

  action_view_helpers = @optimize && source_may_contain_action_view_helpers?(input)
  transform_conditionals = @optimize && action_view_helpers
  parse_result = ::Herb.parse(input, **@parser_options, track_whitespace: true,
                                                        action_view_helpers: action_view_helpers,
                                                        transform_conditionals: transform_conditionals)
  ast = parse_result.value
  parser_errors = parse_result.errors

  if parser_errors.any?
    case @validation_mode
    when :raise
      handle_parser_errors(parser_errors, input, ast)
      return
    when :overlay
      add_parser_error_overlay(parser_errors, input)
    when :none
      # Skip both errors and compilation, but still need minimal Ruby code
    end
  else
    validators = run_validation(ast) unless @validation_mode == :none

    if validators
      handle_validation_errors(validators, input) if @validation_mode == :raise
      add_validation_overlay(validators, input) if @validation_mode == :overlay
    end

    @visitors.each do |visitor|
      ast.accept(visitor)
    end

    compiler = Compiler.new(self, properties)

    ast.accept(compiler)

    compiler.generate_output
  end

  if @validation_error_template
    escaped_html = @validation_error_template.gsub("'", "\\\\'")
    @src << " #{@bufvar} << ('#{escaped_html}'.html_safe).to_s;"
  end

  @src << "\n" unless @src.end_with?("\n")
  add_postamble(postamble)

  @src << "; ensure\n  #{@bufvar} = __original_outvar\nend\n" if properties[:ensure]

  if properties.fetch(:validate_ruby, false)
    ensure_valid_ruby!(@src)
  end

  @src.freeze
  freeze
end

Class Attribute Details

.optimize_warning_issuedObject

: bool



29
30
31
# File 'lib/herb/engine.rb', line 29

def optimize_warning_issued
  @optimize_warning_issued
end

Instance Attribute Details

#bufvarObject (readonly)

Returns the value of attribute bufvar.



21
22
23
# File 'lib/herb/engine.rb', line 21

def bufvar
  @bufvar
end

#content_for_headObject (readonly)

Returns the value of attribute content_for_head.



21
22
23
# File 'lib/herb/engine.rb', line 21

def content_for_head
  @content_for_head
end

#debugObject (readonly)

Returns the value of attribute debug.



21
22
23
# File 'lib/herb/engine.rb', line 21

def debug
  @debug
end

#enabled_validatorsObject (readonly)

Returns the value of attribute enabled_validators.



21
22
23
# File 'lib/herb/engine.rb', line 21

def enabled_validators
  @enabled_validators
end

#filenameObject (readonly)

Returns the value of attribute filename.



21
22
23
# File 'lib/herb/engine.rb', line 21

def filename
  @filename
end

#project_pathObject (readonly)

Returns the value of attribute project_path.



21
22
23
# File 'lib/herb/engine.rb', line 21

def project_path
  @project_path
end

#relative_file_pathObject (readonly)

Returns the value of attribute relative_file_path.



21
22
23
# File 'lib/herb/engine.rb', line 21

def relative_file_path
  @relative_file_path
end

#srcObject (readonly)

Returns the value of attribute src.



21
22
23
# File 'lib/herb/engine.rb', line 21

def src
  @src
end

#validation_error_templateObject (readonly)

Returns the value of attribute validation_error_template.



21
22
23
# File 'lib/herb/engine.rb', line 21

def validation_error_template
  @validation_error_template
end

#visitorsObject (readonly)

Returns the value of attribute visitors.



21
22
23
# File 'lib/herb/engine.rb', line 21

def visitors
  @visitors
end

Class Method Details

.action_view_helper_patternObject



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/herb/engine.rb', line 239

def self.action_view_helper_pattern
  @action_view_helper_pattern ||= begin
    require_relative "action_view/helper_registry"

    names = ::Herb::ActionView::HelperRegistry.supported.flat_map { |entry|
      if entry.receiver_call_detect?
        "#{entry.name}."
      else
        [entry.name, *entry.aliases]
      end
    }

    Regexp.new("\\b(?:#{names.map { |name| Regexp.escape(name) }.join("|")})")
  end
end

.attr(value) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
# File 'lib/herb/engine.rb', line 191

def self.attr(value)
  value.to_s
       .gsub("&", "&amp;")
       .gsub('"', "&quot;")
       .gsub("'", "&#39;")
       .gsub("<", "&lt;")
       .gsub(">", "&gt;")
       .gsub("\n", "&#10;")
       .gsub("\r", "&#13;")
       .gsub("\t", "&#9;")
end

.comment?(code) ⇒ Boolean

Returns:

  • (Boolean)


227
228
229
# File 'lib/herb/engine.rb', line 227

def self.comment?(code)
  code.include?("#")
end

.css(value) ⇒ Object



217
218
219
220
221
# File 'lib/herb/engine.rb', line 217

def self.css(value)
  value.to_s.gsub(/[^\w-]/) do |char|
    "\\#{char.ord.to_s(16).rjust(6, "0")}"
  end
end

.h(value) ⇒ Object



187
188
189
# File 'lib/herb/engine.rb', line 187

def self.h(value)
  value.to_s.gsub(/[&<>"']/, ESCAPE_TABLE)
end

.heredoc?(code) ⇒ Boolean

Returns:

  • (Boolean)


231
232
233
# File 'lib/herb/engine.rb', line 231

def self.heredoc?(code)
  code.match?(/<<[~-]?\s*['"`]?\w/)
end

.js(value) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/herb/engine.rb', line 203

def self.js(value)
  value.to_s.gsub(/[\\'"<>&\n\r\t\f\b]/) do |char|
    case char
    when "\n" then "\\n"
    when "\r" then "\\r"
    when "\t" then "\\t"
    when "\f" then "\\f"
    when "\b" then "\\b"
    else
      "\\x#{char.ord.to_s(16).rjust(2, "0")}"
    end
  end
end

.nested_attribute_value(value) ⇒ Object



223
224
225
# File 'lib/herb/engine.rb', line 223

def self.nested_attribute_value(value)
  value.is_a?(::String) || value.is_a?(::Symbol) ? value.to_s : value.to_json
end

Instance Method Details

#source_may_contain_action_view_helpers?(source) ⇒ Boolean

Returns:

  • (Boolean)


235
236
237
# File 'lib/herb/engine.rb', line 235

def source_may_contain_action_view_helpers?(source)
  self.class.action_view_helper_pattern.match?(source)
end