Last active
December 11, 2015 03:28
-
-
Save gnufied/4537624 to your computer and use it in GitHub Desktop.
objective c reply
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require "readline" | |
require "fileutils" | |
class CompileObjectiveC | |
attr_accessor :code_lines | |
TMP_DIR = "/tmp" | |
def initialize | |
@code_lines = [] | |
end | |
def start_reading | |
while buf = Readline.readline("obj-c> ", true) | |
process_input(buf) | |
end | |
end | |
def process_input(raw_data) | |
raw_data.strip! | |
return if !raw_data || raw_data.empty? | |
case raw_data | |
when 'clear' | |
@code_lines = [] | |
when /print/ | |
if print_stuff(raw_data) | |
@code_lines.pop | |
end | |
when /^NSLog/ | |
add_and_remove_old_log(raw_data) | |
if compile_and_run | |
@code_lines.pop | |
end | |
else | |
@code_lines << raw_data | |
compile_and_run | |
end | |
end | |
def print_stuff(raw_data) | |
print_arg = raw_data.split(' ',2).last | |
print_arg.strip! | |
return false if !print_arg || print_arg.empty? | |
current_line = %Q{IFPrint(@"\%@\\n",#{print_arg})} | |
@code_lines.reject! { |line| line =~ /IFPrint/ } | |
@code_lines << current_line | |
compile_and_run | |
end | |
def add_and_remove_old_log(raw_data) | |
@code_lines.reject! { |line| line =~ /NSLog/ } | |
@code_lines << raw_data | |
end | |
def compile_and_run | |
File.open("/tmp/foo.m","w") do |fl| | |
fl.puts <<-EOD | |
#import <Foundation/Foundation.h> | |
void IFPrint (NSString *format, ...) { | |
va_list args; | |
va_start(args, format); | |
fputs([[[[NSString alloc] initWithFormat:format arguments:args] autorelease] UTF8String], stdout); | |
va_end(args); | |
} | |
int main (int args, const char *arv[]) | |
{ | |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
EOD | |
code_lines.each do |line| | |
if line =~ /;$/ | |
fl.puts "#{line}" | |
else | |
fl.puts "#{line};" | |
end | |
end | |
fl.puts <<-EOD | |
[pool drain]; | |
return 0; | |
} | |
EOD | |
end | |
success_flag = false | |
FileUtils.cd("/tmp") do | |
success_flag = system("clang -framework Foundation foo.m") | |
if success_flag | |
success_flag = system("./a.out") | |
else | |
@code_lines.pop | |
end | |
end | |
success_flag | |
end | |
end | |
if __FILE__ == $0 | |
CompileObjectiveC.new().start_reading | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment