Class: SwiftTools::ObjC2Swift

Inherits:
Object
  • Object
show all
Defined in:
lib/swift_tools/objc_2_swift.rb

Constant Summary collapse

INDENT =
'    '

Instance Method Summary collapse

Constructor Details

#initializeObjC2Swift

Returns a new instance of ObjC2Swift.



6
7
# File 'lib/swift_tools/objc_2_swift.rb', line 6

def initialize
end

Instance Method Details



237
238
239
240
241
242
243
# File 'lib/swift_tools/objc_2_swift.rb', line 237

def capture_copyright(content)
  copyright = nil
  content.match(/^\s*\/\/.*Copyright.*$/) {|m|
    copyright = m[0]
  }
  copyright
end

#capture_implementation(content) ⇒ Object



345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/swift_tools/objc_2_swift.rb', line 345

def capture_implementation(content)
  implementations = {}
  content.scan(/^\s*@implementation *([a-zA-Z0-9_]+)((?:.|\n)*?)@end *\n$/m).each {|m|
    body = m[1]
    methods = capture_methods(body, in_hdr = false)

    implementations[m[0]] = {
        :methods => methods,
        :inits => []
    }
  }
  implementations
end

#capture_imports(h_filename, content) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/swift_tools/objc_2_swift.rb', line 245

