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 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 == 'c'
48 def self.detect(file_context)
49 # start with extension
50 polyglot = EXTENSION_MAP[File.extname(file_context.filename)]
51 polyglot = EXTENSION_MAP[File.extname(file_context.filename).downcase] unless polyglot
55 return polyglot if polyglot.is_a?(String)
57 # extension is ambiguous - requires custom disambiguation
58 self.send(polyglot, file_context)
60 return disambiguate_nil(file_context)
62 raise RuntimeError.new("Unknown file detection type")
66 # Based solely on the filename, makes a judgment whether a file is a binary format.
67 def self.binary_filename?(filename)
95 ignore.include?(File.extname(filename))
98 # If an extension maps to a string, that string must be the name of a glot.
99 # If an extension maps to a Ruby symbol, that symbol must be the name of a
100 # Ruby method which will return the name of a glot.
105 '.asm' => "assembler",
107 '.bas' => "visualbasic",
118 '.el' => "emacslisp",
121 '.cs' => :disambiguate_cs,
124 '.f' => :disambiguate_fortran,
125 '.ftn' => :disambiguate_fortran,
126 '.f77' => :disambiguate_fortran,
127 '.f90' => :disambiguate_fortran,
128 '.f95' => :disambiguate_fortran,
129 '.f03' => :disambiguate_fortran,
130 '.F' => :disambiguate_fortran,
131 '.F77' => :disambiguate_fortran,
132 '.F90' => :disambiguate_fortran,
133 '.F95' => :disambiguate_fortran,
134 '.F03' => :disambiguate_fortran,
135 '.frx' => "visualbasic",
136 '.groovy'=> "groovy",
137 '.h' => :disambiguate_h_header,
147 '.in' => :disambiguate_in,
148 '.inc' => :disambiguate_inc,
150 '.js' => "javascript",
155 '.m' => :matlab_or_objective_c,
157 '.mm' => "objective_c",
158 '.mp' => 'metapost_with_tex',
184 '.st' => "smalltalk",
188 '.vb' => "visualbasic",
189 '.vba' => "visualbasic",
190 '.vbs' => "visualbasic",
192 '.web' => "knuth_web",
194 '.xsd' => "xmlschema",
205 # Returns a count of lines in the buffer matching the given regular expression.
206 def self.lines_matching(buffer, re)
207 buffer.inject(0) { |total, line| line =~ re ? total+1 : total }
210 # For *.m files, differentiates Matlab from Objective-C.
212 # This is done with a weighted heuristic that
213 # scans the *.m file contents for keywords,
214 # and also checks for the presence of matching *.h files.
215 def self.matlab_or_objective_c(file_context)
216 buffer = file_context.contents
218 # if there are .h files in same directory, this probably isn't matlab
220 h_headers = -0.5 if file_context.filenames.select { |a| a =~ /\.h$/ }.any?
222 # if the contents contain 'function (' on a single line - very likely to be matlab
223 # if the contents contain lines starting with '%', its probably matlab comments
224 matlab_signatures = /(^\s*function\s*)|(^\s*%)/
225 matlab_sig_score = 0.1 * lines_matching(buffer, matlab_signatures)
227 # if the contents contains '//' or '/*', likely objective_c
228 objective_c_signatures = /(^\s*\/\/\s*)|(^\s*\/\*)|(^[+-])/
229 obj_c_sig_score = -0.1 * lines_matching(buffer, objective_c_signatures)
231 matlab = h_headers + matlab_sig_score + obj_c_sig_score
233 matlab > 0 ? 'matlab' : 'objective_c'
236 # For *.h files, differentiates C, C++ and Objective-C.
238 # This is done with a weighted heuristic that
239 # scans the *.h file contents for Objective-C keywords,
240 # C++ keywords and C++ headers, and also checks for the
241 # presence of matching *.m files.
242 def self.disambiguate_h_header(file_context)
243 buffer = file_context.contents
245 # could it be realistically be objective_c ? are there any .m files at all?
246 # Speed hack - remember our findings in case we get the same filenames over and over
247 unless defined?(file_context.filenames.contains_m)
248 file_context.filenames.extend(ContainsM)
249 file_context.filenames.contains_m = file_context.filenames.select { |a| a =~ /\.m$/ }.any?
250 file_context.filenames.contains_pike_or_pmod = file_context.filenames.select { |a| a =~ /\.p(ike|mod)$/ }.any?
253 if file_context.filenames.contains_m
254 # if the dir contains a matching *.m file, likely objective_c
255 if file_context.filename =~ /\.h$/
256 m_counterpart = file_context.filename.gsub(/\.h$/, ".m")
257 return 'objective_c' if file_context.filenames.include?(m_counterpart)
260 # ok - it just might be objective_c, let's check contents for objective_c signatures
261 objective_c_signatures = /(^\s*@interface)|(^\s*@end)/
262 objective_c = lines_matching(buffer, objective_c_signatures)
263 return 'objective_c' if objective_c > 1
266 if file_context.filenames.contains_pike_or_pmod
267 # The string "pike" and a selection of common Pike keywords.
268 pike_signatures = /([Pp][Ii][Kk][Ee])|(string )|(mapping)|(multiset)|(import )|(inherit )|(predef)/
269 pike = lines_matching(buffer, pike_signatures)
270 return 'pike' if pike > 0
273 disambiguate_c_cpp(buffer)
276 # A map of headers that indicate C++, but that do not have C++-specific file
277 # extensions. This list is made from the Standard, plus Technical Report 1.
278 CPP_HEADERS_MAP = %w[
368 ].inject({}) { | h, k | h[k] = true ; h }
370 # A map of keywords that indicate C++.
371 CPP_KEYWORDS_MAP = %w[
376 ].inject({}) { | h, k | h[k] = true ; h }
378 # For *.h files that we know aren't Objective-C, differentiates C and C++.
380 # This is done with a weighted heuristic that
381 # scans the *.h file contents for C++ keywords and C++ headers.
382 def self.disambiguate_c_cpp(buffer)
383 # Look for C++ headers
384 return 'cpp' if extract_c_cpp_headers(buffer).detect do | header |
385 EXTENSION_MAP[File.extname(header)] == 'cpp' or CPP_HEADERS_MAP.include? header
388 # Look for C++ keywords. This could check for comments, but doesn't.
389 return 'cpp' if buffer.find do | line |
390 line.split(/\W/).find do | word |
391 CPP_KEYWORDS_MAP.include? word
395 # Nothing to suggest C++
399 # Return a list of files included in a C or C++ source file.
400 def self.extract_c_cpp_headers(buffer)
401 buffer.map do | line |
402 m = line.match(/^#\s*include\s+[<"](.*)[>"]/) and m[1]
403 end.find_all { | a | a }
406 # Tests whether the provided buffer contains binary or text content.
407 # This is not fool-proof -- we basically just check for zero values
408 # in the early bytes of the buffer. If we find a zero, we know it
409 # is not (ascii) text.
410 def self.binary_buffer?(buffer)
412 return true if buffer[i] == 0
417 # True if the provided buffer includes a '?php' directive
418 def self.php_instruction?(buffer)
422 # For *.in files, checks the prior extension.
423 # Typically used for template files (eg Makefile.in, auto.c.in, etc).
424 def self.disambiguate_in(file_context)
425 # if the filename has an extension prior to the .in
426 if file_context.filename =~ /\..*\.in$/
427 filename = file_context.filename.gsub(/\.in$/, "")
428 context = Ohcount::SimpleFileContext.new(filename, file_context.filenames, file_context.contents, file_context.file_location)
429 return detect(context)
434 # For *.inc files, checks for a PHP class.
435 def self.disambiguate_inc(file_context)
436 buffer = file_context.contents
437 return nil if binary_buffer?(buffer)
438 return 'php' if php_instruction?(buffer)
442 # For files with extention *.cs, differentiates C# from Clearsilver.
443 def self.disambiguate_cs(file_context)
444 buffer = file_context.contents
445 return 'clearsilver_template' if lines_matching(file_context.contents, /\<\?cs/) > 0
449 def self.disambiguate_fortran(file_context)
450 buffer = file_context.contents
452 definitely_not_f77 = /^ [^0-9 ]{5}/
453 return 'fortranfixed' if lines_matching(buffer, definitely_not_f77) > 0
455 free_form_continuation = /&\s*\n\s*&/m
456 return 'fortranfree' if buffer.match(free_form_continuation)
458 possibly_fixed = /^ [0-9 ]{5}/
459 contig_number = /^\s*\d+\s*$/
460 buffer.scan(possibly_fixed) {|leader|
461 return 'fortranfixed' if !(leader =~ contig_number) }
462 # Might as well be free-form.
466 # Attempts to determine the Polyglot for files that do not have a
467 # filename extension.
469 # Relies on the bash +file+ command line tool as its primary method.
471 # There must be a file at <tt>file_context.file_location</tt> for +file+
474 def self.disambiguate_nil(file_context)
475 file_location = file_context.file_location
476 output = `file -b #{ file_location }`
478 when /([\w\/]+) script text/, /script text executable for ([\w\/]+)/
480 if script =~ /\/(\w*)$/
483 known_languages = EXTENSION_MAP.values
484 return script.downcase if known_languages.include?(script.downcase)
485 when /([\w\-]*) shell script text/