Class: Bade::Parser

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

Defined Under Namespace

Classes: ParserInternalError, SyntaxError

Constant Summary collapse

WORD_RE =
''.respond_to?(:encoding) ? '\p{Word}' : '\w'
NAME_RE_STRING =
"(#{WORD_RE}(?:#{WORD_RE}|:|-|_)*)"
ATTR_NAME_RE_STRING =
"\\A\\s*#{NAME_RE_STRING}"
CODE_ATTR_RE =
/#{ATTR_NAME_RE_STRING}\s*(&?):\s*/
TAG_RE =
/\A#{NAME_RE_STRING}/
CLASS_TAG_RE =
/\A\.#{NAME_RE_STRING}/
ID_TAG_RE =
/\A##{NAME_RE_STRING}/
RUBY_DELIMITERS_REVERSE =
{
  '(' => ')',
  '[' => ']',
  '{' => '}'
}.freeze
RUBY_QUOTES =
%w(' ").freeze
RUBY_NOT_NESTABLE_DELIMITERS =
RUBY_QUOTES
RUBY_START_DELIMITERS =
(%w(\( [ {) + RUBY_NOT_NESTABLE_DELIMITERS).freeze
RUBY_END_DELIMITERS =
(%w(\) ] }) + RUBY_NOT_NESTABLE_DELIMITERS).freeze
RUBY_ALL_DELIMITERS =
(RUBY_START_DELIMITERS + RUBY_END_DELIMITERS).uniq.freeze
RUBY_START_DELIMITERS_RE =
/\A[#{Regexp.escape RUBY_START_DELIMITERS.join('')}]/
RUBY_END_DELIMITERS_RE =
/\A[#{Regexp.escape RUBY_END_DELIMITERS.join('')}]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Parser

Initialize

Available options:

:tabsize [Int]    default 4
:file [String]    default nil


42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bade/parser.rb', line 42

def initialize(options = {})
  @line = ''

  tabsize = options.delete(:tabsize) { 4 }
  @tabsize = tabsize

  @tab_re = /\G((?: {#{tabsize}})*) {0,#{tabsize-1}}\t/
  @tab = '\1' + ' ' * tabsize

  @options = options

  reset
end

Instance Attribute Details

#dependency_pathsArray<String> (readonly)

Returns:



34
35
36
# File 'lib/bade/parser.rb', line 34

def dependency_paths
  @dependency_paths
end

Instance Method Details

#append_node(type, indent: @indents.length, add: false, data: nil) ⇒ Object

Append element to stacks and result tree

Parameters:

  • type (Symbol)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/bade/parser.rb', line 143

def append_node(type, indent: @indents.length, add: false, data: nil)
  while indent >= @stacks.length
    @stacks << @stacks.last.dup
  end

  parent = @stacks[indent].last
  node = Node.create(type, parent)
  node.lineno = @lineno

  node.data = data

  if add
    @stacks[indent] << node
  end

  node
end

#fixed_trailing_colon(value) ⇒ Object

Parameters:



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

def fixed_trailing_colon(value)
  if value =~ /(:)\Z/
    value = value.sub /:\Z/, ''
    @line.prepend ':'
  end

  value
end

#get_indent(line) ⇒ Int

Calculate indent for line

Parameters:

Returns:

  • (Int)

    indent size



135
136
137
# File 'lib/bade/parser.rb', line 135

def get_indent(line)
  line.get_indent(@tabsize)
end

#next_lineObject



119
120
121
122
123
124
125
126
127
# File 'lib/bade/parser.rb', line 119

def next_line
  if @lines.empty?
    @orig_line = @line = nil
  else
    @orig_line = @lines.shift
    @lineno += 1
    @line = @orig_line.dup
  end
end

#parse(str) ⇒ Bade::Document

Returns root node.

Parameters:

Returns:



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/bade/parser.rb', line 59

def parse(str)
  @document = Document.new(file_path: @options[:file_path])
  @root = @document.root

  @dependency_paths = []

  if str.kind_of? Array
    reset(str, [[@root]])
  else
    reset(str.split(/\r?\n/), [[@root]])
  end

  parse_line while next_line

  reset

  @document
end

#parse_importObject



298
299
300
301
302
303
304
# File 'lib/bade/parser.rb', line 298

def parse_import
  path = eval(@line)
  import_node = append_node :import
  import_node.data = path

  @dependency_paths << path unless @dependency_paths.include?(path)
end

#parse_lineObject



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

def parse_line
  line = @line

  if line =~ /\A\s*\Z/
    append_node :newline
    return
  end

  indent = get_indent(line)

  # left strip
  line.remove_indent!(indent, @tabsize)
  @line = line

  # If there's more stacks than indents, it means that the previous
  # line is expecting this line to be indented.
  expecting_indentation = @stacks.length > @indents.length

  if indent > @indents.last
    @indents << indent
  else
    # This line was *not* indented more than the line before,
    # so we'll just forget about the stack that the previous line pushed.
    @stacks.pop if expecting_indentation

    # This line was deindented.
    # Now we're have to go through the all the indents and figure out
    # how many levels we've deindented.
    while indent < @indents.last
      @indents.pop
      @stacks.pop
    end

    # Remove old stacks we don't need
    while not @stacks[indent].nil? and indent < @stacks[indent].length - 1
      @stacks[indent].pop
    end

    # This line's indentation happens lie "between" two other line's
    # indentation:
    #
    #   hello
    #       world
    #     this      # <- This should not be possible!
    syntax_error('Malformed indentation') if indent != @indents.last
  end

  parse_line_indicators
end

#parse_line_indicatorsObject



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/bade/parser.rb', line 211

def parse_line_indicators
  add_new_line = true

  case @line
    when /\Aimport /
      @line = $'
      parse_import

    when /\Amixin #{NAME_RE_STRING}/
      # Mixin declaration
      @line = $'
      parse_mixin_declaration($1)

    when /\A\+#{NAME_RE_STRING}/
      # Mixin call
      @line = $'
      parse_mixin_call($1)

    when /\Ablock #{NAME_RE_STRING}/
      @line = $'
      if @stacks.last.last.type == :mixin_call
        append_node :mixin_block, data: $1, add: true
      else
        # keyword block used outside of mixin call
        parse_tag($&)
      end

    when /\A\/\/! /
      # HTML comment
      append_node :html_comment, add: true
      parse_text_block $', @indents.last + @tabsize

    when /\A\/\//
      # Comment
      append_node :comment, add: true
      parse_text_block $', @indents.last + @tabsize

    when /\A\|( ?)/
      # Found a text block.
      parse_text_block $', @indents.last + @tabsize

    when /\A</
      # Inline html
      append_node :text, data: @line

    when /\A-\s*(.*)\Z/
      # Found a code block.
      code_node = append_node :ruby_code
      code_node.data = $1
      add_new_line = false

    when /\A(&?)=/
      # Found an output block.
      # We expect the line to be broken or the next line to be indented.
      @line = $'
      output_node = append_node :output
      output_node.escaped = $1.length == 1
      output_node.data = parse_ruby_code("\n")

    when /\A(\w+):\s*\Z/
      # Embedded template detected. It is treated as block.
      @stacks.last << [:slim, :embedded, $1, parse_text_block]

    when /\Adoctype\s/i
      # Found doctype declaration
      append_node :doctype, data: $'.strip

    when TAG_RE
      # Found a HTML tag.
      @line = $' if $1
      parse_tag($&)

    when /\A\./
      # Found class name -> implicit div
      parse_tag 'div'

    when /\A#/
      # Found id name -> implicit div
      parse_tag 'div'

    else
      syntax_error 'Unknown line indicator'
  end

  append_node :newline if add_new_line
end

#parse_mixin_call(mixin_name) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/bade/parser.rb', line 306

def parse_mixin_call(mixin_name)
  mixin_node = append_node :mixin_call, add: true
  mixin_node.data = mixin_name

  parse_mixin_call_params

  case @line
    when /\A /
      @line = $'
      parse_text

    when /\A:\s+/
      # Block expansion
      @line = $'
      parse_line_indicators

    when /\A(&?)=/
      # Handle output code
      parse_line_indicators

    when /^$/
      # nothing

    else
      syntax_error "Unknown symbol after mixin calling, line = `#{@line}'"
  end
end

#parse_mixin_call_paramsObject



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

def parse_mixin_call_params
  # between tag name and attribute must not be space
  # and skip when is nothing other
  if @line =~ /\A\(/
    @line = $'
  else
    return
  end

  end_re = /\A\s*\)/

  while true
    case @line
      when CODE_ATTR_RE
        @line = $'
        attr_node = append_node :mixin_key_param
        attr_node.name = $1
        attr_node.value = parse_ruby_code(',)')

      when /\A\s*,/
        # args delimiter
        @line = $'
        next

      when /^\s*$/
        # spaces and/or end of line
        next_line
        next

      when end_re
        # Find ending delimiter
        @line = $'
        break

      else
        attr_node = append_node :mixin_param
        attr_node.data = parse_ruby_code(',)')
    end
  end
end

#parse_mixin_declaration(mixin_name) ⇒ Object



375
376
377
378
379
380
# File 'lib/bade/parser.rb', line 375

def parse_mixin_declaration(mixin_name)
  mixin_node = append_node :mixin_declaration, add: true
  mixin_node.data = mixin_name

  parse_mixin_declaration_params
end

#parse_mixin_declaration_paramsObject



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/bade/parser.rb', line 382

def parse_mixin_declaration_params
  # between tag name and attribute must not be space
  # and skip when is nothing other
  if @line =~ /\A\(/
    @line = $'
  else
    return
  end

  end_re = /\A\s*\)/

  while true
    case @line
      when CODE_ATTR_RE
        # Value ruby code
        @line = $'
        attr_node = append_node :mixin_key_param
        attr_node.name = $1
        attr_node.value = parse_ruby_code(',)')

      when /\A\s*#{NAME_RE_STRING}/
        @line = $'
        append_node :mixin_param, data: $1

      when /\A\s*&#{NAME_RE_STRING}/
        @line = $'
        append_node :mixin_block_param, data: $1

      when /\A\s*,/
        # args delimiter
        @line = $'
        next

      when end_re
        # Find ending delimiter
        @line = $'
        break

      else
        syntax_error('wrong mixin attribute syntax')
    end
  end
end

#parse_ruby_code(outer_delimiters) ⇒ Void

Parse ruby code, ended with outer delimiters

Parameters:

Returns:

  • (Void)

    parsed ruby code



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

def parse_ruby_code(outer_delimiters)
  code = ''
  end_re = /\A\s*[#{Regexp.escape outer_delimiters.to_s}]/
  delimiters = []

  until @line.empty? or (delimiters.count == 0 and @line =~ end_re)
    char = @line[0]

    # backslash escaped delimiter
    if char == '\\' && RUBY_ALL_DELIMITERS.include?(@line[1])
      code << @line.slice!(0, 2)
      next
    end

    case char
      when RUBY_START_DELIMITERS_RE
        if RUBY_NOT_NESTABLE_DELIMITERS.include?(char) && delimiters.last == char
          # end char of not nestable delimiter
          delimiters.pop
        else
          # diving
          delimiters << char
        end

      when RUBY_END_DELIMITERS_RE
        # rising
        if char == RUBY_DELIMITERS_REVERSE[delimiters.last]
          delimiters.pop
        end
    end

    code << @line.slice!(0)
  end

  unless delimiters.empty?
    syntax_error('Unexpected end of ruby code')
  end

  code.strip
end

#parse_tag(tag) ⇒ Object

Parameters:



447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/bade/parser.rb', line 447

def parse_tag(tag)
  tag = fixed_trailing_colon(tag)

  if tag.is_a? Node
    tag_node = tag
  else
    tag_node = append_node :tag, add: true
    tag_node.name = tag
  end

  parse_tag_attributes

  case @line
    when /\A:\s+/
      # Block expansion
      @line = $'
      parse_line_indicators

    when /\A(&?)=/
      # Handle output code
      parse_line_indicators

    when CLASS_TAG_RE
      # Class name
      @line = $'

      attr_node = append_node :tag_attribute
      attr_node.name = 'class'
      attr_node.value = fixed_trailing_colon($1).single_quote

      parse_tag tag_node

    when ID_TAG_RE
      # Id name
      @line = $'

      attr_node = append_node :tag_attribute
      attr_node.name = 'id'
      attr_node.value = fixed_trailing_colon($1).single_quote

      parse_tag tag_node

    when /\A /
      # Text content
      @line = $'
      parse_text

    when /^$/
      # nothing

    else
      syntax_error "Unknown symbol after tag definition #{@line}"
  end
end

#parse_tag_attributesObject



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
540
541
542
543
544
545
# File 'lib/bade/parser.rb', line 502

def parse_tag_attributes
  # Check to see if there is a delimiter right after the tag name

  # between tag name and attribute must not be space
  # and skip when is nothing other
  if @line =~ /\A\(/
    @line = $'
  else
    return
  end

  end_re = /\A\s*\)/

  while true
    case @line
      when CODE_ATTR_RE
        # Value ruby code
        @line = $'
        attr_node = append_node :tag_attribute
        attr_node.name = $1
        attr_node.value = parse_ruby_code(',)')

      when /\A\s*,/
        # args delimiter
        @line = $'
        next

      when end_re
        # Find ending delimiter
        @line = $'
        break

      else
        # Found something where an attribute should be
        @line.lstrip!
        syntax_error('Expected attribute') unless @line.empty?

        # Attributes span multiple lines
        @stacks.last << [:newline]
        syntax_error("Expected closing delimiter #{delimiter}") if @lines.empty?
        next_line
    end
  end
end

#parse_textObject



426
427
428
429
430
# File 'lib/bade/parser.rb', line 426

def parse_text
  text = @line
  text = text.gsub(/&\{/, '#{ html_escaped ')
  append_node :text, data: text
end

#parse_text_block(first_line, text_indent = nil) ⇒ Object



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/bade/parser.rb', line 547

def parse_text_block(first_line, text_indent = nil)
  if !first_line || first_line.empty?
    text_indent = nil
  else
    @line = first_line
    parse_text
  end

  until @lines.empty?
    if @lines.first =~ /\A\s*\Z/
      next_line
      append_node :newline
    else
      indent = get_indent(@lines.first)
      break if indent <= @indents.last

      next_line

      @line.remove_indent!(text_indent ? text_indent : indent, @tabsize)

      parse_text

      # The indentation of first line of the text block
      # determines the text base indentation.
      text_indent ||= indent
    end
  end
end

#reset(lines = nil, stacks = nil) ⇒ Object



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

def reset(lines = nil, stacks = nil)
  # Since you can indent however you like in Slim, we need to keep a list
  # of how deeply indented you are. For instance, in a template like this:
  #
  #   doctype       # 0 spaces
  #   html          # 0 spaces
  #    head         # 1 space
  #       title     # 4 spaces
  #
  # indents will then contain [0, 1, 4] (when it's processing the last line.)
  #
  # We uses this information to figure out how many steps we must "jump"
  # out when we see an de-indented line.
  @indents = [0]

  # Whenever we want to output something, we'll *always* output it to the
  # last stack in this array. So when there's a line that expects
  # indentation, we simply push a new stack onto this array. When it
  # processes the next line, the content will then be outputted into that
  # stack.
  @stacks = stacks

  @lineno = 0
  @lines = lines

  # @return [String]
  @line = @orig_line = nil
end

#syntax_error(message) ⇒ Object

Raise specific error

Parameters:

Raises:



647
648
649
650
# File 'lib/bade/parser.rb', line 647

def syntax_error(message)
  raise SyntaxError.new(message, @options[:file], @orig_line, @lineno,
              @orig_line && @line ? @orig_line.size - @line.size : 0)
end