Class: Rbind::DefaultParser

Inherits:
RNamespace show all
Extended by:
Logger
Defined in:
lib/rbind/default_parser.rb

Instance Attribute Summary

Attributes included from Logger

#log

Attributes inherited from RNamespace

#consts, #operation_alias, #operations, #root, #type_alias, #used_namespaces

Attributes inherited from RDataType

#cdelete_method, #check_type, #invalid_value, #typedef

Attributes inherited from RBase

#alias, #auto_alias, #cname, #csignature, #doc, #extern_package_name, #ignore, #name, #namespace, #owner, #signature, #version

Instance Method Summary collapse

Methods included from Logger

extend_object

Methods inherited from RNamespace

#add_const, #add_const_val, #add_default_types, #add_namespace, #add_operation, #add_simple_type, #add_simple_types, #add_type_alias, #const, #constructor?, #container?, default_operators, #delete_type, #each_const, #each_container, #each_operation, #each_type, #empty?, #enum_hash, #extern?, #method_missing, #operation, #operation?, #pretty_print, #pretty_print_name, #root?, #type, #type?, #types, #use_namespace, #used_extern_types

Methods included from Hooks

included

Methods inherited from RDataType

#==, #basic_type?, #check_type?, #cname, #const?, #container?, #ownership?, #ptr?, #raw?, #ref?, #remove_const, #remove_ownership, #remove_ptr, #remove_ref, #template?, #to_const, #to_ownership, #to_ptr, #to_raw, #to_ref, #to_single_ptr, #typedef?

Methods inherited from RBase

basename, #binding, #delete!, #doc?, #extern?, #full_name, #generate_signatures, #ignore?, #map_to_namespace, namespace, #namespace?, normalize, #overwrite_c, #overwrite_ruby, #pretty_print, #rename, #specialize_ruby, split_name, to_cname, #to_s

Constructor Details

#initialize(root = nil) ⇒ DefaultParser

Returns a new instance of DefaultParser.



6
7
8
9
# File 'lib/rbind/default_parser.rb', line 6

def initialize(root = nil)
    super(nil,root)
    add_default_types if !root
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Rbind::RNamespace

Instance Method Details

#add_class_name(name) ⇒ Object



37
38
39
40
41
# File 'lib/rbind/default_parser.rb', line 37

def add_class_name(name)
    klass = RClass.new(name)
    add_type klass
    klass
end

#add_data_type_name(name) ⇒ Object



25
26
27
28
29
# File 'lib/rbind/default_parser.rb', line 25

def add_data_type_name(name)
    t = RDataType.new(name)
    add_type t
    t
end

#add_namespace_name(name) ⇒ Object



31
32
33
34
35
# File 'lib/rbind/default_parser.rb', line 31

def add_namespace_name(name)
    ns = RNamespace.new(name)
    add_type ns
    ns
end

#add_type(klass) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/rbind/default_parser.rb', line 209

def add_type(klass)
    if klass2 = type(klass.full_name,false)
        if !klass2.is_a?(RClass) || (!klass2.parent_classes.empty? && klass2.parent_classes != klass.parent_classes)
            raise "Cannot add class #{klass.full_name}. A different type #{klass2} is already registered"
        else
            klass.parent_classes.each do |p|
                klass2.add_parent p
            end
            klass2.extern_package_name = klass.extern_package_name
            klass2
        end
    else
        klass.name = klass.name.gsub(">>","> >")
        super(klass)
        klass
    end
end

#attribute(line_number, string, owner = self) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/rbind/default_parser.rb', line 113

def attribute(line_number,string,owner=self)
    flags = string.split(" /")
    array = flags.shift.split(" ")
    type_name = array[0]
    name = array[1]
    type = find_type(owner,type_name,false)
    # auto embedded types
    type ||= begin
                 t = owner.add_type(RClass.new(RBase.normalize(type_name)))
                 t.extern_package_name = @extern_package_name
                 t
             end
    flags = normalize_flags(line_number,flags,:RW,:R)
    a = RAttribute.new(name,type)
    a.writeable!(true) if flags.include? :RW
    a
