coerceTypeBase and isCovariantParametrizedType defines all hand-coded rules for type coercion.
Other methods should reference these two functions instead of hand-code new rules.
199758
@Override
    public Optional<Type> coerceTypeBase(Type sourceType, String resultTypeBase)
    {
        String sourceTypeName = sourceType.getTypeSignature().getBase();
        if (sourceTypeName.equals(resultTypeBase)) {
            return Optional.of(sourceType);
        }

        switch (sourceTypeName) {
            case UnknownType.NAME: {
                switch (resultTypeBase) {
                    case StandardTypes.BOOLEAN:
                    case StandardTypes.BIGINT:
                    case StandardTypes.INTEGER:
                    case StandardTypes.DOUBLE:
                    case StandardTypes.REAL:
                    case StandardTypes.VARBINARY:
                    case StandardTypes.DATE:
                    case StandardTypes.TIME:
                    case StandardTypes.TIME_WITH_TIME_ZONE:
                    case StandardTypes.TIMESTAMP:
                    case StandardTypes.TIMESTAMP_WITH_TIME_ZONE:
                    case StandardTypes.HYPER_LOG_LOG:
                    case SetDigestType.NAME:
                    case StandardTypes.P4_HYPER_LOG_LOG:
                    case StandardTypes.JSON:
                    case StandardTypes.INTERVAL_YEAR_TO_MONTH:
                    case StandardTypes.INTERVAL_DAY_TO_SECOND:
                    case JoniRegexpType.NAME:
                    case LikePatternType.NAME:
                    case JsonPathType.NAME:
                    case ColorType.NAME:
                    case CodePointsType.NAME:
                        return Optional.of(getType(new TypeSignature(resultTypeBase)));
                    case StandardTypes.VARCHAR:
                        return Optional.of(createVarcharType(0));
                    case StandardTypes.CHAR:
                        return Optional.of(createCharType(0));
                    case StandardTypes.DECIMAL:
                        return Optional.of(createDecimalType(1, 0));
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.TINYINT: {
                switch (resultTypeBase) {
                    case StandardTypes.SMALLINT:
                        return Optional.of(SMALLINT);
                    case StandardTypes.INTEGER:
                        return Optional.of(INTEGER);
                    case StandardTypes.BIGINT:
                        return Optional.of(BIGINT);
                    case StandardTypes.REAL:
                        return Optional.of(REAL);
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    case StandardTypes.DECIMAL:
                        return Optional.of(createDecimalType(3, 0));
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.SMALLINT: {
                switch (resultTypeBase) {
                    case StandardTypes.INTEGER:
                        return Optional.of(INTEGER);
                    case StandardTypes.BIGINT:
                        return Optional.of(BIGINT);
                    case StandardTypes.REAL:
                        return Optional.of(REAL);
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    case StandardTypes.DECIMAL:
                        return Optional.of(createDecimalType(5, 0));
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.INTEGER: {
                switch (resultTypeBase) {
                    case StandardTypes.BIGINT:
                        return Optional.of(BIGINT);
                    case StandardTypes.REAL:
                        return Optional.of(REAL);
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    case StandardTypes.DECIMAL:
                        return Optional.of(createDecimalType(10, 0));
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.BIGINT: {
                switch (resultTypeBase) {
                    case StandardTypes.REAL:
                        return Optional.of(REAL);
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    case StandardTypes.DECIMAL:
                        return Optional.of(createDecimalType(19, 0));
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.DECIMAL: {
                switch (resultTypeBase) {
                    case StandardTypes.REAL:
                        return Optional.of(REAL);
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.REAL: {
                switch (resultTypeBase) {
                    case StandardTypes.DOUBLE:
                        return Optional.of(DOUBLE);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.DATE: {
                switch (resultTypeBase) {
                    case StandardTypes.TIMESTAMP:
                        return Optional.of(TIMESTAMP);
                    case StandardTypes.TIMESTAMP_WITH_TIME_ZONE:
                        return Optional.of(TIMESTAMP_WITH_TIME_ZONE);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.TIME: {
                switch (resultTypeBase) {
                    case StandardTypes.TIME_WITH_TIME_ZONE:
                        return Optional.of(TIME_WITH_TIME_ZONE);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.TIMESTAMP: {
                switch (resultTypeBase) {
                    case StandardTypes.TIMESTAMP_WITH_TIME_ZONE:
                        return Optional.of(TIMESTAMP_WITH_TIME_ZONE);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.VARCHAR: {
                switch (resultTypeBase) {
                    case StandardTypes.CHAR:
                        if (featuresConfig.isLegacyCharToVarcharCoercion()) {
                            return Optional.empty();
                        }

                        VarcharType varcharType = (VarcharType) sourceType;
                        if (varcharType.isUnbounded()) {
                            return Optional.of(CharType.createCharType(CharType.MAX_LENGTH));
                        }

                        return Optional.of(createCharType(Math.min(CharType.MAX_LENGTH, varcharType.getLengthSafe())));
                    case JoniRegexpType.NAME:
                        return Optional.of(JONI_REGEXP);
                    case Re2JRegexpType.NAME:
                        return Optional.of(RE2J_REGEXP);
                    case LikePatternType.NAME:
                        return Optional.of(LIKE_PATTERN);
                    case JsonPathType.NAME:
                        return Optional.of(JSON_PATH);
                    case CodePointsType.NAME:
                        return Optional.of(CODE_POINTS);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.CHAR: {
                switch (resultTypeBase) {
                    case StandardTypes.VARCHAR:
                        if (!featuresConfig.isLegacyCharToVarcharCoercion()) {
                            return Optional.empty();
                        }

                        CharType charType = (CharType) sourceType;
                        return Optional.of(createVarcharType(charType.getLength()));
                    case JoniRegexpType.NAME:
                        return Optional.of(JONI_REGEXP);
                    case Re2JRegexpType.NAME:
                        return Optional.of(RE2J_REGEXP);
                    case LikePatternType.NAME:
                        return Optional.of(LIKE_PATTERN);
                    case JsonPathType.NAME:
                        return Optional.of(JSON_PATH);
                    case CodePointsType.NAME:
                        return Optional.of(CODE_POINTS);
                    default:
                        return Optional.empty();
                }
            }
            case StandardTypes.P4_HYPER_LOG_LOG: {
                switch (resultTypeBase) {
                    case StandardTypes.HYPER_LOG_LOG:
                        return Optional.of(HYPER_LOG_LOG);
                    default:
                        return Optional.empty();
                }
            }
            default:
                return Optional.empty();
        }
    }
862953
function isContextSensitive(node) {
            ts.Debug.assert(node.kind !== 147 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
            switch (node.kind) {
                case 179 /* FunctionExpression */:
                case 180 /* ArrowFunction */:
                    return isContextSensitiveFunctionLikeDeclaration(node);
                case 171 /* ObjectLiteralExpression */:
                    return ts.forEach(node.properties, isContextSensitive);
                case 170 /* ArrayLiteralExpression */:
                    return ts.forEach(node.elements, isContextSensitive);
                case 188 /* ConditionalExpression */:
                    return isContextSensitive(node.whenTrue) ||
                        isContextSensitive(node.whenFalse);
                case 187 /* BinaryExpression */:
                    return node.operatorToken.kind === 52 /* BarBarToken */ &&
                        (isContextSensitive(node.left) || isContextSensitive(node.right));
                case 253 /* PropertyAssignment */:
                    return isContextSensitive(node.initializer);
                case 147 /* MethodDeclaration */:
                case 146 /* MethodSignature */:
                    return isContextSensitiveFunctionLikeDeclaration(node);
                case 178 /* ParenthesizedExpression */:
                    return isContextSensitive(node.expression);
            }
            return false;
        }
808014
public void readLogicalDependency(final InternalFactHandle handle,
                                      final Object object,
                                      final Object value,
                                      final Activation activation,
                                      final PropagationContext context,
                                      final RuleImpl rule,
                                      final ObjectTypeConf typeConf) {
        addLogicalDependency( handle, object, value, activation, context, rule, typeConf, true );
    }
1112544
function reportInferrableType(node, typeNode, initNode) {
            if (!typeNode || !initNode || !typeNode.typeAnnotation) {
                return;
            }

            if (!isInferrable(typeNode, initNode)) {
                return;
            }

            const typeMap = {
                TSBooleanKeyword: "boolean",
                TSNumberKeyword: "number",
                TSStringKeyword: "string",
            };

            const type = typeMap[typeNode.typeAnnotation.type];

            context.report({
                node,
                message:
                    "Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.",
                data: {
                    type,
                },
                fix: fixer => fixer.remove(typeNode),
            });
        }
281258
public boolean isSarlBehavior(LightweightTypeReference type) {
		return !type.isInterfaceType() && (getSarlElementEcoreType(type) == SarlPackage.SARL_BEHAVIOR
				|| type.isSubtypeOf(Behavior.class));
	}
1310955
function narrowType(type, expr, assumeTrue) {
                switch (expr.kind) {
                    case 69 /* Identifier */:
                    case 97 /* ThisKeyword */:
                    case 172 /* PropertyAccessExpression */:
                        return narrowTypeByTruthiness(type, expr, assumeTrue);
                    case 174 /* CallExpression */:
                        return narrowTypeByTypePredicate(type, expr, assumeTrue);
                    case 178 /* ParenthesizedExpression */:
                        return narrowType(type, expr.expression, assumeTrue);
                    case 187 /* BinaryExpression */:
                        return narrowTypeByBinaryExpression(type, expr, assumeTrue);
                    case 185 /* PrefixUnaryExpression */:
                        if (expr.operator === 49 /* ExclamationToken */) {
                            return narrowType(type, expr.operand, !assumeTrue);
                        }
                        break;
                }
                return type;
            }
161389
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
    ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
    if (keys.isEmpty()) {
      return false;
    }

    // Try to infer the template types
    Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
    Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
    for (TemplateType key : keys) {
      JSType type = rawInferrence.get(key);
      if (type == null) {
        type = unknownType;
      }
      inferred.put(key, type);
    }

    // Try to infer the template types using the type transformations
    Map<TemplateType, JSType> typeTransformations =
        evaluateTypeTransformations(keys, inferred, scope);
    if (typeTransformations != null) {
      inferred.putAll(typeTransformations);
    }

    // Replace all template types. If we couldn't find a replacement, we
    // replace it with UNKNOWN.
    TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
    Node callTarget = n.getFirstChild();

    FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
    checkNotNull(replacementFnType);
    callTarget.setJSType(replacementFnType);
    n.setJSType(replacementFnType.getReturnType());

    return replacer.madeChanges;
  }
1033426
public static boolean blockVariantMatches(IBlockState bs, List<Variation> allowedVariants)
    {
        for (IProperty prop : bs.getProperties().keySet())
        {
            if (prop.getName().equals("variant") && prop.getValueClass().isEnum())
            {
                Object current = bs.getValue(prop);
                if (current != null)
                {
                    for (Variation var : allowedVariants)
                    {
                        if (var.getValue().equalsIgnoreCase(current.toString()))
                            return true;
                    }
                }
            }
        }
        return false;
    }
382620
private static boolean typeMayHaveInvariant(Type type, Context context) {
		if (type instanceof Type.Void) {
			return false;
		} else if (type instanceof Type.Null) {
			return false;
		} else if (type instanceof Type.Bool) {
			return false;
		} else if (type instanceof Type.Byte) {
			return false;
		} else if (type instanceof Type.Int) {
			return false;
		} else if (type instanceof Type.Array) {
			Type.Array lt = (Type.Array) type;
			return typeMayHaveInvariant(lt.getElement(), context);
		} else if (type instanceof Type.Record) {
			Type.Record rt = (Type.Record) type;
			Tuple<Type.Field> fields = rt.getFields();
			for (int i = 0; i != fields.size(); ++i) {
				Type.Field field = fields.get(i);
				if (typeMayHaveInvariant(field.getType(), context)) {
					return true;
				}
			}
			return false;
		} else if (type instanceof Type.Reference) {
			Type.Reference lt = (Type.Reference) type;
			return typeMayHaveInvariant(lt.getElement(), context);
		} else if (type instanceof Type.Union) {
			Type.Union t = (Type.Union) type;
			for (int i = 0; i != t.size(); ++i) {
				if (typeMayHaveInvariant(t.get(i), context)) {
					return true;
				}
			}
			return false;
		} else if (type instanceof Type.Callable) {
			Type.Callable ft = (Type.Callable) type;
			return typeMayHaveInvariant(ft.getParameters(), context) || typeMayHaveInvariant(ft.getReturns(), context);
		} else if (type instanceof Type.Nominal) {
			Type.Nominal nt = (Type.Nominal) type;
			// HACK
			return true;
		} else if (type instanceof Type.Variable) {
			// FIXME: unsure what the right solution is here?
			return true;
		} else {
			throw new RuntimeException("unknown type encountered (" + type + ")");
		}
	}
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;
    }
  }
1241807
def _cor_compile(rule, var, val, result_class, key, compilation_list):
        
        compilation = compilation_list.get(key, None)
        if compilation:
            if isinstance(val, ListRule):
                result = []
                for itemv in val.value:
                    result.append(compilation['callback'](itemv))

                val = compilation['listclass'](result)
            else:
                val = compilation['callback'](val)
        return result_class(rule.operation, var, val)
1238383
public final EObject entryRuleXFunctionTypeRef() throws RecognitionException {
        EObject current = null;

        EObject iv_ruleXFunctionTypeRef = null;


        try {
            // InternalXbase.g:5500:57: (iv_ruleXFunctionTypeRef= ruleXFunctionTypeRef EOF )
            // InternalXbase.g:5501:2: iv_ruleXFunctionTypeRef= ruleXFunctionTypeRef EOF
            {
            if ( state.backtracking==0 ) {
               newCompositeNode(grammarAccess.getXFunctionTypeRefRule()); 
            }
            pushFollow(FOLLOW_1);
            iv_ruleXFunctionTypeRef=ruleXFunctionTypeRef();

            state._fsp--;
            if (state.failed) return current;
            if ( state.backtracking==0 ) {
               current =iv_ruleXFunctionTypeRef; 
            }
            match(input,EOF,FOLLOW_2); if (state.failed) return current;

            }

        }

            catch (RecognitionException re) {
                recover(input,re);
                appendSkippedTokens();
            }
        finally {
        }
        return current;
    }
892737
private static boolean hasTypeVariables(final Type type) {
        if (type instanceof TypeVariable<?> || type instanceof GenericArrayType) {
            return true;
        } else if (type instanceof ParameterizedType) {
            for (final Type arg : ((ParameterizedType) type).getActualTypeArguments()) {
                if (hasTypeVariables(arg)) {
                    return true;
                }
            }
        }
        return false;
    }
471303
private static List<MethodCallExpr> ruleMetaAttributes(RuleContext context, RuleDescr ruleDescr) {
        List<MethodCallExpr> ruleMetaAttributes = new ArrayList<>();
        for (String metaAttr : ruleDescr.getAnnotationNames()) {
            MethodCallExpr metaAttributeCall = new MethodCallExpr(METADATA_CALL);
            metaAttributeCall.addArgument(new StringLiteralExpr(metaAttr));
            AnnotationDescr ad = ruleDescr.getAnnotation( metaAttr );
            String adFqn = ad.getFullyQualifiedName();
            if (adFqn != null) {
                AnnotationDefinition annotationDefinition;
                try {
                    annotationDefinition = AnnotationDefinition.build(context.getTypeResolver().resolveType(adFqn),
                                                                      ad.getValueMap(),
                                                                      context.getTypeResolver());
                } catch (NoSuchMethodException | ClassNotFoundException e) {
                    throw new RuntimeException( e );
                }
                if ( annotationDefinition.getValues().size() == 1 && annotationDefinition.getValues().containsKey( AnnotationDescr.VALUE ) ) {
                    Object annValue = annotationDefinition.getPropertyValue(AnnotationDescr.VALUE);
                    metaAttributeCall.addArgument(new StringLiteralExpr(annValue.toString()));
                } else {
                    Map<String, Object> map = new HashMap<>( annotationDefinition.getValues().size() );
                    for ( String key : annotationDefinition.getValues().keySet() ) {
                        map.put( key, annotationDefinition.getPropertyValue( key ) );
                    }
                    metaAttributeCall.addArgument(objectAsJPExpression(map));
                }
            } else {
                if ( ad.hasValue() ) {
                    if ( ad.getValues().size() == 1 ) {
                        metaAttributeCall.addArgument(objectAsJPExpression(resolveValue(ad.getSingleValueAsString())));
                    } else {
                        metaAttributeCall.addArgument(objectAsJPExpression(ad.getValueMap()));
                    }
                } else {
                    metaAttributeCall.addArgument(new NullLiteralExpr());
                }
            }
            ruleMetaAttributes.add(metaAttributeCall);
        }
        return ruleMetaAttributes;
    }
1067434
def _determine_rule_types(self, metamodel):
        """"""

        def _determine_rule_type(cls):
            """
            Determine rule type (abstract, match, common) and inherited
            classes.
            """

            if cls in resolved_classes:
                return
            resolved_classes.add(cls)

            # If there are attributes collected than this is a common
            # rule
            if len(cls._tx_attrs) > 0:
                if cls._tx_type != RULE_COMMON:
                    cls._tx_type = RULE_COMMON
                    has_change[0] = True
                return

            rule = cls._tx_peg_rule

            # Check if this rule is abstract. Abstract are root rules which
            # haven't got any attributes and reference at least one non-match
            # rule.
            abstract = False
            if rule.rule_name and cls.__name__ != rule.rule_name:
                # Special case. Body of the rule is a single rule reference and
                # the referenced rule is not match rule.
                target_cls = metamodel[rule.rule_name]
                _determine_rule_type(target_cls)
                abstract = target_cls._tx_type != RULE_MATCH
            else:
                # Find at least one referenced rule that is not match rule by
                # going down the parser model and finding root rules.
                def _has_nonmatch_ref(rule):
                    for r in rule.nodes:
                        if r.root:
                            _determine_rule_type(r._tx_class)
                            result = r._tx_class._tx_type != RULE_MATCH
                        else:
                            result = _has_nonmatch_ref(r)
                        if result:
                            return True
                abstract = _has_nonmatch_ref(rule)

            if abstract and cls._tx_type != RULE_ABSTRACT:
                cls._tx_type = RULE_ABSTRACT
                has_change[0] = True
                # Add inherited classes to this rule's meta-class
                if rule.rule_name and cls.__name__ != rule.rule_name:
                    if rule._tx_class not in cls._tx_inh_by:
                        cls._tx_inh_by.append(rule._tx_class)
                else:
                    # Recursively append all referenced classes.
                    def _add_reffered_classes(rule, inh_by, start=False):
                        if rule.root and not start:
                            if hasattr(rule, '_tx_class'):
                                _determine_rule_type(rule._tx_class)
                                if rule._tx_class._tx_type != RULE_MATCH and\
                                        rule._tx_class not in inh_by:
                                    inh_by.append(rule._tx_class)
                        else:
                            for r in rule.nodes:
                                _add_reffered_classes(r, inh_by)

                    if type(rule) is OrderedChoice:
                        for r in rule.nodes:
                            _add_reffered_classes(r, cls._tx_inh_by)
                    else:
                        _add_reffered_classes(rule, cls._tx_inh_by, start=True)

        # Multi-pass rule type resolving to support circular rule references.
        # `has_change` is a list to support outer scope variable change in
        # Python 2.x
        has_change = [True]
        while has_change[0]:
            has_change[0] = False
            resolved_classes = set()
            for cls in metamodel:
                _determine_rule_type(cls)
680187
static <FACETEDTYPE extends Faceted<?>, FACETTYPE extends Facet<FACETEDTYPE>> boolean hasCircularConstraints(
            Class<?> inspectedType)
   {
      Set<Class<FACETTYPE>> allRelatedFacets = getAllRelatedFacets(inspectedType);
      for (Class<? extends Facet<?>> requirement : allRelatedFacets)
      {
         for (Class<? extends Facet<?>> subrequirement : getAllRelatedFacets(requirement))
         {
            if (subrequirement.isAssignableFrom(requirement))
               return true;
         }
      }
      return false;
   }
88426
public static <T> T coerceToType(ELContext context, Class<T> toType, Object object) {
        @SuppressWarnings("unchecked")
        T result = (T) getExpressionFactory(context).coerceToType(object, toType);
        return result;
    }