Class: Zafu::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/zafu/parser.rb

Constant Summary collapse

TEXT_CALLBACKS =
%w{before_parse after_parse before_wrap wrap after_wrap after_process}
PROCESS_CALLBACKS =
%w{before_process expander process_unknown}
CALLBACKS =
TEXT_CALLBACKS + PROCESS_CALLBACKS
@@callbacks =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, opts = {}) ⇒ Parser

Returns a new instance of Parser.



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
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/zafu/parser.rb', line 161

def initialize(text, opts={})
  @stack   = []
  @ok      = true
  @blocks  = []
  @errors  = []

  @options = {:mode=>:void, :method=>'void'}.merge(opts)
  @params  = @options.delete(:params) || {}
  @method  = @options.delete(:method)
  @ids     = @options[:ids] ||= {}
  original_ids = @ids.dup
  @defined_ids = {} # ids defined in this node or this node's sub blocks
  mode     = @options.delete(:mode)
  @parent  = @options.delete(:parent)

  if opts[:sub]
    @text = text
  else
    @text = before_parse(text)
  end

  start(mode)

  # set name
  @name ||= extract_name
  @options[:ids][@name] = self if @name

  unless opts[:sub]
    @text = after_parse(@text)
  end

  @ids.keys.each do |k|
    if original_ids[k] != @ids[k]
      @defined_ids[k] = @ids[k]
    end
  end
  @ok
end

Instance Attribute Details

#blocksObject

Returns the value of attribute blocks.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def blocks
  @blocks
end

#defined_idsObject

Returns the value of attribute defined_ids.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def defined_ids
  @defined_ids
end

#errorsObject

Returns the value of attribute errors.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def errors
  @errors
end

#idsObject

Returns the value of attribute ids.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def ids
  @ids
end

#methodObject

Returns the value of attribute method.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def method
  @method
end

#nameObject

Returns the value of attribute name.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def name
  @name
end

#optionsObject

Returns the value of attribute options.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def options
  @options
end

#paramsObject

Method parameters “<r:show attr=‘name’/>” (params contains => ‘name’).



30
31
32
# File 'lib/zafu/parser.rb', line 30

def params
  @params
end

#parentObject

Returns the value of attribute parent.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def parent
  @parent
end

#pass(elems = nil) ⇒ Object

Pass some contextual information to siblings



214
215
216
# File 'lib/zafu/parser.rb', line 214

def pass
  @pass
end

#textObject

Returns the value of attribute text.



27
28
29
# File 'lib/zafu/parser.rb', line 27

def text
  @text
end

Class Method Details

.erb_safe(text) ⇒ Object



52
53
54
# File 'lib/zafu/parser.rb', line 52

def erb_safe(text)
  text.gsub('<%', '&lt;%').gsub('%>', '%&gt;')
end

.get_template_text(path, helper, base_path = nil) ⇒ Object

Retrieve the template text in the current folder or as an absolute path. This method is used when ‘including’ text



42
43
44
45
46
# File 'lib/zafu/parser.rb', line 42

def get_template_text(path, helper, base_path=nil)
  res = helper.send(:get_template_text, path, base_path)
  return [parser_error("template '#{path}' not found", 'include'), nil, nil] unless res
  res
end

.new_with_url(path, opts = {}) ⇒ Object



33
34
35
36
37
38
# File 'lib/zafu/parser.rb', line 33

def new_with_url(path, opts={})
  helper = opts[:helper] || Zafu::MockHelper.new
  text, fullpath, base_path = self.get_template_text(path, helper)
  return parser_error("template '#{path}' not found", 'include') unless text
  self.new(text, :helper => helper, :base_path => base_path, :included_history => [fullpath], :root => path)
end

.parser_error(message, method) ⇒ Object



48
49
50
# File 'lib/zafu/parser.rb', line 48

def parser_error(message, method)
  "<span class='parser_error'><span class='method'>#{erb_safe method}</span> <span class='message'>#{erb_safe message}</span></span>"
end

Instance Method Details

#all_descendantsObject Also known as: public_descendants

Return a hash of all descendants. Find a specific descendant with descendant for example.



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/zafu/parser.rb', line 391