rescue RuntimeError => e
    raise "input line #{line_number}: #{e}"
end

#find_type(owner, type_name, braise = true) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/rbind/default_parser.rb', line 65

def find_type(owner,type_name,braise=true)
    type_name = unmask_template(type_name)
    t = owner.type(type_name,false)
    return t if t

    normalized = type_name.split("_")
    name = normalized.shift
    while !normalized.empty?
        name += "::#{normalized.shift}"
        t = if normalized.empty?
                owner.type(name,false)
            else
                owner.type("#{name}_#{normalized.join("_")}",false)
            end
        return t if t
    end
    t = @on_type_not_found.call(owner,type_name) if @on_type_not_found
    return t if t

    #search again even if we know the type is not there to create a proper error message
    owner.type(type_name,true) if braise
end

#normalize_flags(line_number, flags, *valid_flags) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rbind/default_parser.rb', line 11

def normalize_flags(line_number,flags,*valid_flags)
    flags.map do |flag|
        next if flag.empty?
        if flag =~ /(\w*)(.*)/
            DefaultParser.log.debug "input line #{line_number}: ignoring flag #{$2}" unless $2.empty?
            flag = $1.to_sym
            DefaultParser.log.debug "input line #{line_number}: ignoring flag #{$1}" unless valid_flags.include?(flag)
            flag
        else
            raise "cannot parse flag #{flag.inspect}"
        end
    end.compact
end

#on_type_not_found(&block) ⇒ Object



43
44
45
# File 'lib/rbind/default_parser.rb', line 43

def on_type_not_found(&block)
    @on_type_not_found = block
end

#parameter(line_number, string, owner = self) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rbind/default_parser.rb', line 88

def parameter(line_number,string,owner = self)
    flags = string.split(" /")
    array = flags.shift.split(" ")
    type_name = array.shift
    para_name = array.shift
    default = unmask_template(array.join(" ").gsub("/C",""))
    default.gsub!("/Ref","")
    type = find_type(owner,type_name)
    flags = normalize_flags(line_number,flags,:IO,:O)
    type = if flags.include?(:O) || flags.include?(:IO)
               if type.ptr?
                   type
               else
                   type.to_ref  # the opencv parser encodes references as flags
               end
           elsif type.basic_type?
               type
           else
               type.to_const
           end
    RParameter.new(para_name,type,default)
rescue RuntimeError => e
    raise "input line #{line_number}: #{e}"
end

#parse(string, extern_package_name = nil) ⇒ Object



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
400
401
# File 'lib/rbind/default_parser.rb', line 366

def parse(string,extern_package_name=nil)
    @extern_package_name = extern_package_name

    a = split(string)
    #remove namespances and number at the end of the file
    a.pop if (a.last =~/namespaces:/) == 0
    a.pop if a.last.to_i != 0

    line_number = 1
    a.each do |block|
        begin
        first = block.split(" ",2)[0]
        obj,lines = if first == "const"
                        parse_const(line_number,block)
                    elsif first == "class"
                        parse_class(line_number,block)
                    elsif first == "struct"
                        parse_struct(line_number,block)
                    elsif first == "enum"
                        parse_enum(line_number,block)
                    else
                        parse_operation(line_number,block)
                    end
        line_number+=lines
        rescue RuntimeError => e
            puts "Parsing Error: #{e}"
            puts "Line #{line_number}:"
            puts "--------------------------------------------------"
            puts block
            puts "--------------------------------------------------"
            Kernel.raise
            break
        end
    end
    a.size
end

#parse_class(line_number, string) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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
# File 'lib/rbind/default_parser.rb', line 133

