function(twist) {
      var i, m, o, ori, parity, v;
      if (twist != null) {
        parity = 0;
        for (i = m = 6; m >= 0; i = --m) {
          ori = twist % 3;
          twist = (twist / 3) | 0;
          this.co[i] = ori;
          parity += ori;
        }
        this.co[7] = (3 - parity % 3) % 3;
        return this;
      } else {
        v = 0;
        for (i = o = 0; o <= 6; i = ++o) {
          v = 3 * v + this.co[i];
        }
        return v;
      }
    }

function ( twist ) { var i , m , o , ori , parity , v ; if ( twist != null ) { parity = 0 ; for ( i = m = 6 ; m >= 0 ; i = -- m ) { ori = twist % 3 ; twist = ( twist / 3 ) | 0 ; this . co [ i ] = ori ; parity += ori ; } this . co [ 7 ] = ( 3 - parity % 3 ) % 3 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 6 ; i = ++ o ) { v = 3 * v + this . co [ i ] ; } return v ; } }

The twist of the 8 corners, 0 <= twist < 3^7. The orientation of the DRB corner is fully determined by the orientation of the other corners.

The twist of the 8 corners 0 < = twist < 3^7 . The orientation of the DRB corner is fully determined by the orientation of the other corners .


function(flip) {
      var i, m, o, ori, parity, v;
      if (flip != null) {
        parity = 0;
        for (i = m = 10; m >= 0; i = --m) {
          ori = flip % 2;
          flip = flip / 2 | 0;
          this.eo[i] = ori;
          parity += ori;
        }
        this.eo[11] = (2 - parity % 2) % 2;
        return this;
      } else {
        v = 0;
        for (i = o = 0; o <= 10; i = ++o) {
          v = 2 * v + this.eo[i];
        }
        return v;
      }
    }

function ( flip ) { var i , m , o , ori , parity , v ; if ( flip != null ) { parity = 0 ; for ( i = m = 10 ; m >= 0 ; i = -- m ) { ori = flip % 2 ; flip = flip / 2 | 0 ; this . eo [ i ] = ori ; parity += ori ; } this . eo [ 11 ] = ( 2 - parity % 2 ) % 2 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 10 ; i = ++ o ) { v = 2 * v + this . eo [ i ] ; } return v ; } }

The flip of the 12 edges, 0 <= flip < 2^11. The orientation of the BR edge is fully determined by the orientation of the other edges.

The flip of the 12 edges 0 < = flip < 2^11 . The orientation of the BR edge is fully determined by the orientation of the other edges .


function() {
      var i, j, m, o, ref, ref1, ref2, ref3, s;
      s = 0;
      for (i = m = ref = DRB, ref1 = URF + 1; (ref <= ref1 ? m <= ref1 : m >= ref1); i = ref <= ref1 ? ++m : --m) {
        for (j = o = ref2 = i - 1, ref3 = URF; (ref2 <= ref3 ? o <= ref3 : o >= ref3); j = ref2 <= ref3 ? ++o : --o) {
          if (this.cp[j] > this.cp[i]) {
            s++;
          }
        }
      }
      return s % 2;
    }

function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = DRB , ref1 = URF + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = URF ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . cp [ j ] > this . cp [ i ] ) { s ++ ; } } } return s % 2 ; }


function() {
      var i, j, m, o, ref, ref1, ref2, ref3, s;
      s = 0;
      for (i = m = ref = BR, ref1 = UR + 1; (ref <= ref1 ? m <= ref1 : m >= ref1); i = ref <= ref1 ? ++m : --m) {
        for (j = o = ref2 = i - 1, ref3 = UR; (ref2 <= ref3 ? o <= ref3 : o >= ref3); j = ref2 <= ref3 ? ++o : --o) {
          if (this.ep[j] > this.ep[i]) {
            s++;
          }
        }
      }
      return s % 2;
    }

function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = BR , ref1 = UR + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = UR ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . ep [ j ] > this . ep [ i ] ) { s ++ ; } } } return s % 2 ; }

Parity of the edges permutation. Parity of corners and edges are the same if the cube is solvable.

Parity of the edges permutation . Parity of corners and edges are the same if the cube is solvable .


function all_modulo(tickValues, interval) {

	// we can't modulo-check decimals so we need to multiply by 10^Ndecimals
	var maxDecimals = reduce(tickValues, function(prevMax, tick) {
		if ((tick % 1) !== 0) {
			return Math.max(prevMax, tick.toString().split(".")[1].length);
		} else {
			return prevMax;
		}
	}, 0);

	var decimalOffset = Math.pow(10, maxDecimals);
	interval = interval * decimalOffset;

	return reduce(tickValues, function(prev, curr) {
		return prev && ((curr * decimalOffset) % interval === 0);
	}, true);

}

function all_modulo ( tickValues , interval ) { var maxDecimals = reduce ( tickValues , function ( prevMax , tick ) { if ( ( tick % 1 ) !== 0 ) { return Math . max ( prevMax , tick . toString ( ) . split ( "." ) [ 1 ] . length ) ; } else { return prevMax ; } } , 0 ) ; var decimalOffset = Math . pow ( 10 , maxDecimals ) ; interval = interval * decimalOffset ; return reduce ( tickValues , function ( prev , curr ) { return prev && ( ( curr * decimalOffset ) % interval === 0 ) ; } , true ) ; }

Determine if all tickValues are modulo some interval value


function autoDateFormatAndFrequency(minDate, maxDate, dateFormat, availableWidth) {
	var timespan = Math.abs(maxDate - minDate);
	var years = timespan / 31536000000;
	var months = timespan / 2628000000;
	var days = timespan / 86400000;
	var yearGap;
	var hourGap;
	var interval;

	var targetPixelGap = 64;
	var maximum_ticks = Math.max(Math.floor(availableWidth / targetPixelGap), 1);
	var time_gap = timespan / maximum_ticks;

	if (dateFormat == "auto") {
		//lets go small to large
		if (days <= 2) {
			dateFormat = "h";
		}
		else if (days <= 91) {
			dateFormat = "M1d";
		}
		else if (months < 36) {
			dateFormat = "M";
		}
		else {
			dateFormat = "yy";
		}
	}

	var gapInYears = humanReadableNumber(Math.floor(time_gap / 31536000000));
	var gapInMonths = Math.ceil(time_gap / 2628000000);
	var gapInDays = humanReadableNumber(time_gap / 86400000);
	var gapInHours = humanReadableNumber(time_gap / 3600000);

	//make sure that the interval include the maxDate in the interval list
	maxDate.addMilliseconds(0.1);

	switch (dateFormat) {
		case "yy":
			// Add a day to the max date for years to make inclusive of max date
			// irrespective of time zone / DST
			maxDate = d3.time.day.offset(maxDate, 1);
			interval = d3.time.year.range(minDate, maxDate, gapInYears);
			break;

		case "yyyy":
			// See above
			maxDate = d3.time.day.offset(maxDate, 1);
			interval = d3.time.year.range(minDate, maxDate, gapInYears);
			break;

		case "MM":
			interval = d3.time.month.range(minDate, maxDate, gapInMonths);
			break;

		case "M":
			interval = d3.time.month.range(minDate, maxDate, gapInMonths);
			break;

		case "Mdd":
			interval = d3.time.day.range(minDate, maxDate, gapInDays);
			break;

		case "M1d":
			interval = d3.time.day.range(minDate, maxDate, gapInDays);
			break;

		case "YY":
			interval = d3.time.year.range(minDate, maxDate, gapInYears);
			break;

		case "QJan":
			interval = d3.time.month.range(minDate, maxDate, 4);
			break;

		case "QJul":
			interval = d3.time.month.range(minDate, maxDate, 4);
			break;

		case "h":
			interval = d3.time.hour.range(minDate, maxDate, gapInHours);
			break;

		default:
			interval = d3.time.year.range(minDate, maxDate, 1);
	}

	interval = cleanInterval(interval);
	return {"format": dateFormat, "frequency": interval};
}

function autoDateFormatAndFrequency ( minDate , maxDate , dateFormat , availableWidth ) { var timespan = Math . abs ( maxDate - minDate ) ; var years = timespan / 31536000000 ; var months = timespan / 2628000000 ; var days = timespan / 86400000 ; var yearGap ; var hourGap ; var interval ; var targetPixelGap = 64 ; var maximum_ticks = Math . max ( Math . floor ( availableWidth / targetPixelGap ) , 1 ) ; var time_gap = timespan / maximum_ticks ; if ( dateFormat == "auto" ) { if ( days <= 2 ) { dateFormat = "h" ; } else if ( days <= 91 ) { dateFormat = "M1d" ; } else if ( months < 36 ) { dateFormat = "M" ; } else { dateFormat = "yy" ; } } var gapInYears = humanReadableNumber ( Math . floor ( time_gap / 31536000000 ) ) ; var gapInMonths = Math . ceil ( time_gap / 2628000000 ) ; var gapInDays = humanReadableNumber ( time_gap / 86400000 ) ; var gapInHours = humanReadableNumber ( time_gap / 3600000 ) ; maxDate . addMilliseconds ( 0.1 ) ; switch ( dateFormat ) { case "yy" : maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "yyyy" : maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "MM" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case "M" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case "Mdd" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case "M1d" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case "YY" : interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "QJan" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case "QJul" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case "h" : interval = d3 . time . hour . range ( minDate , maxDate , gapInHours ) ; break ; default : interval = d3 . time . year . range ( minDate , maxDate , 1 ) ; } interval = cleanInterval ( interval ) ; return { "format" : dateFormat , "frequency" : interval } ; }

Automatically calculate date frequency if not selected


function validate_chart_model(modelStr) {
	var parsed;

	try {
		parsed = JSON.parse(modelStr);
	} catch (e) {
		throw new TypeError("Chart model is not valid JSON");
	}

	var isValidChartModel = (parsed.hasOwnProperty("chartProps") && parsed.hasOwnProperty("metadata"));
	if (isValidChartModel) {
		return parsed;
	} else {
		throw new TypeError("Not a valid Chartbuilder model");
	}

}

function
validate_chart_model
(
modelStr
)
{
var
parsed
;
try
{
parsed
=
JSON
.
parse
(
modelStr
)
;
}
catch
(
e
)
{
throw
new
TypeError
(
"Chart model is not valid JSON"
)
;
}
var
isValidChartModel
=
(
parsed
.
hasOwnProperty
(
"chartProps"
)
&&
parsed
.
hasOwnProperty
(
"metadata"
)
)
;
if
(
isValidChartModel
)
{
return
parsed
;
}
else
{
throw
new
TypeError
(
"Not a valid Chartbuilder model"
)
;
}
}

Test whether a string is a valid Chartbuilder model
@param {string} modelStr - unparsed string of chart model JSON
@returns {object or null} parsed - parsed object
@static
@memberof helper


function exact_ticks(domain, numticks) {
	numticks -= 1;
	var ticks = [];
	var delta = domain[1] - domain[0];
	var i;
	for (i = 0; i < numticks; i++) {
		ticks.push(domain[0] + (delta / numticks) * i);
	}
	ticks.push(domain[1]);

	if (domain[1] * domain[0] < 0) {
		//if the domain crosses zero, make sure there is a zero line
		var hasZero = false;
		for (i = ticks.length - 1; i >= 0; i--) {
			//check if there is already a zero line
			if (ticks[i] === 0) {
				hasZero = true;
			}
		}
		if (!hasZero) {
			ticks.push(0);
		}
	}

	return ticks;
}