def capture_imports(h_filename, content)
  r1 = ''
  r2 = ''
  content.to_enum(:scan, /[@#]import *"?([\.a-zA-Z0-9_]+)"? *;? *\n?/m).map { Regexp.last_match }.each {|m|
    s = m[0].strip
    if s.start_with?("#")
      if s.index(h_filename).nil?
        r2 += "// TODO: Add '#{s}' to bridging header\n"
      end
    else
      r1 += "import #{m[1]}\n"
    end
  }
  {:at_imports => r1, :hash_imports => r2}
end

#capture_interfaces(content, in_hdr) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/swift_tools/objc_2_swift.rb', line 279

def capture_interfaces(content, in_hdr)
  interfaces = {}
  content.scan(/^\s*@interface *([a-zA-Z0-9_]+)(?: *: *([a-zA-Z0-9_]+) *)?(?: *\(([a-zA-Z0-9_, ]*)\))?(?: *<(.+)>)?((?:.|\n)*?)@end *\n$/m).each {|m|
    body = m[4]
    properties = capture_properties(body, in_hdr)
    methods = capture_methods(body, in_hdr)

    interfaces[m[0]] = {
      :base => m[1],
      :categories => m[2] == '' ? nil : m[2],
      :protocols => m[3],
      :properties => properties,
      :methods => methods,
      :inits => []
    }
  }
  interfaces
end

#capture_method_args(content) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/swift_tools/objc_2_swift.rb', line 359

def capture_method_args(content)
  args = []
  raw_args = content.gsub(/ *\*/, '*')
  raw_args = raw_args.split(' ') # The only space left should be between the args
  raw_args.each {|raw_arg|
    m = raw_arg.match(/\((.*)\)(.*)/)
    unless m.nil?
      args.push([map_type(remove_ptr(m[1])), m[2]])
    end
  }
  args
end

#capture_methods(content, in_hdr) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/swift_tools/objc_2_swift.rb', line 323

def capture_methods(content, in_hdr)
  methods = {}
  content.to_enum(:scan, /^ *(\+|-)? *\(([a-zA-Z0-9_]+)\) *([a-zA-Z0-9_]+)(?: *: *)?([^}]*?){/m).map { Regexp.last_match }.each {|m|
    if in_hdr
      body = ''
    else
      body_start_offset = m.offset(0)[1]
      body_end_offset = find_close_char_offset(content, body_start_offset, '{', '}') - 1
      body = indent_lines(content[body_start_offset..body_end_offset])
    end

    methods[m[3]] = {
      :scope => (m[1] == '+' ? :static : :instance),
      :return_type => map_type(remove_ptr(m[2])),
      :args => capture_method_args(m[4]),
      :visibility => in_hdr ? :public : :private,
      :body => body
    }
  }
  methods
end

#capture_properties(content, in_hdr) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/swift_tools/objc_2_swift.rb', line 298

def capture_properties(content, in_hdr)
  properties = {}
  content.to_enum(:scan, /^ *@property *\(([a-zA-Z0-9_=, ]*)\) *(IBOutlet)? *([a-zA-Z0-9_\*]+) *([a-zA-Z0-9_\*]+) */m).map { Regexp.last_match }.each {|m|
    name = m[4]
    type = map_type(remove_ptr(m[3]))
    options = Hash[m[1].split(',').map(&:strip).collect {|s|
      a = s.split('=')
      if a.length > 1
        [a[0].to_sym, a[1]]
      else
        [a[0].to_sym, true]
      end
    }]
    if m[2]
      options[:ib_outlet] = true
    end
    properties[remove_ptr(name)] = {
        :type => type,
        :visibility => in_hdr ? :public : :private,
        :scope => :instance
    }.merge(options)
  }
  properties
end

#capture_statics(content) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/swift_tools/objc_2_swift.rb', line 261

def capture_statics(content)
  statics = ''
  content.scan(/static *(.*?);/m) {|m|
    decl = m[0]
    decl.gsub!('const', '')
    decl.gsub!('*', '')
    decl.gsub!('@"', '"')
    decl.scan(/([a-zA-Z0-9_\*]+) +([a-zA-Z0-9_\*]+)(?: *= *(.*))?/m) {|mm|
      statics += "// TODO: Add 'static let #{mm[1]}: #{map_type(mm[0])}"
      if mm[2]
        statics += " = #{mm[2]}"
      end
      statics += "' to one of your classes'\n"
    }
  }
  statics
end

#convert_block_to_closure(content) ⇒ Object



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

def convert_block_to_closure(content)
  content.gsub!(/\^(?:\(([a-zA-Z0-9_,\* ]+)\))?(?: |\n)*\{/m) {|m|
    if $1
      '{ ' + convert_param_list($1) + ' in '
    else
      '{\n'
    end
  }
end

#convert_param_list(content) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
# File 'lib/swift_tools/objc_2_swift.rb', line 457

def convert_param_list(content)
  params = ''
  content.split(/ *, */).each {|param|
    pair = param.split(' ')
    if params.length > 0
      params += ', '
    end
    params += "#{remove_ptr(pair[1])}: #{map_type(remove_ptr(pair[0]))}"
  }
  '(' + params + ')'
end

#convert_to_dot_syntax(content) ⇒ Object



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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/swift_tools/objc_2_swift.rb', line 372

def convert_to_dot_syntax(content)
  # Repeatedly find a [] syntax method call that does not have a nested [] call
  # and convert it until done.
  while m = content.match(/\[([^\[\]]+?)\]/) do
    # Parse m[0], convert to . syntax and substitute into 'content'
    body = m[1].strip
    params = []

    # Get the object name
    obj_match = body.match(/^([a-zA-Z0-9_\.\(\)]+)/)
    obj_name = obj_match[1]

    # Search for label with empty parameter list
    label_match = body.match(/(?:\n| )([a-zA-Z0-9_]+)/, obj_match.offset(0)[1])

    if label_match and label_match.offset(0)[1] >= body.length
      # There are no parameters
      params.push({:name => label_match[1], :value => nil})
    else
      # There are labelled parameters, start parsing them by searching for the labels
      param_label_re = /(?:\n| )+([a-zA-Z0-9_]+) *:/
      label_match = body.match(param_label_re, obj_match.offset(0)[1])

      unless label_match.nil?
        arg = { :name => label_match[1]}

        if block_match = body.match(/ *(?:\(.*?\))?(?: |\n)\{/, label_match.offset(0)[1])
          end_of_param = find_close_char_offset(body, block_match.offset(0)[1], '{', '}') + 1
        else
          # Find the next arg label or the end of the string
          next_label_match = body.match(param_label_re, label_match.offset(0)[1])
          if next_label_match.nil?
            end_of_param = body.length
          else
            end_of_param = next_label_match.offset(0)[0]
          end
        end
        arg[:value] = body[label_match.offset(0)[1]...end_of_param]
        params.push(arg)
        label_match = next_label_match
      end until label_match.nil?
    end

    new_call = "#{obj_name}."
    params.each_index {|i|
      if i == 0
        new_call += params[i][:name] + '(' + (params[i][:value] || '')
      else
        new_call += ", #{params[i][:name]}: #{params[i][:value]}"
      end
    }
    new_call += ')'

    # Replace the orginal method call
    content[Range.make(m.offset(0), true)] = new_call
  end
end

#convert_underscore_props(content, properties) ⇒ Object



441
442
443
444
445
# File 'lib/swift_tools/objc_2_swift.rb', line 441

def convert_underscore_props(content, properties)
  properties.each {|prop_name, prop_data|
      content.gsub!(Regexp.new('\b_' + prop_name + '\b'), "self.#{prop_name}")
  }
end

#convert_var_decls(content) ⇒ Object



430
431
432
433
434
435
436
437
438
439
# File 'lib/swift_tools/objc_2_swift.rb', line 430

def convert_var_decls(content)
  # Note, this must be done _before_ removing EOL semicolons
  content.gsub!(/^( *)([a-zA-Z0-9_\*]+) +([a-zA-Z0-9_\*]+)(?: *= *(.*?))? *;/m) {|m|
    decl = "#{$1}var #{remove_ptr($3)}: #{map_type(remove_ptr($2))}"
    if $4
      decl += " = #{$4}"
    end
    decl
  }
end

#execute(h_file, m_file, swift_file, options) ⇒ Object



9
10
11
12
13
14
15
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
208
209
210
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
# File 'lib/swift_tools/objc_2_swift.rb', line 9

def execute(h_file, m_file, swift_file, options)
  hdr_content = h_file.read()
  h_filename = File.basename(h_file.to_path)

  imports = capture_imports(h_filename, hdr_content)
  statics = capture_statics(hdr_content)
  interfaces = capture_interfaces(hdr_content, in_hdr = true)
  copyright = capture_copyright(hdr_content)

  unless m_file.nil?
    impl_content = m_file.read()
    implementations = capture_implementation(impl_content)
    impl_imports = capture_imports(h_filename, impl_content)
    impl_interfaces = capture_interfaces(impl_content, in_hdr = false)
  end

  # Add copyright
  unless copyright.nil?
    swift_file.write("//\n#{copyright}\n//\n\n")
  end

  # Combine all the imports
  swift_file.write(imports[:at_imports])
  swift_file.write(impl_imports[:at_imports]) unless impl_imports.nil?
  swift_file.write(imports[:hash_imports])
  swift_file.write(impl_imports[:hash_imports]) unless impl_imports.nil?
  swift_file.write("\n")

  # Write statics
  swift_file.write(statics)
  swift_file.write("\n")

  # Combine interfaces
  unless impl_interfaces.nil?
    impl_interfaces.each { |name, data|
      hdr_has_interface = interfaces.include?(name)
      interfaces[name][:properties].merge!(data[:properties]) if hdr_has_interface
      interfaces[name][:methods].merge!(data[:methods]) { |key, v1, v2|
        {
            :scope => v2[:scope],
            :return_type => v2[:return_type],
            :visibility => v1[:visibility]
        }
      } if hdr_has_interface
    }
  end

  # Combine implementations
  unless implementations.nil?
    implementations.each { |name, data|
      have_interface = interfaces.include?(name)
      interfaces[name][:methods].merge!(data[:methods]) { |key, v1, v2|
        {
            :scope => v1[:scope] || v2[:scope],
            :return_type => v1[:return_type],
            :visibility => v1[:visibility],
            :args => v2[:args],
            :body => v2[:body]
        }
      } if have_interface
    }
  end

  # Output classes or extensions from interfaces
  interfaces.each {|interface_name, interface_data|
    swift_file.write("@objc class #{interface_name}")
    if interface_data[:base] != nil
      swift_file.write(": #{interface_data[:base]}")
    end
    if interface_data[:protocols] != nil
      swift_file.write(", #{interface_data[:protocols]}")
    end
    swift_file.write("{\n")

    # Create Swift singletons
    if interface_data[:methods].include?('sharedInstance')
      interface_data[:methods].delete('sharedInstance')
      interface_data[:properties]['sharedInstance'] = {
          :const => true,
          :visibility => :public,
          :scope => :static,
          :initializer => "#{interface_name}()"
      }
      interface_data[:inits].push({
          body: '',
          :visibility => :private
      })
    end

    # Add getter props
    new_properties = {}
    interface_data[:properties].each {|prop_name, prop_data|
      if prop_data[:getter]
        new_properties[prop_data[:getter]] = {
            :visibility => :public,
            :type => 'Bool',
            :scope => prop_data[:scope],
            :body => "return #{prop_name}"
        }

        # Remove :readonly if set and make private
        prop_data.delete(:readonly)
        prop_data[:visibility] = :private
      end
    }
    interface_data[:properties].merge!(new_properties)

    # Write properties
    interface_data[:properties].each {|prop_name, prop_data|
      line = INDENT
      if prop_data[:ib_outlet]
        line += "@IBOutlet "
      end

      if prop_data[:readonly]
        line += "private(set) "
      elsif prop_data[:visibility] == :private
        line += 'private '
      end

      if prop_data[:scope] == :static
        line += "static "
      end

      if prop_data[:weak]
        line += 'weak '
      end

      if prop_data[:const]
        line += 'let '
      else
        line += 'var '
      end

      line += "#{prop_name}"

      if prop_data[:type]
        line += ": #{prop_data[:type]}"
      end

      unless prop_data[:notnull]
        line += '!'
      end

      if prop_data[:initializer]
        line += " = #{prop_data[:initializer]}"
      end

      if prop_data[:body]
        line += " {\n" + INDENT + INDENT + prop_data[:body] + "\n" + INDENT + "}"
      end

      line += "\n"

      swift_file.write(line)
    }

    # Write inits
    interface_data[:inits].each {|init_data|
      line = "\n" + INDENT

      if init_data[:visibility] == :private
        line += 'private '
      end

      if interface_data[:base]
        line += 'override '
      end

      line += "init() {"

      if init_data[:body].length > 0
        line += "\n" + body + "\n"
      end

      line += "}\n"
      swift_file.write(line)
    }

    # Write methods
    interface_data[:methods].each {|method_name, method_data|
      line = "\n" + INDENT

      if method_data[:visibility] == :private
        line += 'private '
      end

      line += "func #{method_name}("
      args = method_data[:args]
      args.each_index {|i|
        if i > 0
          line += ", "
        end
        line += args[i][1] + ": " + args[i][0]
      }
      line += ")"
      if method_data[:return_type] and method_data[:return_type] != 'Void'
        line += " -> #{method_data[:return_type]}"
      end

      line += ' {'

      if method_data[:body].strip.length == 0
        line += "}\n"
      else
        body = method_data[:body]
        convert_var_decls(body)
        remove_eol_semicolons(body)
        convert_to_dot_syntax(body)
        convert_underscore_props(body, interface_data[:properties])
        convert_block_to_closure(body)
        fix_if_statements(body)
        fix_switch_statements(body)
        fix_yes_no(body)
        fix_null(body)
        fix_at_string(body)
        fix_broken_else(body)
        fix_alloc_init(body)
        line += body + INDENT + "}\n"
      end

      swift_file.write(line)
    }

    swift_file.write("}\n")
  }
end

#find_close_char_offset(content, offset, open_char, close_char) ⇒ Object



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/swift_tools/objc_2_swift.rb', line 515

def find_close_char_offset(content, offset, open_char, close_char)
  count = 1
  loop do
    if offset >= content.length
      raise "Ran out of content looking for #{close_char}"
    elsif content[offset] == close_char
      count -= 1
      if count == 0
        break
      end
    elsif content[offset] == open_char
      count += 1
    end
    offset += 1
  end
  offset
end

#fix_alloc_init(content) ⇒ Object



469
470
471
472
473
474
475
476
# File 'lib/swift_tools/objc_2_swift.rb', line 469

def fix_alloc_init(content)
  content.gsub!(/([a-zA-Z0-9_]+)\.alloc\(\)\.init(?:With([a-zA-Z0-9_]+))?\(/) { |m|
    r = "#{$1}("
    if $2
      r += $2[0].downcase + $2[1..-1] + ': '
    end
  }
end

#fix_at_string(content) ⇒ Object



507
508
509
# File 'lib/swift_tools/objc_2_swift.rb', line 507

def fix_at_string(content)
  content.gsub!(/@"/, '"')
end

#fix_broken_else(content) ⇒ Object



503
504
505
# File 'lib/swift_tools/objc_2_swift.rb', line 503

def fix_broken_else(content)
  content.gsub!(/\}(?: |\n)*else(?: |\n)*\{/, '} else {')
end

#fix_if_statements(content) ⇒ Object



478
479
480
481
482
# File 'lib/swift_tools/objc_2_swift.rb', line 478

def fix_if_statements(content)
  content.gsub!(/if *\((.+?)\)(?: |\n)*{/m) {|m|
    "if #{$1} {"
  }
end

#fix_null(content) ⇒ Object



499
500
501
# File 'lib/swift_tools/objc_2_swift.rb', line 499

def fix_null(content)
  content.gsub!(/\bNULL\b/, 'nil')
end

#fix_switch_statements(content) ⇒ Object



484
485
486
487
488
489
490
491
# File 'lib/swift_tools/objc_2_swift.rb', line 484

def fix_switch_statements(content)
  content.gsub!(/switch *\((.+?)\)(?: |\n)*{/m) {|m|
    "switch #{$1} {"
  }
  content.gsub!(/^ *break *\n/m) {|m|
    ''
  }
end

#fix_yes_no(content) ⇒ Object



493
494
495
496
497
# File 'lib/swift_tools/objc_2_swift.rb', line 493

def fix_yes_no(content)
  content.gsub!(/\b(YES|NO)\b/) {|m|
    m == 'YES' ? 'true' : 'false'
  }
end

#indent_lines(content) ⇒ Object



533
534
535
536
537
538
539
# File 'lib/swift_tools/objc_2_swift.rb', line 533

def indent_lines(content)
  s = ''
  content.each_line {|line|
    s += INDENT + line
  }
  s
end

#map_type(content) ⇒ Object



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/swift_tools/objc_2_swift.rb', line 545

def map_type(content)
  case content
  when 'BOOL'
    'Bool'
  when 'int'
    'Int'
  when 'uint'
    'UInt'
  when 'long'
    'Long'
  when 'void'
    'Void'
  when 'NSString'
    'String'
  when 'CGRect'
    'CGRect'
  else
    content
  end
end

#remove_eol_semicolons(content) ⇒ Object



511
512
513
# File 'lib/swift_tools/objc_2_swift.rb', line 511

def remove_eol_semicolons(content)
  content.gsub!(/; *$/m, '')
end

#remove_ptr(content) ⇒ Object



541
542
543
# File 'lib/swift_tools/objc_2_swift.rb', line 541

def remove_ptr(content)
  content.gsub('*', '').strip
end