Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Objective-C code for static analysis

I love static analysis and compile-time checks, almost to a fault, but most of my day job is in Objective-C. To resolve this tension, I'd like to be able to write my own analysis tools that I can run on my Objective-C projects.

But googling around the Internet suggests that people are having a hard time putting together a complete Objective-C grammar. One site basically recommends giving up.

I did find a grammar on the ANTLR website, but when I fired it up, I couldn't get it to parse anything at all. For example, it responded to the line:

void x();

with src/main/resources/somecode.m line 1:0 no viable alternative at input 'void'

:(

I took a closer look at the grammar and found the following disheartening disclaimer:

it's a work in progress, most of the .h file can be parsed

But I need something that can parse both interface and implementation.

Is there a complete Objective-C 2.0 grammar out there somewhere? I'd prefer something that can work with Scala (so anything Java compatible, like ANTLR, would be perfect), but at this point I'd be willing to adapt something designed for another parser toolkit.

like image 888
Bill Avatar asked Jul 22 '11 12:07

Bill


4 Answers

As others mentioned, Clang would be the right solution. You can provide your own AST consumers, i.e. classes that will be invoked when going over the AST, leaving you not having to worry about parsing or messing with grammar.

Clang supports Objective-C in its entirety, and there's a lot of classes already in the static analyzer that you can model your own checks after. (in clang/lib/StaticAnalyzer/Checkers).

That directory contains a lot of static analyzer checkers, but you can also just create a normal AST consumer. Refer to http://code.google.com/p/chromium/wiki/WritingClangPlugins for more information.

like image 175
yan Avatar answered Nov 14 '22 19:11

yan


Clang is a static analysis tool that has support for Objective-C. I've found it very useful in the past.

http://clang-analyzer.llvm.org/

like image 20
Matthieu Cormier Avatar answered Nov 14 '22 20:11

Matthieu Cormier


clang is extensible; you can extend their existing static analysis or create your own. llvm / clang is architected as a series of libraries you can link to (dynamically or statically). A great starting point is the ARC (automatic reference counting) migrator library, which is responsible for statically analysing and rewriting objective-c code.

arcmt-test is a small example program that consumes the ARC migrator library.

like image 4
Stuart Carnie Avatar answered Nov 14 '22 20:11

Stuart Carnie


You can use OCDepend, it's a static analysis tool based on Clang that simplifies managing Objective-C code quality and provides a highly flexible code query framework.

like image 1
Dane Avatar answered Nov 14 '22 20:11

Dane