function exact_ticks ( domain , numticks ) { numticks -= 1 ; var ticks = [ ] ; var delta = domain [ 1 ] - domain [ 0 ] ; var i ; for ( i = 0 ; i < numticks ; i ++ ) { ticks . push ( domain [ 0 ] + ( delta / numticks ) * i ) ; } ticks . push ( domain [ 1 ] ) ; if ( domain [ 1 ] * domain [ 0 ] < 0 ) { var hasZero = false ; for ( i = ticks . length - 1 ; i >= 0 ; i -- ) { if ( ticks [ i ] === 0 ) { hasZero = true ; } } if ( ! hasZero ) { ticks . push ( 0 ) ; } } return ticks ; }

Generate an exact number of ticks given a domain

@param {number[]} domain - min/max of the current scale
@param {number} numticks - desired number of ticks
@return {string[]} Array of ticks
@static
@memberof helper


function round_to_precision(num, precision, supress_thou_sep) {
	//zero should always be "0"
	if (num === 0) return "0";

	var s = Math.round(num * Math.pow(10,precision)) / Math.pow(10,precision);
	s = s + "";

	s = s.split(".");

	if (s.length == 1) {
		s[1] = "";
	}

	if (s[1].length < precision) {
		s[1] += Array(precision-s[1].length + 1).join("0");
	}

	if (!supress_thou_sep) {
		s[0] = d3.format(",")(parseInt(s[0]));
	}

	if (precision === 0) {
		return s[0];
	}

	return s.join(".");
}

function round_to_precision ( num , precision , supress_thou_sep ) { if ( num === 0 ) return "0" ; var s = Math . round ( num * Math . pow ( 10 , precision ) ) / Math . pow ( 10 , precision ) ; s = s + "" ; s = s . split ( "." ) ; if ( s . length == 1 ) { s [ 1 ] = "" ; } if ( s [ 1 ] . length < precision ) { s [ 1 ] += Array ( precision - s [ 1 ] . length + 1 ) . join ( "0" ) ; } if ( ! supress_thou_sep ) { s [ 0 ] = d3 . format ( "," ) ( parseInt ( s [ 0 ] ) ) ; } if ( precision === 0 ) { return s [ 0 ] ; } return s . join ( "." ) ; }

round_to_precision
Round a number to N decimal places

@param {number} num - Number to be rounded
@param {number} precision - Desired precision
@param {boolean} supress_thou_sep
@static
@memberof helper
@return {number} Rounded number


function merge_or_apply(defaults, source) {
	var defaultKeys = keys(defaults);
	var sourceKeys = keys(source);
	return reduce(defaultKeys, function(result, key) {
		if (sourceKeys.indexOf(key) > -1) {
			result[key] = source[key];
			return result;
		} else {
			result[key] = defaults[key];
			return result;
		}
	}, {});
}

function merge_or_apply ( defaults , source ) { var defaultKeys = keys ( defaults ) ; var sourceKeys = keys ( source ) ; return reduce ( defaultKeys , function ( result , key ) { if ( sourceKeys . indexOf ( key ) > - 1 ) { result [ key ] = source [ key ] ; return result ; } else { result [ key ] = defaults [ key ] ; return result ; } } , { } ) ; }

Given a defaults object and a source object, copy the value from the source
if it contains the same key, otherwise return the default. Skip keys that
only exist in the source object.
@param {object} defaults - Default schema
@param {object} source - Source object to copy properties from
@returns {object} - Result has identical keys to defaults
@static
@memberof helper

Given a defaults object and a source object copy the value from the source if it contains the same key otherwise return the default . Skip keys that only exist in the source object .


function suggest_tick_num(domain) {
	var MAX_TICKS = 10;
	var INTERVAL_BASE_VALS = [1, 2, 2.5, 5, 10, 25];
	var range = Math.abs(domain[0] - domain[1])
	var minimum = range / MAX_TICKS;
	var digits = Math.floor(range).toString().length;
	var multiplier = Math.pow(10, (digits - 2));

	var acceptable_intervals = reduce(INTERVAL_BASE_VALS, function(prev, curr) {
		var mult = curr * multiplier;

		if (mult >= minimum) {
			prev = prev.concat([mult]);
		}

		return prev;
	}, []);

	for (var i = 0; i < acceptable_intervals.length; i++) {
		var interval = acceptable_intervals[i]
		if(range % interval == 0) {
			return (range / interval) + 1
		}
	};

	return 11;
}

function suggest_tick_num ( domain ) { var MAX_TICKS = 10 ; var INTERVAL_BASE_VALS = [ 1 , 2 , 2.5 , 5 , 10 , 25 ] ; var range = Math . abs ( domain [ 0 ] - domain [ 1 ] ) var minimum = range / MAX_TICKS ; var digits = Math . floor ( range ) . toString ( ) . length ; var multiplier = Math . pow ( 10 , ( digits - 2 ) ) ; var acceptable_intervals = reduce ( INTERVAL_BASE_VALS , function ( prev , curr ) { var mult = curr * multiplier ; if ( mult >= minimum ) { prev = prev . concat ( [ mult ] ) ; } return prev ; } , [ ] ) ; for ( var i = 0 ; i < acceptable_intervals . length ; i ++ ) { var interval = acceptable_intervals [ i ] if ( range % interval == 0 ) { return ( range / interval ) + 1 } } ; return 11 ; }

Given a the domain of a scale suggest the most numerous number
of round number ticks that it cold be divided into while still containing
values evenly divisible by 1, 2, 2.5, 5, 10, or 25.
@param {array} domain - An array of two number like objects
@returns {integer} - Result is a single integer representing a nice number of ticks to use
@static
@memberof helper

Given a the domain of a scale suggest the most numerous number of round number ticks that it cold be divided into while still containing values evenly divisible by 1 2 2 . 5 5 10 or 25 .


function detectNumberSeparators() {
	var n = 1000.50;
	var l = n.toLocaleString();
	var s = n.toString();
	var o = {
		decimal: l.substring(5,6),
		thousands: l.substring(1,2)
	};

	if (l.substring(5,6) == s.substring(5,6)) {
		o.decimal = ".";
	}
	if (l.substring(1,2) == s.substring(1,2)) {
		o.thousands = ",";
	}

	return o;
}

function detectNumberSeparators ( ) { var n = 1000.50 ; var l = n . toLocaleString ( ) ; var s = n . toString ( ) ; var o = { decimal : l . substring ( 5 , 6 ) , thousands : l . substring ( 1 , 2 ) } ; if ( l . substring ( 5 , 6 ) == s . substring ( 5 , 6 ) ) { o . decimal = "." ; } if ( l . substring ( 1 , 2 ) == s . substring ( 1 , 2 ) ) { o . thousands = "," ; } return o ; }

Get thousands and decimal separators based on locale


function transformerFactory(fileSet, info) {
  return transformer

  // Transformer. Adds references files to the set.
  function transformer(ast, file) {
    var filePath = file.path
    var space = file.data
    var links = []
    var landmarks = {}
    var references
    var current
    var link
    var pathname

    /* istanbul ignore if - stdin */
    if (!filePath) {
      return
    }

    references = gatherReferences(file, ast, info, fileSet)
    current = getPathname(filePath)

    for (link in references) {
      pathname = getPathname(link)

      if (
        fileSet &&
        pathname !== current &&
        getHash(link) &&
        links.indexOf(pathname) === -1
      ) {
        links.push(pathname)
        fileSet.add(pathname)
      }
    }

    landmarks[filePath] = true

    slugs.reset()

    visit(ast, mark)

    space[referenceId] = references
    space[landmarkId] = landmarks

    function mark(node) {
      var data = node.data || {}
      var props = data.hProperties || {}
      var id = props.name || props.id || data.id

      if (!id && node.type === 'heading') {
        id = slugs.slug(toString(node))
      }

      if (id) {
        landmarks[filePath + '#' + id] = true
      }
    }
  }
}

function transformerFactory ( fileSet , info ) { return transformer function transformer ( ast , file ) { var filePath = file . path var space = file . data var links = [ ] var landmarks = { } var references var current var link var pathname if ( ! filePath ) { return } references = gatherReferences ( file , ast , info , fileSet ) current = getPathname ( filePath ) for ( link in references ) { pathname = getPathname ( link ) if ( fileSet && pathname !== current && getHash ( link ) && links . indexOf ( pathname ) === - 1 ) { links . push ( pathname ) fileSet . add ( pathname ) } } landmarks [ filePath ] = true slugs . reset ( ) visit ( ast , mark ) space [ referenceId ] = references space [ landmarkId ] = landmarks function mark ( node ) { var data = node . data || { } var props = data . hProperties || { } var id = props . name || props . id || data . id if ( ! id && node . type === 'heading' ) { id = slugs . slug ( toString ( node ) ) } if ( id ) { landmarks [ filePath + '#' + id ] = true } } } }

Factory to create a transformer based on the given info and set.

Factory to create a transformer based on the given info and set .


function validate(exposed, file) {
  var references = file.data[referenceId]
  var filePath = file.path
  var reference
  var nodes
  var real
  var hash
  var pathname
  var warning
  var suggestion
  var ruleId

  for (reference in references) {
    nodes = references[reference]
    real = exposed[reference]
    hash = getHash(reference)

    // Check if files without `hash` can be linked to.  Because there’s no need
    // to inspect those files for headings they are not added to remark.  This
    // is especially useful because they might be non-markdown files. Here we
    // check if they exist.
    if ((real === undefined || real === null) && !hash && fs) {
      real = fs.existsSync(path.join(file.cwd, decodeURI(reference)))
      references[reference] = real
    }

    if (!real) {
      if (hash) {
        pathname = getPathname(reference)
        warning = 'Link to unknown heading'
        ruleId = headingRuleId

        if (pathname !== filePath) {
          warning += ' in `' + pathname + '`'
          ruleId = headingInFileRuleId
        }

        warning += ': `' + hash + '`'
      } else {
        warning = 'Link to unknown file: `' + decodeURI(reference) + '`'
        ruleId = fileRuleId
      }

      suggestion = getClosest(reference, exposed)

      if (suggestion) {
        warning += '. Did you mean `' + suggestion + '`'
      }

      warnAll(file, nodes, warning, ruleId)
    }
  }
}

function
validate
(
exposed
,
file
)
{
var
references
=
file
.
data
[
referenceId
]
var
filePath
=
file
.
path
var
reference
var
nodes
var
real
var
hash
var
pathname
var
warning
var
suggestion
var
ruleId
for
(
reference
in
references
)
{
nodes
=
references
[
reference
]
real
=
exposed
[
reference
]
hash
=
getHash
(
reference
)
if
(
(
real
===
undefined
||
real
===
)
&&
!
hash
&&
fs
)
{
real
=
fs
.
existsSync
(
path
.
join
(
file
.
cwd
,
decodeURI
(
reference
)
)
)
references
[
reference
]
=
real
}
if
(
!
real
)
{
if
(
hash
)
{
pathname
=
getPathname
(
reference
)
warning
=
'Link to unknown heading'
ruleId
=
headingRuleId
if
(
pathname
!==
filePath
)
{
warning
+=
' in `'
+
pathname
+
'`'
ruleId
=
headingInFileRuleId
}
warning
+=
': `'
+
hash
+
'`'
}
else
{
warning
=
'Link to unknown file: `'
+
decodeURI
(
reference
)
+
'`'
ruleId
=
fileRuleId
}
suggestion
=
getClosest
(
reference
,
exposed
)
if
(
suggestion
)
{
warning
+=
'. Did you mean `'
+
suggestion
+
'`'
}
warnAll
(
file
,
nodes
,
warning
,
ruleId
)
}
}
}

Check if `file` references headings or files not in `exposed`.

Check if file references headings or files not in exposed .