def all_descendants
  @all_descendants ||= begin
    d = {}
    @blocks.each do |b|
      next if b.kind_of?(String)
      b.public_descendants.each do |k,v|
        d[k] ||= []
        d[k]  += v
      end
      # latest is used first: use direct children before grandchildren.
      d[b.method] ||= []
      d[b.method] << b
    end
    d
  end
end

#ancestor(keys) ⇒ Object

Return the last defined parent for the given keys.



436
437
438
439
440
441
442
443
444
# File 'lib/zafu/parser.rb', line 436

def ancestor(keys)
  keys = Array(keys)
  ancestors.reverse_each do |a|
    if keys.include?(a.method)
      return a
    end
  end
  nil
end

#ancestorsObject



423
424
425
426
427
428
429
430
431
# File 'lib/zafu/parser.rb', line 423

def ancestors
  @ancestors ||= begin
    if parent
      parent.ancestors + [parent]
    else
      []
    end
  end
end

#check_params(*args) ⇒ Object



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
# File 'lib/zafu/parser.rb', line 556

def check_params(*args)
  missing = []
  if args[0].kind_of?(Array)
    # or groups
    ok = false
    args.each_index do |i|
      unless args[i].kind_of?(Array)
        missing[i] = [args[i]]
        next
      end
      missing[i] = []
      args[i].each do |arg|
        missing[i] << arg.to_s unless @params[arg]
      end
      if missing[i] == []
        ok = true
        break
      end
    end
    if ok
      return true
    else
      out "[#{@method} parameter(s) missing:#{missing[0].sort.join(', ')}]"
      return false
    end
  else
    args.each do |arg|
      missing << arg.to_s unless @params[arg]
    end
  end
  if missing != []
    out "[#{@method} parameter(s) missing:#{missing.sort.join(', ')}]"
    return false
  end
  true
end

#childObject

Find a direct child with child[method].



409
410
411
412
413
# File 'lib/zafu/parser.rb', line 409

def child
  Hash[*@blocks.map do |b|
    b.kind_of?(String) ? nil : [b.method, b]
  end.compact.flatten]
end

#default_expanderObject

Default processing



266
267
268
269
270
271
272
# File 'lib/zafu/parser.rb', line 266

def default_expander
  if respond_to?("r_#{@method}".to_sym)
    do_method("r_#{@method}".to_sym)
  else
    do_method(:process_unknown)
  end
end

#default_unknownObject

basic rule to display errors



297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/zafu/parser.rb', line 297

def default_unknown
  sp = ""
  @params.each do |k,v|
    sp += " #{k}=#{v.inspect.gsub("'","TMPQUOTE").gsub('"',"'").gsub("TMPQUOTE",'"')}"
  end

  res = "<span class='parser_unknown'>&lt;r:#{@method}#{sp}"
  inner = expand_with
  if inner != ''
    res + "&gt;</span>#{inner}<span class='parser_unknown'>&lt;r:/#{@method}&gt;</span>"
  else
    res + "/&gt;</span>"
  end
end

#descendant(key) ⇒ Object

Return the last defined descendant for the given key.



447
448
449
# File 'lib/zafu/parser.rb', line 447

def descendant(key)
  descendants(key).last
end

#descendants(key) ⇒ Object



419
420
421
# File 'lib/zafu/parser.rb', line 419

def descendants(key)
  all_descendants[key] || []
end

#do_method(sym) ⇒ Object



274
275
276
277
278
279
280
281
282
# File 'lib/zafu/parser.rb', line 274

def do_method(sym)
  res = self.send(sym)
  if res.kind_of?(String)
    @result << res
  elsif @result.blank?
    @result << (@errors.empty? ? '' : show_errors)
  end
  @result
end

#dynamic_blocks?Boolean

Returns:

  • (Boolean)


415
416
417
# File 'lib/zafu/parser.rb', line 415

def dynamic_blocks?
  @blocks.detect { |b| !b.kind_of?(String) }
end

#eat(arg) ⇒ Object

Advance parser.



494
495
496
497
498
499
500
501
502
503
# File 'lib/zafu/parser.rb', line 494

def eat(arg)
  if arg.kind_of?(String)
    len = arg.length
  elsif arg.kind_of?(Fixnum)
    len = arg
  else
    raise
  end
  @text = @text[len..-1]
end

#empty?Boolean

