Based on the type inference in Babel
198820
function baseTypeStrictlyMatches(left, right) {
    let leftTypes, rightTypes;

    if (t.isIdentifier(left)) {
      leftTypes = customTypeAnnotation(left);
    } else if (t.isIdentifier(right)) {
      rightTypes = customTypeAnnotation(right);
    }

    // Early exit
    if (t.isAnyTypeAnnotation(leftTypes) || t.isAnyTypeAnnotation(rightTypes)) {
      return false;
    }

    leftTypes = [].concat(leftTypes, left.getTypeAnnotation());
    rightTypes = [].concat(rightTypes, right.getTypeAnnotation());

    leftTypes = t.createUnionTypeAnnotation(leftTypes);
    rightTypes = t.createUnionTypeAnnotation(rightTypes);

    if (
      !t.isAnyTypeAnnotation(leftTypes) &&
      t.isFlowBaseAnnotation(leftTypes)
    ) {
      return leftTypes.type === rightTypes.type;
    }
  }
626177
function TypeParser(defaultBuilder) {

	/* TODO
	 * - function(this:) // type of this
	 * - function(new:) // constructor
	 */
	var rLexer = /\s*(Array\.?<|Object\.?<|Set\.?<|Promise\.?<|function\(|\{|:|\(|\||\}|>|\)|,|\[\]|\*|\?|!|\.\.\.)|\s*((?:module:)?\w+(?:[\/.#~]\w+)*)|./g;

	var input,
		builder,
		token,
		tokenStr;

	function next(expected) {
		if ( expected !== undefined && token !== expected ) {
			throw new SyntaxError("TypeParser: expected '" + expected + "', but found '" + tokenStr + "' (pos: " + rLexer.lastIndex + ", input='" + input + "')");
		}
		var match = rLexer.exec(input);
		if ( match ) {
			tokenStr = match[1] || match[2];
			token = match[1] || (match[2] && 'symbol');
			if ( !token ) {
				throw new SyntaxError("TypeParser: unexpected '" + tokenStr + "' (pos: " + match.index + ", input='" + input + "')");
			}
		} else {
			tokenStr = token = null;
		}
	}

	function parseType() {
		var nullable = false;
		var mandatory = false;
		if ( token === '?' ) {
			next();
			nullable = true;
		} else if ( token === '!' ) {
			next();
			mandatory = true;
		}

		var type;

		if ( token === 'Array.<' || token === 'Array<' ) {
			next();
			var componentType = parseType();
			next('>');
			type = builder.array(componentType);
		} else if ( token === 'Object.<' || token === 'Object<' ) {
			next();
			var keyType;
			var valueType = parseType();
			if ( token === ',' ) {
				next();
				keyType = valueType;
				valueType = parseType();
			} else {
				keyType = builder.synthetic(builder.simpleType('string'));
			}
			next('>');
			type = builder.object(keyType, valueType);
		} else if ( token === 'Set.<' || token === 'Set<' ) {
			next();
			var elementType = parseType();
			next('>');
			type = builder.set(elementType);
		} else if ( token === 'Promise.<' || token === 'Promise<' ) {
			next();
			var resultType = parseType();
			next('>');
			type = builder.promise(resultType);
		} else if ( token === 'function(' ) {
			next();
			var thisType, constructorType, paramTypes = [], returnType;
			if ( tokenStr === 'this' ) {
				next();
				next(':');
				thisType = parseType();
				if ( token === ',' ) {
					next();
				}
			} else if ( tokenStr === 'new' ) {
				next();
				next(':');
				constructorType = parseType();
				if ( token === ',' ) {
					next();
				}
			}
			while ( token === 'symbol' || token === '...' ) {
				var repeatable = token === '...';
				if ( repeatable) {
					next();
				}
				var paramType = parseType();
				if ( repeatable ) {
					paramType = builder.repeatable(paramType);
				}
				paramTypes.push(paramType);
				if ( token === ',' ) {
					if ( repeatable ) {
						throw new SyntaxError("TypeParser: only the last parameter of a function can be repeatable (pos: " + rLexer.lastIndex + ", input='" + input + "')");
					}
					next();
				}
			}
			next(')');
			if ( token === ':' ) {
				next(':');
				returnType = parseType();
			}
			type = builder.function(paramTypes, returnType, thisType, constructorType);
		} else if ( token === '{' ) {
			var structure = Object.create(null);
			var propName,propType;
			next();
			do {
				propName = tokenStr;
				if ( !/^\w+$/.test(propName) ) {
					throw new SyntaxError("TypeParser: structure field must have a simple name (pos: " + rLexer.lastIndex + ", input='" + input + "', field:'" + propName + "')");
				}
				next('symbol');
				if ( token === ':' ) {
					next();
					propType = parseType();
				} else {
					propType = builder.synthetic(builder.simpleType('any'));
				}
				structure[propName] = propType;
				if ( token === '}' ) {
					break;
				}
				next(',');
			} while (token);
			next('}');
			type = builder.structure(structure);
		} else if ( token === '(' ) {
			next();
			type = parseTypes();
			next(')');
		} else if ( token === '*' ) {
			next();
			type = builder.simpleType('*');
		} else {
			type = builder.simpleType(tokenStr);
			next('symbol');
			while ( token === '[]' ) {
				next();
				type = builder.array(type);
			}
		}
		if ( nullable ) {
			type = builder.nullable(type);
		}
		if ( mandatory ) {
			type = builder.mandatory(type);
		}
		return type;
	}

	function parseTypes() {
		var types = [];
		do {
			types.push(parseType());
			if ( token !== '|' ) {
				break;
			}
			next();
		} while (token);
		return types.length === 1 ? types[0] : builder.union(types);
	}

	this.parse = function(typeStr, tempBuilder) {
		builder = tempBuilder || defaultBuilder || TypeParser.ASTBuilder;
		input = String(typeStr);
		rLexer.lastIndex = 0;
		next();
		var type = parseTypes();
		next(null);
		return type;
	};

}
1029708
function parseVariableIdentifier(kind) {
        var token, node = new Node();

        token = lex();

        if (token.type === Token.Keyword && token.value === 'yield') {
            if (strict) {
                tolerateUnexpectedToken(token, Messages.StrictReservedWord);
            } if (!state.allowYield) {
                throwUnexpectedToken(token);
            }
        } else if (token.type !== Token.Identifier) {
            if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
                tolerateUnexpectedToken(token, Messages.StrictReservedWord);
            } else {
                if (strict || token.value !== 'let' || kind !== 'var') {
                    throwUnexpectedToken(token);
                }
            }
        } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
            tolerateUnexpectedToken(token);
        }

        return node.finishIdentifier(token.value);
    }
612576
private static Iterable<Symbol> typesInEnclosingScope(
      Env<AttrContext> env, PackageSymbol javaLang) {
    // Collect all visible type names declared in this source file by ascending lexical scopes,
    // collecting all members, filtering to keep type symbols and exclude TypeVariableSymbols
    // (otherwise, every type parameter spuriously shadows itself)
    Iterable<Symbol> localSymbolsInScope =
        Streams.stream(env)
            .map(
                ctx ->
                    ctx.tree.getTag() == Tag.CLASSDEF
                        ? ((ClassSymbol) ASTHelpers.getSymbol(ctx.tree)).members().getSymbols()
                        : ctx.info.getLocalElements())
            .flatMap(
                symbols ->
                    Streams.stream(symbols)
                        .filter(
                            sym ->
                                sym instanceof TypeSymbol && !(sym instanceof TypeVariableSymbol)))
            .collect(ImmutableList.toImmutableList());

    // Concatenate with all visible type names declared in other source files:
    // Ignore wildcard imports here since we don't use them and they can cause issues (b/109867096)
    return Iterables.concat(
        localSymbolsInScope, // Local symbols
        env.toplevel.namedImportScope.getSymbols(), // Explicitly named imports
        javaLang.members().getSymbols(), // implicitly imported java.lang.* symbols
        env.toplevel.packge.members().getSymbols()); // Siblings in class hierarchy
  }
1125639
function prepareTypesArg (types) {
  if (Array.isArray(types)) {
    return types
  }
  if (types instanceof String) {
    types += ''
  }
  if (typeof types === 'string') {
    return types.trim().split(' ').filter(Boolean)
  }
  return [types]
}
489016
function getTransformMacroExpressions(babelTemplate) {
  return {
    visitor: {
        StringLiteral(path) {
            const node = path.node;
            if (!node.macro) {
                // This has nothing to do with macros but it's necessary to prevent
                // Babel from escaping Unicode strings. See #784
                if (typeof node.value === "string") {
                    node.extra = {
                        raw: JSON.stringify(node.value),
                        rawValue: node.value,
                    };
                }
                return;
            }

            const DOLLAR_REGEX = /\$\d+/g;
            const buildArgs = {};
            const originalMacro = node.value;
            let macro = originalMacro;

            try {
                // Check if there are more placeholders than args, this may happen
                // if null optional arguments have been removed.
                let m = null;
                const placeholders = [];
                const args = node.args || [];

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    placeholders.push(parseInt(m[0].substr(1), 10));
                }

                if (placeholders.length > 0) {
                    const max = placeholders.reduce((x, y) => Math.max(x, y));
                    // If there're actually more args than placeholders (e.g `$0($1...)`), use the args length
                    const argsLength = Math.max(max + 1, args.length);
                    for (let i = 0; i < argsLength; i++) {
                        buildArgs["$" + String(i)] =
                            args[i] == null
                                ? { type: "NullLiteral" }
                                : args[i];
                    }
                }

                macro = macro
                    // Macro transformations, see http://fable.io/docs/interacting.html#emit-attribute
                    .replace(/\$(\d+)\.\.\./, (_, i) => {
                        const rep = [];
                        for (let j = parseInt(i, 10); j < args.length; j++) {
                            rep.push("$" + j);
                        }
                        return rep.join(",");
                    })
                    .replace(/\{\{\s*\$(\d+)\s*\?(.*?)\:(.*?)\}\}/g, (_, g1, g2, g3) => {
                        const i = parseInt(g1, 10);
                        return typeof args[i] === "object" && args[i].value ? g2 : g3;
                    })
                    .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, (_, g1, g2) => {
                        const i = parseInt(g2, 10);
                        return typeof args[i] === "object" && args[i].type !== "NullLiteral" ? g1 : "";
                    })
                    .replace(/\$(\d+)!/, (_, i) => {
                        const arg = args[parseInt(i, 10)]
                        return typeof arg === "object" && arg.type === "StringLiteral" ? arg.value : "";
                    });

                // Babel 7 throws error if there're unused arguments, remove them
                const actualArgs = [];
                const buildArgKeys = Object.keys(buildArgs);

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    actualArgs.push(m[0]);
                }
                for (const key of buildArgKeys) {
                    if (actualArgs.indexOf(key) < 0) {
                        delete buildArgs[key];
                    }
                }

                // console.log("MACRO 1", originalMacro);
                // console.log("MACRO 2", macro);
                // console.log("MACRO ARGS", buildArgs);

                const builtMacro = babelTemplate(macro, {
                    placeholderPattern: /^\$\d+$/,
                })(buildArgs);

                if (builtMacro != null) {
                    path.replaceWithMultiple(builtMacro);
                } else {
                    // Apparently if the macro is just a string, babel-template will fail
                    path.replaceWith({
                        type: "StringLiteral",
                        value: JSON.parse(macro),
                    });
                }
            } catch (err) {
                throw new Error(
                    "BABEL ERROR: Failed to parse macro: " + originalMacro + " -> " + macro + "\n" +
                    "MACRO ARGUMENTS: " + Object.keys(buildArgs).join() + "\n" +
                    err.message);
            }
        },
    },
  };
}
1209456
def literal(compiler, cont, arg):
  ''''''
  text = compiler.new_var(il.ConstLocalVar('text'))
  pos = compiler.new_var(il.ConstLocalVar('pos'))
  p = compiler.new_var(il.LocalVar('p'))
  i = compiler.new_var(il.LocalVar('i'))
  x = compiler.new_var(il.ConstLocalVar('x'))
  length = compiler.new_var(il.ConstLocalVar('length'))  
  length2 = compiler.new_var(il.ConstLocalVar('length2'))  
  if isinstance(arg, Var):
    return il.Begin((
      il.Assign(x, il.Deref(arg)),
      il.AssignFromList(text, pos, il.parse_state),
      il.Assign(length, il.Len(text)),
      il.Assign(length, il.Len(x)),
      il.Assign(i, il.Integer(0)),
      il.Assign(p, pos),
      il.while_(il.and_(il.Lt(i, length2), il.Lt(p, length), il.Eq(il.GetItem(text, p), il.GetItem(x, i))), 
        il.AddAssign(p, il.Integer(1))),
      il.If(il.Lt(i, length2), 
        il.failcont(il.NONE),
        il.begin(il.append_failcont(compiler, 
          il.SetParseState(il.Tuple(text, pos))),
          il.SetParseState(il.Tuple(text, p)),
          cont(arg)))))
  elif isinstance(arg, String):
    arg = arg.interlang()
    return il.Begin((
      il.AssignFromList(text, pos, il.parse_state),
      il.Assign(length, il.Len(text)),
      il.Assign(length2, il.Len(arg)),
      il.Assign(i, il.Integer(0)),
      il.Assign(p, pos),
      il.while_(il.and_(il.Lt(i, length2), il.Lt(p, length), il.Eq(il.GetItem(text, p), il.GetItem(arg, i))), 
        il.AddAssign(p, il.Integer(1)),
        il.AddAssign(i, il.Integer(1)),
        ),
      il.If(il.Lt(i, length2), 
        il.failcont(il.NONE),
        il.begin(il.append_failcont(compiler, 
          il.SetParseState(il.Tuple(text, pos))),
          il.SetParseState(il.Tuple(text, p)),
          cont(arg)))))
  else:
    raise CompileTypeError
