Check parameter and return types for command finalization hooks.
13081
def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData],
                                                               plugin.CommandFinalizationData]) -> None:
        """"""
        cls._validate_callable_param_count(func, 1)
        signature = inspect.signature(func)
        _, param = list(signature.parameters.items())[0]
        if param.annotation != plugin.CommandFinalizationData:
            raise TypeError("{} must have one parameter declared with type "
                            "'cmd2.plugin.CommandFinalizationData'".format(func.__name__))
        if signature.return_annotation != plugin.CommandFinalizationData:
            raise TypeError("{} must declare return a return type of "
                            "'cmd2.plugin.CommandFinalizationData'".format(func.__name__))
43459
private function validateReturnType(): void
  {
    // Return immediately if designation type is not appropriate for this method.
    if (!in_array($this->designationType, ['function', 'singleton0', 'singleton1'])) return;

    $types = explode('|', $this->returnType);
    $diff  = array_diff($types, ['string', 'int', 'float', 'double', 'bool', 'null']);

    if (!($this->returnType=='mixed' || $this->returnType=='bool' || empty($diff)))
    {
      throw new RoutineLoaderException("Return type must be 'mixed', 'bool', or a combination of 'int', 'float', 'string', and 'null'");
    }

    // The following tests are applicable for singleton0 routines only.
    if (!in_array($this->designationType, ['singleton0'])) return;

    // Return mixed is OK.
    if (in_array($this->returnType, ['bool', 'mixed'])) return;

    // In all other cases return type mus contain null.
    $parts = explode('|', $this->returnType);
    $key   = array_search('null', $parts);
    if ($key===false)
    {
      throw new RoutineLoaderException("Return type must be 'mixed', 'bool', or contain 'null' (with a combination of 'int', 'float', and 'string')");
    }
  }
919348
def check_params_types(self, method):
        ''''''
        mn = method.__name__
        annos = dict(method.__annotations__)
        errors = []
        # Take a look at the syntax
        msg_tuple = 'Parameter {} in method {} is not annotated with a tuple.'
        msg_ptype = 'Parameter {} in method {} is not a valid Ptype.'
        msg_mod = 'Type for param {} in method {} must descend from Model.'
        msg_cls = 'Type for param {} in method {} must be instance (not class)'
        bodies = []
        for pname, anno in annos.items():
            if pname == 'return':
                continue
            elif len(anno) != 2:
                errors.append(msg_tuple.format(pname, mn))
            else:
                param_type, value_type = anno
                if param_type not in Ptypes:
                    errors.append(msg_ptype.format(pname, mn))
                elif param_type == 'body':
                    bodies.append(pname)
                elif param_type == 'path':
                    default = method.signature.parameters[pname].default
                    if default is not inspect._empty:
                        msg = ('Path prameter {} in method {} has a default '
                               'value ({}) that would make it optional (which '
                               'is wrong!)')
                        errors.append(msg.format(pname, mn, default))
                if hasattr(value_type, '__bases__'):
                    errors.append(msg_cls.format(pname, mn))
                elif Model not in value_type.__class__.__bases__:
                    errors.append(msg_mod.format(pname, mn))
        # Only one body parameter!
        if len(bodies) > 1:
            msg = 'Too many "Ptypes.body" params {} for method {} (max=1).'
            errors.append(msg.format(bodies, mn))
        return errors
467934
function wrapCommand (fn) {
  return (...args) => {
    return fn(...args).catch(err => {
      console.error(chalk.red(err.stack))
      process.exitCode = 1
    })
  }
}
706078
def FUNCTION_DECL(self, cursor):
        """"""
        # FIXME to UT
        name = self.get_unique_name(cursor)
        if self.is_registered(name):
            return self.get_registered(name)
        returns = self.parse_cursor_type(cursor.type.get_result())
        attributes = []
        extern = False
        obj = typedesc.Function(name, returns, attributes, extern)
        for arg in cursor.get_arguments():
            arg_obj = self.parse_cursor(arg)
            # if arg_obj is None:
            #    code.interact(local=locals())
            obj.add_argument(arg_obj)
        # code.interact(local=locals())
        self.register(name, obj)
        self.set_location(obj, cursor)
        self.set_comment(obj, cursor)
        return obj
827900
def formatted_completion_sig(completion):
    """"""
    f_result = completion["name"]
    if is_basic_type(completion):
        # It's a raw type
        return f_result
    elif len(completion["typeInfo"]["paramSections"]) == 0:
        return f_result

    # It's a function type
    sections = completion["typeInfo"]["paramSections"]
    f_sections = [formatted_param_section(ps) for ps in sections]
    return u"{}{}".format(f_result, "".join(f_sections))