Returns:

  • (Boolean)


233
234
235
# File 'lib/zafu/parser.rb', line 233

def empty?
  @blocks == [] && (@params == {} || @params == {:part => @params[:part]})
end

#enter(mode) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/zafu/parser.rb', line 505

def enter(mode)
  @stack << mode
  # puts "ENTER(#{@method},:#{mode}) [#{@text}] #{@zafu_tag_count.inspect}"
  if mode == :void
    sym = :scan
  else
    sym = "scan_#{mode}".to_sym
  end
  while (@text != '' && @stack[-1] == mode)
    # puts "CONTINUE(#{@method},:#{mode}) [#{@text}] #{@zafu_tag_count.inspect}"
    self.send(sym)
  end
  # puts "LEAVE(#{@method},:#{mode}) [#{@text}] #{@zafu_tag_count.inspect}"
end

#expand_block(block, new_context = {}) ⇒ Object



593
594
595
# File 'lib/zafu/parser.rb', line 593

def expand_block(block, new_context={})
  block.process(@context.merge(new_context))
end

#expand_with(acontext = {}) ⇒ Object



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
# File 'lib/zafu/parser.rb', line 597

def expand_with(acontext={})

  blocks = acontext.delete(:blocks) || @blocks
  res = ""

  only   = acontext[:only]
  new_context = @context.merge(acontext)

  if acontext[:ignore]
    new_context[:ignore] = (@context[:ignore] || []) + (acontext[:ignore] || []).uniq
  end

  if acontext[:no_ignore]
    new_context[:ignore] = (new_context[:ignore] || []) - acontext[:no_ignore]
  end

  ignore = new_context[:ignore]

  blocks.each do |b|
    if b.kind_of?(String)
      if (!only || (only.kind_of?(Array) && only.include?(:string))) && (!ignore || !ignore.include?(:string))
        res << b
      end
    elsif (!only || (only.kind_of?(Array) && only.include?(b.method)) || only =~ b.method) && (!ignore || !ignore.include?(b.method))
      res << b.process(new_context.dup)
      if pass = b.pass
        new_context.merge!(pass)
      end
    end
  end
  res
end

#expanderObject



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/zafu/parser.rb', line 81

def expander
  self.class.expander_callbacks.reverse_each do |callback|
    if res = send(callback)
      if res.kind_of?(String)
        @result << res
      end
      return @result
    end
  end
  nil
end

#extract_nameObject



200
201
202
# File 'lib/zafu/parser.rb', line 200

def extract_name
  @options[:name] || @params[:id]
end

#failObject



551
552
553
554
# File 'lib/zafu/parser.rb', line 551

def fail
  @ok   = false
  @stack = []
end

#flush(str = @text) ⇒ Object



460
461
462
463
464
465
466
467
468
# File 'lib/zafu/parser.rb', line 460

def flush(str=@text)
  return if str == ''
  if @blocks.last.kind_of?(String)
    @blocks[-1] << str
  else
    @blocks << str
  end
  @text = @text[str.length..-1]
end

#include_part(obj) ⇒ Object

Hook called when including a part “<r:include template=‘layout’ part=‘title’/>”



229
230
231
# File 'lib/zafu/parser.rb', line 229

def include_part(obj)
  [obj]
end

#include_templateObject



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
# File 'lib/zafu/parser.rb', line 325