291986
def parse_object_type_definition(lexer: Lexer) -> Node:
    """"""
    start = lexer.token
    description = parse_description(lexer)
    expect_keyword(lexer, "type")
    name = parse_name(lexer)
    interfaces = parse_implements_interfaces(lexer)
    directives = parse_directives(lexer, True)
    fields = parse_fields_definition(lexer)
    return Node(
        description=description,
        name=name,
        interfaces=interfaces,
        directives=directives,
        fields=fields,
        loc=loc(lexer, start),
    )
1366321
void inferAllScopes(Node node) {
    // Type analysis happens in two major phases.
    // 1) Finding all the symbols.
    // 2) Propagating all the inferred types.
    //
    // The order of this analysis is non-obvious. In a complete inference
    // system, we may need to backtrack arbitrarily far. But the compile-time
    // costs would be unacceptable.
    //
    // We do one pass where we do typed scope creation for all scopes
    // in pre-order.
    //
    // Then we do a second pass where we do all type inference
    // (type propagation) in pre-order.
    //
    // We use a memoized scope creator so that we never create a scope
    // more than once.
    //
    // This will allow us to handle cases like:
    // var ns = {};
    // (function() { /** JSDoc */ ns.method = function() {}; })();
    // ns.method();
    // In this code, we need to build the symbol table for the inner scope in
    // order to propagate the type of ns.method in the outer scope.
    (new NodeTraversal(
        compiler, new FirstScopeBuildingCallback(), scopeCreator))
        .traverseWithScope(node, topScope);

    scopeCreator.resolveTypes();

    (new NodeTraversal(
        compiler, new SecondScopeBuildingCallback(), scopeCreator))
        .traverseWithScope(node, topScope);

    // Resolve any new type names found during the inference.
    // This runs for nested block scopes after infer runs on the CFG root.
    compiler.getTypeRegistry().resolveTypes();
  }