function onresource(node) {
    var link = node.url
    var definition
    var index
    var uri
    var pathname
    var hash

    // Handle references.
    if (node.identifier) {
      definition = getDefinition(node.identifier)
      link = definition && definition.url
    }

    // Ignore definitions without url.
    if (!link) {
      return
    }

    uri = parse(link)

    // Drop `?search`
    uri.search = ''
    link = format(uri)

    if (!fileSet && (uri.hostname || uri.pathname)) {
      return
    }

    if (!uri.hostname) {
      if (lines && lineExpression.test(uri.hash)) {
        uri.hash = ''
      }

      // Handle hashes, or relative files.
      if (!uri.pathname && uri.hash) {
        link = file.path + uri.hash
        uri = parse(link)
      } else {
        link = urljoin(file.dirname, link)

        if (uri.hash) {
          link += uri.hash
        }

        uri = parse(link)
      }
    }

    // Handle full links.
    if (uri.hostname) {
      if (!prefix || !fileSet) {
        return
      }

      if (
        uri.hostname !== info.domain ||
        uri.pathname.slice(0, prefix.length) !== prefix
      ) {
        return
      }

      link = uri.pathname.slice(prefix.length) + (uri.hash || '')

      // Things get interesting here: branches: `foo/bar/baz` could be `baz` on
      // the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo`
      // branch.
      //  Currently, we’re ignoring this and just not supporting branches.
      link = link.slice(link.indexOf('/') + 1)
    }

    // Handle file links, or combinations of files and hashes.
    index = link.indexOf(headingPrefix)

    if (index === -1) {
      pathname = link
      hash = null
    } else {
      pathname = link.slice(0, index)
      hash = link.slice(index + headingPrefix.length)

      if (lines && lineExpression.test(hash)) {
        hash = null
      }
    }

    if (!cache[pathname]) {
      cache[pathname] = []
    }

    cache[pathname].push(node)

    if (hash) {
      link = pathname + '#' + hash

      if (!cache[link]) {
        cache[link] = []
      }

      cache[link].push(node)
    }
  }

function onresource ( node ) { var link = node . url var definition var index var uri var pathname var hash if ( node . identifier ) { definition = getDefinition ( node . identifier ) link = definition && definition . url } if ( ! link ) { return } uri = parse ( link ) uri . search = '' link = format ( uri ) if ( ! fileSet && ( uri . hostname || uri . pathname ) ) { return } if ( ! uri . hostname ) { if ( lines && lineExpression . test ( uri . hash ) ) { uri . hash = '' } if ( ! uri . pathname && uri . hash ) { link = file . path + uri . hash uri = parse ( link ) } else { link = urljoin ( file . dirname , link ) if ( uri . hash ) { link += uri . hash } uri = parse ( link ) } } if ( uri . hostname ) { if ( ! prefix || ! fileSet ) { return } if ( uri . hostname !== info . domain || uri . pathname . slice ( 0 , prefix . length ) !== prefix ) { return } link = uri . pathname . slice ( prefix . length ) + ( uri . hash || '' ) link = link . slice ( link . indexOf ( '/' ) + 1 ) } index = link . indexOf ( headingPrefix ) if ( index === - 1 ) { pathname = link hash = null } else { pathname = link . slice ( 0 , index ) hash = link . slice ( index + headingPrefix . length ) if ( lines && lineExpression . test ( hash ) ) { hash = null } } if ( ! cache [ pathname ] ) { cache [ pathname ] = [ ] } cache [ pathname ] . push ( node ) if ( hash ) { link = pathname + '#' + hash if ( ! cache [ link ] ) { cache [ link ] = [ ] } cache [ link ] . push ( node ) } }


function warnAll(file, nodes, reason, ruleId) {
  nodes.forEach(one)

  function one(node) {
    file.message(reason, node, [sourceId, ruleId].join(':'))
  }
}

function warnAll ( file , nodes , reason , ruleId ) { nodes . forEach ( one ) function one ( node ) { file . message ( reason , node , [ sourceId , ruleId ] . join ( ':' ) ) } }

Utility to warn `reason` for each node in `nodes` on `file`.

Utility to warn reason for each node in nodes on file .


function getClosest(pathname, references) {
  var hash = getHash(pathname)
  var base = getPathname(pathname)
  var dictionary = []
  var reference
  var subhash
  var subbase

  for (reference in references) {
    subbase = getPathname(reference)
    subhash = getHash(reference)

    if (getPathname(reference) === base) {
      if (subhash && hash) {
        dictionary.push(subhash)
      }
    } else if (!subhash && !hash) {
      dictionary.push(subbase)
    }
  }

  return propose(hash ? hash : base, dictionary, {threshold: 0.7})
}

function getClosest ( pathname , references ) { var hash = getHash ( pathname ) var base = getPathname ( pathname ) var dictionary = [ ] var reference var subhash var subbase for ( reference in references ) { subbase = getPathname ( reference ) subhash = getHash ( reference ) if ( getPathname ( reference ) === base ) { if ( subhash && hash ) { dictionary . push ( subhash ) } } else if ( ! subhash && ! hash ) { dictionary . push ( subbase ) } } return propose ( hash ? hash : base , dictionary , { threshold : 0.7 } ) }


function getHash(uri) {
  var hash = parse(uri).hash
  return hash ? hash.slice(1) : null
}

function getHash ( uri ) { var hash = parse ( uri ) . hash return hash ? hash . slice ( 1 ) : null }


function getPrevMap(from) {
        if (typeof options.map.prev === 'string') {
            var mapPath = options.map.prev + path.basename(from) + '.map';

            if (grunt.file.exists(mapPath)) {
                return grunt.file.read(mapPath);
            }
        }
    }

function getPrevMap ( from ) { if ( typeof options . map . prev === 'string' ) { var mapPath = options . map . prev + path . basename ( from ) + '.map' ; if ( grunt . file . exists ( mapPath ) ) { return grunt . file . read ( mapPath ) ; } } }

Returns an input map contents if a custom map path was specified
@param {string} from Input CSS path
@returns {?string}


function (req, res, next) {
                if(req.url.indexOf('.') === -1 && req.url.indexOf(startDir) > -1){
                    req.url = startPath;
                }

                return next();
            }

function ( req , res , next ) { if ( req . url . indexOf ( '.' ) === - 1 && req . url . indexOf ( startDir ) > - 1 ) { req . url = startPath ; } return next ( ) ; }

to add back in logging comment this line out


function parseIPv4(addr) {
        if (typeof(addr) !== 'string')
                throw new TypeError('addr (string) is required');

        var octets = addr.split(/\./).map(function (octet) {
                return (parseInt(octet, 10));
        });
        if (octets.length !== 4)
                throw new TypeError('valid IP address required');

        var uint32 = ((octets[0] * Math.pow(256, 3)) +
                      (octets[1] * Math.pow(256, 2)) +
                      (octets[2] * 256) + octets[3]);
        return (uint32);
}

function
parseIPv4
(
addr
)
{
if
(
typeof
(
addr
)
!==
'string'
)
throw
new
TypeError
(
'addr (string) is required'
)
;
var
octets
=
addr
.
split
(
/
\.
/
)
.
map
(
function
(
octet
)
{
return
(
parseInt
(
octet
,
10
)
)
;
}
)
;
if
(
octets
.
length
!==
4
)
throw
new
TypeError
(
'valid IP address required'
)
;
var
uint32
=
(
(
octets
[
0
]
*
Math
.
pow
(
256
,
3
)
)
+
(
octets
[
1
]
*
Math
.
pow
(
256
,
2
)
)
+
(
octets
[
2
]
*
256
)
+
octets
[
3
]
)
;
return
(
uint32
)
;
}

turns a dotted-decimal address into a UInt32

turns a dotted - decimal address into a UInt32


function getNested(obj, prop) {
        var service = obj[prop];
        if (service === undefined && Bottle.config.strict) {
            throw new Error('Bottle was unable to resolve a service.  `' + prop + '` is undefined.');
        }
        return service;
    }

Iterator used to walk down a nested object.

If Bottle.config.strict is true, this method will throw an exception if it encounters an
undefined path

@param Object obj
@param String prop
@return mixed
@throws Error if Bottle is unable to resolve the requested service.

Iterator used to walk down a nested object .


function getNestedBottle(name) {
        var bottle;
        if (!this.nested[name]) {
            bottle = Bottle.pop();
            this.nested[name] = bottle;
            this.factory(name, function SubProviderFactory() {
                return bottle.container;
            });
        }
        return this.nested[name];
    }

function getNestedBottle ( name ) { var bottle ; if ( ! this . nested [ name ] ) { bottle = Bottle . pop ( ) ; this . nested [ name ] = bottle ; this . factory ( name , function SubProviderFactory ( ) { return bottle . container ; } ) ; } return this . nested [ name ] ; }

Get a nested bottle. Will set and return if not set.

@param String name
@return Bottle

Get a nested bottle . Will set and return if not set .


function applyMiddleware(middleware, name, instance, container) {
        var descriptor = {
            configurable : true,
            enumerable : true
        };
        if (middleware.length) {
            descriptor.get = function getWithMiddlewear() {
                var index = 0;
                var next = function nextMiddleware(err) {
                    if (err) {
                        throw err;
                    }
                    if (middleware[index]) {
                        middleware[index++](instance, next);
                    }
                };
                next();
                return instance;
            };
        } else {
            descriptor.value = instance;
            descriptor.writable = true;
        }

        Object.defineProperty(container, name, descriptor);

        return container[name];
    }

function applyMiddleware ( middleware , name , instance , container ) { var descriptor = { configurable : true , enumerable : true } ; if ( middleware . length ) { descriptor . get = function getWithMiddlewear ( ) { var index = 0 ; var next = function nextMiddleware ( err ) { if ( err ) { throw err ; } if ( middleware [ index ] ) { middleware [ index ++ ] ( instance , next ) ; } } ; next ( ) ; return instance ; } ; } else { descriptor . value = instance ; descriptor . writable = true ; } Object . defineProperty ( container , name , descriptor ) ; return container [ name ] ; }

Function used by provider to set up middleware for each request.

@param Number id
@param String name
@param Object instance
@param Object container
@return void

Function used by provider to set up middleware for each request .


function middleware(fullname, func) {
        var parts, name;
        if (typeof fullname === FUNCTION_TYPE) {
            func = fullname;
            fullname = GLOBAL_NAME;
        }

        parts = fullname.split(DELIMITER);
        name = parts.shift();
        if (parts.length) {
            getNestedBottle.call(this, name).middleware(parts.join(DELIMITER), func);
        } else {
            if (!this.middlewares[name]) {
                this.middlewares[name] = [];
            }
            this.middlewares[name].push(func);
        }
        return this;
    }

function middleware ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . middleware ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . middlewares [ name ] ) { this . middlewares [ name ] = [ ] ; } this . middlewares [ name ] . push ( func ) ; } return this ; }

Register middleware.

@param String name
@param Function func
@return Bottle


function createProvider(name, Provider) {
        var providerName, properties, container, id, decorators, middlewares;

        id = this.id;
        container = this.container;
        decorators = this.decorators;
        middlewares = this.middlewares;
        providerName = name + PROVIDER_SUFFIX;

        properties = Object.create(null);
        properties[providerName] = {
            configurable : true,
            enumerable : true,
            get : function getProvider() {
                var instance = new Provider();
                delete container[providerName];
                container[providerName] = instance;
                return instance;
            }
        };

        properties[name] = {
            configurable : true,
            enumerable : true,
            get : function getService() {
                var provider = container[providerName];
                var instance;
                if (provider) {
                    // filter through decorators
                    instance = getWithGlobal(decorators, name).reduce(reducer, provider.$get(container));

                    delete container[providerName];
                    delete container[name];
                }
                return instance === undefined ? instance : applyMiddleware(getWithGlobal(middlewares, name),
                    name, instance, container);
            }
        };

        Object.defineProperties(container, properties);
        return this;
    }

