[NEW] Add *.ads as an Ada extension
[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                 '.ads'  => "ada",
101                 '.asm'  => "assembler",
102                 '.awk'  => "awk",
103                 '.bas'  => "visualbasic",
104                 '.bat'  => "bat",
105                 '.boo'  => "boo",
106                 '.c'    => "cncpp",
107                 '.cc'   => "cncpp",
108                 '.cpp'  => "cncpp",
109                 '.css'  => "css",
110                 '.c++'  => "cncpp",
111                 '.cxx'  => "cncpp",
112                 '.el'   => "emacslisp",
113                 #               '.cbl'  => "cobol",
114                 #               '.cob'  => "cobol",
115                 '.cs'   => :disambiguate_cs,
116                 '.dylan'=> "dylan",
117                 '.erl'  => "erlang",
118                 '.frx'  => "visualbasic",
119                 '.groovy'=> "groovy",
120                 '.h'    => :disambiguate_h_header,
121                 '.hpp'  => "cncpp",
122                 '.h++'  => "cncpp",
123                 '.hxx'  => "cncpp",
124                 '.hh'   => "cncpp",
125                 '.hrl'  => "erlang",
126                 '.htm'  => "html",
127                 '.html' => "html",
128                 '.inc'  => :disambiguate_inc,
129                 '.java' => "java",
130                 '.js'   => "javascript",
131                 '.jsp'  => "jsp",
132                 '.lua'  => "lua",
133                 '.lsp'  => "lisp",
134                 '.lisp' => "lisp",
135                 '.m'    => :matlab_or_objective_c,
136                 '.mm'   => "objective_c",
137                 '.pas'  => "pascal",
138                 '.pp'   => "pascal",
139                 '.php'  => "php",
140                 '.php3' => "php",
141                 '.php4' => "php",
142                 '.php5' => "php",
143                 '.pl'   => "perl",
144                 '.pm'   => "perl",
145                 '.perl' => "perl",
146                 '.ph'   => "perl",
147                 '.py'   => "python",
148                 '.rhtml'=> "rhtml",
149                 '.rb'   => "ruby",
150                 '.rex'  => "rexx",
151                 '.rexx' => "rexx",
152                 '.s'    => "assembler",
153                 '.S'    => "assembler",
154                 '.sc'   => "scheme",
155                 '.scm'  => "scheme",
156                 '.sh'   => "shell",
157                 '.sql'  => "sql",
158                 '.tcl'  => "tcl",
159                 '.tpl'  => "html",
160                 '.vala' => "vala",
161                 '.vb'   => "visualbasic",
162                 '.vba'  => "visualbasic",
163                 '.vbs'  => "visualbasic",
164                 '.xml'  => "xml",
165                 '.d'            => 'dmd',
166                 '.di'           => 'dmd'
167         }
168
169         protected
170
171         # Returns a count of lines in the buffer matching the given regular expression.
172         def self.lines_matching(buffer, re)
173                 buffer.inject(0) { |total, line| line =~ re ? total+1 : total }
174         end
175
176         # For *.m files, differentiates Matlab from Objective-C.
177         #
178         # This is done with a weighted heuristic that
179         # scans the *.m file contents for keywords,
180         # and also checks for the presence of matching *.h files.
181   def self.matlab_or_objective_c(file_context)
182     buffer = file_context.contents
183
184     # if there are .h files in same directory, this probably isn't matlab
185     h_headers = 0.0
186     h_headers = -0.5 if file_context.filenames.select { |a| a =~ /\.h$/ }.any?
187
188     # if the contents contain 'function (' on a single line - very likely to be matlab
189     # if the contents contain lines starting with '%', its probably matlab comments
190     matlab_signatures = /(^\s*function\s*)|(^\s*%)/
191     matlab_sig_score = 0.1 * lines_matching(buffer, matlab_signatures)
192
193     # if the contents contains '//' or '/*', likely objective_c
194     objective_c_signatures = /(^\s*\/\/\s*)|(^\s*\/\*)|(^[+-])/
195     obj_c_sig_score = -0.1 * lines_matching(buffer, objective_c_signatures)
196
197     matlab = h_headers + matlab_sig_score + obj_c_sig_score
198
199     matlab > 0 ? 'matlab' : 'objective_c'
200   end
201
202         # For *.h files, differentiates C/C++ from Objective-C.
203         #
204         # This is done with a weighted heuristic that
205         # scans the *.h file contents for Objective-C keywords,
206         # and also checks for the presence of matching *.m files.
207         def self.disambiguate_h_header(file_context)
208     buffer = file_context.contents
209
210     objective_c = 0
211
212     # could it be realistically be objective_c ? are there any .m files at all?
213     # Speed hack - remember our findings in case we get the same filenames over and over
214     unless defined?(file_context.filenames.contains_m)
215       file_context.filenames.extend(ContainsM)
216       file_context.filenames.contains_m = file_context.filenames.select { |a| a =~ /\.m$/ }.any?
217     end
218     return 'cncpp' unless file_context.filenames.contains_m
219
220     # if the dir contains a matching *.m file, likely objective_c
221     if file_context.filename =~ /\.h$/
222       m_counterpart = file_context.filename.gsub(/\.h$/, ".m")
223       return 'objective_c' if file_context.filenames.include?(m_counterpart)
224     end
225
226     # ok - it just might be objective_c, let's check contents for objective_c signatures
227     objective_c_signatures = /(^\s*@interface)|(^\s*@end)/
228     objective_c += lines_matching(buffer, objective_c_signatures)
229
230     return objective_c > 1 ? 'objective_c' : 'cncpp'
231         end
232
233         # Tests whether the provided buffer contains binary or text content.
234         # This is not fool-proof -- we basically just check for zero values
235         # in the early bytes of the buffer. If we find a zero, we know it
236         # is not (ascii) text.
237   def self.binary_buffer?(buffer)
238     100.times do |i|
239       return true if buffer[i] == 0
240     end
241     false
242   end
243
244         # True if the provided buffer includes a '?php' directive
245   def self.php_instruction?(buffer)
246     buffer =~ /\?php/
247   end
248
249         # For *.inc files, checks for a PHP class.
250   def self.disambiguate_inc(file_context)
251     buffer = file_context.contents
252     return nil if binary_buffer?(buffer)
253     return 'php' if php_instruction?(buffer)
254     nil
255   end
256
257         # For files with extention *.cs, differentiates C# from Clearsilver.
258   def self.disambiguate_cs(file_context)
259     buffer = file_context.contents
260     return 'clearsilver_template' if lines_matching(file_context.contents, /\<\?cs/) > 0
261     return 'csharp'
262   end
263
264         # Attempts to determine the Polyglot for files that do not have a
265         # filename extension.
266         #
267         # Relies on the bash +file+ command line tool as its primary method.
268         #
269         # There must be a file at <tt>file_context.file_location</tt> for +file+
270         # to operate on.
271         #
272   def self.disambiguate_nil(file_context)
273     file_location = file_context.file_location
274     output = `file -b #{ file_location }`
275     case output
276     when /([\w\/]+) script text/, /script text executable for ([\w\/]+)/
277       script = $1
278       if script =~ /\/(\w*)$/
279         script = $1
280       end
281       known_languages = EXTENSION_MAP.values
282       return script.downcase if known_languages.include?(script.downcase)
283     when /([\w\-]*) shell script text/
284       case $1
285       when "Bourne-Again"
286         return "shell"
287       end
288     end
289
290     # dang... no dice
291     nil
292   end
293
294 end