def parse_class(line_number,string)
    lines = string.split("\n")
    a = lines.shift.rstrip
    unless a =~ /class ([,<>a-zA-Z\.\d_:]*) ?:?([<>a-zA-Z\.\:, \d_]*)(.*)/
        raise "cannot parse class #{a}"
    end
    name = $1
    parent_classes = $2
    flags = $3
    parent_classes = if parent_classes
                         classes = parent_classes.gsub(" ","").split(",")
				 # join templates
				 classes.each_with_index do |val,i|
 next unless val
 if val.include?("<")
					 val = [val]
					 (i+1).upto(classes.size-1) do |i2|
  val2 = classes[i2]
  val << val2
  classes[i2] = nil
  if val2.include?(">")
						 break
  end
					 end
					 classes[i] = val.join(",")
                             elsif val =="cv::class" # bug in parser
                                 puts "ignore: parent class #{val} which is invalid for #{$1}"
					 classes[i] = nil
 end
				 end
				classes.compact!
				classes.map do |name|
                             #TODO this should also call the user callback
                             t = type(RBase.normalize(name),false)
                             # remove namespace and try again
                             # this is workaround for the hdr_parser adding 
                             # always the namespace to the parent class
                             t ||= begin
                                       names = name
                                       while((names=RBase.normalize(names).split("::")).size > 1)
                                             names.shift
                                             names = names.join("::")
                                             t = type(names,false)
                                             break t if t
                                       end
                                   end
                             # auto add parent class
                             t ||= begin
    # TODO fix error in parser
    # the parser always adds the current namespace
    # class Blas : public ::cv::Test
    # --> cv::::cv::Test
    name = name.gsub(/^.*::::/,"")	
                                       t = add_type(RClass.new(RBase.normalize(name)))
                                       t.extern_package_name = @extern_package_name
                                       t
                                   end
                         end
                     end
    flags = if flags
               normalize_flags(line_number,flags.gsub(" ","").split("/").compact,:Simple,:Map)
            end
    t = RClass.new(name,*parent_classes)
    t.extern_package_name = @extern_package_name
    t = add_type(t)
    line_counter = 1
    lines.each do |line|
        a = attribute(line_counter+line_number,line,t)
        t.add_attribute(a)
        line_counter += 1
    end
    [t,line_counter]
rescue RuntimeError  => e
    raise "input line #{line_number}: #{e}"
end

#parse_const(line_number, string) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/rbind/default_parser.rb', line 247

def parse_const(line_number,string)
    raise "multi line const are not supported: #{string}" if string.split("\n").size > 1
    unless string =~ /const ([a-zA-Z\.\d_:]*) ?([^\/]*)(.*)/
        raise "cannot parse const #{string}"
    end
    name = $1
    value = $2.chomp("\n").chomp(" ")
    flags = $3
    flags = if flags
               normalize_flags(line_number,flags.gsub(" ","").split("/").compact)
            end

    c = RParameter.new(name,find_type(self,"const int"),value)
    c.extern_package_name = @extern_package_name
    add_const(c)
    [c,1]
end

#parse_enum(line_number, string) ⇒ Object



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
297
298
299
300
301
302
303
304
305
# File 'lib/rbind/default_parser.rb', line 265

def parse_enum(line_number,string)
    lines = string.split("\n")
    a = lines.shift.rstrip.gsub("enum struct ","enum ")
    a = a.gsub("enum class ","enum ")
    unless a =~ /enum ([<>a-zA-Z\.\d_:]*)/
        raise "cannot parse enum#{a}"
    end
    name = $1.gsub("<unnamed>","Unknown")
    renum = REnum.new(name)
    renum = begin
        add_type(renum)
    rescue => e
        t = type(name)
        if !t.is_a? REnum || (renum.name != "Unknown" && !renum.values.empty?)
            raise "cannot overwrite #{t.class}: #{t} with #{renum.class}: #{renum}. Use forward declaration?"
        end
        t
    end

    line_counter = 1
    lines.each do |line|
        line_counter += 1
        line =~ /const ([<>a-zA-Z\.\d_:]*) (.*) \[\]/
        val = $2.strip
        name = $1.strip
        name = name.gsub("#{renum.full_name.gsub("::",".")}.","")       # bug in hdl_parser giving full name for some of the types
        name = name.gsub("#{renum.namespace.gsub("::",".")}.","")
        Set.new(val.split(/[ ><\+\-\*\/\&\|\)\(\~]/)).each do |v|
            c = const(v,false)
            if c
                val.gsub!(v,c.full_name)
            elsif renum.values.include? v
                val.gsub!(v,renum.values[v])
            end
        end
        renum.add_value(name,val)
    end
    [renum,line_counter]