function createProvider ( name , Provider ) { var providerName , properties , container , id , decorators , middlewares ; id = this . id ; container = this . container ; decorators = this . decorators ; middlewares = this . middlewares ; providerName = name + PROVIDER_SUFFIX ; properties = Object . create ( null ) ; properties [ providerName ] = { configurable : true , enumerable : true , get : function getProvider ( ) { var instance = new Provider ( ) ; delete container [ providerName ] ; container [ providerName ] = instance ; return instance ; } } ; properties [ name ] = { configurable : true , enumerable : true , get : function getService ( ) { var provider = container [ providerName ] ; var instance ; if ( provider ) { instance = getWithGlobal ( decorators , name ) . reduce ( reducer , provider . $get ( container ) ) ; delete container [ providerName ] ; delete container [ name ] ; } return instance === undefined ? instance : applyMiddleware ( getWithGlobal ( middlewares , name ) , name , instance , container ) ; } } ; Object . defineProperties ( container , properties ) ; return this ; }

Create the provider properties on the container

@param String name
@param Function Provider
@return Bottle


function provider(fullname, Provider) {
        var parts, name;
        parts = fullname.split(DELIMITER);
        if (this.providerMap[fullname] && parts.length === 1 && !this.container[fullname + PROVIDER_SUFFIX]) {
            return console.error(fullname + ' provider already instantiated.');
        }
        this.originalProviders[fullname] = Provider;
        this.providerMap[fullname] = true;

        name = parts.shift();

        if (parts.length) {
            getNestedBottle.call(this, name).provider(parts.join(DELIMITER), Provider);
            return this;
        }
        return createProvider.call(this, name, Provider);
    }

function
provider
(
fullname
,
Provider
)
{
var
parts
,
name
;
parts
=
fullname
.
split
(
DELIMITER
)
;
if
(
this
.
providerMap
[
fullname
]
&&
parts
.
length
===
1
&&
!
this
.
container
[
fullname
+
PROVIDER_SUFFIX
]
)
{
return
console
.
error
(
fullname
+
' provider already instantiated.'
)
;
}
this
.
originalProviders
[
fullname
]
=
Provider
;
this
.
providerMap
[
fullname
]
=
true
;
name
=
parts
.
shift
(
)
;
if
(
parts
.
length
)
{
getNestedBottle
.
call
(
this
,
name
)
.
provider
(
parts
.
join
(
DELIMITER
)
,
Provider
)
;
return
this
;
}
return
createProvider
.
call
(
this
,
name
,
Provider
)
;
}

Register a provider.

@param String fullname
@param Function Provider
@return Bottle


function createService(name, Service, isClass) {
        var deps = arguments.length > 3 ? slice.call(arguments, 3) : [];
        var bottle = this;
        return factory.call(this, name, function GenericFactory() {
            var serviceFactory = Service; // alias for jshint
            var args = deps.map(getNestedService, bottle.container);

            if (!isClass) {
                return serviceFactory.apply(null, args);
            }
            return new (Service.bind.apply(Service, [null].concat(args)))();
        });
    }

function createService ( name , Service , isClass ) { var deps = arguments . length > 3 ? slice . call ( arguments , 3 ) : [ ] ; var bottle = this ; return factory . call ( this , name , function GenericFactory ( ) { var serviceFactory = Service ; var args = deps . map ( getNestedService , bottle . container ) ; if ( ! isClass ) { return serviceFactory . apply ( null , args ) ; } return new ( Service . bind . apply ( Service , [ null ] . concat ( args ) ) ) ( ) ; } ) ; }

Private helper for creating service and service factories.

@param String name
@param Function Service
@return Bottle

Private helper for creating service and service factories .


function service(name, Service) {
        return createService.apply(this, [name, Service, true].concat(slice.call(arguments, 2)));
    }

function service ( name , Service ) { return createService . apply ( this , [ name , Service , true ] . concat ( slice . call ( arguments , 2 ) ) ) ; }

Register a class service

@param String name
@param Function Service
@return Bottle


function serviceFactory(name, factoryService) {
        return createService.apply(this, [name, factoryService, false].concat(slice.call(arguments, 2)));
    }

function serviceFactory ( name , factoryService ) { return createService . apply ( this , [ name , factoryService , false ] . concat ( slice . call ( arguments , 2 ) ) ) ; }


function defineValue(name, val) {
        Object.defineProperty(this, name, {
            configurable : true,
            enumerable : true,
            value : val,
            writable : true
        });
    }

function defineValue ( name , val ) { Object . defineProperty ( this , name , { configurable : true , enumerable : true , value : val , writable : true } ) ; }

Define a mutable property on the container.

@param String name
@param mixed val
@return void
@scope container

Define a mutable property on the container .


function setValueObject(container, name) {
        var nestedContainer = container[name];
        if (!nestedContainer) {
            nestedContainer = {};
            defineValue.call(container, name, nestedContainer);
        }
        return nestedContainer;
    }

function setValueObject ( container , name ) { var nestedContainer = container [ name ] ; if ( ! nestedContainer ) { nestedContainer = { } ; defineValue . call ( container , name , nestedContainer ) ; } return nestedContainer ; }

Iterator for setting a plain object literal via defineValue

@param Object container
@param string name


function value(name, val) {
        var parts;
        parts = name.split(DELIMITER);
        name = parts.pop();
        defineValue.call(parts.reduce(setValueObject, this.container), name, val);
        return this;
    }

function value ( name , val ) { var parts ; parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineValue . call ( parts . reduce ( setValueObject , this . container ) , name , val ) ; return this ; }

Register a value

@param String name
@param mixed val
@return Bottle


function constant(name, value) {
        var parts = name.split(DELIMITER);
        name = parts.pop();
        defineConstant.call(parts.reduce(setValueObject, this.container), name, value);
        return this;
    }

function constant ( name , value ) { var parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineConstant . call ( parts . reduce ( setValueObject , this . container ) , name , value ) ; return this ; }

Register a constant

@param String name
@param mixed value
@return Bottle


function decorator(fullname, func) {
        var parts, name;
        if (typeof fullname === FUNCTION_TYPE) {
            func = fullname;
            fullname = GLOBAL_NAME;
        }

        parts = fullname.split(DELIMITER);
        name = parts.shift();
        if (parts.length) {
            getNestedBottle.call(this, name).decorator(parts.join(DELIMITER), func);
        } else {
            if (!this.decorators[name]) {
                this.decorators[name] = [];
            }
            this.decorators[name].push(func);
        }
        return this;
    }

function decorator ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . decorator ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . decorators [ name ] ) { this . decorators [ name ] = [ ] ; } this . decorators [ name ] . push ( func ) ; } return this ; }

Register decorator.

@param String fullname
@param Function func
@return Bottle


function instanceFactory(name, Factory) {
        return factory.call(this, name, function GenericInstanceFactory(container) {
            return {
                instance : Factory.bind(Factory, container)
            };
        });
    }

function instanceFactory ( name , Factory ) { return factory . call ( this , name , function GenericInstanceFactory ( container ) { return { instance : Factory . bind ( Factory , container ) } ; } ) ; }

Register an instance factory inside a generic factory.

@param {String} name - The name of the service
@param {Function} Factory - The factory function, matches the signature required for the
`factory` method
@return Bottle

Register an instance factory inside a generic factory .


function pop(name) {
        var instance;
        if (typeof name === STRING_TYPE) {
            instance = bottles[name];
            if (!instance) {
                bottles[name] = instance = new Bottle();
                instance.constant('BOTTLE_NAME', name);
            }
            return instance;
        }
        return new Bottle();
    }

function pop ( name ) { var instance ; if ( typeof name === STRING_TYPE ) { instance = bottles [ name ] ; if ( ! instance ) { bottles [ name ] = instance = new Bottle ( ) ; instance . constant ( 'BOTTLE_NAME' , name ) ; } return instance ; } return new Bottle ( ) ; }

Get an instance of bottle.

If a name is provided the instance will be stored in a local hash.  Calling Bottle.pop multiple
times with the same name will return the same instance.

@param String name
@return Bottle


function register(Obj) {
        var value = Obj.$value === undefined ? Obj : Obj.$value;
        return this[Obj.$type || 'service'].apply(this, [Obj.$name, value].concat(Obj.$inject || []));
    }

function register ( Obj ) { var value = Obj . $value === undefined ? Obj : Obj . $value ; return this [ Obj . $type || 'service' ] . apply ( this , [ Obj . $name , value ] . concat ( Obj . $inject || [ ] ) ) ; }

Register a service, factory, provider, or value based on properties on the object.

properties:
* Obj.$name   String required ex: `'Thing'`
* Obj.$type   String optional 'service', 'factory', 'provider', 'value'.  Default: 'service'
* Obj.$inject Mixed  optional only useful with $type 'service' name or array of names
* Obj.$value  Mixed  optional Normally Obj is registered on the container.  However, if this
property is included, it's value will be registered on the container
instead of the object itsself.  Useful for registering objects on the
bottle container without modifying those objects with bottle specific keys.

@param Function Obj
@return Bottle

Register a service factory provider or value based on properties on the object .


function resetProviders(names) {
        var tempProviders = this.originalProviders;
        var shouldFilter = Array.isArray(names);

        Object.keys(this.originalProviders).forEach(function resetProvider(originalProviderName) {
            if (shouldFilter && names.indexOf(originalProviderName) === -1) {
                return;
            }
            var parts = originalProviderName.split(DELIMITER);
            if (parts.length > 1) {
                parts.forEach(removeProviderMap, getNestedBottle.call(this, parts[0]));
            }
            removeProviderMap.call(this, originalProviderName);
            this.provider(originalProviderName, tempProviders[originalProviderName]);
        }, this);
    }

function resetProviders ( names ) { var tempProviders = this . originalProviders ; var shouldFilter = Array . isArray ( names ) ; Object . keys ( this . originalProviders ) . forEach ( function resetProvider ( originalProviderName ) { if ( shouldFilter && names . indexOf ( originalProviderName ) === - 1 ) { return ; } var parts = originalProviderName . split ( DELIMITER ) ; if ( parts . length > 1 ) { parts . forEach ( removeProviderMap , getNestedBottle . call ( this , parts [ 0 ] ) ) ; } removeProviderMap . call ( this , originalProviderName ) ; this . provider ( originalProviderName , tempProviders [ originalProviderName ] ) ; } , this ) ; }

Resets providers on a bottle instance. If 'names' array is provided, only the named providers will be reset.

@param Array names
@return void

Resets providers on a bottle instance . If names array is provided only the named providers will be reset .


function throwIfInvalidNode(node, functionName) {
    if (!exports.isASTNode(node)) {
        throw new Error(functionName + "(): " + util.inspect(node) + " is not a valid AST node.");
    }
}

function
throwIfInvalidNode
(
node
,
functionName
)
{
if
(
!
exports
.
isASTNode
(
node
)
)
{
throw
new
Error
(
functionName
+
"(): "
+
util
.
inspect
(
node
)
+
" is not a valid AST node."
)
;
}
}

For internal use. Throws if is passed an invalid AST node, else does nothing.

For internal use . Throws if is passed an invalid AST node else does nothing .


function isEvent(expr, eventDeclarations) {
        for (let { node, enclosingContract } of eventDeclarations) {
            if (expr.callee.name === node.name && sourceCode.isAChildOf(expr, enclosingContract)) {
                return true;
            }
        }
        return false;
    }