def include_template
  return parser_error("missing 'template' attribute") unless @params[:template]
  if @options[:part] && @options[:part] == @params[:part]
    # fetching only a part, do not open this element (same as original caller) as it is useless and will make us loop the loop.
    @method = 'ignore'
    enter(:void)
    return
  end
  @method = 'void'

  # fetch text
  @options[:included_history] ||= []

  included_text, absolute_url, base_path = self.class.get_template_text(@params[:template], @options[:helper], @options[:base_path])

  if absolute_url
    absolute_url += "::#{@params[:part].gsub('/','_')}" if @params[:part]
    absolute_url += "??#{@options[:part].gsub('/','_')}" if @options[:part]
    if @options[:included_history].include?(absolute_url)
      included_text = parser_error("infinity loop: #{(@options[:included_history] + [absolute_url]).join(' --&gt; ')}", 'include')
    else
      included_history  = @options[:included_history] + [absolute_url]
    end
  else
    # Error: included_text contains the error meessage
    @blocks = [included_text]
    return
  end

  res = self.class.new(included_text, :helper => @options[:helper], :base_path => base_path, :included_history => included_history, :part => @params[:part], :parent => self) # we set :part to avoid loop failure when doing self inclusion

  if @params[:part]
    if iblock = res.ids[@params[:part]]
      included_blocks = include_part(iblock)
      # get all ids from inside the included part:
      @ids.merge! iblock.defined_ids
    else
      included_blocks = [parser_error("'#{@params[:part]}' not found in template '#{@params[:template]}'", 'include')]
    end
  else
    included_blocks = res.blocks
    @ids.merge! res.ids
  end

  enter(:void) # normal scan on content
  # replace 'with'

  @blocks.each do |b|
    next if b.kind_of?(String) || b.method != 'with'
    if target = res.ids[b.params[:part]]
      if target.kind_of?(String)
        # error
      elsif b.empty?
        target.method = 'ignore'
      else
        target.replace_with(b)
      end
    else
      # part not found
      parser_error("'#{b.params[:part]}' not found in template '#{@params[:template]}'", 'with')
    end
  end
  @blocks = included_blocks
end

#inspectObject



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
# File 'lib/zafu/parser.rb', line 630

def inspect
  attributes = []
  params = []
  (@params || {}).each do |k,v|
    unless v.nil?
      params << "#{k.inspect.gsub('"', "'")}=>'#{v}'"
    end
  end
  attributes << " {= #{params.sort.join(', ')}}" unless params == []

  context = []
  (@context || {}).each do |k,v|
    unless v.nil?
      context << "#{k.inspect.gsub('"', "'")}=>'#{v}'"
    end
  end
  attributes << " {> #{context.sort.join(', ')}}" unless context == []

  res = []
  @blocks.each do |b|
    if b.kind_of?(String)
      res << b
    else
      res << b.inspect
    end
  end
  result = "[#{@method}#{attributes.join('')}"
  if res != []
    result += "]#{res}[/#{@method}]"
  else
    result += "/]"
  end
  result + @text
end

#leave(mode = nil) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
# File 'lib/zafu/parser.rb', line 539

def leave(mode=nil)
  if mode.nil?
    @stack = []
    return
  end
  pop  = true
  while @stack != [] && pop
    pop = @stack.pop
    break if pop == mode
  end
end

#make(mode, opts = {}) ⇒ Object



520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/zafu/parser.rb', line 520

def make(mode, opts={})
  if opts[:text]
    custom_text = opts.delete(:text)
  end
  text = custom_text || @text
  opts = @options.merge(opts).merge(:sub => true, :mode => mode, :parent => self)
  new_obj = self.class.new(text, opts)
  if new_obj.success?
    @text = new_obj.text unless custom_text
    new_obj.text = ""
    store new_obj
  else
    flush @text[0..(new_obj.text.length - @text.length)] unless custom_text
  end
  # puts "MADE #{new_obj.inspect}"
  # puts "TEXT #{@text.inspect}"
  new_obj
end

#out(str) ⇒ Object

Output ERB code during ast processing.



480
481
482
483
484
# File 'lib/zafu/parser.rb', line 480

def out(str)
  @result << str
  # Avoid double entry when this is the last call in a render method.
  true
end

#out_post(str) ⇒ Object

Output ERB code that will be inserted after @result.



487
488
489
490
491
# File 'lib/zafu/parser.rb', line 487

def out_post(str)
  @out_post << str
  # Avoid double entry when this is the last call in a render method.
  true
end

#parser_continue(message, method = @method) ⇒ Object



144
145
146
# File 'lib/zafu/parser.rb', line 144

def parser_continue(message, method = @method)
  parser_error(message, method, false)
end

#parser_error(message, method = @method, halt = true) ⇒ Object



135
136
137
138
139
140
141
142
# File 'lib/zafu/parser.rb', line 135

def parser_error(message, method = @method, halt = true)
  if halt
    self.class.parser_error(message, method)
  else
    @errors << self.class.parser_error(message, method)
    nil
  end
end

#process(context = {}) ⇒ Object



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
# File 'lib/zafu/parser.rb', line 237

