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.



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
199
200
201
202
203
204
205
206
207
208
# File 'lib/zafu/parser.rb', line 165

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)
    if part = opts[:part]
      # Optimization: try to find part from id
      if @text =~ /^(.*?)<[^<>]+id='#{part}'/m
        eat $1
      end
    end
  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



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

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



56
57
58
# File 'lib/zafu/parser.rb', line 56

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

.get_template_text(path, helper, base_path = nil, opts = {}) ⇒ 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
47
48
49
50
# File 'lib/zafu/parser.rb', line 42

def get_template_text(path, helper, base_path=nil, opts={})
  cache = (visitor.zafu_cache ||= {})
  unless res = cache[path]
    res = helper.send(:get_template_text, path, base_path, opts)
    res = [parser_error("template '#{path}' not found", 'include'), nil, nil] unless res
    cache[path] = res
  end
  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, :master_template => opts[:master_template])
end

.parser_error(message, method) ⇒ Object



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

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.



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/zafu/parser.rb', line 402

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.



447
448
449
450
451
452
453
454
455
# File 'lib/zafu/parser.rb', line 447

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

#ancestorsObject



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

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

#check_params(*args) ⇒ Object



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
593
594
595
596
597
598
599
600
601
602
# File 'lib/zafu/parser.rb', line 567

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].



420
421
422
423
424
# File 'lib/zafu/parser.rb', line 420

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

#default_expanderObject

Default processing



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

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



308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/zafu/parser.rb', line 308

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.



458
459
460
# File 'lib/zafu/parser.rb', line 458

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

#descendants(key) ⇒ Object



430
431
432
# File 'lib/zafu/parser.rb', line 430

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

#do_method(sym) ⇒ Object



285
286
287
288
289
290
291
292
293
# File 'lib/zafu/parser.rb', line 285

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)


426
427
428
# File 'lib/zafu/parser.rb', line 426

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

#eat(arg) ⇒ Object

Advance parser.



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

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)


244
245
246
# File 'lib/zafu/parser.rb', line 244

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

#enter(mode) ⇒ Object



516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/zafu/parser.rb', line 516

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



604
605
606
# File 'lib/zafu/parser.rb', line 604

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

#expand_with(acontext = {}) ⇒ Object



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
637
638
639
# File 'lib/zafu/parser.rb', line 608

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



85
86
87
88
89
90
91
92
93
94
95
# File 'lib/zafu/parser.rb', line 85

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



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

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

#failObject



562
563
564
565
# File 'lib/zafu/parser.rb', line 562

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

#flush(str = @text) ⇒ Object



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

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’/>”



240
241
242
# File 'lib/zafu/parser.rb', line 240

def include_part(obj)
  [obj]
end

#include_templateObject



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
395
396
397
398
399
# File 'lib/zafu/parser.rb', line 336

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



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

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



550
551
552
553
554
555
556
557
558
559
560
# File 'lib/zafu/parser.rb', line 550

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



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/zafu/parser.rb', line 531

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.



491
492
493
494
495
# File 'lib/zafu/parser.rb', line 491

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.



498
499
500
501
502
# File 'lib/zafu/parser.rb', line 498

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



148
149
150
# File 'lib/zafu/parser.rb', line 148

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

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



139
140
141
142
143
144
145
146
# File 'lib/zafu/parser.rb', line 139

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



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

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



152
153
154
155
156
157
158
159
# File 'lib/zafu/parser.rb', line 152

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.



324
325
326
327
328
329
330
# File 'lib/zafu/parser.rb', line 324

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

#r_ignoreObject



332
333
334
# File 'lib/zafu/parser.rb', line 332

def r_ignore
  ''
end

#r_inspectObject



301
302
303
304
305
# File 'lib/zafu/parser.rb', line 301

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

#r_voidObject Also known as: to_s



295
296
297
# File 'lib/zafu/parser.rb', line 295

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’.



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

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

#restore_state(saved) ⇒ Object

Restore state from a hash



133
134
135
136
137
# File 'lib/zafu/parser.rb', line 133

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).



463
464
465
# File 'lib/zafu/parser.rb', line 463

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…



121
122
123
124
125
126
127
128
129
130
# File 'lib/zafu/parser.rb', line 121

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



161
162
163
# File 'lib/zafu/parser.rb', line 161

def show_errors
  @errors.join(' ')
end

#start(mode) ⇒ Object



219
220
221
# File 'lib/zafu/parser.rb', line 219

def start(mode)
  enter(mode)
end

#store(obj) ⇒ Object

Build blocks



482
483
484
485
486
487
488
# File 'lib/zafu/parser.rb', line 482

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)


467
468
469
# File 'lib/zafu/parser.rb', line 467

def success?
  return @ok
end

#to_erb(context) ⇒ Object



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

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

#wrap(text) ⇒ Object



110
111
112
113
114
115
116
117
# File 'lib/zafu/parser.rb', line 110

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

#wrap_callbacksObject



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

alias wrap_callbacks wrap