function isEvent ( expr , eventDeclarations ) { for ( let { node , enclosingContract } of eventDeclarations ) { if ( expr . callee . name === node . name && sourceCode . isAChildOf ( expr , enclosingContract ) ) { return true ; } } return false ; }

Determines whether the given call name refers to an event declaration using scope resolution.

Determines whether the given call name refers to an event declaration using scope resolution .


function registerEventName(emitted) {
        const { node } = emitted;
        (!emitted.exit) && events.push({ node, enclosingContract: sourceCode.getParent(node) });
    }

function registerEventName ( emitted ) { const { node } = emitted ; ( ! emitted . exit ) && events . push ( { node , enclosingContract : sourceCode . getParent ( node ) } ) ; }

Stores each declared event in the file and its corresponding parent contract


function inspectVariableDeclarator(emitted) {
            let node = emitted.node;

            if (!emitted.exit) {
                allVariableDeclarations [node.id.name] = node;
            }
        }

function inspectVariableDeclarator ( emitted ) { let node = emitted . node ; if ( ! emitted . exit ) { allVariableDeclarations [ node . id . name ] = node ; } }

collect all variable declarations from VariableDeclarators and DeclarativeExpressions


function inspectProgram(emitted) {

            if (emitted.exit) {
                Object.keys(allVariableDeclarations).forEach(function(name) {
                    context.report({
                        node: allVariableDeclarations [name],
                        message: "Variable '" + name + "' is declared but never used."
                    });
                });
            }

        }

function
inspectProgram
(
emitted
)
{
if
(
emitted
.
exit
)
{
Object
.
keys
(
allVariableDeclarations
)
.
forEach
(
function
(
name
)
{
context
.
report
(
{
node
:
allVariableDeclarations
[
name
]
,
message
:
"Variable '"
+
name
+
"' is declared but never used."
}
)
;
}
)
;
}
}

While exiting Progam Node, all the vars that haven't been used still exist inside VariableDeclarations. Report them

While exiting Progam Node all the vars that haven t been used still exist inside VariableDeclarations . Report them


function inspectIdentifier(emitted) {
            if (!emitted.exit) {
                let node = emitted.node,
                    sourceCode = context.getSourceCode();

                if (
                    allVariableDeclarations [node.name] &&
					sourceCode.getParent(node).type !== "VariableDeclarator"
                ) {
                    delete allVariableDeclarations [node.name];
                }
            }
        }

function inspectIdentifier ( emitted ) { if ( ! emitted . exit ) { let node = emitted . node , sourceCode = context . getSourceCode ( ) ; if ( allVariableDeclarations [ node . name ] && sourceCode . getParent ( node ) . type !== "VariableDeclarator" ) { delete allVariableDeclarations [ node . name ] ; } } }

As soon as the first use of a variable is encountered, delete that variable's node from allVariableDeclarations

As soon as the first use of a variable is encountered delete that variable s node from allVariableDeclarations


function inspectFunctionsOfContract(emitted) {
            if (emitted.exit) {
                return;
            }

            const { node } = emitted, { body } = node;
            let cursor = 0;

            // Filter out non-function nodes
            body.filter(child => {
                return ["FunctionDeclaration", "ConstructorDeclaration"].includes(child.type);
            }).forEach(funcNode => {
                // Return if the function is ignored or in the correct order.
                if (
                    (context.options && isIgnored(funcNode, node, context.options[0].ignore)) ||
                    isFunctionVisibility(node, funcNode, functionOrder[cursor])
                ) {
                    return;
                }

                const funcPosInOrder = findFuncPosInOrder(node, funcNode);

                if (funcPosInOrder > cursor) {
                    cursor = funcPosInOrder;
                    return;
                }

                context.report({ node: funcNode, message: errorMessage });
            });
        }

function inspectFunctionsOfContract ( emitted ) { if ( emitted . exit ) { return ; } const { node } = emitted , { body } = node ; let cursor = 0 ; body . filter ( child => { return [ "FunctionDeclaration" , "ConstructorDeclaration" ] . includes ( child . type ) ; } ) . forEach ( funcNode => { if ( ( context . options && isIgnored ( funcNode , node , context . options [ 0 ] . ignore ) ) || isFunctionVisibility ( node , funcNode , functionOrder [ cursor ] ) ) { return ; } const funcPosInOrder = findFuncPosInOrder ( node , funcNode ) ; if ( funcPosInOrder > cursor ) { cursor = funcPosInOrder ; return ; } context . report ( { node : funcNode , message : errorMessage } ) ; } ) ; }

Set cursor to point to first visibility in order of vis. array.
For each function Fi inside contract, if Fi's vis is same as that pointed by cursor, ignore func.
If not, check the pos in the order of Fi's vis. If ahead, simply move cursor forward to Fi's vis.'s
position in array. If behind, report func.

Set cursor to point to first visibility in order of vis . array . For each function Fi inside contract if Fi s vis is same as that pointed by cursor ignore func . If not check the pos in the order of Fi s vis . If ahead simply move cursor forward to Fi s vis . s position in array . If behind report func .


function inspectCallExpression(emitted) {
            let node = emitted.node,
                callArgs = node.arguments;

            if (emitted.exit) {
                return;
            }

            let nodeCode = sourceCode.getText(node);

            //for a 0-argument call, ensure that name is followed by '()'
            if (!callArgs.length) {
                for (let i = nodeCode.length; i > 0; i--) {
                    if (nodeCode [i] === ")" && nodeCode [i-1] === "(") {
                        return;
                    }
                    if (/[\s\(\)]/.test(nodeCode [i])) {
                        break;
                    }
                }

                return context.report({
                    node: node,
                    message: "\"" + nodeCode + "\": " +
					"A call without arguments should have brackets without any whitespace between them, like 'functionName ()'."
                });
            }

            let lastCallArg = callArgs.slice(-1) [0];

            //if call spans over multiple lines (due to too many arguments), below rules don't apply
            if (sourceCode.getLine(node) !== sourceCode.getEndingLine(lastCallArg)) {
                return;
            }

            let charBeforeFirstArg = sourceCode.getPrevChar(callArgs [0]),
                charAfterLastCallArg = sourceCode.getNextChar(lastCallArg);

            (callArgs [0].type !== "NameValueAssignment" && charBeforeFirstArg !== "(") && context.report({
                node: callArgs [0],
                location: {
                    column: sourceCode.getColumn(callArgs [0]) - 1
                },
                message: "'" + node.callee.name + "': The first argument must not be preceded by any whitespace or comments (only '(')."
            });

            (lastCallArg.type !== "NameValueAssignment" && charAfterLastCallArg !== ")") && context.report({
                node: callArgs [0],
                location: {
                    column: sourceCode.getEndingColumn(lastCallArg) + 1
                },
                message: "'" + node.callee.name + "': The last argument must not be succeeded by any whitespace or comments (only ')')."
            });
        }

same could potentially be applied to FunctionDeclaration


function inspectExperimentalPragmaStatement(emitted) {
            if (emitted.exit) {
                return;
            }

            const { node } = emitted,
                nodesAllowedAbove = ["ExperimentalPragmaStatement", "PragmaStatement"],
                programNode = context.getSourceCode().getParent(node);

            for (let childNode of programNode.body) {
                // If we've reached this exp. pragma while traversing body, it means its position is fine.
                if (node.start === childNode.start) {
                    return;
                }

                // We found the first node not allowed above experimental pragma, report and exit.
                const pragmaCode = context.getSourceCode().getText(node);

                if (nodesAllowedAbove.indexOf(childNode.type) < 0) {
                    const errObject = {
                        node,
                        fix(fixer) {
                            return [fixer.remove(node),
                                fixer.insertTextBefore(childNode, `${pragmaCode}${EOL}`)];
                        },
                        message: "Experimental Pragma must precede everything except Solidity Pragma."
                    };

                    return context.report(errObject);
                }
            }
        }

Experimental pragmas, if they exist, must be above everything EXCEPT pragma solidity & other experimental pragmas.

Experimental pragmas if they exist must be above everything EXCEPT pragma solidity & other experimental pragmas .


function(sourceCode, errorMessages) {
        let fixedSourceCode = "", fixes = [], fixesApplied = [], remainingMessages = [];
        let cursor = Number.NEGATIVE_INFINITY;

        function attemptFix(fix) {
            let start = fix.range [0], end = fix.range [1];

            // If this fix overlaps with the previous one or has negaive range, return.
            // Note that when cursor === start, its NOT an overlap since when source code in range
            // [i, j] is being edited, the code covered is actually from i to j-1.
            if (cursor > start || start > end) {
                return false;
            }

            fixedSourceCode += sourceCode.slice(Math.max(0, cursor), Math.max(0, start));
            fixedSourceCode += fix.text;
            cursor = end;
            return true;
        }

        // Segregate errors that can be fixed from those that can't for sure.
        errorMessages.forEach(function(msg) {
            if (msg.fix) {
                // If msg.fix is an Array of fix packets, merge them into a single fix packet.
                try {
                    msg.fix = mergeFixes(msg.fix, sourceCode);
                } catch (e) {
                    throw new Error("An error occured while applying fix of rule \""
						+ msg.ruleName + "\" for error \"" + msg.message + "\": " + e.message);
                }

                return fixes.push(msg);
            }

            remainingMessages.push(msg);
        });

        // Fixes will be applied in top-down approach. The fix that arrives first (line-wise, followed by column-wise)
        // gets applied first. But if current fix is applied successfully & the next one overlaps the current one,
        // then the next one is simply skipped. Hence, it is NOT guranteed that all fixes will be applied.
        fixes.sort(compareMessagesByFixRange).forEach(function(msg) {
            if (attemptFix(msg.fix)) {
                return fixesApplied.push(msg);
            }

            remainingMessages.push(msg);
        });

        fixedSourceCode += sourceCode.slice(Math.max(0, cursor));
        remainingMessages.sort(compareMessagesByLocation);

        return {
            fixesApplied: fixesApplied,
            fixedSourceCode: fixedSourceCode,
            remainingErrorMessages: remainingMessages
        };
    }

Apply fixes to source code depending on whichever errors can be fixed.
@param {String} sourceCode Code to fix
@param {Array} errorMessages Error objects that describe the error and possibly how to fix it.
@returns {Object} fixed Contains fixed code and information about fixes applied & remaining un-fixed errors.

Apply fixes to source code depending on whichever errors can be fixed .


function inspectTopLevelDeclaration(emitted) {
            let body = emitted.node.body || [],
                levelOneIndentRegExp = new RegExp("^\\n" + BASE_INDENTATION_STYLE + "$"),
                endingLineRegExp = new RegExp("^" + BASE_INDENTATION_STYLE + "(\\S| \\*)$"),	//either a non-whitespace character or 1 extra whitespace followed by * (closing of multi-line comment)
                endingLineExtraIndentRegExp = new RegExp("^" + BASE_INDENTATION_STYLE.repeat(2) + "(\\S| \\*)$");

            if (emitted.exit) {
                return;
            }

            function inspectChild(child) {
                let prevChars = sourceCode.getPrevChars(child, BASE_INDENTATION_STYLE.length+1),
                    endingLineNum = sourceCode.getEndingLine(child);

                //if the start of node doesn't follow correct indentation
                if (!levelOneIndentRegExp.test(prevChars)) {
                    context.report({
                        node: child,
                        message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                    });
                }

                // If the node starts & ends on same line, exit.
                if (sourceCode.getLine(child) === endingLineNum) {
                    return;
                }

                // If node starts & ends on diff lines, the ending line must also follow correct indentation.
                // Exception to this is an abstract function whose declaration spans over multiple lines. Eg-
                // function foo()
                //     payable
                //     returns (uint, string);

                if (child.type === "FunctionDeclaration" && child.is_abstract) {

                    if (!endingLineExtraIndentRegExp.test(
                        sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.repeat(2).length+1))) {
                        context.report({
                            node: child,
                            location: {
                                line: endingLineNum,
                                column: 0
                            },
                            message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                        });
                    }

                    return;
                }

                if (!endingLineRegExp.test(
                    sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.length+1))) {
                    context.report({
                        node: child,
                        location: {
                            line: endingLineNum,
                            column: 0
                        },
                        message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
                    });
                }
            }

            body.forEach(inspectChild);
        }

