Does Swift compile to native code? - swift

Simple question really, however there doesn't seem to be a straight answer in the current developer documentation.
Does Swift compile to machine language (i.e. assembly), or does it compile to some intermediary form that then runs on a virtual machine?
(I suspect it does, but being unfamiliar with development in Apple's world it is not clear to me like it may be to someone who is.)

Yes, it compiles to machine language by way of LLVM Bitcode and, as #connor said, runs on top of the Objective-C runtime.

Swift not only compiles to native machine code but it has also been designed specifically for it. Unlike e.g. Java which has been designed specifically as a JITed language. By that I mean Swift achieves best performance with ahead of time compilation while Java benefits most from JITing.
There are many reasons for these design choices but among them is that Swift has a much bigger scope than managed languages like Java. It is supposed to work on both desktop computers and phones with more restricted hardware. You can use Swift as a systems programming language unlike say C#, Java or Python because it has little runtime requirements and allow fairly detailed control of memory. So in theory one should be able to build an OS kernel with Swift which would be difficult with say Java.

Swift, just like objective-c compiles to native code using llvm
A good explanation can be found in Apple's top secret Swift language grew from work to sustain Objective C, which it now aims to replace
From that article, talking about Swift
The compiler is optimized for performance, and the language is
optimized for development, without compromising on either.

Swift, like Objective-C, is compiled to machine code that runs on the Objective-C runtime.

Related

Building a simple bridge between objc and lua?

I have integrated Lua with my ObjC code (iphone game). The setup was pretty easy, but now, I have a little problem with the bridging. I have googled for results, etc... and it seems there isn't anything that could work without modifications. I mean, I have checked luaobjc bridge (it seems pretty old and dicontinued), I heard about LuaCocoa but it seems not to work on iphone, and wax is too thick.
My needs are pretty spare, I just need to be able to call objc methods from lua and don't mind having to do extra work to make it work (I don't need a totally authomatic bridging system).
So, I have decided to build a little bridge myself based on this page http://anti-alias.me/?p=36. It has key information about how to accomplish what I need, but the tutorial is not completed and I have some doubts about how to deal with method overloading when called from lua, etc...
Do anybody know if there exist any working bridge between objc and lua on the iphone or if it could be so hard to complete the bridge the above site offers?
Any information will be welcomed.
Don't reinvent the wheel!
First, you are correct that luaobjc and some other variants are outdated. A good overview can be found on the LuaCocoa page. LuaCocoa is fine but apparently doesn't support iPhone development, so the only other choice is Wax. Both LuaCocoa and Wax are runtime bridges, which means that you can (in theory) access every Objective-C class and method in Lua at the expense of runtime performance.
For games and from my experience the runtime performance overhead is so significant that it doesn't warrant the use of any runtime binding library. From a perspective of why one would use a scripting language, both libraries defy the purpose of favoring a scripting language over a lower-level language: they don't provide a DSL solution - which means you're still going to write what is essentially Objective-C code but with a slightly different syntax, no runtime debugging support, and no code editing support in Xcode. In other words: runtime Lua binding is a questionable solution at best, and has lots of cons going against it. Runtime Lua bindings are particularly unsuited for fast-paced action games aiming at a constantly high framerate.
What you want is a static binding. Static bindings at a minimum require you to declare what kind of methods will be available in Lua code. Some binding libraries scan your header files, others require you to provide a special declaration file similar to a header file. Most binding libraries can use both approaches. The benefit is optimal runtime performance, and being able to actually design what classes, methods and variables Lua scripts have access to.
There are but 3 candidates to bind Lua code to an iPhone app. To be fair, there are a lot more but most have one or more crucial flaws or are simply not stable or for special purposes only, or simply don't work for iPhone apps. The candidates are:
tolua and tolua++
luabind
SWIG
Big disadvantage shared by all Lua static binding libraries: none of them can bind directly to Objective-C code. All require to have an additional C or C++ layer available that ultimately interfaces with your Objective-C code. This has to do with how Objective-C works as a language and how small a role it has played (so far) when it comes to embedding Lua in Objective-C apps.
I recently evaluated all three binding libraries and came to enjoy SWIG. It is very well documented but has a bit of a learning curve. But I believe that learning curve is warranted because SWIG can be used to combine nearly any programming and scripting language, it can be advantageous to know how to use SWIG for future projects. Plus, once you understand their definition file implementation it turns out to be very easy (especially when compared to luabind) and considerably more flexible than tolua.
OK, bit late to the party but in case others come late also to this post here's another approach to add to the choices available: hand-code your LUA APIs.
I did a lecture on this topic where I live coded some basic LUA bindings in an hour. Its not hard. From the lecture I made a set of video tutorials that shows how to get started.
The approach of using a bindings generation tool like SWIG is a good one if you already have exactly the APIs that you need to call written in Objective-C and it makes sense to bring all those same API's over into LUA.
The pros of the hand-coding approach:
your project just compiles with one standard Xcode target
your project is all C & Obj-C
the LUA is just data shipped along with your images
no fiddling with "do I check in generated code" to Git
you create LUA functions for just the things you want
you can easily have hosted scripts that live inside an object
the API is under your control and is well known
dont expose engine APIs to level building team/tools
The last point is just that if you have detail functions that only make sense at the engine level and you don't want to see those when coding the game play you'll need to tell SWIG not to bind those.
Steffens answer is perfect and this approach is just another option, that may suit some folks better depending on the project.

