Collect the preconditions, snapshots and postconditions from a contract checker of a function.
543045
def _preconditions_snapshots_postconditions(checker: Callable) -> _PrePostSnaps:
    """"""
    preconditions = getattr(checker, "__preconditions__", [])  # type: List[List[icontract._Contract]]

    assert all(isinstance(precondition_group, list) for precondition_group in preconditions)
    assert (all(
        isinstance(precondition, icontract._Contract) for precondition_group in preconditions
        for precondition in precondition_group))

    # Filter empty precondition groups ("require else" blocks)
    preconditions = [group for group in preconditions if len(group) > 0]

    snapshots = getattr(checker, "__postcondition_snapshots__", [])  # type: List[icontract._Snapshot]
    assert all(isinstance(snap, icontract._Snapshot) for snap in snapshots)

    postconditions = getattr(checker, "__postconditions__", [])  # type: List[icontract._Contract]

    assert all(isinstance(postcondition, icontract._Contract) for postcondition in postconditions)

    return _PrePostSnaps(preconditions=preconditions, snapshots=snapshots, postconditions=postconditions)
153159
private static DebuggableScript[] getAllFunctions
            (DebuggableScript function) {
        ObjArray functions = new ObjArray();
        collectFunctions_r(function, functions);
        DebuggableScript[] result = new DebuggableScript[functions.size()];
        functions.toArray(result);
        return result;
    }
881892
def find_checker(func: CallableT) -> Optional[CallableT]:
    """"""
    contract_checker = None  # type: Optional[CallableT]
    for a_wrapper in _walk_decorator_stack(func):
        if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "__postconditions__"):
            contract_checker = a_wrapper

    return contract_checker
497170
function wafr(options, callback) {
  const contractsPath = options.path;
  const optimizeCompiler = options.optimize;
  const sourcesExclude = options.exclude;
  const sourcesInclude = options.include;
  const focusContract = options.focus;
  const reportLogs = {
    contracts: {},
    status: 'success',
    failure: 0,
    success: 0,
    logs: {},
  };

  // get allinput sources
  getInputSources(contractsPath, sourcesExclude, sourcesInclude, focusContract, (inputError, sources) => {
    if (inputError) {
      throwError(`while getting input sources: ${inputError}`);
    }

    // build contract sources input for compiler
    const compilerInput = {
      sources: Object.assign({ 'wafr/Test.sol': testContract }, sources),
    };

    // compiling contracts
    log(`compiling contracts from ${Object.keys(sources).length} sources...`);

    // compile solc output (sync method)
    const output = solc.compile(compilerInput, optimizeCompiler);

    // output compiler warnings
    filterErrorErrors(output.errors).forEach((outputError) => {
      log(`while compiling contracts in path warning.. ${contractsPath}: ${outputError}`);
    });

    // handle all compiling errors
    if (filterErrorWarnings(output.errors).length > 0) {
      output.errors.forEach((outputError) => {
        throwError(`while compiling contracts in path ${contractsPath}: ${outputError}`);
      });
    } else {
      // compiling contracts
      log('contracts compiled!');

      const outputContracts = contractNameProcessing(options.onlyContractName, output.contracts);

      // add output to report
      reportLogs.contracts = outputContracts;

      // find and build test contracts array
      const testContracts = buildTestContractsArray(outputContracts);
      const startIndex = 0;

      // done function
      const contractComplete = (contractReport) => {
        // if contract failed, then all tests fail
        if (contractReport !== false) {
          if (contractReport.status === 'failure') {
            reportLogs.status = 'failure';
            reportLogs.failure += contractReport.failure;
          } else {
            reportLogs.success += contractReport.success;
          }
        }

        // if contract report is false, there is no more contracts to test
        if (contractReport === false) {
          // report done in log
          report(`

  ${reportLogs.failure && chalk.red(`${reportLogs.failure} not passing`) || ''}
  ${reportLogs.success && chalk.green(`${reportLogs.success} passing`) || ''}
`);

          // report logs
          callback(null, reportLogs);
        } else {
          reportLogs.logs[contractReport.name] = contractReport;
        }
      };

      // if no test contracts, end testing
      if (testContracts.length === 0) {
        contractComplete(false);
      } else {
        // test each contract sequentially
        testContractsSeq(startIndex, testContracts, contractComplete);
      }
    }
  });
}
570568
def _detect(self):
        
        results = []
        for c in self.slither.contracts_derived:
            ret = self.detect_uninitialized(c)
            for variable, functions in ret:
                info = "{}.{} ({}) is never initialized. It is used in:\n"
                info = info.format(variable.contract.name,
                                   variable.name,
                                   variable.source_mapping_str)
                for f in functions:
                    info += "\t- {} ({})\n".format(f.name, f.source_mapping_str)

                source = [variable.source_mapping]
                source += [f.source_mapping for f in functions]

                json = self.generate_json_result(info)
                self.add_variable_to_json(variable, json)
                self.add_functions_to_json(functions, json)
                results.append(json)

        return results