function
inspectTopLevelDeclaration
(
emitted
)
{
let
body
=
emitted
.
node
.
body
||
[
]
,
levelOneIndentRegExp
=
new
RegExp
(
"^\\n"
+
\\
+
BASE_INDENTATION_STYLE
)
,
"$"
,
endingLineRegExp
=
new
RegExp
(
"^"
+
BASE_INDENTATION_STYLE
+
"(\\S| \\*)$"
)
;
\\
\\
endingLineExtraIndentRegExp
=
new
RegExp
(
"^"
+
BASE_INDENTATION_STYLE
.
repeat
(
2
)
+
"(\\S| \\*)$"
)
}

Ensure level 1 indentation before all immediate children of top-level declarations

Ensure level 1 indentation before all immediate children of top - level declarations


function inspectBlockStatement(emitted) {
            let node = emitted.node;

            //if the complete block resides on the same line, no need to check for indentation
            if (emitted.exit || (sourceCode.getLine(node) === sourceCode.getEndingLine(node))) {
                return;
            }

            let parent = sourceCode.getParent(node),
                parentDeclarationLine = sourceCode.getLine(parent),
                parentDeclarationLineText = sourceCode.getTextOnLine(parentDeclarationLine),
                currentIndent, currentIndentLevel;

            function inspectBlockItem(blockIndent, blockIndentDesc, blockItem) {
                let prevChars = sourceCode.getPrevChars(blockItem, blockIndent.length+1),
                    endingLineNum = sourceCode.getEndingLine(blockItem),
                    endingLineRegExp = new RegExp("^" + blockIndent + "(" + BASE_INDENTATION_STYLE + ")?\\S.*$");

                if (prevChars !== ("\n" + blockIndent)) {
                    context.report({
                        node: blockItem,
                        message: `Only use indent of ${blockIndentDesc}.`
                    });
                }

                /**
				 * If the block item spans over multiple lines, make sure the ending line also follows the indent rule
				 * An exception to this is the if-else statements when they don't have BlockStatement as their body
				 * eg-
				 * if (a)
				 *     foo();
				 * else
				 *     bar();
				 *
				 * Another exception is chaining.
				 * eg-
				 * function() {
				 *   myObject
				 *     .funcA()
				 *     .funcB()
				 *     [0];
				 * }
				 * Ending line has 1 extra indentation but this is acceptable.
				 */
                if (
                    blockItem.type !== "IfStatement" &&
					sourceCode.getLine(blockItem) !== endingLineNum &&
					!endingLineRegExp.test(sourceCode.getTextOnLine(endingLineNum))
                ) {
                    context.report({
                        node: blockItem,
                        location: {
                            line: endingLineNum,
                            column: 0
                        },
                        message: `Only use indent of ${blockIndentDesc}.`
                    });
                }
            }

            currentIndent = parentDeclarationLineText.slice(
                0,
                parentDeclarationLineText.indexOf(parentDeclarationLineText.trim())
            );

            //in case of no match, match() returns null. Return [] instead to avoid crash
            currentIndentLevel = (currentIndent.match(BASE_INDENTATION_STYLE_REGEXP_GLOBAL) || []).length;

            //ensure that there is only whitespace of correct level before the block's parent's code
            if (getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel) !== currentIndent) {
                return;	//exit now, we can' proceed further unless this is fixed
            }

            //indentation of items inside block should be 1 level greater than that of parent
            const blockIndent = getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel + 1);
            const blockIndentDesc = getIndentDescription(BASE_INDENTATION_STYLE, currentIndentLevel + 1);

            node.body.forEach(inspectBlockItem.bind(null, blockIndent, blockIndentDesc));
        }

function inspectBlockStatement ( emitted ) { let node = emitted . node ; if ( emitted . exit || ( sourceCode . getLine ( node ) === sourceCode . getEndingLine ( node ) ) ) { return ; } let parent = sourceCode . getParent ( node ) , parentDeclarationLine = sourceCode . getLine ( parent ) , parentDeclarationLineText = sourceCode . getTextOnLine ( parentDeclarationLine ) , currentIndent , currentIndentLevel ; function inspectBlockItem ( blockIndent , blockIndentDesc , blockItem ) { let prevChars = sourceCode . getPrevChars ( blockItem , blockIndent . length + 1 ) , endingLineNum = sourceCode . getEndingLine ( blockItem ) , endingLineRegExp = new RegExp ( "^" + blockIndent + "(" + BASE_INDENTATION_STYLE + ")?\\S.*$" ) ; \\ if ( prevChars !== ( "\n" + \n ) ) blockIndent } { context . report ( { node : blockItem , message : ` ${ blockIndentDesc } ` } ) ; } if ( blockItem . type !== "IfStatement" && sourceCode . getLine ( blockItem ) !== endingLineNum && ! endingLineRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) ) ) { context . report ( { node : blockItem , location : { line : endingLineNum , column : 0 } , message : ` ${ blockIndentDesc } ` } ) ; } currentIndent = parentDeclarationLineText . slice ( 0 , parentDeclarationLineText . indexOf ( parentDeclarationLineText . trim ( ) ) ) ; currentIndentLevel = ( currentIndent . match ( BASE_INDENTATION_STYLE_REGEXP_GLOBAL ) || [ ] ) . length ; if ( getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel ) !== currentIndent ) { return ; } const blockIndent = getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; }

Ensure 1 extra indentation inside Block than before it


function(node, beforeCount, afterCount) {
        let sourceCodeText = this.text;

        if (node) {
            if (astUtils.isASTNode(node)) {

                return this.text.slice(
                    Math.max(0, node.start - (Math.abs(beforeCount) || 0)),
                    node.end + (Math.abs(afterCount) || 0)
                );

            }

            throw new Error("Invalid Node object");
        }

        return sourceCodeText;
    }

function
(
node
,
beforeCount
,
afterCount
)
{
let
sourceCodeText
=
this
.
text
;
if
(
node
)
{
if
(
astUtils
.
isASTNode
(
node
)
)
{
return
this
.
text
.
slice
(
Math
.
max
(
0
,
node
.
start
(
Math
.
abs
(
beforeCount
)
||
0
)
)
,
node
.
end
+
(
Math
.
abs
(
afterCount
)
||
0
)
)
;
}
throw
new
Error
(
"Invalid Node object"
)
;
}
return
sourceCodeText
;
}

Function to retrieve the source code text being linted. Returns the complete source code if no node specified
@param {Object} node The AST node whose source code (specifically) is needed
@param {int} beforeCount Include beforeCount number of characters prior to the node's code
@param {int} afterCount Include afterCount number of characters following the node's code
@returns {String} sourceCodeText source code of the specified node plus extra characters specified by beforeCount & afterCount

Function to retrieve the source code text being linted . Returns the complete source code if no node specified


function inspectVariableDeclaration(emitted) {
            let node = emitted.node, code = sourceCode.getText(node);

            if (emitted.exit) {
                return;
            }

            //if a particular character is '=', check its left and right for single space
            for (let i = 2; i < code.length; i++) {
                if (code [i] === "=") {
                    (!/^[^\/\s] $/.test(code.slice(i-2, i))) && context.report({
                        node: node,
                        message: "There should be only a single space between assignment operator '=' and its left side."
                    });

                    (!/^ [^\/\s]$/.test(code.slice(i+1, i+3))) && context.report({
                        node: node,
                        message: "There should be only a single space between assignment operator '=' and its right side."
                    });
                }
            }
        }

statement like `var x = 10` doesn't come under AssignmentExpression, so needs to be checked separately

statement like var x = 10 doesn t come under AssignmentExpression so needs to be checked separately


function RuleContext(ruleName, ruleDesc, ruleMeta, Solium) {
    let contextObject = this;

    // Set contect attribute 'options' iff options were provided.
    ruleDesc.options && Object.assign(contextObject, { options: ruleDesc.options });

    //set read-only properties of the context object
    Object.defineProperties(contextObject, {

        name: {
            value: ruleName,
            writable: false	//though the default is false anyway, I think its better to express your intention clearly
        },

        meta: {
            value: ruleDesc,
            writable: false
        }

    });

    //inherit all Solium methods which are of relevance to the rule
    INHERITABLE_METHODS.forEach(function(methodName) {
        contextObject [methodName] = function(s, z, a, b, o) {	//every method will receive 5 arguments tops
            return Solium [methodName].call(Solium, s, z, a, b, o);
        };
    });

    /**
     * wrapper around Solium.report () which adds some additional information to the error object
     * @param {Object} error An object describing the lint error, sent by the rule currently running
     */
    contextObject.report = function(error) {

        if (!isErrObjectValid(error)) {
            throw new Error(
                `Rule "${ruleName}": invalid error object was passed. AJV message:${EOL}${util.inspect(isErrObjectValid.errors)}`
            );
        }

        Object.assign(error, { ruleName: ruleName, ruleMeta: ruleMeta, type: contextObject.meta.type });
        Solium.report(error);

    };
}

function RuleContext ( ruleName , ruleDesc , ruleMeta , Solium ) { let contextObject = this ; ruleDesc . options && Object . assign ( contextObject , { options : ruleDesc . options } ) ; Object . defineProperties ( contextObject , { name : { value : ruleName , writable : false } , meta : { value : ruleDesc , writable : false } } ) ; INHERITABLE_METHODS . forEach ( function ( methodName ) { contextObject [ methodName ] = function ( s , z , a , b , o ) { return Solium [ methodName ] . call ( Solium , s , z , a , b , o ) ; } ; } ) ; contextObject . report = function ( error ) { if ( ! isErrObjectValid ( error ) ) { throw new Error ( ` ${ ruleName } ${ EOL } ${ util . inspect ( isErrObjectValid . errors ) } ` ) ; } Object . assign ( error , { ruleName : ruleName , ruleMeta : ruleMeta , type : contextObject . meta . type } ) ; Solium . report ( error ) ; } ; }

context object Constructor to set read-only properties and provide additional functionality to the rules using it
@param {String} ruleName Name of the rule the object is for
@param {Object} ruleDesc Description of the rule the object is for
@param {Object} ruleMeta meta object defined inside the rule file by rule developer
@param {Object} Solium Main Solium object from which to inherit functionality to provide to the rules

context object Constructor to set read - only properties and provide additional functionality to the rules using it


function resolveUpstream(upstream) {
    let coreRulesetRegExp = /^solium:[a-z_]+$/;

    // Determine whether upstream is a solium core ruleset or a sharable config.
    if (coreRulesetRegExp.test(upstream)) {
        try {
            return require("../../config/rulesets/solium-" + upstream.split(":") [1]).rules;
        } catch (e) {
            throw new Error("\"" + upstream + "\" is not a core ruleset.");
        }
    }

    // If flow reaches here, it means upstream is a sharable config.
    let configName = constants.SOLIUM_SHARABLE_CONFIG_PREFIX + upstream, config;

    try {
        config = require(configName);
    } catch (e) {
        if (e.code === "MODULE_NOT_FOUND") {
            throw new Error(
                "The sharable config \"" + configName + "\" is not installed. " +
				"If Solium is installed globally, install the config globally using " +
				"\"npm install -g " + configName + "\". Else install locally using " +
				"\"npm install --save-dev " + configName + "\"."
            );
        }

        throw new Error("The sharable config \"" + configName + "\" could not be loaded: " + e.message);
    }

    if (isAValidSharableConfig(config)) {
        return config.rules;
    }

    throw new Error("Invalid sharable config \"" +
		configName + "\". AJV message:\n" + util.inspect(isAValidSharableConfig.errors));
}