How much of the "Objective-C" I'm learning is universal Objective-C, and not Apple's frameworks?

This question is related to one of my others about C: What can you do in C without “std” includes? Are they part of “C,” or just libraries?
I've become curious lately as to what is really contained the the core Objective-C language, and what parts of the Objective-C I've done for iPhone/OS X development is specific to Apple platforms.
I know that things like syntax are the same, but for instance, is NSObject and its torrent of NS-subclasses actually part of "standard" Objective-C? Could I use them in, say, Windows?
What parts are universal for the most part, and what parts would I only find on an Apple platform?
If you want, giving an example of Objective-C used elsewhere as an example of what is more "universal" would help me as well.
Thanks! =)
There are only two current implementations of the core Objective-C libraries, previously known as the NextStep (hence NS prefixes) and OPENSTEP: GNUStep and Apple's OS X. On Linux, if you maintain compatibility with the OPENSTEP specification, GNUStep works very well. However, the specification is ancient, and modern code for OS X will likely not work correctly (especially in the UI area). The situation on Windows is even worse.
You can use the Objective-C language anywhere GCC supports the build target. The "NS" classes are not part of the language proper.
If you're trying to maintain compatibility across platforms in your code base, stick to C or C++, only move UI specific behavior to Objective-C.
Objective-c is C plus these keywords:
#interface, #implementation, #protocol, #end, #private, #protected, #public, #try,
#throw, #catch, #finally, #class, #selector, #encode, #"string", #synchronized,
#property, #synthesized
Plus the message sending syntax: [anObject aMessage];
EDIT
Given that you have an objective-c compiler such as GCC you still need an Objective-c runtime in order to make the above stuff work. e.g. [anObject aMessage] is actually compiled to
objc_msgSend( anObject, #selector(aMessage));
...therefore the symbol objc_msgSend is one of several that must exist at runtime. In theory this could be provided by a compiler intrinsic but in practice you are probably going to link to an Objective-c runtime library - a quick search of my hard drive shows i have three installed:- Apple's, GNUStep, and Cocotron - there are more but Apple's (open source) is without doubt the most important and influential.
With an Objective-c compiler and runtime - but without any Apple Objective-c frameworks (NSObject, etc.) - you have a fabulous and very useful C-with-Classses that is much simpler (where simpler means 'better for me') than C++.
You can a lot on Windows using Cocotron, which is a free implementation of Apple's frameworks. It's not complete, and you may run into bugs, but if you're lucky, you can compile your Xcode project as a Windows app without too many changes.
None of the class library is part of the language itself. If you want to see the core Objective-C types, look in include/objc. The core language itself, without any added library, is really scant and not particularly useful.
In practice, however, Objective-C is just about never used outside of the context of an OpenStep framework like Cocoa or GNUstep. So you could view that as the de facto standard library, in which case Foundation is almost universal. (Not 100% of Foundation is that way, but the majority is.)

Interpret Objective C scripts at runtime on iPhone?

Is there anyway to load an objective c script at runtime, and run it against the classes/methods/objects/functions in the current iPhone app?
MAJOR NOTE: The major reason I'd like to do this is to allow me to rapidly prototype an application, and then, after I'm done a major prototyping phase, take the scripts I was writing and compile them at build time instead. I don't ever plan on shipping an app with an objective c interpreter in it.
The reason i ask is that I've been playing around with iPhone wax, a lua interpreter that can be embedded in an iPhone app, and it works very nicely, in the sense that any object/method/function that's publically available in your Objective C code is automatically bridged, and available in lua.
This allows you to rapidly prototype applications by simply making the core of your app be lua files that are in the users documents directory. Just reload the app, and you can test out changes to your lua files without needing to rebuild the app in XCode - a big time saver!
But, with Apples recent 3.1.3 SDK stuff, it got me thinking that the safest approach for doing this type of rapid prototypeing would be if you could use Objective C as the interpreted code... That way, worst case scenario, you could just compile it into your app before your release instead. I have heard that the lua source can be compiled to byte code, and linked in at build time, but I think the ultimate safe thing would be if the scripted source was in objective c, not lua. That way your source is always in objective c, regardless.
This leads me to wondering (i've searched, but come up with nothing) if there are any examples on how to embed an Objective C Interpreter in an iPhone app? This would allow you to rapidly prototype your app against the current classes that are built into your binary, and, when your about to deploy your app, instead of running the classes through the in app interpreter, you compile them in instead.
With the iPad and OS 4, bluetooth and virtual keyboards can work with iPhones and iPads... That's going to make this type of rapid prototyping something much more useful, at least for dev time. If you have an interpreter built into your app and have it on your iPad, for example, you can code against the interpreter while on the road, without XCode. And to me, the most useful way to get the source back to an "apple approved" state would be if the scripts were Objective C.
Objective-C is really just C with a runtime and some syntactic sugar. It's an inherently compiled language (I don't think there are any production-ready interpreters for C, although I might be wrong).
Xcode used to have a feature called ZeroLink to speed up compile time, but removed it in Xcode 3 because it caused too many bugs.
It's not exactly impossible, but it wouldn't be easy enough to be worth it. Objective-C isn't normally an interpreted language. This isn't insurmountable — interpreted vs. compiled is just an implementation choice in most cases. For example, Ruby is traditionally considered an interpreted scripting language, but MacRuby compiles it down to code just like Objective-C produces. So it would be possible to write an interpreter for Objective-C, but nobody has done this. You would have to write it yourself.
Also, the rules forbid interpreters other than Apple's Javascript interpreter. So far this hasn't been enforced on anyone, but if you're trying to be a very straight arrow, interpreted code is unfortunately out as well.
Well, there's a couple worthwhile points to bring up:
Why interpret Objective-C code when you can compile it? I understand the "rapid prototyping" idea, but part of the reason to do that in, e.g., Lua, is because Lua is a much terser language than Objective-C. I don't know if interpreting Objective-C will have as much of a bonus.
If you want to have plugins or dynamically-loadable modules in your app, you can always compile them as a separate bundle and load them, using NSBundle or a similar mechanism.
All that said, I don't know of any Objective-C interpreters. You'd likely have to write your own. I'm not sure if it would violate Apple's guidelines or not: it'd still be Objective-C code, but I thought they had rules against interpreted code, too. (I suppose they never envisioned a hypothetical scenario in which Objective-C was interpreted, though.)
There is a basic Objective-C interpreter:
Check out the posting:
Is there an Objective-C Interpreter for the Mac?
Also:
http://forrst.com/posts/Beginnings_of_a_Objective_C_Interpreter-Tdl
Ch is a commercial C/C++ interpreter. It's made by a company called SoftIntegration.
Not on IPhone, but on Simulator, you can do this with
Dynamic Code Injection Tool
http://dyci.github.com/
There's also another tool, that works a little different way, but allows same functionality
http://injectionforxcode.com/
You should take a look at cycript. You can hook into apps, replace methods on the fly, change variables, you-name-it. It's an hybrid language between Objective-C and JavaScript.
You'll need to jailbreak your iDevice to install it.
Take a look at the documentation for objc_msgSend() and other parts of the Objective-C Runtime Reference. You can essentially parse text and send it to the runtime.

Why isn't there a good scheme/lisp on llvm?

There is Gambit Scheme, MIT Scheme, PLT Scheme, Chicken Scheme, Bigloo, Larceny, ...; then there are all the lisps.
Yet, there's not (to my knowledge) a single popular scheme/lisp on LLVM, even though LLVM provides lots of nice things like:
easier to generate code than x86
easy to make C FFI calls
...
So why is it that there isn't a good scheme/lisp on LLVM?
LLVM provides a lot, but it's still only a small part of the runtime a functional language needs. And C FFI calls are uncomplicated because LLVM leaves memory management to be handled by someone else. Interacting the Garbage Collector is what makes FFI calls difficult in languages such as Scheme.
You might be interested in HLVM, but it's still more than experimental at this point.
For CL: Clasp is a Common Lisp implementation on LLVM, and mocl implements a subset of Common Lisp on LLVM.
For Scheme: there's a self-hosting Scheme->LLVM demo and a prototype LLVM backend for Bigloo Scheme.
For Clojure: there's Rhine, which is a Clojure-inspired lisp.
There's a very small and apparently unoptimised Scheme compiler here:
http://www.ida.liu.se/~tobnu/scheme2llvm/
Taking your question literally,
Writing compilers is hard.
A poor implementation like the one linked above can block new implementations. People going to the LLVM page see that there's a Scheme already, and don't bother writing one.
There's a limited number of people who write and use Scheme (I'm one, not a hater, btw).
There are lots of existing Scheme intepreters and compilers and there's not a screaming need to have a new one.
There's not an immediate, clear benefit to writing a new interpreter using LLVM. Would it be faster, easier, more flexible, better in some way than the other dozens of Scheme implementations?
The LLVM project went with another language (C) to demo their technology, and haven't seen a need to implement a lot of others.
I think that it could be a lot of fun for someone to build an LLVM-based Scheme compiler. The Scheme compilers in SICP and PAIP are both good examples.
Maybe I'm completely misunderstanding the question or context, but I believe that you could use ECL, which is a Common Lisp that compiles down to C, and use the Clang compiler to target LLVM (instead of GCC).
I'm not sure what (if any) benefit this would give you, but it would give you a Lisp running on LLVM =].
One thing to keep in mind is that many of these implementations have C FFIs and native-code compilers that significantly predate LLVM.
CL-LLVM provides Common Lisp bindings for LLVM. It takes the FFI approach, rather than attempting to output LLVM assembly or bitcode directly.
This library is available via Quicklisp.
mocl is a compiler for a relatively static subset of Common Lisp. It compiles via LLVM/Clang.
there's not (to my knowledge) a single
popular scheme/lisp on LLVM
Currently, llvm-gcc is the nearest thing to a popular implementation of any language on LLVM. In particular, there are no mature LLVM-based language implementations with garbage collection yet. I am sure LLVM will be used as the foundation for lots of exciting next-generation language implementations but that will take a lot of time and effort and it is early days for LLVM in this context.
My own HLVM project is one of the only LLVM-based implementations with garbage collection and its GC is multicore-capable but loosely bound: I used a shadow stack for an "uncooperative environment" rather than hacking the C++ code in LLVM to integrate real stack walking.
There is a Scheme2LLVM, apparently based on SICP:
The code is quite similar to the code in the book SICP (Structure and Interpretation of Computer Programs), chapter five, with the difference that it implements the extra functionality that SICP assumes that the explicit control evaluator (virtual machine) already have. Much functionality of the compiler is implemented in a subset of scheme, llvm-defines, which are compiled to llvm functions.
I don't know if it's "good".
GHC is experimenting with a scheme backend and getting really exciting preliminary results over their native code compiler. Granted, that's haskell. But they've recently pushed new changes into LLVM making tail calls easier IIRC. This could be good for some scheme implementation.

