Imported Upstream version 6.10.0.49

Former-commit-id: 1d6753294b2993e1fbf92de9366bb9544db4189b
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2020-01-16 16:38:04 +00:00
parent d94e79959b
commit 468663ddbb
48518 changed files with 2789335 additions and 61176 deletions

View File

@@ -0,0 +1,85 @@
option(CLANG_INSTALL_SCANBUILD "Install the scan-build tool" ON)
include(GNUInstallDirs)
if (WIN32 AND NOT CYGWIN)
set(BinFiles
scan-build
scan-build.bat)
set(LibexecFiles
ccc-analyzer
c++-analyzer
ccc-analyzer.bat
c++-analyzer.bat)
else()
set(BinFiles
scan-build)
set(LibexecFiles
ccc-analyzer
c++-analyzer)
if (APPLE)
list(APPEND BinFiles
set-xcode-analyzer)
endif()
endif()
set(ManPages
scan-build.1)
set(ShareFiles
scanview.css
sorttable.js)
if(CLANG_INSTALL_SCANBUILD)
foreach(BinFile ${BinFiles})
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/bin/${BinFile}
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/bin
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/bin/${BinFile}
${CMAKE_BINARY_DIR}/bin/
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/bin/${BinFile})
list(APPEND Depends ${CMAKE_BINARY_DIR}/bin/${BinFile})
install(PROGRAMS bin/${BinFile} DESTINATION bin)
endforeach()
foreach(LibexecFile ${LibexecFiles})
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/libexec/${LibexecFile}
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/libexec
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/libexec/${LibexecFile}
${CMAKE_BINARY_DIR}/libexec/
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libexec/${LibexecFile})
list(APPEND Depends ${CMAKE_BINARY_DIR}/libexec/${LibexecFile})
install(PROGRAMS libexec/${LibexecFile} DESTINATION libexec)
endforeach()
foreach(ManPage ${ManPages})
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage}
${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
list(APPEND Depends ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage})
install(PROGRAMS man/${ManPage} DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
endforeach()
foreach(ShareFile ${ShareFiles})
add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/share/scan-build/${ShareFile}
COMMAND ${CMAKE_COMMAND} -E make_directory
${CMAKE_BINARY_DIR}/share/scan-build
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/share/scan-build/${ShareFile}
${CMAKE_BINARY_DIR}/share/scan-build/
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/share/scan-build/${ShareFile})
list(APPEND Depends ${CMAKE_BINARY_DIR}/share/scan-build/${ShareFile})
install(FILES share/scan-build/${ShareFile} DESTINATION share/scan-build)
endforeach()
add_custom_target(scan-build ALL DEPENDS ${Depends})
set_target_properties(scan-build PROPERTIES FOLDER "Misc")
endif()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
perl -S scan-build %*

View File