1209600
def _build_preconditions_table(self):
        ''''''
        self.local_action_preconditions = dict()
        self.global_action_preconditions = []
        action_fluents = self.action_fluents
        for precond in self.preconds:
            scope = precond.scope
            action_scope = [action for action in scope if action in action_fluents]
            if len(action_scope) == 1:
                name = action_scope[0]
                self.local_action_preconditions[name] = self.local_action_preconditions.get(name, [])
                self.local_action_preconditions[name].append(precond)
            else:
                self.global_action_preconditions.append(precond)
1118160
def check(f):
    
    if hasattr(f, 'wrapped_fn'):
        return f
    else:
        @wraps(f)
        def decorated(*args, **kwargs):
            return check_conditions(f, args, kwargs)
        decorated.wrapped_fn = f
        return decorated
1344674
function getProductsPromise (types) {
  return this.getProductsLists().then(function (lists) {
    return this.getProductsDetails(selectProducts(types, lists));
  }.bind(this));
}
18262
private AssumptionSet generateFunctionOrMethodAssumptionSet(WyilFile.Decl.FunctionOrMethod declaration,
			LocalEnvironment environment) {
		Tuple<WyilFile.Decl.Variable> parameters = declaration.getParameters();
		Expr[] preconditions = new Expr[declaration.getRequires().size()];
		Expr[] arguments = new Expr[parameters.size()];
		// Translate parameters as arguments to invocation
		for (int i = 0; i != arguments.length; ++i) {
			WyilFile.Decl.Variable var = parameters.get(i);
			WyalFile.VariableDeclaration versionedVar = environment.read(var);
			arguments[i] = new Expr.VariableAccess(versionedVar);
		}
		//
		for (int i = 0; i != preconditions.length; ++i) {
			WyalFile.Name name = convert(declaration.getQualifiedName(), "_requires_" + i, declaration.getName());
			preconditions[i] = new Expr.Invoke(null, name, null, arguments);
		}
		// Add all the preconditions as assupmtions
		return AssumptionSet.ROOT.add(preconditions);
	}
885940
def _detect(self):
        
        results = []

        self.results = []
        self.visited_all_paths = {}

        for contract in self.slither.contracts:
            for function in contract.functions:
                if function.is_implemented and function.contract == contract:
                    if function.contains_assembly:
                        continue
                    # dont consider storage variable, as they are detected by another detector
                    uninitialized_local_variables = [v for v in function.local_variables if not v.is_storage and v.uninitialized]
                    function.entry_point.context[self.key] = uninitialized_local_variables
                    self._detect_uninitialized(function, function.entry_point, [])
        all_results = list(set(self.results))
        for(function, uninitialized_local_variable) in all_results:
            var_name = uninitialized_local_variable.name

            info = "{} in {}.{} ({}) is a local variable never initialiazed\n"
            info = info.format(var_name,
                               function.contract.name,
                               function.name,
                               uninitialized_local_variable.source_mapping_str)


            json = self.generate_json_result(info)
            self.add_variable_to_json(uninitialized_local_variable, json)
            self.add_function_to_json(function, json)
            results.append(json)

        return results
245942
function buildExcludeCheck (transpileDependencies = []) {
  const dependencyChecks = transpileDependencies.map((dependency) => (
    new RegExp(`node_modules.${dependency}`)
  ))

  // see: https://webpack.js.org/configuration/module/#condition
  return function (assetPath) {
    const shouldTranspile = dependencyChecks
      .reduce((result, check) => result || assetPath.match(check), false)

    if (shouldTranspile) { return false }
    return !!assetPath.match(/node_modules/)
  }
}
387825
function extractContractDefinitions (sourcesList) {
  var ret = {
    contractsById: {},
    contractsByName: {},
    sourcesByContract: {}
  }
  var walker = new AstWalker()
  for (var k in sourcesList) {
    walker.walk(sourcesList[k].legacyAST, { 'ContractDefinition': function (node) {
      ret.contractsById[node.id] = node
      ret.sourcesByContract[node.id] = k
      ret.contractsByName[k + ':' + node.attributes.name] = node
      return false
    }})
  }
  return ret
}
461691
def check_preconditions(f, args, kwargs):
    
    f = getattr(f, 'wrapped_fn', f)
    if f and hasattr(f, 'preconditions'):
        for cond in f.preconditions:
            cond(args, kwargs)