732122
def apply_type_shim(cls, _context=None) -> Iterator:
    
    if cls.name in ["IntField", "SmallIntField"]:
        base_nodes = scoped_nodes.builtin_lookup("int")
    elif cls.name in ["CharField", "TextField"]:
        base_nodes = scoped_nodes.builtin_lookup("str")
    elif cls.name == "BooleanField":
        base_nodes = scoped_nodes.builtin_lookup("bool")
    elif cls.name == "FloatField":
        base_nodes = scoped_nodes.builtin_lookup("float")
    elif cls.name == "DecimalField":
        base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal")
    elif cls.name == "DatetimeField":
        base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime")
    elif cls.name == "DateField":
        base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date")
    elif cls.name == "ForeignKeyField":
        base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation")
    elif cls.name == "ManyToManyField":
        base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup(
            "ManyToManyRelationManager"
        )
    else:
        return iter([cls])

    return iter([cls] + base_nodes[1])
386433
def parse_type_reference(lexer: Lexer) -> TypeNode:
    """"""
    start = lexer.token
    if expect_optional_token(lexer, TokenKind.BRACKET_L):
        type_ = parse_type_reference(lexer)
        expect_token(lexer, TokenKind.BRACKET_R)
        type_ = ListTypeNode(type=type_, loc=loc(lexer, start))
    else:
        type_ = parse_named_type(lexer)
    if expect_optional_token(lexer, TokenKind.BANG):
        return NonNullTypeNode(type=type_, loc=loc(lexer, start))
    return type_
