9 ms·
Porting Graphing Calculator from C++ to Swift
- snovv_crash 4y agoI wonder how a rewrite of the core algorithms in modern C++ and a Swift wrapper + UI would have compared. This also would have allowed easy porting of the core to other platforms.
- KerrAvon 4y agoVery difficult to do that in practice, because there’s currently no way to bridge C++ directly to Swift. You could bridge it via C, but any reasonable implementation would have to severely limit the amount of direct Swift interaction with the core code, or you’d be spending infinite time maintaining the bridge.
- omar0226 4y agoActually C++ could be bridged thru Objective-C++ which at the same time can be bridged to Swift. A little bit manual, but possible
- avitzur 4y agoYes, precisely. I looked into bridging to C++ initially, but it was impractical.
- boulos 4y agoWas it in C++ originally not C? (It seems like a C FFI bridge would have been straightforward from). Or did it already go from C => Objective-C++ a while back? (I read the article hours ago and didn't notice you'd posted. Btw, I think we would have gotten better conversation if you had said "Hey, this is me! AMA" as a top-level comment)
- avitzur 4y agoIt has been in continuous development since 1985. Before the port, parts were in C, C++, Objective-C, and Objective-C++, as well as Lex, Yacc, GLSL, and Python. Will do the top-level comment.
- danappelxx 4y agoThere’s partial support which is under active development. https://github.com/apple/swift/tree/main/docs/CppInteroperability https://github.com/apple/swift/tree/main/docs/CppInteroperab... https://forums.swift.org/t/swift-and-c-interoperability-workgroup-announcement/54998 https://forums.swift.org/t/swift-and-c-interoperability-work...
- aaaaaaaaaaab 4y ago>You could bridge it via C *Objective-C++
- socialdemocrat 4y agoSwift is portable to other platforms. Not the UI but core logic in Swift would have been portable. Swift can be exposed as C APIs.
- krallja 4y agoGraphing Calculator was one of the delightfully “impossible” things I discovered in the hard disk of our brand new iMac back in 1998. I had just started using a TI-83+ at school, so seeing a 3D full-color animatable graphing calculator with a beautiful equation editor slotted directly into my brain as “this shouldn’t be possible! yet here it is!!” I have never found a real use for it, but always wish I could. I bought the iOS version when I found out about it to pay back the authors for my teen-aged delight. The origin story is cool as heck, too. As discussed many many times on HN: http://pacifict.com/Story/ http://pacifict.com/Story/
- jonhohle 4y agoIf you need to include graphs or equations in a presentation or document, Graphing Calculator provides vectorized versions of both which scale and print beautifully. It’s been a while, but I wrote a few different “slow start” functions for a load balancer and used Graphing Calculator to not only illustrate the behavior, but also show which parameters were tunable.
- elcritch 4y agoOh can it output SVG?
- jonhohle 4y agoBy default EPS, PDF, and TIFF but I haven’t checked the clipboard types to see if there are any other vector formats.
- avitzur 4y agoApplications / Utilities / Grapher is a different application (formerly Curvus Pro X from Arizona Software) which replaced the original Mac OS 7 Apple menu Graphing Calculator because I was very slow porting to Mac OS X.
- noisy_boy 4y agoI browse HN almost daily but have never seen that story. It was wonderful - thanks for sharing.
- viktorcode 4y ago> When I ported individual sections of functionality, the Swift source typically measured 30% the size of the corresponding C++ code. This is impressive.
- GeorgeTirebiter 4y agoWell... there are other metrics besides code size in some sections, such as the total code size for all sections; the speed of compilation/linking; and ultimately, the user experience --- is it as fast or faster than C++ ? When people make 'size' comparisons, I sometimes wonder if they'd best be done using lzip or something on the two code bases -- because the compressors are trying to remove redundancy in coding, and if one uses lots of whitespace in C++ to enhance readability, this should not punish C++ in the size department. You generally want some 'system' ('language' seems too restrictive) to enable one to capture the algorithms rapidly and accurately in some notation (again, 'language' seems not quite the right word), and to as quickly as possible convert said notation into working binary (compiler, interpreter, JIT, etc all fair game) that satisfies the user need. I claim (wrongly?) that these days, we generally only need a decent 'glue' notation that allows us to mash together existing libraries/classes/etc to produce the final product. Some of this glue would be sort-of templates, lispish macros, some would just be e.g. an FFT routine. But only by burying complexity in well-tested, lower-level chunks will we be able to build big systems that don't collapse. Sorry, enough soapbox. I guess I'm suggesting that it's interesting to compare Swift to C++. It sort of begs the question: what is 'the best' way to get some functionality (e.g. this cool calc app) written?
- lebuffon 4y agoThis site gives some insights into potential tradeoffs between Swift and C++ in memory usage and execution times. https://programming-language-benchmarks.vercel.app/swift-vs-cpp https://programming-language-benchmarks.vercel.app/swift-vs-... It's really hard not to like reducing code size to 30% of C++ for long term maintenance IMHO.
- socialdemocrat 4y agoC++ requires a lot more code because it is so clunky and inflexible. Swift is just a lot better language which is why you can get away with much shorter code for the same functionality. I spent 15 years doing C++ and read so many books but always felt the language would get in the way. When switching to the Swift stuff just worked the way it should. No need to read tons of books to find clever tricks to get around inherent limitations of C++. C++ was good for it’s time but it is strange that people think one cannot radically improve on what C++ is with newer languages. It is tied down with backwards compatibility with a 50 year old language. That had lots of advantages, but downsides has caught up with advantages.
- gumby 4y agoCurious what boilerplate is common in C++ that isn’t needed in Swift. I find the repetitive boilerplate level of C++ pretty minimal, especially compared to languages like Java. Template specification used to need a lot of decoration but with auto most of that is gone.
- jcelerier 4y agoif the code started in the 80s, I doubt there's many autos or templates
- unnouinceput 4y agoThat makes 2 of us. When I've read "So much of the repetitive boilerplate code that was necessary for C++ melted away in Swift" my eyes rolled over. For me Swift repetitive boilerplate is on par with the one in C++. Clearly the author never touched Ada nor Python, if that's the number one reason he wanted another language to eliminate the repetitive boilerplate. I suspect he just wanted to learn Swift and that's a good reason enough to make this rewrite, as he admits in the final paragraphs of the article: "I’ve enjoyed learning Swift and am much happier with the state of the code now"
- heavyset_go 4y agoOld code is going to have long implementations of things we take for granted now.
- tomovo 4y agoHeaders? Awkward string manipulation? Very thin standard library? Fragmented build systems? I would describe dealing with those issues as "boilerplate" because it's just a lot of code you should not have to write. Swift is so much more comfortable and fun. (btw I still love C++ and cross platform support completely flips the script)
- _gabe_ 4y ago> Very thin standard library? I'm not sure we're thinking of the same standard library if you would describe it as thin...[0] [0]: https://docs.microsoft.com/en-us/cpp/standard-library/cpp-standard-library-header-files?view=msvc-170 https://docs.microsoft.com/en-us/cpp/standard-library/cpp-st...
- codetrotter 4y ago> Since the ‘80s, I’ve intended to eventually open source my code. As I considered doing that with the C++ code base, I realized that would not be a useful contribution due to the decades of accumulated technical debt making the C++ code unmaintainable. I am confident now that the new code can be made into useful stand-alone Swift Packages for mathematical typesetting, editing, numeric and symbolic computation, and graphing. I hope he decides to also open source the C++ version. It would be interesting to be able to see both versions, and to compare them. Perhaps one of the greatest benefits of open sourcing both versions, that I can see, is that others could then look at the two versions of Ron’s code for inspiration on how to go about porting their own legacy applications from C++ to Swift. Aside from that, it also provides historical context that future programmers and future programming language creators could learn from. Both in terms of good things and any of the lesser good sides.
- ngcc_hk 4y agoWhere is the swift code I wonder ?
- tambourine_man 4y ago> When SwiftUI works it is a nigh-magical delight, but when it behaves unexpectedly or when behavior outside the prescribed path is desired, it can be difficult to understand and work around its limitations. The author is being kind. Once outside the prescribed path, you’re in deep trouble. And that’s the thing with declarative code. There must be a great escape hatch. The framework can’t foresee all possible use cases.
- andrekandre 4y ago> There must be a great escape hatch. or you wait for the next os release (which really hurts adoption and dirties code with lots of workarounds)
- tambourine_man 4y ago100% coverage is impossible. That has to be recognized while still chasing that asymptote
- andrekandre 4y agoyes, definitely, though would hope they could do a better job of back-porting than current...
- spideymans 4y agoA lot of developers seem convinced that Apple will abandon UIKit for SwiftUI, but I just can’t see it happening for this reason
- pilif 4y agoThey will continue to use UIKit / AppKit for their own apps. They will just make it so that doing so will require a private entitlement. 3rd party apps will be restricted to SwiftUI. Apple is very much in the camp of maybe tolerating third parties, but only so long as they only ever do stuff in the bounds of what Apple wants them to do
- 4y ago
- lenkite 4y agoSorry, but boilerplate in C++ ? Did he ever try using templates ? C++ is one language where you can get rid of boilerplate with a truckload of strategies. I suspect [Ancient C/C++] weighed down with tech debt and utilising a plethora of old-code frameworks to Swift is what let him save 30%. If he did the port to Modern C++ and modern libs, he would have likely saved 50%.
- mkl 4y agoHe "typically" saved 70%, and overall >80% (152000 lines down to 29000).
- suby 4y agoI'm surprised by this take. C++ requires you to duplicate signatures in header files, which that alone requires a good degree of boilerplate. Modern C++ offers some tools to be more terse such as keywords like auto, but often times the "proper" way of doing things is the more verbose way. This is a bit of a strawman, but [[nodiscard]] constexpr int Add(const int& a, const int& b) const noexcept { return a + b; }
- bpye 4y agoI guess modules help this a little right? I haven’t used them for anything non-trivial so perhaps I’m overly optimistic.
- mpyne 4y agoThat example has nothing to do with modules. It doesn't even use templates (where concepts would help at least) or the "noexcept(noexcept(...))" thing. Modern C++ does help with most type specification, looping over containers, writing constructors and making value classes. It's definitely not all bad, but there's still a lot of boilerplate to C++.
- bpye 4y agoSorry, I was thinking of modules in response to > C++ requires you to duplicate signatures in header files, which that alone requires a good degree of boilerplate.
- pshirshov 4y ago> I love Swift’s syntax. So much of the repetitive boilerplate code that was necessary for C++ melted away in Swift, leaving only code necessary to represent the logic, making the meaning clearer. To be honest, swift feels more like a bad parody on Scala.
- avitzur 4y agoI wrote the blog post. AMA.
- boulos 4y ago(Thanks!) Can you say more about the parse tree impact on performance? Is the expression left in a tree form and effectively "interpreted" from the AST for all points? Is that the critical path?
- avitzur 4y agoThe math is internally represented as a tree for display and editing. Most of the performance critical code is the numeric evaluation when graphing. For that, the math is compiled to a linear byte code which vastly improves locality of reference and is an opportunity to apply optimizations such as common subexpression elimination and loop invariant code motion.
- boulos 4y agoI hadn't followed the link in article originally to get to https://mobile.twitter.com/RonAvitzur/status/1461023215724097536 https://mobile.twitter.com/RonAvitzur/status/146102321572409.... So literally the process of parsing the expression and producing the byte code is the performance challenge now? Or is it also walking the bytecode to do anything? My basic question would be: why not go back to flex/bison/yacc/whatever via C-FFI? (But I think it would still be bad, since you'll want to get to a Swift data structure for your ops and those will still have the Arc issues)
- avitzur 4y agoThat thread describes me working through performance issues in the initial port eight months ago. Those cases perform adequately now. Parsing is not a bottleneck. Walking the bytecode remains a performance hotspot, as that is where all the numeric calculations occur, but no more or less so comparing the C++ and Swift implementations. I did investigate maintaining the flex/bison parser, since its generated state machine C code is more robust than my handwritten recursive descent parser when presented with pathological input. However, as you say, since I need a Swift data structure in the end, there is little to be gained and a lot of complication bridging via a C-FFI.
- sharikous 4y agoIt's so nice to see an historic application being ported and maintained all the way from the '80s macs to SwiftUI!
- black_13 4y ago