Looking for example GUI applications written in Python for the iPhone

I have a little script I wrote in python and it actually works on the iPhone via the terminal. I am looking for code snippets or documentation for the GUI writing for the iPhone -
Actually what I need is to implement an input and some output.
nothing fancy - for now.
I have found this page: http://www.saurik.com/id/5
but as i understand from the article i will need to write it in objective-c which i am not familiar with - do i have to? or can i write in python or just C?
and it is very descriptive, looking for more docs...
Thanks Alot :)
You cannot write an iPhone app in Python that will run on non-jailbroken phones. Apple's SDK license prohibits interpreted code on the iPhone, which definitely excludes Python. Although you can write OS X apps in Python using PyObjC, you still need to understand the Objective-C language both for documentation and for groking the many Cocoa patterns that are closely tied to Objective-C's way of doing things.
Learn Objective-C. For a programer that knows C or C++, it takes only a couple of days to become proficient in Objective-C. If you've never used a language that has pointers before, it may take a little longer. On the flip side, embracing Objective-C's dynamic nature is much easier for developers coming from dynamic languages as opposed to statically typed languages like C/C++/Java/C#.
There is a GUI sample in that link. The whole app is written in Python with ObjC runtime (but no ObjC code involved).
Still, the ObjC "feel" cannot be avoided because UIKit is designed for and uses ObjC. Note that the GUI programmed in Python is extremely slow on the iPhoneOS. Python can be used as testing, but never release an (interpreted) iPhoneOS Python GUI app to public.