@@ -0,0 +1,114 @@
#!/usr/bin/python
# [PR 11661] Note that we hardwire to /usr/bin/python because we
# want to the use the system version of Python on Mac OS X.
# This one has the scripting bridge enabled.
import sys
if sys.version_info < (2, 7):
print "set-xcode-analyzer requires Python 2.7 or later"
sys.exit(1)
import os
import subprocess
import re
import tempfile
import shutil
import stat
from AppKit import *
def FindClangSpecs(path):
print "(+) Searching for xcspec file in: ", path
for root, dirs, files in os.walk(path):
for f in files:
if f.endswith(".xcspec") and f.startswith("Clang LLVM"):
yield os.path.join(root, f)
def ModifySpec(path, isBuiltinAnalyzer, pathToChecker):
t = tempfile.NamedTemporaryFile(delete=False)
foundAnalyzer = False
with open(path) as f:
if isBuiltinAnalyzer:
# First search for CLANG_ANALYZER_EXEC. Newer
# versions of Xcode set EXEC_PATH to be CLANG_ANALYZER_EXEC.
with open(path) as f2:
for line in f2:
if line.find("CLANG_ANALYZER_EXEC") >= 0:
pathToChecker = "$(CLANG_ANALYZER_EXEC)"
break
# Now create a new file.
for line in f:
if not foundAnalyzer:
if line.find("Static Analyzer") >= 0:
foundAnalyzer = True
else:
m = re.search('^(\s*ExecPath\s*=\s*")', line)
if m:
line = "".join([m.group(0), pathToChecker, '";\n'])
# Do not modify further ExecPath's later in the xcspec.
foundAnalyzer = False
t.write(line)
t.close()
print "(+) processing:", path
try:
shutil.copy(t.name, path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
except IOError, why:
print " (-) Cannot update file:", why, "\n"
except OSError, why:
print " (-) Cannot update file:", why, "\n"
os.unlink(t.name)
def main():
from optparse import OptionParser
parser = OptionParser('usage: %prog [options]')
parser.set_description(__doc__)
parser.add_option("--use-checker-build", dest="path",
help="Use the Clang located at the provided absolute path, e.g. /Users/foo/checker-1")
parser.add_option("--use-xcode-clang", action="store_const",
const="$(CLANG)", dest="default",
help="Use the Clang bundled with Xcode")
(options, args) = parser.parse_args()
if options.path is None and options.default is None:
parser.error("You must specify a version of Clang to use for static analysis. Specify '-h' for details")
# determine if Xcode is running
for x in NSWorkspace.sharedWorkspace().runningApplications():
if x.localizedName().find("Xcode") >= 0:
print "(-) You must quit Xcode first before modifying its configuration files."
sys.exit(1)
isBuiltinAnalyzer = False
if options.path:
# Expand tildes.
path = os.path.expanduser(options.path)
if not path.endswith("clang"):
print "(+) Using Clang bundled with checker build:", path
path = os.path.join(path, "bin", "clang");
else:
print "(+) Using Clang located at:", path
else:
print "(+) Using the Clang bundled with Xcode"
path = options.default
isBuiltinAnalyzer = True
try:
xcode_path = subprocess.check_output(["xcode-select", "-print-path"])
except AttributeError:
# Fall back to the default install location when using Python < 2.7.0
xcode_path = "/Developer"
if (xcode_path.find(".app/") != -1):
# Cut off the 'Developer' dir, as the xcspec lies in another part
# of the Xcode.app subtree.
xcode_path = xcode_path.rsplit('/Developer', 1)[0]
foundSpec = False
for x in FindClangSpecs(xcode_path):
foundSpec = True
ModifySpec(x, isBuiltinAnalyzer, path)
if foundSpec == False:
print "(-) No compiler configuration file was found. Xcode's analyzer has not been updated."
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env perl
use Cwd qw/ abs_path /;
use File::Basename qw/ dirname /;
# Add scan-build dir to the list of places where perl looks for modules.
use lib dirname(abs_path($0));
do 'ccc-analyzer';

View File

@@ -0,0 +1 @@
perl -S c++-analyzer %*

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
perl -S ccc-analyzer %*

View File

@@ -0,0 +1,349 @@
.\" This file is distributed under the University of Illinois Open Source
.\" License. See LICENSE.TXT for details.
.\" $Id$
.Dd May 25, 2012
.Dt SCAN-BUILD 1
.Os "clang" "3.5"
.Sh NAME
.Nm scan-build
.Nd Clang static analyzer
.Sh SYNOPSIS
.Nm
.Op Fl ohkvV
.Op Fl analyze-headers
.Op Fl enable-checker Op Ar checker_name
.Op Fl disable-checker Op Ar checker_name
.Op Fl Fl help
.Op Fl Fl help-checkers
.Op Fl Fl html-title Op Ar =title
.Op Fl Fl keep-going
.Op Fl plist
.Op Fl plist-html
.Op Fl Fl status-bugs
.Op Fl Fl use-c++ Op Ar =compiler_path
.Op Fl Fl use-cc Op Ar =compiler_path
.Op Fl Fl view
.Op Fl constraints Op Ar model
.Op Fl maxloop Ar N
.Op Fl no-failure-reports
.Op Fl stats
.Op Fl store Op Ar model
.Ar build_command
.Op build_options
.\"
.\" Sh DESCRIPTION
.Sh DESCRIPTION
.Nm
is a Perl script that invokes the Clang static analyzer. Options used by
.Nm
or by the analyzer appear first, followed by the
.Ar build_command
and any
.Ar build_options
normally used to build the target system.
.Pp
The static analyzer employs a long list of checking algorithms, see
.Sx CHECKERS .
Output can be written in standard
.Li .plist
and/or HTML format.
.Pp
The following options are supported:
.Bl -tag -width indent
.It Fl analyze-headers
Also analyze functions in #included files.
.It Fl enable-checker Ar checker_name , Fl disable-checker Ar checker_name
Enable/disable
.Ar checker_name .
See
.Sx CHECKERS .
.It Fl h , Fl Fl help
Display this message.
.It Fl Fl help-checkers
List default checkers, see
.Sx CHECKERS .
.It Fl Fl html-title Ns Op = Ns Ar title
Specify the title used on generated HTML pages.
A default title is generated if
.Ar title
is not specified.
.It Fl k , Fl Fl keep-going
Add a
.Dq keep on going
option to
.Ar build_command .
Currently supports make and xcodebuild. This is a convenience option;
one can specify this behavior directly using build options.
.It Fl o
Target directory for HTML report files. Subdirectories will be
created as needed to represent separate invocations
of the analyzer. If this option is not specified, a directory is
created in /tmp (TMPDIR on Mac OS X) to store the reports.
.It Fl plist
Output the results as a set of
.Li .plist
files. (By default the output of
.Nm
is a set of HTML files.)
.It Fl plist-html
Output the results as a set of HTML and .plist files
.It Fl Fl status-bugs
Set exit status to 1 if it found potential bugs and 0 otherwise. By
default the exit status of
.Nm
is that returned by
.Ar build_command .
.It Fl Fl use-c++ Ns Op = Ns Ar compiler_path
Guess the default compiler for your C++ and Objective-C++ code. Use this
option to specify an alternate compiler.
.It Fl Fl use-cc Ns Op = Ns Ar compiler_path
Guess the default compiler for your C and Objective-C code. Use this
option to specify an alternate compiler.
.It Fl v
Verbose output from
.Nm
and the analyzer. A second and
third
.Ar v
increases verbosity.
.It Fl V , Fl Fl view
View analysis results in a web browser when the build completes.
.It Fl constraints Op Ar model
Specify the contraint engine used by the analyzer. By default the
.Ql range
model is used. Specifying
.Ql basic
uses a simpler, less powerful constraint model used by checker-0.160
and earlier.
.It Fl maxloop Ar N
Specifiy the number of times a block can be visited before giving
up. Default is 4. Increase for more comprehensive coverage at a
cost of speed.
.It Fl no-failure-reports
Do not create a
.Ql failures
subdirectory that includes analyzer crash reports and preprocessed
source files.
.It Fl stats
Generates visitation statistics for the project being analyzed.
.It Fl store Op Ar model
Specify the store model used by the analyzer. By default, the
.Ql region
store model is used.
.Ql region
specifies a field-
sensitive store model. Users can also specify
.Ql basic
which is far less precise but can more quickly analyze code.
.Ql basic
was the default store model for checker-0.221 and earlier.
.\"
.El
.Sh EXIT STATUS
.Nm
returns the value returned by
.Ar build_command
unless
.Fl Fl status-bugs
or
.Fl Fl keep-going
is used.
.\"
.\" Other sections not yet used ...
.\" .Sh ENVIRONMENT
.\" .Sh FILES
.\" .Sh DIAGNOSTICS
.\" .Sh COMPATIBILITY
.\" .Sh HISTORY
.\" .Sh BUGS
.\"
.Sh CHECKERS
The checkers listed below may be enabled/disabled using the
.Fl enable-checker
and
.Fl disable-checker
options.
A default group of checkers is run unless explicitly disabled.
Exactly which checkers constitute the default group is a function
of the operating system in use; they are listed with
.Fl Fl help-checkers .
.Bl -tag -width indent.
.It core.AdjustedReturnValue
Check to see if the return value of a function call is different than
the caller expects (e.g., from calls through function pointers).
.It core.AttributeNonNull
Check for null pointers passed as arguments to a function whose arguments are marked with the
.Ql nonnull
attribute.
.It core.CallAndMessage
Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers).
.It core.DivideZero
Check for division by zero.
.It core.NullDereference
Check for dereferences of null pointers.
.It core.StackAddressEscape
Check that addresses to stack memory do not escape the function.
.It core.UndefinedBinaryOperatorResult
Check for undefined results of binary operators.
.It core.VLASize
Check for declarations of VLA of undefined or zero size.
.It core.builtin.BuiltinFunctions
Evaluate compiler builtin functions, e.g.
.Fn alloca .
.It core.builtin.NoReturnFunctions
Evaluate
.Ql panic
functions that are known to not return to the caller.
.It core.uninitialized.ArraySubscript
Check for uninitialized values used as array subscripts.
.It core.uninitialized.Assign
Check for assigning uninitialized values.
.It core.uninitialized.Branch
Check for uninitialized values used as branch conditions.
.It core.uninitialized.CapturedBlockVariable
Check for blocks that capture uninitialized values.
.It core.uninitialized.UndefReturn
Check for uninitialized values being returned to the caller.
.It deadcode.DeadStores
Check for values stored to variables that are never read afterwards.
.It debug.DumpCFG
Display Control-Flow Graphs.
.It debug.DumpCallGraph
Display Call Graph.
.It debug.DumpDominators
Print the dominance tree for a given Control-Flow Graph.
.It debug.DumpLiveVars
Print results of live variable analysis.
.It debug.Stats
Emit warnings with analyzer statistics.
.It debug.TaintTest
Mark tainted symbols as such.
.It debug.ViewCFG
View Control-Flow Graphs using
.Ic GraphViz .
.It debug.ViewCallGraph
View Call Graph using
.Ic GraphViz .
.It llvm.Conventions
Check code for LLVM codebase conventions.
.It osx.API
Check for proper uses of various Mac OS X APIs.
.It osx.AtomicCAS
Evaluate calls to
.Vt OSAtomic
functions.
.It osx.SecKeychainAPI
Check for proper uses of Secure Keychain APIs.
.It osx.cocoa.AtSync
Check for null pointers used as mutexes for @synchronized.
.It osx.cocoa.ClassRelease
Check for sending
.Ql retain ,
.Ql release,
or
.Ql autorelease
directly to a Class.
.It osx.cocoa.IncompatibleMethodTypes
Warn about Objective-C method signatures with type incompatibilities.
.It osx.cocoa.NSAutoreleasePool
Warn for suboptimal uses of
.Vt NSAutoreleasePool
in Objective-C GC mode.
.It osx.cocoa.NSError
Check usage of NSError** parameters.
.It osx.cocoa.NilArg
Check for prohibited nil arguments to Objective-C method calls.
.It osx.cocoa.RetainCount
Check for leaks and improper reference count management.
.It osx.cocoa.SelfInit
Check that
.Ql self
is properly initialized inside an initializer method.
.It osx.cocoa.UnusedIvars
Warn about private ivars that are never used.
.It osx.cocoa.VariadicMethodTypes
Check for passing non-Objective-C types to variadic methods that expect only Objective-C types.
.It osx.coreFoundation.CFError
Check usage of CFErrorRef* parameters.
.It osx.coreFoundation.CFNumber
Check for proper uses of
.Fn CFNumberCreate .
.It osx.coreFoundation.CFRetainRelease
Check for null arguments to
.Fn CFRetain ,
.Fn CFRelease ,
and
.Fn CFMakeCollectable .
.It osx.coreFoundation.containers.OutOfBounds
Checks for index out-of-bounds when using the
.Vt CFArray
API.
.It osx.coreFoundation.containers.PointerSizedValues
Warns if
.Vt CFArray ,
.Vt CFDictionary ,
or
.Vt CFSet
are created with non-pointer-size values.
.It security.FloatLoopCounter
Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP).
.It security.insecureAPI.UncheckedReturn
Warn on uses of functions whose return values must be always checked.
.It security.insecureAPI.getpw
Warn on uses of
.Fn getpw .
.It security.insecureAPI.gets
Warn on uses of
.Fn gets .
.It security.insecureAPI.mkstemp
Warn when
.Fn mkstemp
is passed fewer than 6 X's in the format string.
.It security.insecureAPI.mktemp
Warn on uses of
.Fn mktemp .
.It security.insecureAPI.rand
Warn on uses of
.Fn rand ,
.Fn random ,
and related functions.
.It security.insecureAPI.strcpy
Warn on uses of
.Fn strcpy
and
.Fn strcat .
.It security.insecureAPI.vfork
Warn on uses of
.Fn vfork .
.It unix.API
Check calls to various UNIX/Posix functions.
.It unix.Malloc
Check for memory leaks, double free, and use-after-free.
.It unix.cstring.BadSizeArg
Check the size argument passed into C string functions for common
erroneous patterns.
.It unix.cstring.NullArg
Check for null pointers being passed as arguments to C string functions.
.El
.\"
.Sh EXAMPLE
.Ic scan-build -o /tmp/myhtmldir make -j4
.Pp
The above example causes analysis reports to be deposited into
a subdirectory of
.Pa /tmp/myhtmldir
and to run
.Ic make
with the
.Fl j4
option.
A different subdirectory is created each time
.Nm
analyzes a project.
The analyzer should support most parallel builds, but not distributed builds.
.Sh AUTHORS
.Nm
was written by
.An "Ted Kremenek" .
Documentation contributed by
.An "James K. Lowden" Aq jklowden@schemamania.org .