260817
def check_invocation(node, type)
      args = sort_args_by_position(node.args,
                                   node.splat,
                                   node.keywords.values,
                                   node.kwarg_splat)

      check_commas_after_args(args, "#{type} arguments")
    end
1069023
def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None:
        """"""
        self._validate_prepostcmd_hook(func, plugin.PrecommandData)
        self._precmd_hooks.append(func)
508567
def finalize(cls):
		""
		for finalizer in cls._finalizers:
			try:
				finalizer()
			except Exception:
				log.exception("Error in finalizer %s", finalizer)
1030593
def finalize(self, result):
        """"""
        sys.stderr = self._stderr.pop()
        sys.stdout = self._stdout.pop()
        pdb.set_trace = self._set_trace.pop()
        pdb.Pdb.cmdloop = self._cmdloop.pop()
589906
def type_check(arg_name, pos, reqd_type):
    

    def decorator(fn):

        # brevity compromised in favour of readability
        def logic(*args, **kwargs):
            arg_count = len(args)
            if arg_count:
                if pos < arg_count:
                    if isinstance(args[pos], reqd_type):
                        return fn(*args, **kwargs)
                    else:
                        raise TypeError("'{0}' at position {1} not of type {2}".format(args[pos], pos, reqd_type))
                else:
                    if arg_name in kwargs:
                        value = kwargs[arg_name]
                        if isinstance(value, reqd_type):
                            return fn(*args, **kwargs)
                        else:
                            raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))
                    else:
                        # partially applied functions because of incomplete args, let python handle this
                        return fn(*args, **kwargs)
            else:
                if arg_name in kwargs:
                    value = kwargs[arg_name]
                    if isinstance(value, reqd_type):
                        return fn(*args, **kwargs)
                else:
                    raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))

        return logic

    return decorator
1036322
function report(type, state, params)
{
  var reporter = defaultReporter;

  // get rest of arguments
  params  = Array.prototype.slice.call(arguments, 1);

  // `init` and `done` types don't have command associated with them
  if (['init', 'done'].indexOf(type) == -1)
  {
    // second (1) position is for command
    // if command present get string representation of it
    params[1] = stringifyCommand(state, params[1]);
  }

  if (state && state.options && state.options.reporter)
  {
    reporter = state.options.reporter;
  }

  reporter[type].apply(null, params);
}
40865
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"):
    
    variables_needed = []
    variables_optional = []
    imports = set()
    if params_string:  # WHITELISTED_FUNCS have no params
        for param in params_string.split("\n"):
            variable = parse_param_types(param)
            # any variable.types has always_is_value => lenght must be 1.
            assert (not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1)
            if variable.optional:
                variables_optional.append(variable)
            else:
                variables_needed.append(variable)
            # end if
            imports.update(variable.all_imports)
        # end for
    # end if
    imports = list(imports)
    imports.sort()
    returns = Variable(types=as_types(return_type, variable_name="return type"), description=returns)
    func_object = Function(
        imports=imports, api_name=command, link=link, description=description, returns=returns,
        parameters=variables_needed, keywords=variables_optional
    )
    return func_object
224629
def check_return_space(event, callable_):
    """"""
    if event.type() == QEvent.KeyPress:
        if event.key() in [Qt.Key_Return, Qt.Key_Space]:
            callable_()
            return True
    return False
740701
protected static boolean isFinalizeMethod(Method method) {
        return method.getReturnType() == void.class && method.getParameterTypes().length == 0 &&
                method.getName().equals("finalize");
    }
526261
def handle_type_inspect(self, call_id, payload):
        """"""
        style = 'fullName' if self.full_types_enabled else 'name'
        interfaces = payload.get("interfaces")
        ts = [i["type"][style] for i in interfaces]
        prefix = "( " + ", ".join(ts) + " ) => "
        self.editor.raw_message(prefix + payload["type"][style])
67497
def __findout_decl_type(match_class, **keywds):
        """"""
        if 'decl_type' in keywds:
            return keywds['decl_type']

        matcher_args = keywds.copy()
        del matcher_args['function']
        del matcher_args['recursive']
        if 'allow_empty' in matcher_args:
            del matcher_args['allow_empty']

        decl_matcher = match_class(**matcher_args)
        if decl_matcher.decl_type:
            return decl_matcher.decl_type
        return None