public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) { return SimplifyExpression( node, newNode: base.VisitCastExpression(node), simplifier: SimplifyCast); }
private static bool IsRequiredCastForReferenceEqualityComparison(ITypeSymbol outerType, CastExpressionSyntax castExpression, SemanticModel semanticModel, out ExpressionSyntax other) { if (outerType.SpecialType == SpecialType.System_Object) { var expression = castExpression.WalkUpParentheses(); var parentNode = expression.Parent; if (parentNode.IsKind(SyntaxKind.EqualsExpression) || parentNode.IsKind(SyntaxKind.NotEqualsExpression)) { // Reference comparison. var binaryExpression = (BinaryExpressionSyntax)parentNode; other = binaryExpression.Left == expression ? binaryExpression.Right : binaryExpression.Left; // Explicit cast not required if we are comparing with type parameter with a class constraint. var otherType = semanticModel.GetTypeInfo(other).Type; if (otherType != null && otherType.TypeKind != TypeKind.TypeParameter) { return !other.WalkDownParentheses().IsKind(SyntaxKind.CastExpression); } } } other = null; return false; }
private static ExpressionSyntax SimplifyCast(CastExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (!node.IsUnnecessaryCast(semanticModel, cancellationToken)) { return node; } var leadingTrivia = node.OpenParenToken.LeadingTrivia .Concat(node.OpenParenToken.TrailingTrivia) .Concat(node.Type.GetLeadingTrivia()) .Concat(node.Type.GetTrailingTrivia()) .Concat(node.CloseParenToken.LeadingTrivia) .Concat(node.CloseParenToken.TrailingTrivia) .Concat(node.Expression.GetLeadingTrivia()) .Where(t => !t.IsElastic()); var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic()); var resultNode = node.Expression .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia); resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); return resultNode; }
protected override IValue VisitCastExpression(CastExpressionSyntax node) { var e = Visit(node.Expression); var tt = ModelExtensions.GetTypeInfo(context.RoslynModel, node); var t = context.Roslyn_ResolveType(tt.Type); // var t1 = context.Roslyn_ResolveType(node.Type); return(new CastExpression(e, t)); }
public override Ust VisitCastExpression(CastExpressionSyntax node) { var type = ConvertType(base.Visit(node.Type)); var expression = (Expression)base.Visit(node.Expression); var result = new CastExpression(type, expression, node.GetTextSpan()); return(result); }
private Doc PrintCastExpressionSyntax(CastExpressionSyntax node) { return(Concat( this.PrintSyntaxToken(node.OpenParenToken), this.Print(node.Type), this.PrintSyntaxToken(node.CloseParenToken), this.Print(node.Expression) )); }
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) { node = (DefaultExpressionSyntax)base.VisitDefaultExpression(node); node = node.ReplaceType(node.Type); CastExpressionSyntax castExpressionSyntax = SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0))); return(SyntaxFactory.ParenthesizedExpression(castExpressionSyntax)); }
/// <summary> /// Normalizes the <paramref name="cast" />. /// </summary> public override SyntaxNode VisitCastExpression(CastExpressionSyntax cast) { if (!IsFormulaType(cast)) { return(base.VisitCastExpression(cast)); } return(CreateInvocation(cast.Expression)); }
private static ExpressionSyntax SimplifyCast(CastExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (!node.IsUnnecessaryCast(semanticModel, cancellationToken)) { return(node); } return(node.Uncast()); }
private static void WriteCastOperator(HaxeWriter writer, CastExpressionSyntax expression, IMethodSymbol symbol, string destTypeHaxe) { writer.Write(TypeProcessor.ConvertType(symbol.ContainingType)); writer.Write(".op_Explicit_"); writer.Write(destTypeHaxe.TrySubstringBeforeFirst('<').Replace('.', '_')); writer.Write("("); Core.Write(writer, expression.Expression); writer.Write(")"); }
public static Doc Print(CastExpressionSyntax node) { return(Doc.Concat( Token.Print(node.OpenParenToken), Node.Print(node.Type), Token.Print(node.CloseParenToken), Node.Print(node.Expression) )); }
public static bool IsUnnecessaryCast(this CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken) { try { return((bool)isUnnecessaryCastMethod.Invoke(null, new object[] { cast, semanticModel, cancellationToken })); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return(false); } }
public override Expression VisitCastExpression(CastExpressionSyntax node) { if (node.Type is ArrayTypeSyntax) { // TODO maybe only prevent for nodes that haven't been identified as arrays before? // TODO at this time it's not possible to create an alias for an array type in C#, this might change in the future. throw new UnsupportedSyntaxException($"detected cast to array type in node '{node}'"); } return(node.Expression.Accept(this)); }
public override AccessorOrMutator VisitCastExpression(CastExpressionSyntax node) { var operand = Visit(node.Expression); var operandMutator = operand.GetMutator(this); var resultTypeSymbol = Model.GetSymbolInfo(node.Type).Symbol; var resultType = Mapper.GetSortMapping(resultTypeSymbol); return(operandMutator.Cast(resultType)); }
private static bool PointerCastDefinitelyCantBeRemoved(CastExpressionSyntax cast) { if (cast.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) && cast.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression)) { return(true); } return(false); }
private static async Task <Document> RefactorAsync( Document document, BinaryExpressionSyntax binaryExpression, CancellationToken cancellationToken) { CastExpressionSyntax castExpression = CastExpression((TypeSyntax)binaryExpression.Right, binaryExpression.Left) .WithTriviaFrom(binaryExpression) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(binaryExpression, castExpression, cancellationToken).ConfigureAwait(false)); }
public Conversion GetConversion(CastExpressionSyntax expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } var boundExpression = GetBoundExpression(expression) as BoundConversionExpression; return(boundExpression?.Conversion); }
public override void VisitCastExpression(CastExpressionSyntax node) { var typeInfo = m_Model.GetTypeInfo(node.Type); var type = typeInfo.Type as ITypeParameterSymbol; if (null != type && type.TypeParameterKind == TypeParameterKind.Type) { m_UseExplicitTypeParam = true; } base.VisitCastExpression(node); }
private static bool EnumCastDefinitelyCantBeRemoved(CastExpressionSyntax cast, ITypeSymbol expressionType) { if (expressionType != null && expressionType.IsEnumType() && cast.WalkUpParentheses().IsParentKind(SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression)) { return(true); } return(false); }
private static bool CastPassedToParamsArrayDefinitelyCantBeRemoved( CastExpressionSyntax cast, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // When a casted value is passed as the single argument to a params parameter, // we can only remove the cast if it is implicitly convertible to the parameter's type, // but not the parameter's element type. Otherwise, we could end up changing the invocation // to pass an array rather than an array with a single element. // // IOW, given the following method... // // static void Goo(params object[] x) { } // // ...we should remove this cast... // // Goo((object[])null); // // ...but not this cast... // // Goo((object)null); var parent = cast.WalkUpParentheses().Parent; if (parent is ArgumentSyntax argument) { // If there are any arguments to the right, we can assume that this is not a // *single* argument passed to a params parameter. if (argument.Parent is BaseArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex < argumentList.Arguments.Count - 1) { return false; } } var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } if (parent is AttributeArgumentSyntax attributeArgument) { if (attributeArgument.Parent is AttributeArgumentListSyntax attributeArgumentList) { // We don't check the position of the argument because in attributes it is allowed that // params parameter are positioned in between if named arguments are used. // The *single* argument check above is also broken: https://github.com/dotnet/roslyn/issues/20742 var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel); } } return false; }
public CastExpression(CastExpressionSyntax expression, SemanticModel semanticModel) { this.expression = expression; var symbolType = (ITypeSymbol)semanticModel.GetSymbolInfo(expression.Type).Symbol; typeName = Tools.GetFullTypeName(symbolType); typeFullName = Tools.GetFullTypeName(symbolType); typeFullNameFlat = Tools.GetFullTypeNameFlat(symbolType); castFromExpression = CreateExpression(this, expression.Expression, semanticModel); }
/// <summary> /// Runs cast expression. /// [Syntax] (int)b /// </summary> private HybInstance RunCast(CastExpressionSyntax node) { var cache = OptCache.GetOrCreate(node, () => { return(new OptCastNode() { type = Resolver.GetType($"{node.Type}") }); }); var value = RunExpression(node.Expression); return(value.Cast(cache.type)); }
public override SyntaxNode?VisitCastExpression(CastExpressionSyntax node) { var type = node.Type; if (type is NullableTypeSyntax) { return(node); } return(NullUtilities.CanBeNull(node.Expression, _semanticModel) ? node.WithType(NullUtilities.ToNullable(type)) : node); }
private static void CastExpressionCheck(CastExpressionSyntax castExpression, SemanticModel semanticModel, Action <Diagnostic> reportDiagnostic, string filePath, CancellationToken cancellationToken) { if (castExpression.Expression != null) { var castTypeInfo = semanticModel.GetTypeInfo(castExpression, cancellationToken); var expressionTypeInfo = semanticModel.GetTypeInfo(castExpression.Expression, cancellationToken); if (castTypeInfo.Type?.IsReferenceType == true && expressionTypeInfo.Type?.IsValueType == true) { reportDiagnostic(Diagnostic.Create(ValueTypeToReferenceTypeConversionRule, castExpression.Expression.GetLocation(), EmptyMessageArgs)); } } }
public override IExpression VisitCastExpression(CastExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); var t = this.mapper.Map(o.Type); var result = new Microsoft.Cci.MutableCodeModel.Conversion() { ValueToConvert = this.Visit(node.Expression), Type = t, TypeAfterConversion = t, }; return(result); }
public override void VisitCastExpression(CastExpressionSyntax node) { if (!PreVisit(node)) { return; } node.Type?.Accept(this); node.Expression?.Accept(this); base.VisitCastExpression(node); PostVisit(node); }
public static Task <Document> RefactorAsync( Document document, CastExpressionSyntax castExpression, CancellationToken cancellationToken) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)castExpression.Parent; ParenthesizedExpressionSyntax newNode = parenthesizedExpression .WithExpression(castExpression.Expression.WithTriviaFrom(castExpression)) .WithFormatterAnnotation() .WithSimplifierAnnotation(); return(document.ReplaceNodeAsync(parenthesizedExpression, newNode, cancellationToken)); }
private static Task <Document> RefactorAsync( Document document, CastExpressionSyntax castExpression, CancellationToken cancellationToken) { ExpressionSyntax expression = castExpression.Expression; TypeSyntax type = castExpression.Type; BinaryExpressionSyntax newNode = CSharpFactory.AsExpression(expression.WithTriviaFrom(type), type.WithTriviaFrom(expression)) .WithTriviaFrom(castExpression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(castExpression, newNode, cancellationToken)); }
public override void VisitCastExpression(CastExpressionSyntax node) { FileLinePositionSpan span = node.SyntaxTree.GetLineSpan(node.Span); TypeSyntax typeSyntax = node.Type; ExpressionSyntax expressionSyntax = node.Expression; TypeInfo typeModel = Model.GetTypeInfo(typeSyntax); TypeInfo expressionTypeModel = Model.GetTypeInfo(expressionSyntax); if (typeModel.Equals(expressionTypeModel)) { Data.Add(new CollectedData <String>(typeModel.Type.ToDisplayString(), span.StartLinePosition, span.EndLinePosition)); } base.VisitCastExpression(node); }
public override void VisitCastExpression(CastExpressionSyntax node) { if (lang == TargetLang.TypeScript) { Visit(node.Expression); } else { emit("("); Visit(node.Type); emit(")"); Visit(node.Expression); } }
private static SyntaxNode GenerateReplacementNode(CastExpressionSyntax node) { var literalExpressionSyntax = !(node.Expression.WalkDownParentheses() is PrefixUnaryExpressionSyntax plusMinusSyntax) ? (LiteralExpressionSyntax)node.Expression.WalkDownParentheses() : (LiteralExpressionSyntax)plusMinusSyntax.Operand.WalkDownParentheses(); var typeToken = node.Type.GetFirstToken(); var replacementLiteral = literalExpressionSyntax.WithLiteralSuffix(typeToken.Kind()); var replacementNode = node.Expression.ReplaceNode(literalExpressionSyntax, replacementLiteral) .WithLeadingTrivia(node.GetLeadingTrivia().Concat(node.CloseParenToken.TrailingTrivia).Concat(node.Expression.GetLeadingTrivia())) .WithTrailingTrivia(node.Expression.GetTrailingTrivia().Concat(node.GetTrailingTrivia())); return(replacementNode); }
private static async Task <Document> RefactorAsync( Document document, BinaryExpressionSyntax binaryExpression, CancellationToken cancellationToken) { SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); CastExpressionSyntax castExpression = CastExpression((TypeSyntax)binaryExpression.Right, binaryExpression.Left) .WithTriviaFrom(binaryExpression) .WithFormatterAnnotation(); SyntaxNode newRoot = root.ReplaceNode(binaryExpression, castExpression); return(document.WithSyntaxRoot(newRoot)); }
static Document PerformAction(Document document, SyntaxNode root, CastExpressionSyntax castExpr) { ExpressionSyntax nodeToReplace = castExpr; while (nodeToReplace.Parent is ParenthesizedExpressionSyntax) { nodeToReplace = (ExpressionSyntax)nodeToReplace.Parent; } // The syntax factory doesn't automatically add spaces around the operator ! var token = SyntaxFactory.ParseToken(" as "); var asExpr = (ExpressionSyntax)SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, castExpr.Expression, token, castExpr.Type); if (nodeToReplace.Parent is ExpressionSyntax) asExpr = SyntaxFactory.ParenthesizedExpression(asExpr); var newRoot = root.ReplaceNode((SyntaxNode)nodeToReplace, asExpr); return document.WithSyntaxRoot(newRoot); }
private bool TryGenerateCast(CastExpressionSyntax castExpression) { var type = SemanticModel.GetTypeInfo(castExpression.Type).Type; if (type == null) { return(false); } using (CastTag()) { GenerateType(type); return(TryGenerateExpression(castExpression.Expression)); } }
private static async Task<Document> RemoveUnnecessaryCastAsync( Document document, CastExpressionSyntax cast, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var annotatedCast = cast.WithAdditionalAnnotations(Simplifier.Annotation); if (annotatedCast.Expression is ParenthesizedExpressionSyntax) { annotatedCast = annotatedCast.WithExpression( annotatedCast.Expression.WithAdditionalAnnotations(Simplifier.Annotation)); } else { annotatedCast = annotatedCast.WithExpression( annotatedCast.Expression.Parenthesize()); } ExpressionSyntax oldNode = cast; ExpressionSyntax newNode = annotatedCast; // Ensure that we simplify any parenting parenthesized expressions not just on the syntax tree level but also on Token based // Case 1: // In the syntax, (((Task<Action>)x).Result)() // oldNode = (Task<Action>)x // newNode = (Task<Action>)(x) // Final newNode will be (((Task<Action>)(x)).Result) while (oldNode.Parent.IsKind(SyntaxKind.ParenthesizedExpression) || oldNode.GetFirstToken().GetPreviousToken().Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)oldNode.GetFirstToken().GetPreviousToken().Parent; newNode = parenthesizedExpression.ReplaceNode(oldNode, newNode) .WithAdditionalAnnotations(Simplifier.Annotation); oldNode = parenthesizedExpression; } newNode = newNode.WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode(oldNode, newNode); return document.WithSyntaxRoot(newRoot); }
private static bool PointerCastDefinitelyCantBeRemoved(CastExpressionSyntax cast) { if (cast.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) && cast.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression)) { return true; } return false; }
/// <summary> /// Normalizes the <paramref name="cast" />. /// </summary> public override SyntaxNode VisitCastExpression(CastExpressionSyntax cast) { if (!IsFormulaType(cast)) return base.VisitCastExpression(cast); return CreateInvocation(cast.Expression); }
private ProgramState ProcessCastAccess(ProgramState programState, CastExpressionSyntax castExpression) { var typeExpression = semanticModel.GetTypeInfo(castExpression.Expression).Type; if (typeExpression == null || !typeExpression.OriginalDefinition.Is(KnownType.System_Nullable_T)) { return programState; } var type = semanticModel.GetTypeInfo(castExpression.Type).Type; if (type == null || !semanticModel.Compilation.ClassifyConversion(typeExpression, type).IsNullable || !programState.PeekValue().HasConstraint(ObjectConstraint.Null, programState)) { return programState; } if (!context.Equals(default(SyntaxNodeAnalysisContext))) { context.ReportDiagnostic(Diagnostic.Create(Rule, castExpression.GetLocation(), MessageDefinite)); } return null; }
private static SyntaxNode GenerateReplacementNodeBasedOnValue(CastExpressionSyntax node, object desiredValue) { var typeToken = node.Type.GetFirstToken(); var correspondingSuffix = LiteralSyntaxKindToSuffix[typeToken.Kind()]; var fixedCodePreservingText = SyntaxFactory.ParseExpression(desiredValue + correspondingSuffix); return fixedCodePreservingText.WithTriviaFrom(node); }
private static bool IsInExplicitCheckedOrUncheckedContext(CastExpressionSyntax cast) { SyntaxNode currentNode = cast; do { switch(currentNode.Kind()) { case SyntaxKind.UncheckedExpression: case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedExpression: case SyntaxKind.CheckedStatement: return true; } currentNode = currentNode.Parent; } while (currentNode is ExpressionSyntax || currentNode is StatementSyntax); return false; }
public void VisitCastExpression(CastExpressionSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); ExpressionStart(node); _writer.WriteSyntax(Syntax.OpenParen); if (_writer.Configuration.Spaces.WithinParentheses.TypeCastParentheses) _writer.WriteSpace(); node.Type.Accept(this); if (_writer.Configuration.Spaces.WithinParentheses.TypeCastParentheses) _writer.WriteSpace(); _writer.WriteSyntax(Syntax.CloseParen); if (_writer.Configuration.Spaces.Other.AfterTypeCastParentheses) _writer.WriteSpace(); node.Expression.Accept(this); ExpressionEnd(node); }
public CastExpressionTranslation(CastExpressionSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Type = syntax.Type.Get<TypeTranslation>(this); Expression = syntax.Expression.Get<ExpressionTranslation>(this); }
public FlatOperand Resolve(CastExpressionSyntax node, TypeInfo result_type, FlatOperand into_lvalue, List<FlatStatement> instructions) { /* // Summary: // SyntaxToken representing the close parenthesis. public SyntaxToken CloseParenToken { get; } // // Summary: // ExpressionSyntax node representing the expression that is being casted. public ExpressionSyntax Expression { get; } // // Summary: // SyntaxToken representing the open parenthesis. public SyntaxToken OpenParenToken { get; } // // Summary: // TypeSyntax node representing the type the expression is being casted to. public TypeSyntax Type { get; } /**/ return ResolveExpression(node.Expression, into_lvalue, instructions); }
public static void Go(OutputWriter writer, CastExpressionSyntax expression) { var symbol = TypeProcessor.GetSymbolInfo(expression); var castingFrom = TypeProcessor.GetTypeInfo(expression.Expression).Type ?? TypeProcessor.GetTypeInfo(expression).Type; var srcTypeDlang = TypeProcessor.ConvertType(castingFrom); var destType = TypeProcessor.GetTypeInfo(expression.Type).Type; var destTypeDlang = TypeProcessor.TryConvertType(expression.Type); if (destTypeDlang == srcTypeDlang) Core.Write(writer, expression.Expression); else //if (symbol.Symbol != null)// && srcTypeCpp != "int" && srcTypeCpp != "System.String" && srcTypeCpp != "bool") { // if (castingFrom != destType) // Check for implicit first then explicit bool useType = true; //We should start with exact converters and then move to more generic convertors i.e. base class or integers which are implicitly convertible var correctConverter = destType.GetImplicitCoversionOp(destType, castingFrom, true); // initializerType.Type.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); if (correctConverter == null) { useType = false; correctConverter = castingFrom.GetImplicitCoversionOp(destType, castingFrom, true); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); } if (correctConverter != null) { // Core.Write(writer, expression.Left); // writer.Write(" = "); if (correctConverter.ReturnType != destType) writer.Write("Cast!(" + destTypeDlang + (destType.IsValueType ? "" : "") + ")("); if (castingFrom.SpecialType == SpecialType.System_Decimal && destType.IsPrimitiveInteger()) { } else { if (useType) { writer.Write(TypeProcessor.ConvertType(destType) + "." + "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType, false, true, false).Replace(".","_")); } else { writer.Write(TypeProcessor.ConvertType(castingFrom) + "." + "op_Implicit_" + TypeProcessor.ConvertType(correctConverter.ReturnType, false, true, false).Replace(".", "_")); } } writer.Write("("); Core.Write(writer, expression.Expression); writer.Write(")"); if (correctConverter.ReturnType != destType) writer.Write(")"); return; } useType = true; //We should start with exact converters and then move to more generic convertors i.e. base class or integers which are implicitly convertible correctConverter = destType.GetExplictCoversionOp(destType, castingFrom, true); // initializerType.Type.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); if (correctConverter == null) { useType = false; correctConverter = castingFrom.GetExplictCoversionOp(destType, castingFrom, true); //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType); } if (correctConverter != null) { var iscast = correctConverter.ReturnType != destType; if (iscast) writer.Write("Cast!(" + destTypeDlang + ")("); // Core.Write(writer, expression.Left); // writer.Write(" = "); if (castingFrom.SpecialType == SpecialType.System_Decimal && destType.IsPrimitiveInteger()) { } else { if (useType) writer.Write(TypeProcessor.ConvertType(destType) + "." + "op_Explicit"); else writer.Write(TypeProcessor.ConvertType(castingFrom) + "." + "op_Explicit"); } writer.Write("("); Core.Write(writer, expression.Expression); writer.Write(")"); if(iscast) writer.Write(")"); return; } if (TypeProcessor.IsPrimitiveType(srcTypeDlang) && TypeProcessor.IsPrimitiveType(destTypeDlang)) {//primitives can be directly cast writer.Write("cast(" + destTypeDlang + ")"); Core.Write(writer, expression.Expression); } else { var convertedType = TypeProcessor.GetTypeInfo(expression).Type; var type = TypeProcessor.GetTypeInfo(expression.Expression).Type; if (type.IsValueType && !convertedType.IsValueType) { //We have to box then cast if not Object if (destType.Name != "Object") writer.Write("Cast!(" + destTypeDlang + ")("); //Box writer.Write("BOX!(" + TypeProcessor.ConvertType(type) + ")("); //When passing an argument by ref or out, leave off the .Value suffix // writer.Write(" >("); Core.Write(writer, expression.Expression); writer.Write(")"); if (destType.Name != "Object") writer.Write(")"); } else if (!type.IsValueType && convertedType.IsValueType) { //UnBox // writer.Write("(Cast!( Boxed!(" + TypeProcessor.ConvertType(convertedType) + ") )("); // Core.Write(writer, expression.Expression); // writer.Write(")).Value"); writer.Write("UNBOX!(" + TypeProcessor.ConvertType(convertedType) + ")("); Core.Write(writer, expression.Expression); writer.Write(")"); } else if (type.IsValueType && convertedType.IsValueType) { if (convertedType.TypeKind == TypeKind.Pointer) { //cannot use ascast here, its for boxed types and objects writer.Write("cast(" + destTypeDlang + (destType.IsValueType ? "" : "") + ")("); Core.Write(writer, expression.Expression); writer.Write(")"); } else { //cannot use ascast here, its for boxed types and objects writer.Write("Cast!(" + destTypeDlang + (destType.IsValueType ? "" : "") + ")("); Core.Write(writer, expression.Expression); writer.Write(")"); } } else { writer.Write("Cast!("); writer.Write(destTypeDlang); writer.Write(")("); Core.Write(writer, expression.Expression); writer.Write(")"); } } } }
private static void AddCastExpressionTerms(CastExpressionSyntax castExpression, IList<string> terms, ref ExpressionType expressionType) { // For a cast, just add the nested expression. Note: this is technically // unsafe as the cast *may* have side effects. However, in practice this is // extremely rare, so we allow for this since it's ok in the common case. var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(castExpression.Expression, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(castExpression.Expression, flags, terms); // If the subexpression is a valid term, so is the cast expression expressionType = flags; }
/// <summary> /// Normalizes the <paramref name="cast" />. /// </summary> public override SyntaxNode VisitCastExpression(CastExpressionSyntax cast) { var expressionType = DetermineType(cast); if (expressionType == ExpressionType.Other) return base.VisitCastExpression(cast); return CreateInvocation(expressionType, cast.Expression); }
private Method TraverseCastExpressions(CastExpressionSyntax ces) { Method retMethod = new Method(); if (ces.HasLeadingTrivia) { SetOuterComments(retMethod, ces.GetLeadingTrivia().ToFullString()); } if (ces.HasTrailingTrivia) { SetInnerComments(retMethod, ces.GetTrailingTrivia().ToFullString()); } var variables = from aVariable in ces.ChildNodes().OfType<IdentifierNameSyntax>() select aVariable; Model.Type type = new Model.Type(); type.Name = ces.Type.ToString(); type.IsKnownType = SyntaxFacts.IsKeywordKind(ces.Type.CSharpKind()); type.IsNotUserDefined = SyntaxFacts.IsKeywordKind(ces.Type.CSharpKind()); foreach (IdentifierNameSyntax ins in variables) { //TODO put a bp here and test if this adds method names (bad) or just var names(good) Variables vars = new Variables(); vars.Name = ins.Identifier.ValueText; vars.IsReferenced = true; vars.Type = type; retMethod.AccessedVariables.Add(vars); } var binaryExprs = from aBinaryExpr in ces.ChildNodes().OfType<BinaryExpressionSyntax>() select aBinaryExpr; foreach (BinaryExpressionSyntax bes in binaryExprs) { Method retMethod2 = TraverseBinaryExpression(bes); retMethod.AccessedVariables.AddRange(retMethod2.AccessedVariables); retMethod.InvokedMethods.AddRange(retMethod2.InvokedMethods); } var invokedMethods = from aInvokedMethod in ces.ChildNodes().OfType<InvocationExpressionSyntax>() select aInvokedMethod; foreach (InvocationExpressionSyntax ies in invokedMethods) { Method tempMethod = TraverseInvocationExpression(ies); retMethod.InvokedMethods.AddRange(tempMethod.InvokedMethods); retMethod.AccessedVariables.AddRange(tempMethod.AccessedVariables); } var castExprs = from aCastExpr in ces.ChildNodes().OfType<CastExpressionSyntax>() select aCastExpr; foreach (CastExpressionSyntax ces2 in castExprs) { Method retMethod3 = TraverseCastExpressions(ces2); retMethod.AccessedVariables.AddRange(retMethod3.AccessedVariables); retMethod.InvokedMethods.AddRange(retMethod3.InvokedMethods); } return retMethod; }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitCastExpression(CastExpressionSyntax node) { this.OnNodeVisited(node, this.type.IsInstanceOfType(node)); base.VisitCastExpression(node); }
public virtual void VisitPrefixCastExpression(CastExpressionSyntax node) { DefaultVisit(node); }
public override void VisitCastExpression(CastExpressionSyntax node) { base.VisitCastExpression(node); }
private IEnumerable<ITypeSymbol> InferTypeInCastExpression(CastExpressionSyntax castExpression, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { if (expressionOpt != null && castExpression.Expression != expressionOpt) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // If we have a position, then it has to be after the close paren. if (previousToken.HasValue && previousToken.Value != castExpression.CloseParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return this.GetTypes(castExpression.Type); }
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) { //Note:Js don't care type, throw the type info away. VisitExpression(node.Expression); return node; }
private static SyntaxNode GenerateReplacementNode(CastExpressionSyntax node) { var plusMinusSyntax = node.Expression as PrefixUnaryExpressionSyntax; var literalExpressionSyntax = plusMinusSyntax == null ? (LiteralExpressionSyntax)node.Expression : (LiteralExpressionSyntax)plusMinusSyntax.Operand; var typeToken = node.Type.GetFirstToken(); var prefix = plusMinusSyntax == null ? string.Empty : plusMinusSyntax.OperatorToken.Text; var literalWithoutSuffix = literalExpressionSyntax.StripLiteralSuffix(); var correspondingSuffix = LiteralSyntaxKindToSuffix[typeToken.Kind()]; var fixedCodePreservingText = SyntaxFactory.ParseExpression(prefix + literalWithoutSuffix + correspondingSuffix); return fixedCodePreservingText.WithTriviaFrom(node); }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitCastExpression(CastExpressionSyntax node) { this.OnNodeVisited(node); if (!this.traverseRootOnly) base.VisitCastExpression(node); }
private bool TryGenerateCast(CastExpressionSyntax castExpression) { var type = SemanticModel.GetTypeInfo(castExpression.Type).Type; if (type == null) { return false; } using (CastTag()) { GenerateType(type); return TryGenerateExpression(castExpression.Expression); } }
static Document PerformAction(Document document, SyntaxNode root, CastExpressionSyntax castExpr) { ExpressionSyntax nodeToReplace = castExpr.ReplaceToken(castExpr.Keyword, SyntaxFactory.Token(SyntaxKind.TryCastKeyword)); var newRoot = root.ReplaceNode(castExpr, nodeToReplace); return document.WithSyntaxRoot(newRoot); }
private static bool CastPassedToParamsArrayDefinitelyCantBeRemoved( CastExpressionSyntax cast, ITypeSymbol castType, SemanticModel semanticModel, CancellationToken cancellationToken) { // Special case: When a null literal is cast and passed as the single argument to a params parameter, // we can only remove the cast if it is implicitly convertible to the parameter's type, // but not the parameter's element type. Otherwise, we could end up changing the invocation // to pass a null array rather than an array with a null single element. // // IOW, given the following method... // // static void Foo(params object[] x) { } // // ...we should remove this cast... // // Foo((object[])null); // // ...but not this cast... // // Foo((object)null); if (cast.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression)) { var argument = cast.WalkUpParentheses().Parent as ArgumentSyntax; if (argument != null) { // If there are any arguments to the right, we can assume that this is not a // *single* argument passed to a params parameter. var argumentList = argument.Parent as BaseArgumentListSyntax; if (argumentList != null) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex < argumentList.Arguments.Count - 1) { return false; } } var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); if (parameter != null && parameter.IsParams) { Debug.Assert(parameter.Type is IArrayTypeSymbol); var parameterType = (IArrayTypeSymbol)parameter.Type; var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType); if (conversion.Exists && conversion.IsImplicit) { return false; } var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType); if (conversionElementType.Exists && conversionElementType.IsImplicit) { return true; } } } } return false; }
protected abstract void CompileCastExpression(CastExpressionSyntax expression);