.h++ and .hxx extensions for C++ are now supported
[ohcount] / lib / ohcount / detector.rb
1 # The Detector determines which Monoglot or Polyglot should be
2 # used to parse a source file.
3 #
4 # The Detector primarily uses filename extensions to identify languages.
5 #
6 # The hash EXTENSION_MAP maps a filename extension to the name of a parser.
7 #
8 # If a filename extension is not enough to determine the correct parser (for
9 # instance, the *.m extension can indicate either a Matlab or Objective-C file),
10 # then the EXTENSION_MAP hash will contain a symbol identifying a Ruby method
11 # which will be invoked. This Ruby method can examine the file
12 # contents and return the name of the correct parser.
13 #
14 # Many source files do not have an extension. The method +disambiguate_nil+
15 # is called in these cases. The +file+ command line tool is used to determine
16 # the type of file and select a parser.
17 #
18 # The Detector is covered by DetectorTest.
19 #
20 class Ohcount::Detector
21
22         module ContainsM
23                 # A performance hack -- once we've checked for the presence of *.m files, the result
24                 # is stored here to avoid checking twice.
25                 attr_accessor :contains_m
26         end
27
28         # The primary entry point for the detector.
29         # Given a file context containing the file name, content, and an array of
30         # other filenames in the source tree, attempts to detect which
31         # language family (Monoglot or Polyglot) is in use for this file.
32         #
33         # Returns nil if the language is not recognized or if the file does not
34         # contain any code.
35         #
36         # Example:
37         #
38         #   # List all C/C++ files in the 'src' directory
39         #   Dir.entries("src").each do |file|
40         #     context = Ohcount::SimpleFileContext.new(file)
41         #     polyglot = Ohcount::Detector.detect(context)
42         #     puts "#{file}" if polyglot == 'cncpp'
43         #   end
44         #
45         def self.detect(file_context)
46                 # start with extension
47                 polyglot = EXTENSION_MAP[File.extname(file_context.filename).downcase]
48     case polyglot
49     when String
50       # simplest case
51                   return polyglot if polyglot.is_a?(String)
52     when Symbol
53                   # extension is ambiguous - requires custom disambiguation
54                         self.send(polyglot, file_context)
55     when NilClass
56       return disambiguate_nil(file_context)
57     else
58       raise RuntimeError.new("Unknown file detection type")
59           end
60   end
61
62         # Based solely on the filename, makes a judgment whether a file is a binary format.
63         def self.binary_filename?(filename)
64                 ignore = [
65                         ".svn",
66                         ".jar",
67                         ".tar",
68                         ".gz",
69                         ".tgz",
70                         ".zip",
71                         ".gif",
72                         ".jpg",
73                         ".jpeg",
74                         ".bmp",
75                         ".png",
76                         ".tif",
77                         ".tiff",
78                         ".ogg",
79                         ".aiff",
80                         ".wav",
81                         ".mp3",
82                         ".au",
83                         ".ra",
84                         ".m4a",
85                         ".pdf",
86                         ".mpg",
87                         ".mov",
88                         ".qt",
89                         ".avi"
90                         ]
91                 ignore.include?(File.extname(filename))
92         end
93
94         # If an extension maps to a string, that string must be the name of a glot.
95         # If an extension maps to a Ruby symbol, that symbol must be the name of a
96         # Ruby method which will return the name of a glot.
97         EXTENSION_MAP = {
98                 '.ada'  => "ada",
99                 '.adb'  => "ada",
100                 '.asm'  => "assembler",
101                 '.awk'  => "awk",
102                 '.bas'  => "visualbasic",
103                 '.bat'  => "bat",
104                 '.boo'  => "boo",
105                 '.c'    => "cncpp",
106                 '.cc'   => "cncpp",
107                 '.cpp'  => "cncpp",
108                 '.css'  => "css",
109                 '.c++'  => "cncpp",
110                 '.cxx'  => "cncpp",
111                 '.el'   => "emacslisp",
112                 #               '.cbl'  => "cobol",
113                 #               '.cob'  => "cobol",
114                 '.cs'   => :disambiguate_cs,
115                 '.dylan'=> "dylan",
116                 '.erl'  => "erlang",
117                 '.frx'  => "visualbasic",
118                 '.groovy'=> "groovy",
119                 '.h'    => :disambiguate_h_header,
120                 '.hpp'  => "cncpp",
121                 '.h++'  => "cncpp",
122                 '.hxx'  => "cncpp",
123                 '.hh'   => "cncpp",
124                 '.hrl'  => "erlang",
125                 '.htm'  => "html",
126                 '.html' => "html",
127                 '.inc'  => :disambiguate_inc,
128                 '.java' => "java",
129                 '.js'   => "javascript",
130                 '.jsp'  => "jsp",
131                 '.lua'  => "lua",
132                 '.lsp'  => "lisp",
133                 '.lisp' => "lisp",
134                 '.m'    => :matlab_or_objective_c,
135                 '.mm'   => "objective_c",
136                 '.pas'  => "pascal",
137                 '.pp'   => "pascal",
138                 '.php'  => "php",
139                 '.php3' => "php",
140                 '.php4' => "php",
141                 '.php5' => "php",
142                 '.pl'   => "perl",
143                 '.pm'   => "perl",
144                 '.perl' => "perl",
145                 '.ph'   => "perl",
146                 '.py'   => "python",
147                 '.rhtml'=> "rhtml",
148                 '.rb'   => "ruby",
149                 '.rex'  => "rexx",
150                 '.rexx' => "rexx",
151                 '.s'    => "assembler",
152                 '.S'    => "assembler",
153                 '.sc'   => "scheme",
154                 '.scm'  => "scheme",
155                 '.sh'   => "shell",
156                 '.sql'  => "sql",
157                 '.tcl'  => "tcl",
158                 '.tpl'  => "html",
159                 '.vala' => "vala",
160                 '.vb'   => "visualbasic",
161                 '.vba'  => "visualbasic",
162                 '.vbs'  => "visualbasic",
163                 '.xml'  => "xml",
164                 '.d'            => 'dmd',
165                 '.di'           => 'dmd'
166         }
167
168         protected
169
170         # Returns a count of lines in the buffer matching the given regular expression.
171         def self.lines_matching(buffer, re)
172                 buffer.inject(0) { |total, line| line =~ re ? total+1 : total }
173         end
174
175         # For *.m files, differentiates Matlab from Objective-C.
176         #
177         # This is done with a weighted heuristic that
178         # scans the *.m file contents for keywords,
179         # and also checks for the presence of matching *.h files.
180   def self.matlab_or_objective_c(file_context)
181     buffer = file_context.contents
182
183     # if there are .h files in same directory, this probably isn't matlab
184     h_headers = 0.0
185     h_headers = -0.5 if file_context.filenames.select { |a| a =~ /\.h$/ }.any?
186
187     # if the contents contain 'function (' on a single line - very likely to be matlab
188     # if the contents contain lines starting with '%', its probably matlab comments
189     matlab_signatures = /(^\s*function\s*)|(^\s*%)/
190     matlab_sig_score = 0.1 * lines_matching(buffer, matlab_signatures)
191
192     # if the contents contains '//' or '/*', likely objective_c
193     objective_c_signatures = /(^\s*\/\/\s*)|(^\s*\/\*)|(^[+-])/
194     obj_c_sig_score = -0.1 * lines_matching(buffer, objective_c_signatures)
195
196     matlab = h_headers + matlab_sig_score + obj_c_sig_score
197
198     matlab > 0 ? 'matlab' : 'objective_c'
199   end
200
201         # For *.h files, differentiates C/C++ from Objective-C.
202         #
203         # This is done with a weighted heuristic that
204         # scans the *.h file contents for Objective-C keywords,
205         # and also checks for the presence of matching *.m files.
206         def self.disambiguate_h_header(file_context)
207     buffer = file_context.contents
208
209     objective_c = 0
210
211     # could it be realistically be objective_c ? are there any .m files at all?
212     # Speed hack - remember our findings in case we get the same filenames over and over
213     unless defined?(file_context.filenames.contains_m)
214       file_context.filenames.extend(ContainsM)
215       file_context.filenames.contains_m = file_context.filenames.select { |a| a =~ /\.m$/ }.any?
216     end
217     return 'cncpp' unless file_context.filenames.contains_m
218
219     # if the dir contains a matching *.m file, likely objective_c
220     if file_context.filename =~ /\.h$/
221       m_counterpart = file_context.filename.gsub(/\.h$/, ".m")
222       return 'objective_c' if file_context.filenames.include?(m_counterpart)
223     end
224
225     # ok - it just might be objective_c, let's check contents for objective_c signatures
226     objective_c_signatures = /(^\s*@interface)|(^\s*@end)/
227     objective_c += lines_matching(buffer, objective_c_signatures)
228
229     return objective_c > 1 ? 'objective_c' : 'cncpp'
230         end
231
232         # Tests whether the provided buffer contains binary or text content.
233         # This is not fool-proof -- we basically just check for zero values
234         # in the early bytes of the buffer. If we find a zero, we know it
235         # is not (ascii) text.
236   def self.binary_buffer?(buffer)
237     100.times do |i|
238       return true if buffer[i] == 0
239     end
240     false
241   end
242
243         # True if the provided buffer includes a '?php' directive
244   def self.php_instruction?(buffer)
245     buffer =~ /\?php/
246   end
247
248         # For *.inc files, checks for a PHP class.
249   def self.disambiguate_inc(file_context)
250     buffer = file_context.contents
251     return nil if binary_buffer?(buffer)
252     return 'php' if php_instruction?(buffer)
253     nil
254   end
255
256         # For files with extention *.cs, differentiates C# from Clearsilver.
257   def self.disambiguate_cs(file_context)
258     buffer = file_context.contents
259     return 'clearsilver_template' if lines_matching(file_context.contents, /\<\?cs/) > 0
260     return 'csharp'
261   end
262
263         # Attempts to determine the Polyglot for files that do not have a
264         # filename extension.
265         #
266         # Relies on the bash +file+ command line tool as its primary method.
267         #
268         # There must be a file at <tt>file_context.file_location</tt> for +file+
269         # to operate on.
270         #
271   def self.disambiguate_nil(file_context)
272     file_location = file_context.file_location
273     output = `file -b #{ file_location }`
274     case output
275     when /([\w\/]+) script text/, /script text executable for ([\w\/]+)/
276       script = $1
277       if script =~ /\/(\w*)$/
278         script = $1
279       end
280       known_languages = EXTENSION_MAP.values
281       return script.downcase if known_languages.include?(script.downcase)
282     when /([\w\-]*) shell script text/
283       case $1
284       when "Bourne-Again"
285         return "shell"
286       end
287     end
288
289     # dang... no dice
290     nil
291   end
292
293 end