View File

@@ -0,0 +1,62 @@
body { color:#000000; background-color:#ffffff }
body { font-family: Helvetica, sans-serif; font-size:9pt }
h1 { font-size: 14pt; }
h2 { font-size: 12pt; }
table { font-size:9pt }
table { border-spacing: 0px; border: 1px solid black }
th, table thead {
background-color:#eee; color:#666666;
font-weight: bold; cursor: default;
text-align:center;
font-weight: bold; font-family: Verdana;
white-space:nowrap;
}
.W { font-size:0px }
th, td { padding:5px; padding-left:8px; text-align:left }
td.SUMM_DESC { padding-left:12px }
td.DESC { white-space:pre }
td.Q { text-align:right }
td { text-align:left }
tbody.scrollContent { overflow:auto }
table.form_group {
background-color: #ccc;
border: 1px solid #333;
padding: 2px;
}
table.form_inner_group {
background-color: #ccc;
border: 1px solid #333;
padding: 0px;
}
table.form {
background-color: #999;
border: 1px solid #333;
padding: 2px;
}
td.form_label {
text-align: right;
vertical-align: top;
}
/* For one line entires */
td.form_clabel {
text-align: right;
vertical-align: center;
}
td.form_value {
text-align: left;
vertical-align: top;
}
td.form_submit {
text-align: right;
vertical-align: top;
}
h1.SubmitFail {
color: #f00;
}
h1.SubmitOk {
}

View File

@@ -0,0 +1,492 @@
/*
SortTable
version 2
7th April 2007
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
Instructions:
Download this file
Add <script src="sorttable.js"></script> to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
Thanks to many, many people for contributions and suggestions.
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
This basically means: do what you want with it.
*/
var stIsIE = /*@cc_on!@*/false;
sorttable = {
init: function() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
if (!document.createElement || !document.getElementsByTagName) return;
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
forEach(document.getElementsByTagName('table'), function(table) {
if (table.className.search(/\bsortable\b/) != -1) {
sorttable.makeSortable(table);
}
});
},
makeSortable: function(table) {
if (table.getElementsByTagName('thead').length == 0) {
// table doesn't have a tHead. Since it should have, create one and
// put the first table row in it.
the = document.createElement('thead');
the.appendChild(table.rows[0]);
table.insertBefore(the,table.firstChild);
}
// Safari doesn't support table.tHead, sigh
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
// "total" rows, for example). This is B&R, since what you're supposed
// to do is put them in a tfoot. So, if there are sortbottom rows,
// for backward compatibility, move them to tfoot (creating it if needed).
sortbottomrows = [];
for (var i=0; i<table.rows.length; i++) {
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
sortbottomrows[sortbottomrows.length] = table.rows[i];
}
}
if (sortbottomrows) {
if (table.tFoot == null) {
// table doesn't have a tfoot. Create one.
tfo = document.createElement('tfoot');
table.appendChild(tfo);
}
for (var i=0; i<sortbottomrows.length; i++) {
tfo.appendChild(sortbottomrows[i]);
}
delete sortbottomrows;
}
// work through each column and calculate its type
headrow = table.tHead.rows[0].cells;
for (var i=0; i<headrow.length; i++) {
// manually override the type with a sorttable_type attribute
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
if (mtch) { override = mtch[1]; }
if (mtch && typeof sorttable["sort_"+override] == 'function') {
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
} else {
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
}
// make it clickable to sort
headrow[i].sorttable_columnindex = i;
headrow[i].sorttable_tbody = table.tBodies[0];
dean_addEvent(headrow[i],"click", function(e) {
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
// if we're already sorted by this column, just
// reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted',
'sorttable_sorted_reverse');
this.removeChild(document.getElementById('sorttable_sortfwdind'));
sortrevind = document.createElement('span');
sortrevind.id = "sorttable_sortrevind";
sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
this.appendChild(sortrevind);
return;
}
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
// if we're already sorted by this column in reverse, just
// re-reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted_reverse',
'sorttable_sorted');
this.removeChild(document.getElementById('sorttable_sortrevind'));
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
this.appendChild(sortfwdind);
return;
}
// remove sorttable_sorted classes
theadrow = this.parentNode;
forEach(theadrow.childNodes, function(cell) {
if (cell.nodeType == 1) { // an element
cell.className = cell.className.replace('sorttable_sorted_reverse','');
cell.className = cell.className.replace('sorttable_sorted','');
}
});
sortfwdind = document.getElementById('sorttable_sortfwdind');
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
sortrevind = document.getElementById('sorttable_sortrevind');
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
this.className += ' sorttable_sorted';
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
this.appendChild(sortfwdind);
// build an array to sort. This is a Schwartzian transform thing,
// i.e., we "decorate" each row with the actual sort key,
// sort based on the sort keys, and then put the rows back in order
// which is a lot faster because you only do getInnerText once per row
row_array = [];
col = this.sorttable_columnindex;
rows = this.sorttable_tbody.rows;
for (var j=0; j<rows.length; j++) {
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
}
/* If you want a stable sort, uncomment the following line */
sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
/* and comment out this one */
//row_array.sort(this.sorttable_sortfunction);
tb = this.sorttable_tbody;
for (var j=0; j<row_array.length; j++) {
tb.appendChild(row_array[j][1]);
}
delete row_array;
});
}
}
},
guessType: function(table, column) {
// guess the type of a column based on its first non-blank row
sortfn = sorttable.sort_alpha;
for (var i=0; i<table.tBodies[0].rows.length; i++) {
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
if (text != '') {
if (text.match(/^-?[<5B>$<24>]?[\d,.]+%?$/)) {
return sorttable.sort_numeric;
}
// check for a date: dd/mm/yyyy or dd/mm/yy
// can have / or . or - as separator
// can be mm/dd as well
possdate = text.match(sorttable.DATE_RE)
if (possdate) {
// looks like a date
first = parseInt(possdate[1]);
second = parseInt(possdate[2]);
if (first > 12) {
// definitely dd/mm
return sorttable.sort_ddmm;
} else if (second > 12) {
return sorttable.sort_mmdd;
} else {
// looks like a date, but we can't tell which, so assume
// that it's dd/mm (English imperialism!) and keep looking
sortfn = sorttable.sort_ddmm;
}
}
}
}
return sortfn;
},
getInnerText: function(node) {
// gets the text we want to use for sorting for a cell.
// strips leading and trailing whitespace.
// this is *not* a generic getInnerText function; it's special to sorttable.
// for example, you can override the cell text with a customkey attribute.
// it also gets .value for <input> fields.
hasInputs = (typeof node.getElementsByTagName == 'function') &&
node.getElementsByTagName('input').length;
if (node.getAttribute("sorttable_customkey") != null) {
return node.getAttribute("sorttable_customkey");
}
else if (typeof node.textContent != 'undefined' && !hasInputs) {
return node.textContent.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.innerText != 'undefined' && !hasInputs) {
return node.innerText.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.text != 'undefined' && !hasInputs) {
return node.text.replace(/^\s+|\s+$/g, '');
}
else {
switch (node.nodeType) {
case 3:
if (node.nodeName.toLowerCase() == 'input') {
return node.value.replace(/^\s+|\s+$/g, '');
}
case 4:
return node.nodeValue.replace(/^\s+|\s+$/g, '');
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += sorttable.getInnerText(node.childNodes[i]);
}
return innerText.replace(/^\s+|\s+$/g, '');
break;
default:
return '';
}
}
},
reverse: function(tbody) {
// reverse the rows in a tbody
newrows = [];
for (var i=0; i<tbody.rows.length; i++) {
newrows[newrows.length] = tbody.rows[i];
}
for (var i=newrows.length-1; i>=0; i--) {
tbody.appendChild(newrows[i]);
}
delete newrows;
},
/* sort functions
each sort function takes two parameters, a and b
you are comparing a[0] and b[0] */
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
sort_ddmm: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
sort_mmdd: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
shaker_sort: function(list, comp_func) {
// A stable sort function to allow multi-level sorting of data
// see: http://en.wikipedia.org/wiki/Cocktail_sort
// thanks to Joseph Nahmias
var b = 0;
var t = list.length - 1;
var swap = true;
while(swap) {
swap = false;
for(var i = b; i < t; ++i) {
if ( comp_func(list[i], list[i+1]) > 0 ) {
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
swap = true;
}
} // for
t--;
if (!swap) break;
for(var i = t; i > b; --i) {
if ( comp_func(list[i], list[i-1]) < 0 ) {
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
swap = true;
}
} // for
b++;
} // while(swap)
}
}
/* ******************************************************************
Supporting functions: bundled here to avoid depending on a library
****************************************************************** */
// Dean Edwards/Matthias Miller/John Resig
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", sorttable.init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
sorttable.init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
sorttable.init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = sorttable.init;
// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
function dean_addEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
// assign each event handler a unique ID
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
element["on" + type] = handleEvent;
}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else {
// delete the event handler from the hash table
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
}
};
function handleEvent(event) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};
function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
}
// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
forEach, version 1.0
Copyright 2006, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
Array.forEach = function(array, block, context) {
for (var i = 0; i < array.length; i++) {
block.call(context, array[i], i, array);
}
};
}
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
// character enumeration
String.forEach = function(string, block, context) {
Array.forEach(string.split(""), function(chr, index) {
block.call(context, chr, index, string);
});
};
// globally resolve forEach enumeration
var forEach = function(object, block, context) {
if (object) {
var resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.forEach(block, context);
return;
} else if (typeof object == "string") {
// the object is a string
resolve = String;
} else if (typeof object.length == "number") {
// the object is array-like
resolve = Array;
}
resolve.forEach(object, block, context);
}
};