Given a babel AST path to a tagged template literal, return an AST if it is
a graphql literal being used in a valid way.
If it is some other type of template literal then return nothing.
180579
function getValidGraphQLTag(path: any): ?DocumentNode {
  const tag = path.get('tag');

  if (!tag.isIdentifier({name: 'graphql'})) {
    return null;
  }

  const quasis = path.node.quasi.quasis;

  if (quasis.length !== 1) {
    throw new Error(
      'BabelPluginRelay: Substitutions are not allowed in graphql fragments. ' +
        'Included fragments should be referenced as `...MyModule_propName`.',
    );
  }

  const text = quasis[0].value.raw;

  const ast = GraphQL.parse(text);

  if (ast.definitions.length === 0) {
    throw new Error('BabelPluginRelay: Unexpected empty graphql tag.');
  }

  return ast;
}
1286373
function templateVisitAll(visitor, asts, context) {
    if (context === void 0) { context = null; }
    var /** @type {?} */ result = [];
    var /** @type {?} */ visit = visitor.visit ?
        function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
        function (ast) { return ast.visit(visitor, context); };
    asts.forEach(function (ast) {
        var /** @type {?} */ astResult = visit(ast);
        if (astResult) {
            result.push(astResult);
        }
    });
    return result;
}
320943
def _compile_literal(self, schema):
        
        # Prepare self
        self.compiled_type = const.COMPILED_TYPE.LITERAL
        self.name = get_literal_name(schema)

        # Error partials
        schema_type = type(schema)
        err_type  = self.Invalid(_(u'Wrong value type'), get_type_name(schema_type))
        err_value = self.Invalid(_(u'Invalid value'), self.name)

        # Matcher
        if self.matcher:
            def match_literal(v):
                return type(v) == schema_type and v == schema, v
            return match_literal

        # Validator
        def validate_literal(v):
            # Type check
            if type(v) != schema_type:
                # expected=<type>, provided=<type>
                raise err_type(get_type_name(type(v)))
            # Equality check
            if v != schema:
                # expected=<value>, provided=<value>
                raise err_value(get_literal_name(v))
            # Fine
            return v
        return validate_literal
1095298
function(template, map, fallback) {
    if (!map)
      return template;
    return template.replace(/\$\{.+?}/g, (match) => {
      const path = match.substr(2, match.length - 3).trim();
      return get(path, map, fallback);
    });
  }
804380
def es_query_template(path):
    

    if not is_text(path):
        Log.error("expecting path to be a string")

    if path != ".":
        f0 = {}
        f1 = {}
        output = wrap({
            "query": es_and([
                f0,
                {"nested": {
                    "path": path,
                    "query": f1,
                    "inner_hits": {"size": 100000}
                }}
            ]),
            "from": 0,
            "size": 0,
            "sort": []
        })
        return output, wrap([f0, f1])
    else:
        f0 = {}
        output = wrap({
            "query": es_and([f0]),
            "from": 0,
            "size": 0,
            "sort": []
        })
        return output, wrap([f0])
920864
def do_get_page(parser, token):
    
    bits = token.split_contents()
    if 4 != len(bits):
        raise TemplateSyntaxError('%r expects 4 arguments' % bits[0])
    if bits[-2] != 'as':
        raise TemplateSyntaxError(
            '%r expects "as" as the second argument' % bits[0])
    page_filter = parser.compile_filter(bits[1])
    varname = bits[-1]
    return GetPageNode(page_filter, varname)
637063
def grab_literal(template, l_del):
    """"""

    global _CURRENT_LINE

    try:
        # Look for the next tag and move the template to it
        literal, template = template.split(l_del, 1)
        _CURRENT_LINE += literal.count('\n')
        return (literal, template)

    # There are no more tags in the template?
    except ValueError:
        # Then the rest of the template is a literal
        return (template, '')
1319382
def match_template(tree, template, args=None):
    
    tokens = get_tokens(template.split())
    cur_args = {}
    if match_tokens(tree, tokens, cur_args):
        if args is not None:
            for k, v in cur_args.items():
                args[k] = v
        logger.debug('MATCHED: {0}'.format(template))
        return True
    else:
        return False
251418
def template(path, source, type = :template)
      if source
        template = Template.new(source, @context, source_path: path)
      else
        template_path = case type
                        when :partial
                          find_partial(path)
                        when :layout
                          find_layout(path)
                        else
                          path
                        end

        if template_path && File.exist?(template_path)
          template = Template.open(template_path, @context)
        else
          template_not_found!(type, path)
        end
      end

      prevent_recursion!(template)

      template
    end
140946
function astValue(node) {

  switch (node.type) {

  case 'ExpressionStatement':
    return astValue(node.expression);

  case 'ObjectExpression':
    return node.properties.reduce(
      (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}),
      {}
    );

  case 'ArrayExpression':
    return node.elements.map(element => astValue(element));

  case 'Literal':
    return node.value;

  default:
    throw new Error(`Unexpected ast node type: ${node.type}`);

  }
}
1212878
def _get_inline_fragment(ast):
    """"""
    if not ast.selection_set:
        # There is nothing selected here, so no fragment.
        return None

    fragments = [
        ast_node
        for ast_node in ast.selection_set.selections
        if isinstance(ast_node, InlineFragment)
    ]

    if not fragments:
        return None

    if len(fragments) > 1:
        raise GraphQLCompilationError(u'Cannot compile GraphQL with more than one fragment in '
                                      u'a given selection set.')

    return fragments[0]