Given a ruleset name, determine whether its a core set or a sharable config and load the rule config accordingly.
@param {String} upstream The ruleset to resolve
@returns {Object} ruleConfigs Set of rule configs exported by the upstream ruleset.

Given a ruleset name determine whether its a core set or a sharable config and load the rule config accordingly .


function resolvePluginConfig(name, plugin) {
    let config = {};

    Object.keys(plugin.rules).forEach(function(ruleName) {
        config [name + "/" + ruleName] = plugin.rules [ruleName].meta.docs.type;
    });

    return config;
}

function resolvePluginConfig ( name , plugin ) { let config = { } ; Object . keys ( plugin . rules ) . forEach ( function ( ruleName ) { config [ name + "/" + ruleName ] = plugin . rules [ ruleName ] . meta . docs . type ; } ) ; return config ; }

Create provided plugin's default rule configuration
@param {String} name Plugin name without 'solium-plugin-' prefix
@param {Object} plugin The plugin Object as exported by the solium plugin
@returns {Object} config Rule configuration object for the given plugin

Create provided plugin s default rule configuration


function writeConfigFile(config) {
    try {
        fs.writeFileSync(
            SOLIUMRC_FILENAME_ABSOLUTE,
            JSON.stringify(config, null, 2)
        );
    } catch (e) {
        errorReporter.reportFatal(
            `An error occurred while writing to ${SOLIUMRC_FILENAME_ABSOLUTE}:${EOL}${e.message}`);
        process.exit(errorCodes.WRITE_FAILED);
    }
}