1038886
def parse_object_type_extension(lexer: Lexer) -> Node:
    """"""
    start = lexer.token
    expect_keyword(lexer, "extend")
    expect_keyword(lexer, "type")
    name = parse_name(lexer)
    interfaces = parse_implements_interfaces(lexer)
    directives = parse_directives(lexer, True)
    fields = parse_fields_definition(lexer)
    if not (interfaces or directives or fields):
        raise unexpected(lexer)
    return Node(
        name=name,
        interfaces=interfaces,
        directives=directives,
        fields=fields,
        loc=loc(lexer, start),
    )
13295
function (expression, types) {
        var args = types.split(" | "),
            i, len, found = false;

        for (i=0, len=args.length; i < len && !found && expression.hasNext(); i++) {
            found = this.isType(expression, args[i]);
        }

        return found;
    }
106174
def _infer_type_impl(self, partial, *args, **kwargs):
        """"""
        # pylint: disable=too-many-locals
        if len(args) != 0 and len(kwargs) != 0:
            raise ValueError('Can only specify known argument \
                    types either by positional or kwargs way.')
        sdata = []
        if len(args) != 0:
            keys = c_array(ctypes.c_char_p, [])
            for s in args:
                if s is not None:
                    s = _numpy.dtype(s).type
                    if s not in _DTYPE_NP_TO_MX:
                        raise TypeError('Argument need to be one of ' + str(_DTYPE_NP_TO_MX))
                    sdata.append(_DTYPE_NP_TO_MX[s])
                else:
                    sdata.append(-1)
        else:
            str_keys = []
            for k, v in kwargs.items():
                v = _numpy.dtype(v).type
                if v in _DTYPE_NP_TO_MX:
                    str_keys.append(k)
                    sdata.append(_DTYPE_NP_TO_MX[v])
            keys = c_str_array(str_keys)
        arg_type_size = mx_uint()
        arg_type_data = ctypes.POINTER(ctypes.c_int)()
        out_type_size = mx_uint()
        out_type_data = ctypes.POINTER(ctypes.c_int)()
        aux_type_size = mx_uint()
        aux_type_data = ctypes.POINTER(ctypes.c_int)()
        complete = ctypes.c_int()
        if partial:
            infer_func = _LIB.MXSymbolInferTypePartial
        else:
            infer_func = _LIB.MXSymbolInferType
        check_call(infer_func(
            self.handle,
            mx_uint(len(sdata)),
            keys,
            c_array_buf(ctypes.c_int, array('i', sdata)),
            ctypes.byref(arg_type_size),
            ctypes.byref(arg_type_data),
            ctypes.byref(out_type_size),
            ctypes.byref(out_type_data),
            ctypes.byref(aux_type_size),
            ctypes.byref(aux_type_data),
            ctypes.byref(complete)))
        if complete.value != 0:
            arg_types = [
                _DTYPE_MX_TO_NP[arg_type_data[i]] for i in range(arg_type_size.value)]
            out_types = [
                _DTYPE_MX_TO_NP[out_type_data[i]] for i in range(out_type_size.value)]
            aux_types = [
                _DTYPE_MX_TO_NP[aux_type_data[i]] for i in range(aux_type_size.value)]
            return (arg_types, out_types, aux_types)
        else:
            return (None, None, None)
1367307
function isTagExpr (node) {
  return typeof(node) === 'object' && node.type === 'assign' && !node.local
    && node.varname === 'tags'
    && node.value.length > 2
    && node.value[0].type === 'lookup' && node.value[0].varname === 'tags'
    && node.value[1] === ' '
}
1228278
function typeFactory(test) {
  return type

  function type(node) {
    return Boolean(node && node.type === test)
  }
}
834458
function at_type() {
  match(/@type/);
  add_tag("type");
  skip_horiz_white();
  if (look(/\{/)) {
    var tdf = typedef();
    current_tag["type"] = tdf["type"];
    current_tag["optional"] = tdf["optional"] ? true : false;
  }
  else if (look(/\S/)) {
    current_tag["type"] = match(/\S+/);
  }
  skip_white();
}