3149
function getTemplate(template, options) {
  stack.clear();
  parser.reset();

  let opts = typeof options === 'undefined' ? {} : options;
  opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
  opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
  opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
  opts.logger = opts.logger != null ? opts.logger : {};

  let lambdas = {};
  if (_.isArray(opts.lambdas)) {
    for (let i = 0; i < opts.lambdas.length; i++) {
      lambdas[opts.lambdas[i]] = true;
    }
  }
  opts.lambdas = lambdas;
  opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true;

  compilerLogger.setStrictMode(opts.strict);
  compilerLogger.setOverrides(opts.logger);
  stack.setHtmlValidation(opts.validateHtml);

  let templateStr = template.toString();

  processTemplate(templateStr, opts);

  let output = {};

  if (stack.stack.length > 0) {
    compilerErrors.notAllTagsWereClosedProperly(stack.stack);
  }

  parser.end();
  output.templateObj = stack.getOutput();
  const Template = require('../template');
  output.template = new Template(output.templateObj);
  output.source = template;
  output.tokens = {};
  _.each(stack.tokens, function(values, type) {
    output.tokens[type] = _.keys(values);
  });
  return output;
}
742308
function isRequireReactDOM(t, path) {
  return (
    t.isIdentifier(path.node.callee, { name: 'require' }) &&
    path.get('arguments.0').isStringLiteral({ value: 'react-dom' })
  );
}
1091952
def parse(cls, parser, token):
        
        bits, as_var = parse_as_var(parser, token)
        tag_name, args, kwargs = parse_token_kwargs(parser, bits, allowed_kwargs=cls.allowed_kwargs, compile_args=True, compile_kwargs=True)

        # Play with the arguments
        if len(args) == 2:
            parent_expr = args[0]
            slot_expr = args[1]
        elif len(args) == 1:
            # Allow 'page' by default. Works with most CMS'es, including django-fluent-pages.
            parent_expr = Variable('page')
            slot_expr = args[0]
        else:
            raise TemplateSyntaxError("""{0} tag allows two arguments: 'parent object' 'slot name' and optionally: title=".." role="..".""".format(tag_name))

        cls.validate_args(tag_name, *args, **kwargs)
        return cls(
            tag_name=tag_name,
            as_var=as_var,
            parent_expr=parent_expr,
            slot_expr=slot_expr,
            **kwargs
        )
482651
def get_variable_values(
    schema,  # type: GraphQLSchema
    definition_asts,  # type: List[VariableDefinition]
    inputs,  # type: Any
):
    # type: (...) -> Dict[str, Any]
    """"""
    if inputs is None:
        inputs = {}

    values = {}
    for def_ast in definition_asts:
        var_name = def_ast.variable.name.value
        var_type = type_from_ast(schema, def_ast.type)
        value = inputs.get(var_name)

        if not is_input_type(var_type):
            raise GraphQLError(
                'Variable "${var_name}" expected value of type "{var_type}" which cannot be used as an input type.'.format(
                    var_name=var_name, var_type=print_ast(def_ast.type)
                ),
                [def_ast],
            )
        elif value is None:
            if def_ast.default_value is not None:
                values[var_name] = value_from_ast(
                    def_ast.default_value, var_type
                )  # type: ignore
            if isinstance(var_type, GraphQLNonNull):
                raise GraphQLError(
                    'Variable "${var_name}" of required type "{var_type}" was not provided.'.format(
                        var_name=var_name, var_type=var_type
                    ),
                    [def_ast],
                )
        else:
            errors = is_valid_value(value, var_type)
            if errors:
                message = u"\n" + u"\n".join(errors)
                raise GraphQLError(
                    'Variable "${}" got invalid value {}.{}'.format(
                        var_name, json.dumps(value, sort_keys=True), message
                    ),
                    [def_ast],
                )
            coerced_value = coerce_value(var_type, value)
            if coerced_value is None:
                raise Exception("Should have reported error.")

            values[var_name] = coerced_value

    return values
1112016
def fmt_tag(cur_namespace, tag, val):
    
    if tag == 'type':
        fq_val = val
        if '.' not in val and cur_namespace is not None:
            fq_val = cur_namespace.name + '.' + fq_val
        return fq_val
    elif tag == 'route':
        if ':' in val:
            val, version = val.split(':', 1)
            version = int(version)
        else:
            version = 1
        return fmt_func(val, version) + "()"
    elif tag == 'link':
        anchor, link = val.rsplit(' ', 1)
        # There's no way to have links in TSDoc, so simply use JSDoc's formatting.
        # It's entirely possible some editors support this.
        return '[%s]{@link %s}' % (anchor, link)
    elif tag == 'val':
        # Value types seem to match JavaScript (true, false, null)
        return val
    elif tag == 'field':
        return val
    else:
        raise RuntimeError('Unknown doc ref tag %r' % tag)
565361
function template(tmpl, context) {
			return tmpl.replace(/\{([^\}]+)\}/g, function(m, key) {
				return context[key];
			});
		}