1 # The Detector determines which Monoglot or Polyglot should be
2 # used to parse a source file.
4 # The Detector primarily uses filename extensions to identify languages.
6 # The hash EXTENSION_MAP maps a filename extension to the name of a parser.
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.
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.
18 # The Detector is covered by DetectorTest.
20 class Ohcount::Detector
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 # A performance hack -- once we've checked for the presence of *.pike and *.pmod files, the result
27 # is stored here to avoid checking twice.
28 attr_accessor :contains_pike_or_pmod
31 # The primary entry point for the detector.
32 # Given a file context containing the file name, content, and an array of
33 # other filenames in the source tree, attempts to detect which
34 # language family (Monoglot or Polyglot) is in use for this file.
36 # Returns nil if the language is not recognized or if the file does not
41 # # List all C/C++ files in the 'src' directory
42 # Dir.entries("src").each do |file|
43 # context = Ohcount::SimpleFileContext.new(file)
44 # polyglot = Ohcount::Detector.detect(context)
45 # puts "#{file}" if polyglot == 'cncpp'
48 def self.detect(file_context)
49 # start with extension
50 polyglot = EXTENSION_MAP[File.extname(file_context.filename).downcase]
54 return polyglot if polyglot.is_a?(String)
56 # extension is ambiguous - requires custom disambiguation
57 self.send(polyglot, file_context)
59 return disambiguate_nil(file_context)
61 raise RuntimeError.new("Unknown file detection type")
65 # Based solely on the filename, makes a judgment whether a file is a binary format.
66 def self.binary_filename?(filename)
94 ignore.include?(File.extname(filename))
97 # If an extension maps to a string, that string must be the name of a glot.
98 # If an extension maps to a Ruby symbol, that symbol must be the name of a
99 # Ruby method which will return the name of a glot.
104 '.asm' => "assembler",
106 '.bas' => "visualbasic",
115 '.el' => "emacslisp",
118 '.cs' => :disambiguate_cs,
121 '.f' => :disambiguate_fortran,
122 '.ftn' => :disambiguate_fortran,
123 '.f77' => :disambiguate_fortran,
124 '.f90' => :disambiguate_fortran,
125 '.f95' => :disambiguate_fortran,
126 '.f03' => :disambiguate_fortran,
127 '.F' => :disambiguate_fortran,
128 '.F77' => :disambiguate_fortran,
129 '.F90' => :disambiguate_fortran,
130 '.F95' => :disambiguate_fortran,
131 '.F03' => :disambiguate_fortran,
132 '.frx' => "visualbasic",
133 '.groovy'=> "groovy",
134 '.h' => :disambiguate_h_header,
143 '.inc' => :disambiguate_inc,
145 '.js' => "javascript",
150 '.m' => :matlab_or_objective_c,
151 '.mm' => "objective_c",
175 '.st' => "smalltalk",
179 '.vb' => "visualbasic",
180 '.vba' => "visualbasic",
181 '.vbs' => "visualbasic",
183 '.xsd' => "xmlschema",
193 # Returns a count of lines in the buffer matching the given regular expression.
194 def self.lines_matching(buffer, re)
195 buffer.inject(0) { |total, line| line =~ re ? total+1 : total }
198 # For *.m files, differentiates Matlab from Objective-C.
200 # This is done with a weighted heuristic that
201 # scans the *.m file contents for keywords,
202 # and also checks for the presence of matching *.h files.
203 def self.matlab_or_objective_c(file_context)
204 buffer = file_context.contents
206 # if there are .h files in same directory, this probably isn't matlab
208 h_headers = -0.5 if file_context.filenames.select { |a| a =~ /\.h$/ }.any?
210 # if the contents contain 'function (' on a single line - very likely to be matlab
211 # if the contents contain lines starting with '%', its probably matlab comments
212 matlab_signatures = /(^\s*function\s*)|(^\s*%)/
213 matlab_sig_score = 0.1 * lines_matching(buffer, matlab_signatures)
215 # if the contents contains '//' or '/*', likely objective_c
216 objective_c_signatures = /(^\s*\/\/\s*)|(^\s*\/\*)|(^[+-])/
217 obj_c_sig_score = -0.1 * lines_matching(buffer, objective_c_signatures)
219 matlab = h_headers + matlab_sig_score + obj_c_sig_score
221 matlab > 0 ? 'matlab' : 'objective_c'
224 # For *.h files, differentiates C/C++ from Objective-C.
226 # This is done with a weighted heuristic that
227 # scans the *.h file contents for Objective-C keywords,
228 # and also checks for the presence of matching *.m files.
229 def self.disambiguate_h_header(file_context)
230 buffer = file_context.contents
234 # could it be realistically be objective_c ? are there any .m files at all?
235 # Speed hack - remember our findings in case we get the same filenames over and over
236 unless defined?(file_context.filenames.contains_m)
237 file_context.filenames.extend(ContainsM)
238 file_context.filenames.contains_m = file_context.filenames.select { |a| a =~ /\.m$/ }.any?
239 file_context.filenames.contains_pike_or_pmod = file_context.filenames.select { |a| a =~ /\.p(ike|mod)$/ }.any?
241 unless file_context.filenames.contains_pike_or_pmod
242 return 'cncpp' unless file_context.filenames.contains_m
245 if file_context.filenames.contains_m
246 # if the dir contains a matching *.m file, likely objective_c
247 if file_context.filename =~ /\.h$/
248 m_counterpart = file_context.filename.gsub(/\.h$/, ".m")
249 return 'objective_c' if file_context.filenames.include?(m_counterpart)
252 # ok - it just might be objective_c, let's check contents for objective_c signatures
253 objective_c_signatures = /(^\s*@interface)|(^\s*@end)/
254 objective_c += lines_matching(buffer, objective_c_signatures)
256 return 'objective_c' if objective_c > 1
259 if file_context.filenames.contains_pike_or_pmod
260 # The string "pike" and a selection of common Pike keywords.
261 pike_signatures = /([Pp][Ii][Kk][Ee])|(string )|(mapping)|(multiset)|(import )|(inherit )|(predef)/
262 pike = lines_matching(buffer, pike_signatures)
263 return 'pike' if pike > 0
270 # Tests whether the provided buffer contains binary or text content.
271 # This is not fool-proof -- we basically just check for zero values
272 # in the early bytes of the buffer. If we find a zero, we know it
273 # is not (ascii) text.
274 def self.binary_buffer?(buffer)
276 return true if buffer[i] == 0
281 # True if the provided buffer includes a '?php' directive
282 def self.php_instruction?(buffer)
286 # For *.inc files, checks for a PHP class.
287 def self.disambiguate_inc(file_context)
288 buffer = file_context.contents
289 return nil if binary_buffer?(buffer)
290 return 'php' if php_instruction?(buffer)
294 # For files with extention *.cs, differentiates C# from Clearsilver.
295 def self.disambiguate_cs(file_context)
296 buffer = file_context.contents
297 return 'clearsilver_template' if lines_matching(file_context.contents, /\<\?cs/) > 0
301 def self.disambiguate_fortran(file_context)
302 buffer = file_context.contents
304 definitely_not_f77 = /^ [^0-9 ]{5}/
305 return 'fortranfixed' if lines_matching(buffer, definitely_not_f77) > 0
307 free_form_continuation = /&\s*\n\s*&/m
308 return 'fortranfree' if buffer.match(free_form_continuation)
310 possibly_fixed = /^ [0-9 ]{5}/
311 contig_number = /^\s*\d+\s*$/
312 buffer.scan(possibly_fixed) {|leader|
313 return 'fortranfixed' if !(leader =~ contig_number) }
314 # Might as well be free-form.
318 # Attempts to determine the Polyglot for files that do not have a
319 # filename extension.
321 # Relies on the bash +file+ command line tool as its primary method.
323 # There must be a file at <tt>file_context.file_location</tt> for +file+
326 def self.disambiguate_nil(file_context)
327 file_location = file_context.file_location
328 output = `file -b #{ file_location }`
330 when /([\w\/]+) script text/, /script text executable for ([\w\/]+)/
332 if script =~ /\/(\w*)$/
335 known_languages = EXTENSION_MAP.values
336 return script.downcase if known_languages.include?(script.downcase)
337 when /([\w\-]*) shell script text/