Class: Pdfrb::Content::Parser

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

Overview

Groups a token stream into (operator, operands) invocations. Reuses Source::Tokenizer for operand lexing (content streams use the same PDF object syntax as COS values).

Each invocation is yielded as [operator_class, operands].

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tokenizer) ⇒ Parser

Returns a new instance of Parser.



15
16
17
# File 'lib/pdfrb/content/parser.rb', line 15

def initialize(tokenizer)
  @tokenizer = tokenizer
end

Instance Attribute Details

#tokenizerObject (readonly)

Returns the value of attribute tokenizer.



13
14
15
# File 'lib/pdfrb/content/parser.rb', line 13

def tokenizer
  @tokenizer
end

Class Method Details

.parse(io_or_string) ⇒ Object



19
20
21
22
# File 'lib/pdfrb/content/parser.rb', line 19

def self.parse(io_or_string)
  io = io_or_string.is_a?(::String) ? StringIO.new(io_or_string.b) : io_or_string
  new(Pdfrb::Source::Tokenizer.new(io))
end

Instance Method Details

#each_invocationObject

Yields (operator_class, operands) pairs. Returns an Enumerator if no block.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/pdfrb/content/parser.rb', line 26

def each_invocation
  return enum_for(:each_invocation) unless block_given?

  operands = []
  while (tok = tokenizer.next_token)
    case tok.type
    when :keyword
      op = Pdfrb::Content::Operator[tok.value]
      yield(op || Pdfrb::Content::Operator::Unknown, operands) if op
      operands = []
    when :name
      operands << Pdfrb::Model::Cos::NameEncoding.decode(tok.value)
    when :integer, :real, :true, :false, :null
      operands << tok.value
    when :string, :hex_string
      operands << tok.value
    when :array_open
      operands << consume_array
    when :dict_open
      operands << consume_dict
    end
  end
  self
end