def process(context={})
  return '' if @method == 'ignore' || @method.blank?

  saved = save_state

  if @name
    # we pass the name as 'context' in the children tags
    @context = context.merge(:name => @name)
  else
    @context = context
  end
  # FIXME: replace with array and join (faster)
  @result   = ""
  @out_post = ""
  @pass     = nil

  before_process

  res = wrap(expander || default_expander)

  res = after_process(res)

  # restore state
  restore_state(saved)

  res
end

#process_unknownObject



148
149
150
151
152
153
154
155
# File 'lib/zafu/parser.rb', line 148

def process_unknown
  self.class.process_unknown_callbacks.each do |callback|
    if res = send(callback)
      return res
    end
  end
  @errors.empty? ? default_unknown : show_errors
end

#r_expand_withObject

Set context with variables (unsafe) from template.



313
314
315
316
317
318
319
# File 'lib/zafu/parser.rb', line 313

def r_expand_with
  hash = {}
  @params.each do |k,v|
    hash["exp_#{k}"] = v.inspect
  end
  expand_with(hash)
end

#r_ignoreObject



321
322
323
# File 'lib/zafu/parser.rb', line 321

def r_ignore
  ''
end

#r_inspectObject



290
291
292
293
294
# File 'lib/zafu/parser.rb', line 290

def r_inspect
  expand_with(:preflight=>true)
  @blocks = []
  self.inspect
end

#r_voidObject Also known as: to_s



284
285
286
# File 'lib/zafu/parser.rb', line 284

def r_void
  expand_with
end

#replace_with(obj) ⇒ Object

Hook called when replacing part of an included template with ‘<r:with part=’main’>…</r:with>‘ This replaces the current object ’self’ which is in the original included template, with the custom version ‘obj’.



222
223
224
225
226
# File 'lib/zafu/parser.rb', line 222

def replace_with(obj)
  # keep @method (obj's method is always 'with')
  @blocks = obj.blocks.empty? ? @blocks : obj.blocks
  @params.merge!(obj.params)
end

#restore_state(saved) ⇒ Object

Restore state from a hash



129
130
131
132
133
# File 'lib/zafu/parser.rb', line 129

def restore_state(saved)
  saved.each do |key, value|
    instance_variable_set(key, value)
  end
end

#rootObject

Return the root block (the one opened first).



452
453
454
# File 'lib/zafu/parser.rb', line 452

def root
  @root ||= parent ? parent.root : self
end

#save_stateObject

This method is called at the very beginning of the processing chain and is used to store state to make ‘process’ reintrant…



117
118
119
120
121
122
123
124
125
126
# File 'lib/zafu/parser.rb', line 117

def save_state
  {
   :@context  => @context, # <== we need this when rendering twice the same part
   :@result   => @result,
   :@out_post => @out_post,
   :@params   => @params.dup,
   :@method   => @method,
   :@var      => @var,
  }
end

#show_errorsObject



157
158
159
# File 'lib/zafu/parser.rb', line 157

def show_errors
  @errors.join(' ')
end

#start(mode) ⇒ Object



209
210
211
# File 'lib/zafu/parser.rb', line 209

def start(mode)
  enter(mode)
end

#store(obj) ⇒ Object

Build blocks



471
472
473
474
475
476
477
# File 'lib/zafu/parser.rb', line 471

def store(obj)
  if obj.kind_of?(String) && @blocks.last.kind_of?(String)
    @blocks[-1] << obj
  elsif obj != ''
    @blocks << obj
  end
end

#success?Boolean

Returns:

  • (Boolean)


456
457
458
# File 'lib/zafu/parser.rb', line 456

def success?
  return @ok
end

#to_erb(context) ⇒ Object



204
205
206
207
# File 'lib/zafu/parser.rb', line 204

def to_erb(context)
  context[:helper] ||= @options[:helper]
  process(context)
end

#wrap(text) ⇒ Object



106
107
108
109
110
111
112
113
# File 'lib/zafu/parser.rb', line 106

def wrap(text)
  after_wrap(
    wrap_callbacks(
      before_wrap(text) + @out_post
    )
    # @text contains unparsed data (white space)
  ) + @text
end

#wrap_callbacksObject



104
# File 'lib/zafu/parser.rb', line 104

alias wrap_callbacks wrap