rescue RuntimeError  => e
    raise "input line #{line_number}: #{e}"
end

#parse_operation(line_number, string) ⇒ Object



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
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
# File 'lib/rbind/default_parser.rb', line 307

def parse_operation(line_number,string)
    string = string.gsub(";"," ")        # strip wrong characters from the parser
    a = string.split("\n")
    line = a.shift
    flags = line.split(" /")
    line = flags.shift
    elements = line.split(" ")
    name = elements.shift
    return_type_name = elements.shift
    if return_type_name == "()"
        name += return_type_name
        return_type_name = elements.shift
    end
    alias_name = elements.shift
    alias_name = if alias_name
                     raise "#{line_number}: cannot parse #{string}" unless alias_name =~/^=.*/
                     alias_name.gsub("=","")
                 end

    ns = RBase.namespace(name)
    owner = type(ns,false)
    owner ||= add_namespace_name(ns)
    if return_type_name == "explicit"
        flags << return_type_name
        return_type_name = nil
    end
    flags = normalize_flags(line_number,flags,:S,:O)
    return_type = if return_type_name && !return_type_name.empty?
                      t = find_type(owner,return_type_name)
 if flags.include?(:O)
				  if t.ptr?
 t
				  else
  t.to_ref  # the opencv parser encodes references as flags
				  end
 elsif t.basic_type? && t.name != "c_string"
				  t
 else
				  t.to_const
 end
                  end
    line_counter = 1
    args = a.map do |line|
        p = parameter(line_number+line_counter,line,owner)
        line_counter += 1
        p
    end
    op = ::Rbind::ROperation.new(name,return_type,*args)
    op.alias = alias_name if alias_name && !alias_name.empty?
    op = if flags.include?(:S)
             op.to_static
         else
             op
         end
    type(op.namespace,true).add_operation(op)
    op.extern_package_name = @extern_package_name
    [op,line_counter]
end

#parse_struct(line_number, string) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/rbind/default_parser.rb', line 227

def parse_struct(line_number,string)
    a = string.split("\n")
    first_line = a.shift
    flags = first_line.split(" /")
    name = flags.shift.split(" ")[1]
    flags = normalize_flags(line_number,flags)
    klass = RClass.new(name)
    klass = add_type(klass)
    line_counter = 1
    a.each do |line|
        a = attribute(line_counter+line_number,line,klass)
        klass.add_attribute(a)
        line_counter += 1
    end
    klass.extern_package_name = @extern_package_name
    [klass,line_counter]
rescue RuntimeError  => e
    raise "input line #{line_number}: #{e}"
end

#split(string) ⇒ Object



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

def split(string)
    array = []
    if string
        string.each_line do |line|
            if line == "\n" || line.empty?
               next
            elsif line[0] != " "
                array << line
            elsif !array.empty?
                array[array.size-1] = array.last + line
            end
        end
    end
    array
end

#unmask_template(type_name) ⇒ Object

reverse template masking done by the opencv parser



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rbind/default_parser.rb', line 48

def unmask_template(type_name)
    if(type_name =~/<.*>/)
        return type_name
    end

    type_name = type_name.gsub("cv::vector","vector") # fix namespace
    if(type_name =~/^vector/ || type_name =~/^Ptr/)
       if(type_name =~ /^([a-zA-Z\d]*)_([_a-zA-Z\d]*) ?(\(?.*)\)? */)
          "#{$1}<#{unmask_template($2)}>#{$3}"
       else
           type_name
       end
    else
        type_name
    end
end