add .ltx as LaTeX 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                 '.f'    => :disambiguate_fortran,
119                 '.ftn'  => :disambiguate_fortran,
120                 '.f77'  => :disambiguate_fortran,
121                 '.f90'  => :disambiguate_fortran,
122                 '.f95'  => :disambiguate_fortran,
123                 '.f03'  => :disambiguate_fortran,
124                 '.F'    => :disambiguate_fortran,
125                 '.F77'  => :disambiguate_fortran,
126                 '.F90'  => :disambiguate_fortran,
127                 '.F95'  => :disambiguate_fortran,
128                 '.F03'  => :disambiguate_fortran,
129                 '.frx'  => "visualbasic",
130                 '.groovy'=> "groovy",
131                 '.h'    => :disambiguate_h_header,
132                 '.hpp'  => "cncpp",
133                 '.h++'  => "cncpp",
134                 '.hs'   => "haskell",
135                 '.hxx'  => "cncpp",
136                 '.hh'   => "cncpp",
137                 '.hrl'  => "erlang",
138                 '.htm'  => "html",
139                 '.html' => "html",
140                 '.inc'  => :disambiguate_inc,
141                 '.java' => "java",
142                 '.js'   => "javascript",
143                 '.jsp'  => "jsp",
144                 '.lua'  => "lua",
145                 '.lsp'  => "lisp",
146                 '.lisp' => "lisp",
147                 '.m'    => :matlab_or_objective_c,
148                 '.mm'   => "objective_c",
149                 '.pas'  => "pascal",
150                 '.pp'   => "pascal",
151                 '.php'  => "php",
152                 '.php3' => "php",
153                 '.php4' => "php",
154                 '.php5' => "php",
155                 '.pl'   => "perl",
156                 '.pm'   => "perl",
157                 '.perl' => "perl",
158                 '.ph'   => "perl",
159                 '.py'   => "python",
160                 '.rhtml'=> "rhtml",
161                 '.rb'   => "ruby",
162                 '.rex'  => "rexx",
163                 '.rexx' => "rexx",
164                 '.s'    => "assembler",
165                 '.S'    => "assembler",
166                 '.sc'   => "scheme",
167                 '.scm'  => "scheme",
168                 '.sh'   => "shell",
169                 '.sql'  => "sql",
170                 '.st'   => "smalltalk",
171                 '.tcl'  => "tcl",
172                 '.tpl'  => "html",
173                 '.vala' => "vala",
174                 '.vb'   => "visualbasic",
175                 '.vba'  => "visualbasic",
176                 '.vbs'  => "visualbasic",
177                 '.xml'  => "xml",
178                 '.xsd'  => "xmlschema",
179                 '.xsl'  => "xslt",
180                 '.d'            => 'dmd',
181                 '.di'           => 'dmd',
182                 '.tex'  => 'tex',
183                 '.ltx'  => 'tex',
184                 '.latex'=> 'tex'
185         }
186
187         protected
188
189         # Returns a count of lines in the buffer matching the given regular expression.
190         def self.lines_matching(buffer, re)
191                 buffer.inject(0) { |total, line| line =~ re ? total+1 : total }
192         end
193
194         # For *.m files, differentiates Matlab from Objective-C.
195         #
196         # This is done with a weighted heuristic that
197         # scans the *.m file contents for keywords,
198         # and also checks for the presence of matching *.h files.
199   def self.matlab_or_objective_c(file_context)
200     buffer = file_context.contents
201
202     # if there are .h files in same directory, this probably isn't matlab
203     h_headers = 0.0
204     h_headers = -0.5 if file_context.filenames.select { |a| a =~ /\.h$/ }.any?
205
206     # if the contents contain 'function (' on a single line - very likely to be matlab
207     # if the contents contain lines starting with '%', its probably matlab comments
208     matlab_signatures = /(^\s*function\s*)|(^\s*%)/
209     matlab_sig_score = 0.1 * lines_matching(buffer, matlab_signatures)
210
211     # if the contents contains '//' or '/*', likely objective_c
212     objective_c_signatures = /(^\s*\/\/\s*)|(^\s*\/\*)|(^[+-])/
213     obj_c_sig_score = -0.1 * lines_matching(buffer, objective_c_signatures)
214
215     matlab = h_headers + matlab_sig_score + obj_c_sig_score
216
217     matlab > 0 ? 'matlab' : 'objective_c'
218   end
219
220         # For *.h files, differentiates C/C++ from Objective-C.
221         #
222         # This is done with a weighted heuristic that
223         # scans the *.h file contents for Objective-C keywords,
224         # and also checks for the presence of matching *.m files.
225         def self.disambiguate_h_header(file_context)
226     buffer = file_context.contents
227
228     objective_c = 0
229
230     # could it be realistically be objective_c ? are there any .m files at all?
231     # Speed hack - remember our findings in case we get the same filenames over and over
232     unless defined?(file_context.filenames.contains_m)
233       file_context.filenames.extend(ContainsM)
234       file_context.filenames.contains_m = file_context.filenames.select { |a| a =~ /\.m$/ }.any?
235     end
236     return 'cncpp' unless file_context.filenames.contains_m
237
238     # if the dir contains a matching *.m file, likely objective_c
239     if file_context.filename =~ /\.h$/
240       m_counterpart = file_context.filename.gsub(/\.h$/, ".m")
241       return 'objective_c' if file_context.filenames.include?(m_counterpart)
242     end
243
244     # ok - it just might be objective_c, let's check contents for objective_c signatures
245     objective_c_signatures = /(^\s*@interface)|(^\s*@end)/
246     objective_c += lines_matching(buffer, objective_c_signatures)
247
248     return objective_c > 1 ? 'objective_c' : 'cncpp'
249         end
250
251         # Tests whether the provided buffer contains binary or text content.
252         # This is not fool-proof -- we basically just check for zero values
253         # in the early bytes of the buffer. If we find a zero, we know it
254         # is not (ascii) text.
255   def self.binary_buffer?(buffer)
256     100.times do |i|
257       return true if buffer[i] == 0
258     end
259     false
260   end
261
262         # True if the provided buffer includes a '?php' directive
263   def self.php_instruction?(buffer)
264     buffer =~ /\?php/
265   end
266
267         # For *.inc files, checks for a PHP class.
268   def self.disambiguate_inc(file_context)
269     buffer = file_context.contents
270     return nil if binary_buffer?(buffer)
271     return 'php' if php_instruction?(buffer)
272     nil
273   end
274
275         # For files with extention *.cs, differentiates C# from Clearsilver.
276   def self.disambiguate_cs(file_context)
277     buffer = file_context.contents
278     return 'clearsilver_template' if lines_matching(file_context.contents, /\<\?cs/) > 0
279     return 'csharp'
280   end
281
282   def self.disambiguate_fortran(file_context)
283     buffer = file_context.contents
284
285     definitely_not_f77 = /^ [^0-9 ]{5}/
286     return 'fortranfixed' if lines_matching(buffer, definitely_not_f77) > 0
287
288     free_form_continuation = /&\s*\n\s*&/m
289     return 'fortranfree' if buffer.match(free_form_continuation)
290
291     possibly_fixed = /^ [0-9 ]{5}/
292     contig_number = /^\s*\d+\s*$/
293     buffer.scan(possibly_fixed) {|leader|
294       return 'fortranfixed' if !(leader =~ contig_number) }
295     # Might as well be free-form.
296     return 'fortranfree'
297   end
298
299         # Attempts to determine the Polyglot for files that do not have a
300         # filename extension.
301         #
302         # Relies on the bash +file+ command line tool as its primary method.
303         #
304         # There must be a file at <tt>file_context.file_location</tt> for +file+
305         # to operate on.
306         #
307   def self.disambiguate_nil(file_context)
308     file_location = file_context.file_location
309     output = `file -b #{ file_location }`
310     case output
311     when /([\w\/]+) script text/, /script text executable for ([\w\/]+)/
312       script = $1
313       if script =~ /\/(\w*)$/
314         script = $1
315       end
316       known_languages = EXTENSION_MAP.values
317       return script.downcase if known_languages.include?(script.downcase)
318     when /([\w\-]*) shell script text/
319       case $1
320       when "Bourne-Again"
321         return "shell"
322       end
323     end
324
325     # dang... no dice
326     nil
327   end
328
329 end