Class: Markie::Parser

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

Class Method Summary collapse

Class Method Details

.parse(tokens) ⇒ Object



7
8
9
# File 'lib/markie/parser.rb', line 7

def parse(tokens)
  parse_body(tokens)
end

.parse_body(tokens) ⇒ Object



11
12
13
14
# File 'lib/markie/parser.rb', line 11

def parse_body(tokens)
  children = [parse_paragraph(tokens)]
  Node.new(type: :body, token_count: children.map(&:token_count).sum, children: children)
end

.parse_paragraph(tokens, children = []) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/markie/parser.rb', line 16

def parse_paragraph(tokens, children = [])
  if tokens[0].type == :eof
    return Node.new(type: :paragraph, token_count: children.map(&:token_count).sum, children: children)

  elsif tokens[0].type == :text
    next_child = Node.new(type: :text, token_count: 1, value: tokens[0].value)

  elsif tokens[0].type == :underscore && tokens[1].type == :text && tokens[2].type == :underscore
    next_child = Node.new(type: :emphasis, token_count: 3, value: tokens[1].value)

  elsif tokens[0].type == :asterisk && tokens[1].type == :text && tokens[2].type == :asterisk
    next_child = Node.new(type: :emphasis, token_count: 3, value: tokens[1].value)

  elsif tokens[0].type == :open_square_bracket && tokens[1].type == :text && tokens[2].type == :close_square_bracket && tokens[3].type == :open_parenthesis && tokens[4].type == :text && tokens[5].type == :close_parenthesis
    next_child = Node.new(type: :link, token_count: 6, value: tokens[4].value, children: [
      Node.new(type: :text, token_count: 1, value: tokens[1].value),
    ])

  end

  children.append(next_child)
  next_tokens = tokens[next_child.token_count..-1]

  parse_paragraph(next_tokens, children)
end