Construct a parser for a standard function format
776387
def function(name, *args, **kwargs):
    
    if kwargs.get("caseless"):
        name = upkey(name)
    else:
        name = Word(name)
    fxn_args = None
    for i, arg in enumerate(args):
        if i == 0:
            fxn_args = arg
        else:
            fxn_args += Suppress(",") + arg
    if fxn_args is None:
        return name + Suppress("(") + Suppress(")")
    if kwargs.get("optparen"):
        return name + ((Suppress("(") + fxn_args + Suppress(")")) | fxn_args)
    else:
        return name + Suppress("(") + fxn_args + Suppress(")")
1016343
def parse(self, line=None):
        """"""
        args = self.parser.parse_args(args=line)
        return args.func(args)
25084
function getFormatFunction (name) {
  // lookup format
  var fmt = morgan[name] || name || morgan.default

  // return compiled format
  return typeof fmt !== 'function'
    ? compile(fmt)
    : fmt
}
595371
function formatType(node) {
  let result;

  if (!node) {
    return [t('any')];
  }

  switch (node.type) {
    case Syntax.NullableLiteral:
      return [t('?')];
    case Syntax.AllLiteral:
      return [t('any')];
    case Syntax.NullLiteral:
      return [t('null')];
    case Syntax.VoidLiteral:
      return [t('void')];
    case Syntax.UndefinedLiteral:
      return [t('undefined')];
    case Syntax.NameExpression:
      return [t(node.name)];
    case Syntax.ParameterType:
      result = [];

      if (node.name) {
        result.push(c(node.name), t(': '));
      }

      return result.concat(formatType(node.expression));

    case Syntax.TypeApplication:
      return formatType(node.expression).concat(
        commaList(node.applications, '<', '>'),
      );
    case Syntax.UnionType:
      return commaList(node.elements, '(', ')', ' | ');

    case Syntax.ArrayType:
      return commaList(node.elements, '[', ']');
    case Syntax.RecordType:
      return commaList(node.fields, '{', '}');

    case Syntax.FieldType:
      if (node.value) {
        return [t(node.key + ': ')].concat(formatType(node.value));
      }
      return [t(node.key)];

    case Syntax.FunctionType:
      result = [t('function(')];

      if (node['this']) {
        if (node['new']) {
          result.push(t('new: '));
        } else {
          result.push(t('this: '));
        }

        result = result.concat(formatType(node['this']));

        if (node.params.length !== 0) {
          result.push(t(', '));
        }
      }

      result = result.concat(commaList(node.params, '', ')'));

      if (node.result) {
        result = result.concat([t(': ')].concat(formatType(node.result)));
      }
      return result;

    case Syntax.RestType:
      // note that here we diverge from doctrine itself, which
      // lets the expression be omitted.
      return [t('...'), ...formatType(node.expression)];
    case Syntax.OptionalType:
      if (node.default) {
        return [
          ...formatType(node.expression),
          t('?'),
          t('= ' + c(node.default)),
        ];
      }
      return [...formatType(node.expression), t('?')];
    case Syntax.NonNullableType:
      return node.prefix
        ? [t('?'), ...formatType(node.expression)]
        : [...formatType(node.expression), t('?')];
    case Syntax.NullableType:
      return [...formatType(node.expression), t('?')];
    case Syntax.StringLiteralType:
      return [c(JSON.stringify(node.value))];
    case Syntax.NumericLiteralType:
    case Syntax.BooleanLiteralType:
      return [c(String(node.value))];

    default:
      throw new Error('Unknown type ' + node.type);
  }
}
113024
def split_function_call(tokens, loc):
    """"""
    pos_args = []
    star_args = []
    kwd_args = []
    dubstar_args = []
    for arg in tokens:
        argstr = "".join(arg)
        if len(arg) == 1:
            if star_args or kwd_args or dubstar_args:
                raise CoconutDeferredSyntaxError("positional arguments must come first", loc)
            pos_args.append(argstr)
        elif len(arg) == 2:
            if arg[0] == "*":
                if kwd_args or dubstar_args:
                    raise CoconutDeferredSyntaxError("star unpacking must come before keyword arguments", loc)
                star_args.append(argstr)
            elif arg[0] == "**":
                dubstar_args.append(argstr)
            else:
                kwd_args.append(argstr)
        else:
            raise CoconutInternalException("invalid function call argument", arg)
    return pos_args, star_args, kwd_args, dubstar_args
1101640
def format_function(function):
    '''
    '''
    args = [format_variable(arg) for arg in function.args]
    return ['{}{} {}({})'.format(
        function.type, function.pointer, function.name, ', '.join(args))]
758604
def str_lexer(mode):
    
    cast_to_const = ConstStrPool.cast_to_const

    def f_raw(inp_str, pos):
        return cast_to_const(mode) if inp_str.startswith(mode, pos) else None

    def f_collection(inp_str, pos):
        for each in mode:
            if inp_str.startswith(each, pos):
                return cast_to_const(each)
        return None

    if isinstance(mode, str):
        return f_raw

    if len(mode) is 1:
        mode = mode[0]
        return f_raw

    return f_collection