1156930
def check_methods(self, resource):
        ''''''
        checker = ResourceMethodChecker()
        errors = []
        for callback in resource.callbacks:
            new_errors = checker(callback)
            if new_errors:
                errors.extend(new_errors)
        return errors
1223930
@Override
	public void snapshotState(FunctionSnapshotContext context) throws Exception {
		Preconditions.checkState(this.checkpointedState != null,
			"The " + getClass().getSimpleName() + " has not been properly initialized.");

		this.checkpointedState.clear();
		this.checkpointedState.add(this.numElementsEmitted);
	}
629609
def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
    """"""
    # pylint: disable=too-many-branches
    # pylint: disable=too-many-locals

    value = namespace[key]
    assert inspect.isfunction(value) or isinstance(value, (staticmethod, classmethod))

    # Determine the function to be decorated
    if inspect.isfunction(value):
        func = value
    elif isinstance(value, (staticmethod, classmethod)):
        func = value.__func__
    else:
        raise NotImplementedError("Unexpected value for a function: {}".format(value))

    # Collect preconditions and postconditions of the function
    preconditions = []  # type: List[List[Contract]]
    snapshots = []  # type: List[Snapshot]
    postconditions = []  # type: List[Contract]

    contract_checker = icontract._checkers.find_checker(func=func)
    if contract_checker is not None:
        preconditions = contract_checker.__preconditions__  # type: ignore
        snapshots = contract_checker.__postcondition_snapshots__  # type: ignore
        postconditions = contract_checker.__postconditions__  # type: ignore

    # Collect the preconditions and postconditions from bases.
    #
    # Preconditions and postconditions of __init__ of base classes are deliberately ignored (and not collapsed) since
    # initialization is an operation specific to the concrete class and does not relate to the class hierarchy.
    if key not in ['__init__']:
        base_preconditions = []  # type: List[List[Contract]]
        base_snapshots = []  # type: List[Snapshot]
        base_postconditions = []  # type: List[Contract]

        bases_have_func = False
        for base in bases:
            if hasattr(base, key):
                bases_have_func = True

                # Check if there is a checker function in the base class
                base_func = getattr(base, key)
                base_contract_checker = icontract._checkers.find_checker(func=base_func)

                # Ignore functions which don't have preconditions or postconditions
                if base_contract_checker is not None:
                    base_preconditions.extend(base_contract_checker.__preconditions__)  # type: ignore
                    base_snapshots.extend(base_contract_checker.__postcondition_snapshots__)  # type: ignore
                    base_postconditions.extend(base_contract_checker.__postconditions__)  # type: ignore

        # Collapse preconditions and postconditions from the bases with the the function's own ones
        preconditions = _collapse_preconditions(
            base_preconditions=base_preconditions,
            bases_have_func=bases_have_func,
            preconditions=preconditions,
            func=func)

        snapshots = _collapse_snapshots(base_snapshots=base_snapshots, snapshots=snapshots)

        postconditions = _collapse_postconditions(
            base_postconditions=base_postconditions, postconditions=postconditions)

    if preconditions or postconditions:
        if contract_checker is None:
            contract_checker = icontract._checkers.decorate_with_checker(func=func)

            # Replace the function with the function decorated with contract checks
            if inspect.isfunction(value):
                namespace[key] = contract_checker
            elif isinstance(value, staticmethod):
                namespace[key] = staticmethod(contract_checker)

            elif isinstance(value, classmethod):
                namespace[key] = classmethod(contract_checker)

            else:
                raise NotImplementedError("Unexpected value for a function: {}".format(value))

        # Override the preconditions and postconditions
        contract_checker.__preconditions__ = preconditions  # type: ignore
        contract_checker.__postcondition_snapshots__ = snapshots  # type: ignore
        contract_checker.__postconditions__ = postconditions
284377
function _checkPredicates (checkAll) {
    return function (predicates) {
        if (!Array.isArray(predicates)) {
            throw _makeTypeErrorFor(predicates, "array");
        }

        return function () {
            for (var i = 0, len = predicates.length, result; i < len; i++) {
                result = predicates[i].apply(this, arguments);

                if (checkAll && !result) {
                    return false;
                } else if (!checkAll && result) {
                    return true;
                }
            }

            return checkAll;
        };
    };
}