function writeConfigFile ( config ) { try { fs . writeFileSync ( SOLIUMRC_FILENAME_ABSOLUTE , JSON . stringify ( config , null , 2 ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }

Synchronously write the passed configuration to the file whose absolute path is SOLIUMRC_FILENAME_ABSOLUTE
@param {Object} config User Configuration object
@returns {void}


function lintString(sourceCode, userConfig, errorReporter, fileName) {
    let lintErrors, fixesApplied;

    try {
        if (userConfig.options.autofix || userConfig.options.autofixDryrun) {
            let result = solium.lintAndFix(sourceCode, userConfig);

            lintErrors = result.errorMessages;
            if (userConfig.options.autofix) {
                applyFixes(fileName, result);
                fixesApplied = result.fixesApplied;
            } else {
                errorReporter.reportDiff(fileName,
                    sourceCode, result.fixedSourceCode, result.fixesApplied.length);
            }
        } else {
            lintErrors = solium.lint(sourceCode, userConfig);
        }
    } catch (e) {
        // Don't abort in case of a parse error, just report it as a normal lint issue.
        if (e.name !== "SyntaxError") {
            const messageOrStackrace = userConfig.options.debug ? e.stack : e.message;
            errorReporter.reportFatal(`An error occured while linting over ${fileName}:${EOL}${messageOrStackrace}`);
            process.exit(errorCodes.ERRORS_FOUND);
        }

        lintErrors = [{
            ruleName: "",
            type: "error",
            message: `Syntax error: unexpected token ${e.found}`,
            line: e.location.start.line,
            column: e.location.start.column
        }];
    }

    // If any lint/internal errors/warnings exist, report them
    lintErrors.length &&
        errorReporter.report(fileName, sourceCode, lintErrors, fixesApplied);

    return lintErrors.reduce(function(numOfErrors, err) {
        return err.type === "error" ? numOfErrors+1 : numOfErrors;
    }, 0);
}

function lintString ( sourceCode , userConfig , errorReporter , fileName ) { let lintErrors , fixesApplied ; try { if ( userConfig . options . autofix || userConfig . options . autofixDryrun ) { let result = solium . lintAndFix ( sourceCode , userConfig ) ; lintErrors = result . errorMessages ; if ( userConfig . options . autofix ) { applyFixes ( fileName , result ) ; fixesApplied = result . fixesApplied ; } else { errorReporter . reportDiff ( fileName , sourceCode , result . fixedSourceCode , result . fixesApplied . length ) ; } } else { lintErrors = solium . lint ( sourceCode , userConfig ) ; } } catch ( e ) { if ( e . name !== "SyntaxError" ) { const messageOrStackrace = userConfig . options . debug ? e . stack : e . message ; errorReporter . reportFatal ( ` ${ fileName } ${ EOL } ${ messageOrStackrace } ` ) ; process . exit ( errorCodes . ERRORS_FOUND ) ; } lintErrors = [ { ruleName : "" , type : "error" , message : ` ${ e . found } ` , line : e . location . start . line , column : e . location . start . column } ] ; } lintErrors . length && errorReporter . report ( fileName , sourceCode , lintErrors , fixesApplied ) ; return lintErrors . reduce ( function ( numOfErrors , err ) { return err . type === "error" ? numOfErrors + 1 : numOfErrors ; } , 0 ) ; }

Lint a source code string based on user settings. If autofix is enabled, write the fixed code back to file.
@param {String} sourceCode The source code to be linted
@param {Object} userConfig User configuration
@param {Object} errorReporter The error reporter to use
@param {String} fileName (optional) File name to use when reporting errors
@returns {Integer} numOfErrors Number of Lint ERRORS that occured.

Lint a source code string based on user settings . If autofix is enabled write the fixed code back to file .


function lintFile(fileName, userConfig, errorReporter) {
    let sourceCode;

    try {
        sourceCode = fs.readFileSync(fileName, "utf8");
    } catch (e) {
        errorReporter.reportFatal("Unable to read " + fileName + ": " + e.message);
        process.exit(errorCodes.FILE_NOT_FOUND);
    }

    return lintString(sourceCode, userConfig, errorReporter, fileName);
}

function
lintFile
(
fileName
,
userConfig
,
errorReporter
)
{
let
sourceCode
;
try
{
sourceCode
=
fs
.
readFileSync
(
fileName
,
"utf8"
)
;
}
catch
(
e
)
{
errorReporter
.
reportFatal
(
"Unable to read "
+
fileName
+
": "
+
e
.
message
)
;
process
.
exit
(
errorCodes
.
FILE_NOT_FOUND
)
;
}
return
lintString
(
sourceCode
,
userConfig
,
errorReporter
,
fileName
)
;
}

Lint a file based on user settings
@param {String} fileName The path to the file to be linted
@param {Object} userConfig User configuration
@param {Object} errorReporter The error reporter to use
@returns {Integer} numOfErrors Number of Lint ERRORS that occured (the result returned by lintString())


function createCliOptions(cliObject) {
    function collect(val, memo) {
        memo.push(val);
        return memo;
    }

    cliObject
        .version(`Solium version ${version}`)
        .description("Linter to find & fix style and security issues in Solidity smart contracts.")
        .usage("[options] <keyword>")

        .option("-i, --init", "Create default rule configuration files")
        .option("-f, --file [filepath::String]", "Solidity file to lint")
        .option("-d, --dir [dirpath::String]", "Directory containing Solidity files to lint")
        .option("-R, --reporter [name::String]", "Format to report lint issues in (pretty | gcc)", "pretty")
        .option("-c, --config [filepath::String]", "Path to the .soliumrc configuration file")
        .option("-, --stdin", "Read input file from stdin")
        .option("--fix", "Fix Lint issues where possible")
        .option("--fix-dry-run", "Output fix diff without applying it")
        .option("--debug", "Display debug information")
        .option("--watch", "Watch for file changes")
        .option("--hot", "(Deprecated) Same as --watch")
        .option("--no-soliumignore", "Do not look for .soliumignore file")
        .option("--no-soliumrc", "Do not look for soliumrc configuration file")
        .option(
            "--rule [rule]",
            "Rule to execute. This overrides the specified rule's configuration in soliumrc if present",
            collect,
            []
        )
        .option(
            "--plugin [plugin]",
            "Plugin to execute. This overrides the specified plugin's configuration in soliumrc if present",
            collect,
            []
        );
}

Function responsible for defining all the available commandline options & version information
@param {Object} cliObject Commander Object handling the cli


function(options, listItemsSchema) {
        let validateOptionsList = SchemaValidator.compile({
            type: "array",
            minItems: listItemsSchema.length,
            additionalItems: false,
            items: listItemsSchema
        });

        return validateOptionsList(options);
    }

function ( options , listItemsSchema ) { let validateOptionsList = SchemaValidator . compile ( { type : "array" , minItems : listItemsSchema . length , additionalItems : false , items : listItemsSchema } ) ; return validateOptionsList ( options ) ; }

Determine whether the options object supplied is valid according to the schema passed.
@param {Array} options List of options
@param {Array} listItemsSchema A list of schema objects defining schema for every item in the options list.
@returns {Boolean} isValid True if options list is valid, false otherwise.

Determine whether the options object supplied is valid according to the schema passed .


function inspectFD(emitted) {
            const { node } = emitted,
                visibilityModifiers = ["public", "external", "internal", "private"];
            const modifiers = (node.modifiers || []),
                firstVisibilityModifierIndex = modifiers.findIndex(m => visibilityModifiers.includes(m.name));

            // If no visibility modifiers exist in function declaration, exit now
            if (emitted.exit || firstVisibilityModifierIndex === -1) {
                return;
            }

            const firstNonVisModifBeforeFirstVisModif = modifiers.slice(0, firstVisibilityModifierIndex).find(m => !visibilityModifiers.includes(m.name));

            // TODO: Add fix() for this rule
            if (firstNonVisModifBeforeFirstVisModif) {
                const issue = {
                    node: modifiers[firstVisibilityModifierIndex],
                    message: `Visibility modifier "${modifiers[firstVisibilityModifierIndex].name}" should come before other modifiers.`
                };
                context.report(issue);
            }
        }

function inspectFD ( emitted ) { const { node } = emitted , visibilityModifiers = [ "public" , "external" , "internal" , "private" ] ; const modifiers = ( node . modifiers || [ ] ) , firstVisibilityModifierIndex = modifiers . findIndex ( m => visibilityModifiers . includes ( m . name ) ) ; if ( emitted . exit || firstVisibilityModifierIndex === - 1 ) { return ; } const firstNonVisModifBeforeFirstVisModif = modifiers . slice ( 0 , firstVisibilityModifierIndex ) . find ( m => ! visibilityModifiers . includes ( m . name ) ) ; if ( firstNonVisModifBeforeFirstVisModif ) { const issue = { node : modifiers [ firstVisibilityModifierIndex ] , message : ` ${ modifiers [ firstVisibilityModifierIndex ] . name } ` } ; context . report ( issue ) ; } }

Find index of the first visibility modifier in declaration. Find the first non-VM before this first VM found above. If non-VM found, report the VM.

Find index of the first visibility modifier in declaration . Find the first non - VM before this first VM found above . If non - VM found report the VM .


function isHex(literal) {
    let reg = /^[0-9a-f]+$/i;

    //test for '0x' separately because hex notation should not be a part of the standard RegExp
    if (literal.slice(0, 2) !== "0x") {
        return false;
    }

    return reg.test(literal.slice(2));
}

function isHex ( literal ) { let reg = / ^[0-9a-f]+$ / i ; if ( literal . slice ( 0 , 2 ) !== "0x" ) { return false ; } return reg . test ( literal . slice ( 2 ) ) ; }

Determine whether the provided literal is in Hex Notation
@param {String} literal The literal to test for Hex Notation
@returns {Boolean}


function Soundfont (ctx, nameToUrl) {
  console.warn('new Soundfont() is deprected')
  console.log('Please use Soundfont.instrument() instead of new Soundfont().instrument()')
  if (!(this instanceof Soundfont)) return new Soundfont(ctx)

  this.nameToUrl = nameToUrl || Soundfont.nameToUrl
  this.ctx = ctx
  this.instruments = {}
  this.promises = []
}

Create a Soundfont object

@param {AudioContext} context - the [audio context](https://developer.mozilla.org/en/docs/Web/API/AudioContext)
@param {Function} nameToUrl - (Optional) a function that maps the sound font name to the url
@return {Soundfont} a soundfont object


function oscillatorPlayer (ctx, defaultOptions) {
  defaultOptions = defaultOptions || {}
  return function (note, time, duration, options) {
    console.warn('The oscillator player is deprecated.')
    console.log('Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.')
    var midi = note > 0 && note < 129 ? +note : parser.midi(note)
    var freq = midi ? parser.midiToFreq(midi, 440) : null
    if (!freq) return

    duration = duration || 0.2

    options = options || {}
    var destination = options.destination || defaultOptions.destination || ctx.destination
    var vcoType = options.vcoType || defaultOptions.vcoType || 'sine'
    var gain = options.gain || defaultOptions.gain || 0.4

    var vco = ctx.createOscillator()
    vco.type = vcoType
    vco.frequency.value = freq

    /* VCA */
    var vca = ctx.createGain()
    vca.gain.value = gain

    /* Connections */
    vco.connect(vca)
    vca.connect(destination)

    vco.start(time)
    if (duration > 0) vco.stop(time + duration)
    return vco
  }
}

Returns a function that plays an oscillator

@param {AudioContext} ac - the audio context
@param {Hash} defaultOptions - (Optional) a hash of options:
- vcoType: the oscillator type (default: 'sine')
- gain: the output gain value (default: 0.4)
- destination: the player destination (default: ac.destination)


function instrument (ac, name, options) {
  if (arguments.length === 1) return function (n, o) { return instrument(ac, n, o) }
  var opts = options || {}
  var isUrl = opts.isSoundfontURL || isSoundfontURL
  var toUrl = opts.nameToUrl || nameToUrl
  var url = isUrl(name) ? name : toUrl(name, opts.soundfont, opts.format)

  return load(ac, url, { only: opts.only || opts.notes }).then(function (buffers) {
    var p = player(ac, buffers, opts).connect(opts.destination ? opts.destination : ac.destination)
    p.url = url
    p.name = name
    return p
  })
}

function instrument ( ac , name , options ) { if ( arguments . length === 1 ) return function ( n , o ) { return instrument ( ac , n , o ) } var opts = options || { } var isUrl = opts . isSoundfontURL || isSoundfontURL var toUrl = opts . nameToUrl || nameToUrl var url = isUrl ( name ) ? name : toUrl ( name , opts . soundfont , opts . format ) return load ( ac , url , { only : opts . only || opts . notes } ) . then ( function ( buffers ) { var p = player ( ac , buffers , opts ) . connect ( opts . destination ? opts . destination : ac . destination ) p . url = url p . name = name return p } ) }

Load a soundfont instrument. It returns a promise that resolves to a
instrument object.

The instrument object returned by the promise has the following properties:

- name: the instrument name
- play: A function to play notes from the buffer with the signature
`play(note, time, duration, options)`

The valid options are:

- `format`: the soundfont format. 'mp3' by default. Can be 'ogg'
- `soundfont`: the soundfont name. 'MusyngKite' by default. Can be 'FluidR3_GM'
- `nameToUrl` <Function>: a function to convert from instrument names to URL
- `destination`: by default Soundfont uses the `audioContext.destination` but you can override it.
- `gain`: the gain of the player (1 by default)
- `notes`: an array of the notes to decode. It can be an array of strings
with note names or an array of numbers with midi note numbers. This is a
performance option: since decoding mp3 is a cpu intensive process, you can limit
limit the number of notes you want and reduce the time to load the instrument.

@param {AudioContext} ac - the audio context
@param {String} name - the instrument name. For example: 'acoustic_grand_piano'
@param {Object} options - (Optional) the same options as Soundfont.loadBuffers
@return {Promise}

@example
var Soundfont = require('sounfont-player')
Soundfont.instrument('marimba').then(function (marimba) {
marimba.play('C4')
})

Load a soundfont instrument . It returns a promise that resolves to a instrument object .


function hasSystemLib (lib) {
  var libName = 'lib' + lib + '.+(so|dylib)'
  var libNameRegex = new RegExp(libName)

    // Try using ldconfig on linux systems
  if (hasLdconfig()) {
    try {
      if (childProcess.execSync('ldconfig -p 2>/dev/null | grep -E "' + libName + '"').length) {
        return true
      }
    } catch (err) {
      // noop -- proceed to other search methods
    }
  }

    // Try checking common library locations
  return SYSTEM_PATHS.some(function (systemPath) {
    try {
      var dirListing = fs.readdirSync(systemPath)
      return dirListing.some(function (file) {
        return libNameRegex.test(file)
      })
    } catch (err) {
      return false
    }
  })
}

function
hasSystemLib
(
lib
)
{
var
libName
=
'lib'
+
lib
+
'.+(so|dylib)'
var
libNameRegex
=
new
RegExp
(
libName
)
if
(
hasLdconfig
(
)
)
{
try
{
if
(
childProcess
.
execSync
(
'ldconfig -p 2>/dev/null | grep -E "'
+
libName
+
'"'
)
.
length
)
{
return
true
}
}
catch
(
err
)
{
}
}
return
SYSTEM_PATHS
.
some
(
function
(
systemPath
)
{
try
{
var
dirListing
=
fs
.
readdirSync
(
systemPath
)
return
dirListing
.
some
(
function
(
file
)
{
return
libNameRegex
.
test
(
file
)
}
)
}
catch
(
err
)
{
return
false
}
}
)
}

Checks for lib using ldconfig if present, or searching SYSTEM_PATHS
otherwise.
@param String library name, e.g. 'jpeg' in 'libjpeg64.so' (see first line)
@return Boolean exists

Checks for lib using ldconfig if present or searching SYSTEM_PATHS otherwise .


async function thenify(fn) {
  return await new Promise(function(resolve, reject) {
    function callback(err, res) {
      if (err) return reject(err);
      return resolve(res);
    }

    fn(callback);
  });
}

async function thenify ( fn ) { return await new Promise ( function ( resolve , reject ) { function callback ( err , res ) { if ( err ) return reject ( err ) ; return resolve ( res ) ; } fn ( callback ) ; } ) ; }

Helper function to convert a callback to a Promise.

Helper function to convert a callback to a Promise .


function startWatching(opts) {
    var chokidarOpts = createChokidarOpts(opts);
    var watcher = chokidar.watch(opts.patterns, chokidarOpts);

    var throttledRun = _.throttle(run, opts.throttle);
    var debouncedRun = _.debounce(throttledRun, opts.debounce);
    watcher.on('all', function(event, path) {
        var description = EVENT_DESCRIPTIONS[event] + ':';

        if (opts.verbose) {
            console.error(description, path);
        } else {
            if (!opts.silent) {
                console.log(event + ':' + path);
            }
        }

        // XXX: commands might be still run concurrently
        if (opts.command) {
            debouncedRun(
                opts.command
                    .replace(/\{path\}/ig, path)
                    .replace(/\{event\}/ig, event)
            );
        }
    });

    watcher.on('error', function(error) {
        console.error('Error:', error);
        console.error(error.stack);
    });

    watcher.once('ready', function() {
        var list = opts.patterns.join('", "');
        if (!opts.silent) {
            console.error('Watching', '"' + list + '" ..');
        }
    });
}

function
startWatching
(
opts
)
{
var
chokidarOpts
=
createChokidarOpts
(
opts
)
;
var
watcher
=
chokidar
.
watch
(
opts
.
patterns
,
chokidarOpts
)
;
var
throttledRun
=
_
.
throttle
(
run
,
opts
.
throttle
)
;
var
debouncedRun
=
_
.
debounce
(
throttledRun
,
opts
.
debounce
)
;
watcher
.
on
(
'all'
,
function
(
event
,
path
)
{
var
description
=
EVENT_DESCRIPTIONS
[
event
]
+
':'
;
if
(
opts
.
verbose
)
{
console
.
error
(
description
,
path
)
;
}
else
{
if
(
!
opts
.
silent
)
{
console
.
log
(
event
+
':'
+
path
)
;
}
}
if
(
opts
.
command
)
{
debouncedRun
(
opts
.
command
.
replace
(
/
\{path\}
/
ig
,
path
)
.
replace
(
/
\{event\}
/
ig
,
event
)
)
;
}
}
)
;
watcher
.
on
(
'error'
,
function
(
error
)
{
console
.
error
(
'Error:'
,
error
)
;
console
.
error
(
error
.
stack
)
;
}
)
;
watcher
.
once
(
'ready'
,
function
(
)
{
var
list
=
opts
.
patterns
.
join
(
'", "'
)
;
if
(
!
opts
.
silent
)
{
console
.
error
(
'Watching'
,
'"'
+
list
+
'" ..'
)
;
}
}
)
;
}

Estimates spent working hours based on commit dates


function _resolveIgnoreOpt(ignoreOpt) {
    if (!ignoreOpt) {
        return ignoreOpt;
    }

    var ignores = !_.isArray(ignoreOpt) ? [ignoreOpt] : ignoreOpt;

    return _.map(ignores, function(ignore) {
        var isRegex = ignore[0] === '/' && ignore[ignore.length - 1] === '/';
        if (isRegex) {
            // Convert user input to regex object
            var match = ignore.match(new RegExp('^/(.*)/(.*?)$'));
            return new RegExp(match[1], match[2]);
        }

        return ignore;
    });
}

function _resolveIgnoreOpt ( ignoreOpt ) { if ( ! ignoreOpt ) { return ignoreOpt ; } var ignores = ! _ . isArray ( ignoreOpt ) ? [ ignoreOpt ] : ignoreOpt ; return _ . map ( ignores , function ( ignore ) { var isRegex = ignore [ 0 ] === '/' && ignore [ ignore . length - 1 ] === '/' ; if ( isRegex ) { var match = ignore . match ( new RegExp ( '^/(.*)/(.*?)$' ) ) ; return new RegExp ( match [ 1 ] , match [ 2 ] ) ; } return ignore ; } ) ; }


function requireProp(props, propName, componentName) {
  return isEmpty(props[propName])
    ? new Error(
        `The prop \`${propName}\` is required for \`${componentName}\`.`
      )
    : null
}

function requireProp ( props , propName , componentName ) { return isEmpty ( props [ propName ] ) ? new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) : null }


function _0to1(props, propName, componentName) {
  if (isEmpty(props[propName])) {
    return null
  }
  if (
    typeof props[propName] === 'number' &&
    props[propName] >= 0 &&
    props[propName] <= 1
  ) {
    return null
  }
  return new Error(
    `Invalid prop \`${propName}\` supplied to \`${componentName}\`. Please provide a number in the 0-1 range.`
  )
}

function _0to1 ( props , propName , componentName ) { if ( isEmpty ( props [ propName ] ) ) { return null } if ( typeof props [ propName ] === 'number' && props [ propName ] >= 0 && props [ propName ] <= 1 ) { return null } return new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) }