184939
def parse(cls, format):
        

        fmt = cls()

        # Return an empty Format if format is empty
        if not format:
            return fmt

        # Initialize the state for parsing
        state = ParseState(fmt, format)

        # Loop through the format string with a state-based parser
        for idx, char in enumerate(format):
            # Some characters get ignored
            if state.check_ignore():
                continue

            if state == 'string':
                if char == '%':
                    # Handle '%%'
                    if format[idx:idx + 2] == '%%':
                        # Add one % to the string context
                        state.add_text(idx + 1, idx + 2)
                        state.set_ignore(1)
                    else:
                        state.add_text(idx)
                        state.conversion(idx)
                elif char == '\\':
                    state.add_text(idx)
                    state.escape(idx)
            elif state == 'escape':
                state.add_escape(idx + 1, char)
                state.pop_state(idx + 1)
            elif state == 'param':
                if char == '}':
                    state.set_param(idx)
                    state.pop_state()
            elif state == 'conv':
                if char == ')':
                    state.set_conversion(idx)
                    state.pop_state()  # now in 'conversion'
                    state.pop_state(idx + 1)  # now in 'string'
            else:  # state == 'conversion'
                if char in '<>':
                    # Allowed for Apache compatibility, but ignored
                    continue
                elif char == '!':
                    state.set_reject()
                    continue
                elif char == ',' and state.code_last:
                    # Syntactically allowed ','
                    continue
                elif char.isdigit():
                    # True if the code is valid
                    if state.set_code(idx):
                        continue
                elif char == '{' and state.param_begin is None:
                    state.param(idx + 1)
                    continue
                elif char == '(' and state.conv_begin is None:
                    state.conv(idx + 1)
                    continue

                # OK, we have a complete conversion
                state.set_conversion(idx)
                state.pop_state(idx + 1)

        # Finish the parse and return the completed format
        return state.end_state()
665696
function makeFunctionLongform(fixer, node) {
            const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key);
            const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key);
            const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
            let functionHeader = "function";

            if (node.value.async) {
                functionHeader = `async ${functionHeader}`;
            }
            if (node.value.generator) {
                functionHeader = `${functionHeader}*`;
            }

            return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`);
        }
336177
def format(f = nil)
      if f.nil?
        default_options[:format]
      else
        parser(Parser) if parser.nil?
        default_options[:format] = f
        validate_format
      end
    end
184010
def module_function(string):
    
    parts = string.split(':', 2)
    if len(parts) < 2:
        raise ValueError(
            "Illegal specification. Should be module:function[:parameter]")
    module_path, function_name = parts[:2]

    # Import the module
    module_vars = {}
    exec(compile(open(module_path).read(), module_path, 'exec'), module_vars)

    try:
        function = module_vars[function_name]
    except KeyError:
        raise argparse.ArgumentTypeError("{0} has no attribute '{1}'".format(
            module_path, function_name))

    if len(parts) == 3:
        old_function = function
        function = lambda r: old_function(r, parts[2])

    return function
359333
def normalize(expr):
    """"""
    args = [normalize(arg) for arg in expr.args]

    return type(expr)(expr.func, *args, start=expr.start, end=expr.end)
1095393
function getFormatFunction(name) {
  // lookup format
  const fmt = formats[name] || name || formats.default;
  // return compiled format
  return typeof fmt !== 'function' ? compile(fmt) : fmt;
}
639420
function parse(str, opts) {
  var parser = new Parser(str, opts);
  return {attrs: parser._readProtocol(), imports: parser._imports};
}
1166824
function parseDefFunction( $funcName, &$args, $tpl, &$text, &$text_len, &$cur_pos,
                               $relatedTemplateName, $startLine, $startColumn, $rootNamespace )
    {
        if ( $cur_pos == $text_len && $funcName == 'def' ) // no more arguments
        {
            $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                          $funcName, 'Not enough arguments' );
            return;
        }

        while ( $cur_pos < $text_len )
        {
            // parse variable name
            if ( $text[$cur_pos] != '$' )
            {
                $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                              $funcName, '($) expected' );
                return;
            }

            $cur_pos++;
            $wordEndPos = $this->ElementParser->identifierEndPosition( $tpl, $text, $cur_pos, $text_len );
            $varName = substr( $text, $cur_pos, $wordEndPos-$cur_pos );
            $cur_pos = $wordEndPos;

            if ( !$varName )
            {
                $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                              $funcName, 'Empty variable name' );
                return;
            }

            if ( $funcName == 'def' )
            {
                // skip whitespaces
                $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

                // parse variable value
                if ( $cur_pos >= $text_len || $text[$cur_pos] != '=' )
                {
                    $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                                  $funcName, '(=) expected' );
                    return;
                }
                $cur_pos++;

                // skip whitespaces
                $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

                $args[$varName] = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $text, $cur_pos, $cur_pos, $text_len, $rootNamespace );
            }
            else
            {
                $varValueText = '1';
                $args[$varName] = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $varValueText, 0, $varValPos, 1, $rootNamespace );
            }


            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );
        }
    }
39424
def parse(self):
        
        standard_formatters = re.compile(r'\((.+?)\)', re.IGNORECASE)
        return standard_formatters.findall(self._fmt)
1086629
function makeStringParser ( s ) {
				var len = s.length;

				return function () {
					var result = null;

					if ( message.substr( pos, len ) === s ) {
						result = s;
						pos += len;
					}

					return result;
				};
			}