コード例 #1
0
        public SyntaxList <StatementSyntax> InsertGeneratedClassMemberDeclarations(
            SyntaxList <StatementSyntax> convertedStatements, CS.CSharpSyntaxNode originaNode, bool isModule)
        {
            var descendantNodes = originaNode.DescendantNodes().ToList();
            var propertyBlocks  = descendantNodes.OfType <CSS.PropertyDeclarationSyntax>()
                                  .Where(e => e.AccessorList != null && e.AccessorList.Accessors.Any(a => a.Body == null && a.ExpressionBody == null && a.Modifiers.ContainsDeclaredVisibility()))
                                  .ToList();

            return(convertedStatements.InsertRange(0, ConvertToDeclarationStatement(propertyBlocks, isModule)));
        }
コード例 #2
0
 static SyntaxToken GetDefaultModifiers(this CS.CSharpSyntaxNode node)
 {
     //SyntaxToken vbDefaultModifire;
     if (node.Parent == null || node.Parent.IsKind(CS.SyntaxKind.CompilationUnit) || node.Parent.IsKind(CS.SyntaxKind.NamespaceDeclaration))
     {
         return VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword);
     }
     else
     {
         return VB.SyntaxFactory.Token(VB.SyntaxKind.PrivateKeyword);
     }
 }
コード例 #3
0
        private SyntaxList <StatementSyntax> InsertRequiredDeclarations(
            SyntaxList <StatementSyntax> convertedStatements, CS.CSharpSyntaxNode originaNode)
        {
            var descendantNodes        = originaNode.DescendantNodes().ToList();
            var declarationExpressions = descendantNodes.OfType <CSS.DeclarationExpressionSyntax>()
                                         .Where(e => !e.Parent.IsKind(CSSyntaxKind.ForEachVariableStatement)) //Handled inline for tuple loop
                                         .ToList();
            var isPatternExpressions = descendantNodes.OfType <CSS.IsPatternExpressionSyntax>().ToList();

            if (declarationExpressions.Any() || isPatternExpressions.Any())
            {
                convertedStatements = convertedStatements.InsertRange(0, ConvertToDeclarationStatement(declarationExpressions, isPatternExpressions));
            }

            return(convertedStatements);
        }
コード例 #4
0
        private string AdjustIfEventIdentifier(string valueText, CS.CSharpSyntaxNode parent)
        {
            var  symbol  = GetSymbol(parent) as IEventSymbol;
            bool isEvent = symbol.IsKind(SymbolKind.Event);

            if (!isEvent)
            {
                return(valueText);
            }

            var operation = _semanticModel.GetAncestorOperationOrNull <IEventReferenceOperation>(parent);

            if (operation == null || !operation.Event.Equals(symbol) || operation.Parent is IEventAssignmentOperation ||
                operation.Parent is IRaiseEventOperation || operation.Parent is IInvocationOperation ||
                operation.Parent is IConditionalAccessOperation cao && cao.WhenNotNull is IInvocationOperation)
            {
                return(valueText);
            }
コード例 #5
0
        private static T WithConvertTrivia <T>(this T vbNode, CS.CSharpSyntaxNode csNode) where T : SyntaxNode
        {
            var last = csNode.ChildNodesAndTokens().LastOrDefault();

            if (last.IsKind(CS.SyntaxKind.CloseBraceToken))
            {
                var lastToken        = last.AsToken();
                var vbLastTriviaList = ConvertTriviaList(lastToken.LeadingTrivia);
                var vbOldLast        = vbNode.ChildNodes().LastOrDefault();
                var vbNewLast        = vbOldLast.WithLeadingTrivia(vbLastTriviaList);
                vbNode = vbNode.ReplaceNode(vbOldLast, vbNewLast);
            }
            else if (last.IsKind(CS.SyntaxKind.Block))
            {
                var lastBlock        = last.AsNode();
                var vbLastTriviaList = ConvertTriviaList(lastBlock.GetLastToken().LeadingTrivia);
                var vbOldLast        = vbNode.ChildNodes().LastOrDefault();
                var vbNewLast        = vbOldLast.WithLeadingTrivia(vbLastTriviaList);
                vbNode = vbNode.ReplaceNode(vbOldLast, vbNewLast);
            }

            return((T)vbNode.WithLeadingTrivia(csNode.GetLeadingTrivia().ConvertTriviaList())
                   .WithTrailingTrivia(csNode.GetTrailingTrivia().ConvertTriviaList()));
        }
コード例 #6
0
 public override BoundNode VisitEventAccess(BoundEventAccess node)
 {
     syntaxWithReceiver = node.Syntax;
     return(base.VisitEventAccess(node));
 }
コード例 #7
0
 public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
 {
     syntaxWithReceiver = node.Syntax;
     return(base.VisitPropertyAccess(node));
 }
コード例 #8
0
 internal override ImmutableArray <LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
 {
     throw ExceptionUtilities.Unreachable;
 }
コード例 #9
0
            void MarkPatchInlineAssignHelper(CS.CSharpSyntaxNode node)
            {
                var parentDefinition = node.AncestorsAndSelf().OfType <CSS.BaseTypeDeclarationSyntax>().FirstOrDefault();

                inlineAssignHelperMarkers.Add(parentDefinition);
            }
コード例 #10
0
ファイル: Binder.cs プロジェクト: sperling/cskarp
 internal static void Error(DiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax, params object[] args)
 {
     diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), syntax.Location));
 }
コード例 #11
0
 private SpeculativeSyntaxTreeSemanticModel(SyntaxTreeSemanticModel parentSemanticModel, CSharpSyntaxNode root, Binder rootBinder, int position, SpeculativeBindingOption bindingOption)
     : base(parentSemanticModel.Compilation, parentSemanticModel.SyntaxTree, root.SyntaxTree)
 {
     _parentSemanticModel = parentSemanticModel;
     _root          = root;
     _rootBinder    = rootBinder;
     _position      = position;
     _bindingOption = bindingOption;
 }
コード例 #12
0
ファイル: Binder.cs プロジェクト: sperling/cskarp
 internal static void Error(DiagnosticBag diagnostics, DiagnosticInfo info, CSharpSyntaxNode syntax)
 {
     diagnostics.Add(new CSDiagnostic(info, syntax.Location));
 }
コード例 #13
0
ファイル: Binder.cs プロジェクト: sperling/cskarp
 internal static void Error(DiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax)
 {
     diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), syntax.Location));
 }
コード例 #14
0
ファイル: Binder.cs プロジェクト: sperling/cskarp
 /// <summary>
 /// Get locals declared immediately in scope represented by the node.
 /// </summary>
 internal virtual ImmutableArray <LocalSymbol> GetDeclaredLocalsForScope(CSharpSyntaxNode node)
 {
     return(this.Next.GetDeclaredLocalsForScope(node));
 }
コード例 #15
0
ファイル: Binder.cs プロジェクト: sperling/cskarp
 /// <summary>
 /// Some nodes have special binder's for their contents (like Block's)
 /// </summary>
 internal virtual Binder GetBinder(CSharpSyntaxNode node)
 {
     return(this.Next.GetBinder(node));
 }
コード例 #16
0
ファイル: Binder.cs プロジェクト: zarenner/roslyn
 /// <summary>
 /// Get local functions declared immediately in scope designated by the node.
 /// </summary>
 internal virtual ImmutableArray <LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
 {
     return(this.Next.GetDeclaredLocalFunctionsForScope(scopeDesignator));
 }
コード例 #17
0
        internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
        {
            var expression = (ExpressionSyntax)node;

            return(_parentSemanticModel.GetSpeculativeTypeInfoWorker(_position, expression, this.GetSpeculativeBindingOption(expression)));
        }
コード例 #18
0
        private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment(
            CSharpSyntaxNode node,
            ExpressionSyntax left,
            BoundExpression boundRHS,
            ArrayBuilder <DeconstructionVariable> checkedVariables,
            bool resultIsUsed,
            DiagnosticBag diagnostics)
        {
            uint rightEscape = GetValEscape(boundRHS, this.LocalScopeDepth);

            if ((object?)boundRHS.Type == null || boundRHS.Type.IsErrorType())
            {
                // we could still not infer a type for the RHS
                FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape);
                var voidType = GetSpecialType(SpecialType.System_Void, diagnostics, node);

                var type = boundRHS.Type ?? voidType;
                return(new BoundDeconstructionAssignmentOperator(
                           node,
                           DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true),
                           new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, conversionGroupOpt: null,
                                               constantValueOpt: null, type: type, hasErrors: true),
                           resultIsUsed,
                           voidType,
                           hasErrors: true));
            }

            Conversion conversion;
            bool       hasErrors = !MakeDeconstructionConversion(
                boundRHS.Type,
                node,
                boundRHS.Syntax,
                diagnostics,
                checkedVariables,
                out conversion);

            if (conversion.Method != null)
            {
                CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics);
            }

            FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape);

            var lhsTuple = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: diagnostics.HasAnyErrors() || !resultIsUsed);

            Debug.Assert(hasErrors || lhsTuple.Type is object);
            TypeSymbol returnType = hasErrors ? CreateErrorType() : lhsTuple.Type !;

            uint leftEscape = GetBroadestValEscape(lhsTuple, this.LocalScopeDepth);

            boundRHS = ValidateEscape(boundRHS, leftEscape, isByRef: false, diagnostics: diagnostics);

            var boundConversion = new BoundConversion(
                boundRHS.Syntax,
                boundRHS,
                conversion,
                @checked: false,
                explicitCastInCode: false,
                conversionGroupOpt: null,
                constantValueOpt: null,
                type: returnType,
                hasErrors: hasErrors)
            {
                WasCompilerGenerated = true
            };

            return(new BoundDeconstructionAssignmentOperator(node, lhsTuple, boundConversion, resultIsUsed, returnType));
        }
コード例 #19
0
        private static SpeculativeSyntaxTreeSemanticModel CreateCore(SyntaxTreeSemanticModel parentSemanticModel, CSharpSyntaxNode root, Binder rootBinder, int position, SpeculativeBindingOption bindingOption)
        {
            Debug.Assert(parentSemanticModel is SyntaxTreeSemanticModel);
            Debug.Assert(root != null);
            Debug.Assert(root is TypeSyntax || root is CrefSyntax);
            Debug.Assert(rootBinder != null);
            Debug.Assert(rootBinder.IsSemanticModelBinder);

            var speculativeModel = new SpeculativeSyntaxTreeSemanticModel(parentSemanticModel, root, rootBinder, position, bindingOption);

            return(speculativeModel);
        }
コード例 #20
0
        /// <summary>When boundRHS is a tuple literal, fix it up by inferring its types.</summary>
        private BoundExpression FixTupleLiteral(ArrayBuilder <DeconstructionVariable> checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, DiagnosticBag diagnostics)
        {
            if (boundRHS.Kind == BoundKind.TupleLiteral)
            {
                // Let's fix the literal up by figuring out its type
                // For declarations, that means merging type information from the LHS and RHS
                // For assignments, only the LHS side matters since it is necessarily typed

                // If we already have diagnostics at this point, it is not worth collecting likely duplicate diagnostics from making the merged type
                bool       hadErrors       = diagnostics.HasAnyErrors();
                TypeSymbol?mergedTupleType = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, Compilation, hadErrors ? null : diagnostics);
                if ((object?)mergedTupleType != null)
                {
                    boundRHS = GenerateConversionForAssignment(mergedTupleType, boundRHS, diagnostics);
                }
            }
            else if ((object?)boundRHS.Type == null)
            {
                Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, boundRHS.Syntax);
            }

            return(boundRHS);
        }
コード例 #21
0
        /// <summary>
        /// Find the Deconstruct method for the expression on the right, that will fit the number of assignable variables on the left.
        /// Returns an invocation expression if the Deconstruct method is found.
        ///     If so, it outputs placeholders that were coerced to the output types of the resolved Deconstruct method.
        /// The overload resolution is similar to writing `receiver.Deconstruct(out var x1, out var x2, ...)`.
        /// </summary>
        private BoundExpression MakeDeconstructInvocationExpression(
            int numCheckedVariables, BoundExpression receiver, CSharpSyntaxNode syntax,
            DiagnosticBag diagnostics, out ImmutableArray <BoundDeconstructValuePlaceholder> outPlaceholders)
        {
            var receiverSyntax = receiver.Syntax;

            if (receiver.Type.IsDynamic())
            {
                Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, receiverSyntax);
                outPlaceholders = default(ImmutableArray <BoundDeconstructValuePlaceholder>);

                return(BadExpression(receiverSyntax, receiver));
            }

            var analyzedArguments = AnalyzedArguments.GetInstance();
            var outVars           = ArrayBuilder <OutDeconstructVarPendingInference> .GetInstance(numCheckedVariables);

            try
            {
                for (int i = 0; i < numCheckedVariables; i++)
                {
                    var variable = new OutDeconstructVarPendingInference(syntax);
                    analyzedArguments.Arguments.Add(variable);
                    analyzedArguments.RefKinds.Add(RefKind.Out);
                    outVars.Add(variable);
                }

                const string methodName   = "Deconstruct";
                var          memberAccess = BindInstanceMemberAccess(
                    receiverSyntax, receiverSyntax, receiver, methodName, rightArity: 0,
                    typeArgumentsSyntax: default(SeparatedSyntaxList <TypeSyntax>), typeArguments: default(ImmutableArray <TypeSymbol>),
                    invoked: true, diagnostics: diagnostics);

                memberAccess = CheckValue(memberAccess, BindValueKind.RValueOrMethodGroup, diagnostics);
                memberAccess.WasCompilerGenerated = true;

                if (memberAccess.Kind != BoundKind.MethodGroup)
                {
                    return(MissingDeconstruct(receiver, syntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver));
                }

                // After the overload resolution completes, the last step is to coerce the arguments with inferred types.
                // That step returns placeholder (of correct type) instead of the outVar nodes that were passed in as arguments.
                // So the generated invocation expression will contain placeholders instead of those outVar nodes.
                // Those placeholders are also recorded in the outVar for easy access below, by the `SetInferredType` call on the outVar nodes.
                BoundExpression result = BindMethodGroupInvocation(
                    receiverSyntax, receiverSyntax, methodName, (BoundMethodGroup)memberAccess, analyzedArguments, diagnostics, queryClause: null,
                    allowUnexpandedForm: true);

                result.WasCompilerGenerated = true;

                if (result.HasErrors && !receiver.HasAnyErrors)
                {
                    return(MissingDeconstruct(receiver, syntax, numCheckedVariables, diagnostics, out outPlaceholders, result));
                }

                // Verify all the parameters (except "this" for extension methods) are out parameters
                if (result.Kind != BoundKind.Call)
                {
                    return(MissingDeconstruct(receiver, syntax, numCheckedVariables, diagnostics, out outPlaceholders, result));
                }

                var deconstructMethod = ((BoundCall)result).Method;
                var parameters        = deconstructMethod.Parameters;
                for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++)
                {
                    if (parameters[i].RefKind != RefKind.Out)
                    {
                        return(MissingDeconstruct(receiver, syntax, numCheckedVariables, diagnostics, out outPlaceholders, result));
                    }
                }

                if (outVars.Any(v => (object)v.Placeholder == null))
                {
                    return(MissingDeconstruct(receiver, syntax, numCheckedVariables, diagnostics, out outPlaceholders, result));
                }

                outPlaceholders = outVars.SelectAsArray(v => v.Placeholder);

                return(result);
            }
            finally
            {
                analyzedArguments.Free();
                outVars.Free();
            }
        }
コード例 #22
0
 internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax)
 {
     Single          = variable;
     NestedVariables = null;
     Syntax          = (CSharpSyntaxNode)syntax;
 }
コード例 #23
0
 private static IEnumerable <CSS.BlockSyntax> GetDeepestBlocks(CS.CSharpSyntaxNode body)
 {
     return(body.DescendantNodesAndSelf().OfType <CSS.BlockSyntax>().Where(x => x.DescendantNodes().OfType <CSS.BlockSyntax>().IsEmpty()));
 }
コード例 #24
0
 public static VisualBasicSyntaxNode Convert(CS.CSharpSyntaxNode input, SemanticModel semanticModel, Document targetDocument)
 {
     return(input.Accept(new NodesVisitor(semanticModel, targetDocument)));
 }
コード例 #25
0
        public LambdaExpressionSyntax ConvertLambdaExpression(CSS.AnonymousFunctionExpressionSyntax node, CS.CSharpSyntaxNode body, IEnumerable <ParameterSyntax> parameters, SyntaxTokenList modifiers)
        {
            var symbol        = (IMethodSymbol)ModelExtensions.GetSymbolInfo(_semanticModel, node).Symbol;
            var parameterList = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Select(p => (Microsoft.CodeAnalysis.VisualBasic.Syntax.ParameterSyntax)p.Accept(_nodesVisitor))));
            LambdaHeaderSyntax      header;
            EndBlockStatementSyntax endBlock;
            SyntaxKind multiLineExpressionKind;
            SyntaxKind singleLineExpressionKind;
            bool       isSub = symbol.ReturnsVoid;

            if (isSub)
            {
                header = SyntaxFactory.SubLambdaHeader(SyntaxFactory.List <AttributeListSyntax>(),
                                                       ConvertModifiers(modifiers, TokenContext.Local), parameterList, null);
                endBlock = SyntaxFactory.EndBlockStatement(SyntaxKind.EndSubStatement,
                                                           SyntaxFactory.Token(SyntaxKind.SubKeyword));
                multiLineExpressionKind  = SyntaxKind.MultiLineSubLambdaExpression;
                singleLineExpressionKind = SyntaxKind.SingleLineSubLambdaExpression;
            }
            else
            {
                header = CreateFunctionHeader(modifiers, parameterList, out endBlock, out multiLineExpressionKind);
                singleLineExpressionKind = SyntaxKind.SingleLineFunctionLambdaExpression;
            }

            SyntaxList <StatementSyntax> statements;

            if (body is CSS.BlockSyntax block)
            {
                statements = ConvertStatements(block.Statements);
            }
            else if (body.Kind() == CSSyntaxKind.ThrowExpression)
            {
                var csThrowExpression = (CSS.ThrowExpressionSyntax)body;
                var vbThrowExpression = (ExpressionSyntax)csThrowExpression.Expression.Accept(_nodesVisitor);
                var vbThrowStatement  = SyntaxFactory.ThrowStatement(SyntaxFactory.Token(SyntaxKind.ThrowKeyword), vbThrowExpression);

                return(SyntaxFactory.MultiLineFunctionLambdaExpression(header,
                                                                       SyntaxFactory.SingletonList <StatementSyntax>(vbThrowStatement), endBlock));
            }
            else
            {
                var stmt = GetStatementSyntax(body.Accept(_nodesVisitor),
                                              expression => isSub ? (StatementSyntax)SyntaxFactory.ExpressionStatement(expression) : SyntaxFactory.ReturnStatement(expression));
                statements = InsertRequiredDeclarations(SyntaxFactory.SingletonList(stmt), body);
            }

            return(CreateLambdaExpression(singleLineExpressionKind, multiLineExpressionKind, header, statements, endBlock));
        }
コード例 #26
0
        /// <summary>
        /// There are two kinds of deconstruction-assignments which this binding handles: tuple and non-tuple.
        ///
        /// Returns a BoundDeconstructionAssignmentOperator with a list of deconstruction steps and assignment steps.
        /// Deconstruct steps for tuples have no invocation to Deconstruct, but steps for non-tuples do.
        /// The caller is responsible for releasing all the ArrayBuilders in checkedVariables.
        /// </summary>
        private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment(
            CSharpSyntaxNode node,
            ExpressionSyntax right,
            ArrayBuilder <DeconstructionVariable> checkedVariables,
            DiagnosticBag diagnostics,
            bool isDeclaration,
            BoundDeconstructValuePlaceholder rhsPlaceholder = null)
        {
            // receiver for first Deconstruct step
            var boundRHS = rhsPlaceholder ?? BindValue(right, diagnostics, BindValueKind.RValue);

            boundRHS = FixTupleLiteral(checkedVariables, boundRHS, node, diagnostics);

            if ((object)boundRHS.Type == null)
            {
                // we could still not infer a type for the RHS
                FailRemainingInferences(checkedVariables, diagnostics);

                return(new BoundDeconstructionAssignmentOperator(
                           node, isDeclaration, FlattenDeconstructVariables(checkedVariables), boundRHS,
                           ImmutableArray <BoundDeconstructionDeconstructStep> .Empty,
                           ImmutableArray <BoundDeconstructionAssignmentStep> .Empty,
                           ImmutableArray <BoundDeconstructionAssignmentStep> .Empty,
                           ImmutableArray <BoundDeconstructionConstructionStep> .Empty,
                           GetSpecialType(SpecialType.System_Void, diagnostics, node),
                           hasErrors: true));
            }

            var deconstructionSteps = ArrayBuilder <BoundDeconstructionDeconstructStep> .GetInstance(1);

            var conversionSteps = ArrayBuilder <BoundDeconstructionAssignmentStep> .GetInstance(1);

            var assignmentSteps = ArrayBuilder <BoundDeconstructionAssignmentStep> .GetInstance(1);

            var constructionStepsOpt = isDeclaration ? null : ArrayBuilder <BoundDeconstructionConstructionStep> .GetInstance(1);

            bool hasErrors = !DeconstructIntoSteps(
                new BoundDeconstructValuePlaceholder(boundRHS.Syntax, boundRHS.Type),
                node,
                diagnostics,
                checkedVariables,
                deconstructionSteps,
                conversionSteps,
                assignmentSteps,
                constructionStepsOpt);

            TypeSymbol returnType = isDeclaration ?
                                    GetSpecialType(SpecialType.System_Void, diagnostics, node) :
                                    hasErrors?
                                    CreateErrorType() :
                                        constructionStepsOpt.Last().OutputPlaceholder.Type;

            var deconstructions = deconstructionSteps.ToImmutableAndFree();
            var conversions     = conversionSteps.ToImmutableAndFree();
            var assignments     = assignmentSteps.ToImmutableAndFree();
            var constructions   = isDeclaration ? default(ImmutableArray <BoundDeconstructionConstructionStep>) : constructionStepsOpt.ToImmutableAndFree();

            FailRemainingInferences(checkedVariables, diagnostics);

            return(new BoundDeconstructionAssignmentOperator(
                       node, isDeclaration, FlattenDeconstructVariables(checkedVariables), boundRHS,
                       deconstructions, conversions, assignments, constructions, returnType, hasErrors: hasErrors));
        }
コード例 #27
0
 internal DeconstructionVariable(ArrayBuilder <DeconstructionVariable> variables, SyntaxNode syntax)
 {
     Single          = null;
     NestedVariables = variables;
     Syntax          = (CSharpSyntaxNode)syntax;
 }
コード例 #28
0
ファイル: Binder_QueryErrors.cs プロジェクト: belav/roslyn
        internal static void ReportQueryInferenceFailed(
            CSharpSyntaxNode queryClause,
            string methodName,
            BoundExpression receiver,
            AnalyzedArguments arguments,
            ImmutableArray <Symbol> symbols,
            BindingDiagnosticBag diagnostics
            )
        {
            string clauseKind = null;
            bool   multiple   = false;

            switch (queryClause.Kind())
            {
            case SyntaxKind.JoinClause:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.JoinKeyword);
                multiple   = true;
                break;

            case SyntaxKind.LetClause:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.LetKeyword);
                break;

            case SyntaxKind.SelectClause:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.SelectKeyword);
                break;

            case SyntaxKind.WhereClause:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.WhereKeyword);
                break;

            case SyntaxKind.OrderByClause:
            case SyntaxKind.AscendingOrdering:
            case SyntaxKind.DescendingOrdering:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.OrderByKeyword);
                multiple   = true;
                break;

            case SyntaxKind.QueryContinuation:
                clauseKind = SyntaxFacts.GetText(SyntaxKind.IntoKeyword);
                break;

            case SyntaxKind.GroupClause:
                clauseKind =
                    SyntaxFacts.GetText(SyntaxKind.GroupKeyword)
                    + " "
                    + SyntaxFacts.GetText(SyntaxKind.ByKeyword);
                multiple = true;
                break;

            case SyntaxKind.FromClause:
                if (
                    ReportQueryInferenceFailedSelectMany(
                        (FromClauseSyntax)queryClause,
                        methodName,
                        receiver,
                        arguments,
                        symbols,
                        diagnostics
                        )
                    )
                {
                    return;
                }
                clauseKind = SyntaxFacts.GetText(SyntaxKind.FromKeyword);
                break;

            default:
                throw ExceptionUtilities.UnexpectedValue(queryClause.Kind());
            }

            diagnostics.Add(
                new DiagnosticInfoWithSymbols(
                    multiple
                      ? ErrorCode.ERR_QueryTypeInferenceFailedMulti
                      : ErrorCode.ERR_QueryTypeInferenceFailed,
                    new object[] { clauseKind, methodName },
                    symbols
                    ),
                queryClause.GetFirstToken().GetLocation()
                );
        }
コード例 #29
0
        public static VB.VisualBasicSyntaxNode Convert(this CS.CSharpSyntaxNode node)
        {
            if (node == null)
            {
                return(null);
            }

            switch (node.Kind())
            {
            case CS.SyntaxKind.CompilationUnit:
                return(((CSS.CompilationUnitSyntax)node).ConvertCompilationUnit());

            case CS.SyntaxKind.UsingDirective:
                return(((CSS.UsingDirectiveSyntax)node).ConvertUsingDirective());

                #region Block
            case CS.SyntaxKind.NamespaceDeclaration:
                return(((CSS.NamespaceDeclarationSyntax)node).ConvertNamespaceDeclaration());

            case CS.SyntaxKind.ClassDeclaration:
            case CS.SyntaxKind.InterfaceDeclaration:
            case CS.SyntaxKind.StructDeclaration:
                return(((CSS.BaseTypeDeclarationSyntax)node).ConvertTypeDeclaration());

            case CS.SyntaxKind.EnumDeclaration:
                return(((CSS.EnumDeclarationSyntax)node).ConvertEnumDeclaration());

            case CS.SyntaxKind.MethodDeclaration:
                return(((CSS.MethodDeclarationSyntax)node).ConvertMethodDeclaration());

            case CS.SyntaxKind.ConstructorDeclaration:
                return(((CSS.ConstructorDeclarationSyntax)node).ConvertConstructor());

            case CS.SyntaxKind.BaseConstructorInitializer:
            case CS.SyntaxKind.ThisConstructorInitializer:
                return(((CSS.ConstructorInitializerSyntax)node).ConvertConstructorInitializer());

            case CS.SyntaxKind.DestructorDeclaration:
                return(((CSS.DestructorDeclarationSyntax)node).ConvertDestructor());

            case CS.SyntaxKind.Block:
                return(ConvertBlock((CSS.BlockSyntax)node));

                #region Field, Property
            case CS.SyntaxKind.EventFieldDeclaration:
                return(((CSS.EventFieldDeclarationSyntax)node).ConvertEventFieldDeclaration());

            case CS.SyntaxKind.EventDeclaration:
                return(((CSS.EventDeclarationSyntax)node).ConvertEventBlock());

            case CS.SyntaxKind.AddAccessorDeclaration:
            case CS.SyntaxKind.RemoveAccessorDeclaration:
                return(ConvertEventAccessor((CSS.AccessorDeclarationSyntax)node));

            case CS.SyntaxKind.IndexerDeclaration:
                return(((CSS.IndexerDeclarationSyntax)node).ConvertIndexer());

            case CS.SyntaxKind.PropertyDeclaration:
                return(((CSS.PropertyDeclarationSyntax)node).ConvertProperty());

            case CS.SyntaxKind.GetAccessorDeclaration:
            case CS.SyntaxKind.SetAccessorDeclaration:
                return(((CSS.AccessorDeclarationSyntax)node).ConvertGetSet());

            case CS.SyntaxKind.AccessorList:
                //Need call ConvertAccessorList
                return(null);

            case CS.SyntaxKind.FieldDeclaration:
                return(ConvertFieldDeclaration((CSS.FieldDeclarationSyntax)node));

            case CS.SyntaxKind.VariableDeclaration:
                return(ConvertVariableDeclaration((CSS.VariableDeclarationSyntax)node));

            case CS.SyntaxKind.VariableDeclarator:
                return(ConvertVariableDeclarator((CSS.VariableDeclaratorSyntax)node));

            case CS.SyntaxKind.LocalDeclarationStatement:
                return(((CSS.LocalDeclarationStatementSyntax)node).ConvertLocalDeclaration());

            case CS.SyntaxKind.EnumMemberDeclaration:
                return(((CSS.EnumMemberDeclarationSyntax)node).ConvertEnumMemberDeclaration());

            case CS.SyntaxKind.DelegateDeclaration:
                return(((CSS.DelegateDeclarationSyntax)node).ConvertDelegateDeclaration());

            case CS.SyntaxKind.OperatorDeclaration:
                return(((CSS.OperatorDeclarationSyntax)node).ConvertOperator());


                #endregion

                #endregion

                #region Flow
            case CS.SyntaxKind.IfStatement:
                return(((CSS.IfStatementSyntax)node).ConvertIfStatement());

            case CS.SyntaxKind.ElseClause:
                return(((CSS.ElseClauseSyntax)node).ConvertElseClauseStatement());

            case CS.SyntaxKind.SwitchStatement:
                return(((CSS.SwitchStatementSyntax)node).ConvertSwitchStatementAndRewriteGoto());

            case CS.SyntaxKind.SwitchSection:
                return(((CSS.SwitchSectionSyntax)node).ConvertSwitchSelection());

            case CS.SyntaxKind.CaseSwitchLabel:
                return(((CSS.CaseSwitchLabelSyntax)node).ConvertCaseSwitchLabel());

            case CS.SyntaxKind.DefaultSwitchLabel:
                return(VB.SyntaxFactory.ElseCaseClause());

            case CS.SyntaxKind.GotoCaseStatement:
            case CS.SyntaxKind.GotoDefaultStatement:
                //Need call ConvertSwitchStatementAndRewriteGoto
                return(null);

            case CS.SyntaxKind.GotoStatement:
                return(((CSS.GotoStatementSyntax)node).ConvertGoto());

            case CS.SyntaxKind.LabeledStatement:
                return(((CSS.LabeledStatementSyntax)node).ConvertLabel());

            case CS.SyntaxKind.BreakStatement:
                return(((CSS.BreakStatementSyntax)node).ConvertBreak());

            case CS.SyntaxKind.ContinueStatement:
                return(((CSS.ContinueStatementSyntax)node).ConvertContinue());

            case CS.SyntaxKind.ForStatement:
                return(((CSS.ForStatementSyntax)node).ConvertFor());

            case CS.SyntaxKind.ForEachStatement:
                return(((CSS.ForEachStatementSyntax)node).ConvertForEach());

            case CS.SyntaxKind.DoStatement:
                return(((CSS.DoStatementSyntax)node).ConvertDo());

            case CS.SyntaxKind.WhileStatement:
                return(((CSS.WhileStatementSyntax)node).ConvertWhile());

            case CS.SyntaxKind.ReturnStatement:
                return(((CSS.ReturnStatementSyntax)node).ConvertReturn());

            case CS.SyntaxKind.YieldBreakStatement:
                return(VB.SyntaxFactory.ExitFunctionStatement());

            case CS.SyntaxKind.YieldReturnStatement:
                return(((CSS.YieldStatementSyntax)node).ConvertYield());


                #endregion

                #region  try-catch-finally
            case CS.SyntaxKind.ThrowStatement:
                return(((CSS.ThrowStatementSyntax)node).ConvertThrow());

            case CS.SyntaxKind.TryStatement:
                return(((CSS.TryStatementSyntax)node).ConvertTry());

            case CS.SyntaxKind.CatchClause:
                return(((CSS.CatchClauseSyntax)node).ConvertCatchClause());

            case CS.SyntaxKind.CatchDeclaration:
                return(((CSS.CatchDeclarationSyntax)node).ConvertCatchDeclaration());

            case CS.SyntaxKind.CatchFilterClause:
                return(((CSS.CatchFilterClauseSyntax)node).ConvertCatchFilter());

            case CS.SyntaxKind.FinallyClause:
                return(((CSS.FinallyClauseSyntax)node).ConvertFinally());

                #endregion

                #region Attribute

            case CS.SyntaxKind.AttributeList:
            {
                var csAttributeList = (CSS.AttributeListSyntax)node;
                var vbAttributes    = csAttributeList.Attributes.ConvertSyntaxNodes <VBS.AttributeSyntax>().ToArray();

                var vbTarget = (VBS.AttributeTargetSyntax)csAttributeList.Target.Convert();

                if (vbAttributes != null && vbTarget != null)
                {
                    for (int i = 0; i < vbAttributes.Length; i++)
                    {
                        vbAttributes[i] = vbAttributes[i].WithTarget(vbTarget);
                    }
                }
                return(VB.SyntaxFactory.AttributeList().AddAttributes(vbAttributes));
            }

            case CS.SyntaxKind.AttributeTargetSpecifier:
            {
                // https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
                var csTarget   = (CSS.AttributeTargetSpecifierSyntax)node;
                var targetText = csTarget.Identifier.ValueText;

                switch (targetText)
                {
                case "assembly":
                    return(VB.SyntaxFactory.AttributeTarget(VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword)));

                case "module":
                    return(VB.SyntaxFactory.AttributeTarget(VB.SyntaxFactory.Token(VB.SyntaxKind.ModuleKeyword)));

                case "field":
                    return(VB.SyntaxFactory.AttributeTarget(VB.SyntaxFactory.Token(VB.SyntaxKind.FieldDeclaration)));

                case "event":
                case "method":
                case "param":
                case "property":
                case "return":
                case "Type":
                    break;
                }
                return(null);
            }

            case CS.SyntaxKind.Attribute:
            {
                var csAttribute = (CSS.AttributeSyntax)node;
                var vbName      = (VBS.NameSyntax)csAttribute.Name.Convert();
                var vbArgs      = (VBS.ArgumentListSyntax)csAttribute.ArgumentList.Convert();
                var vbAttribute = VB.SyntaxFactory.Attribute(vbName);
                vbAttribute = vbAttribute.WithArgumentList(vbArgs);
                return(vbAttribute);
            }

            case CS.SyntaxKind.AttributeArgumentList:
            {
                var csArguments = (CSS.AttributeArgumentListSyntax)node;
                var vbArgs      = csArguments.Arguments.Convert <CSS.AttributeArgumentSyntax, VBS.ArgumentSyntax>().ToArray();
                return(VB.SyntaxFactory.ArgumentList().AddArguments(vbArgs));
            }

            case CS.SyntaxKind.AttributeArgument:
            {
                var csAttributeArgument = (CSS.AttributeArgumentSyntax)node;
                var vbExpression        = (VBS.ExpressionSyntax)csAttributeArgument.Expression.ConvertAssignRightExpression();
                var vbNameEQ            = (VBS.NameColonEqualsSyntax)csAttributeArgument.NameEquals.Convert();

                var vbNameColon = (VBS.NameColonEqualsSyntax)csAttributeArgument.NameColon.Convert();
                if (vbNameColon != null)
                {
                }
                return(VB.SyntaxFactory.SimpleArgument(vbExpression).WithNameColonEquals(vbNameEQ));
            }


            case CS.SyntaxKind.NameColon:
                return(((CSS.NameColonSyntax)node).ConvertNameCollon());

                #endregion

                #region Type
            case CS.SyntaxKind.TypeParameterList://genericの型
                return(((CSS.TypeParameterListSyntax)node).ConvertTypeParameterList());

            case CS.SyntaxKind.TypeParameter:
                return(((CSS.TypeParameterSyntax)node).ConvertTypeParameter());

            case CS.SyntaxKind.BaseList://継承の型一覧
                return(((CSS.BaseListSyntax)node).ConvertBaseList());

            case CS.SyntaxKind.SimpleBaseType://単純な型
                return(((CSS.SimpleBaseTypeSyntax)node).ConvertSimpleBaseType());

            case CS.SyntaxKind.TypeArgumentList://ジェネリックの型引数
                return(((CSS.TypeArgumentListSyntax)node).ConvertTypeArgumentList());

            case CS.SyntaxKind.PredefinedType://標準型?
                return(((CSS.PredefinedTypeSyntax)node).ConvertPredefinedTypeType());

            case CS.SyntaxKind.ArrayType://配列
                return(((CSS.ArrayTypeSyntax)node).ConvertArrayType());

            case CS.SyntaxKind.ArrayRankSpecifier://配列型の次元
                return(((CSS.ArrayRankSpecifierSyntax)node).ConvertArrayRank());

            case CS.SyntaxKind.NullableType://Null許容型
                return(((CSS.NullableTypeSyntax)node).ConvertNullableType());

                #endregion

                #region Parameter

            case CS.SyntaxKind.ParameterList://関数等の引数の一覧
                return(((CSS.ParameterListSyntax)node).ConvertParameterList());

            case CS.SyntaxKind.Parameter://関数等の引数
                return(ConvertParameter((CSS.ParameterSyntax)node));

            case CS.SyntaxKind.TypeParameterConstraintClause:
                return(((CSS.TypeParameterConstraintClauseSyntax)node).ConvertTypeParameterConstraintClauseSyntax());

            case CS.SyntaxKind.ClassConstraint:
                return(VB.SyntaxFactory.ClassConstraint(VB.SyntaxFactory.Token(VB.SyntaxKind.ClassKeyword)));

            case CS.SyntaxKind.StructConstraint:
                return(VB.SyntaxFactory.StructureConstraint(VB.SyntaxFactory.Token(VB.SyntaxKind.StructureKeyword)));

            case CS.SyntaxKind.ConstructorConstraint:
                return(VB.SyntaxFactory.NewConstraint(VB.SyntaxFactory.Token(VB.SyntaxKind.NewKeyword)));

            case CS.SyntaxKind.TypeConstraint:
            {
                var csTypeParameterConsraint = (CSS.TypeParameterConstraintSyntax)node;
                var csTypeConstraint         = (CSS.TypeConstraintSyntax)node;
                var vbType = (VBS.TypeSyntax)csTypeConstraint.Type.Convert();
                return(VB.SyntaxFactory.TypeConstraint(vbType));
            }
                #endregion

                #region Name

            case CS.SyntaxKind.IdentifierName://ユニークな名前
                return(((CSS.IdentifierNameSyntax)node).ConvertIdentifierName());

            case CS.SyntaxKind.GenericName://ジェネリック型の型引数を除いた名前
                return(((CSS.GenericNameSyntax)node).ConvertGenericName());

            case CS.SyntaxKind.QualifiedName://NameSpaceや型名付の名前
                return(((CSS.QualifiedNameSyntax)node).ConvertQualifiedName());

            case CS.SyntaxKind.AliasQualifiedName:
                return(((CSS.AliasQualifiedNameSyntax)node).ConvertAliasQualifiedName());

                #endregion

                #region Expression
            case CS.SyntaxKind.ThisExpression:
                return(VB.SyntaxFactory.MeExpression());

            case CS.SyntaxKind.BaseExpression:
                return(VB.SyntaxFactory.MyBaseExpression());

            case CS.SyntaxKind.ExpressionStatement:
                return(((CSS.ExpressionStatementSyntax)node).ConvertExpressionStatement());

            case CS.SyntaxKind.DefaultExpression: //default(T)
                return(((CSS.DefaultExpressionSyntax)node).ConvertDefaultExpression());

            case CS.SyntaxKind.CastExpression:
                return(((CSS.CastExpressionSyntax)node).ConvertCast());

            case CS.SyntaxKind.AsExpression:
                return(((CSS.BinaryExpressionSyntax)node).ConvertAs());

            case CS.SyntaxKind.SimpleAssignmentExpression:
                return(((CSS.AssignmentExpressionSyntax)node).ConvertSimpleAssignment());

            case CS.SyntaxKind.AddAssignmentExpression:         // +=
            case CS.SyntaxKind.SubtractAssignmentExpression:    // -=
            case CS.SyntaxKind.MultiplyAssignmentExpression:    // *=
            case CS.SyntaxKind.DivideAssignmentExpression:      // /=
            case CS.SyntaxKind.LeftShiftAssignmentExpression:   // <<=
            case CS.SyntaxKind.RightShiftAssignmentExpression:  // >>=
            case CS.SyntaxKind.ModuloAssignmentExpression:      // Mod
            case CS.SyntaxKind.AndAssignmentExpression:         // &=
            case CS.SyntaxKind.OrAssignmentExpression:          // |=
            case CS.SyntaxKind.ExclusiveOrAssignmentExpression: // ^=
                return(ConvertAssignmentExpression((CSS.AssignmentExpressionSyntax)node));

            case CS.SyntaxKind.NameEquals:
                return(((CSS.NameEqualsSyntax)node).ConvertNameEquals());

            case CS.SyntaxKind.EqualsValueClause:
                return(((CSS.EqualsValueClauseSyntax)node).ConvertEqualsValue());

            case CS.SyntaxKind.ObjectCreationExpression:
                return(((CSS.ObjectCreationExpressionSyntax)node).ConvertObjectCreation());

            case CS.SyntaxKind.ObjectInitializerExpression:
                return(((CSS.InitializerExpressionSyntax)node).ConvertObjectCreationInitializer());

            case CS.SyntaxKind.ArrayInitializerExpression://int[] array ={1,2,3}
                return(((CSS.InitializerExpressionSyntax)node).ConvertArrayInitializer());

            case CS.SyntaxKind.ArrayCreationExpression:
                return(((CSS.ArrayCreationExpressionSyntax)node).ConvertArrayCreation());

            case CS.SyntaxKind.ArgumentList:          //引数一覧
            case CS.SyntaxKind.BracketedArgumentList: //accessing argument for array or indexer
                return(((CSS.BaseArgumentListSyntax)node).ConvertBaeArgumentList());

            case CS.SyntaxKind.BracketedParameterList:// [int a, int b]
                return(((CSS.BracketedParameterListSyntax)node).ConvertBracketedParameter());

            case CS.SyntaxKind.OmittedArraySizeExpression:
                return(null);// VB.SyntaxFactory.OmittedArgument();

            case CS.SyntaxKind.Argument:
                return(((CSS.ArgumentSyntax)node).ConvertArgument());

            case CS.SyntaxKind.InvocationExpression:
                return(((CSS.InvocationExpressionSyntax)node).ConvertInvocationExpretion());

            case CS.SyntaxKind.SimpleMemberAccessExpression:
                return(((CSS.MemberAccessExpressionSyntax)node).ConvertMemberAccess());

            case CS.SyntaxKind.ElementAccessExpression:
                return(((CSS.ElementAccessExpressionSyntax)node).ConvertElementAccess());

            case CS.SyntaxKind.ParenthesizedExpression:
                return(((CSS.ParenthesizedExpressionSyntax)node).ConvertParenthesized());

            case CS.SyntaxKind.NullLiteralExpression://null
                return(ConvertNullLiteral());

            case CS.SyntaxKind.TrueLiteralExpression:// true
                return(ConvertTrueLiteral());

            case CS.SyntaxKind.FalseLiteralExpression:// false
                return(ConvertFalseLiteral());

            case CS.SyntaxKind.UnaryPlusExpression:
                return(((CSS.PrefixUnaryExpressionSyntax)node).ConvertUnraryPlus());

            case CS.SyntaxKind.UnaryMinusExpression:
                return(((CSS.PrefixUnaryExpressionSyntax)node).ConvertUnraryMinus());

            case CS.SyntaxKind.NumericLiteralExpression:
                return(((CSS.LiteralExpressionSyntax)node).ConvertLiteral());

            case CS.SyntaxKind.CharacterLiteralExpression:
                return(((CSS.LiteralExpressionSyntax)node).ConvertLiteralChar());

            case CS.SyntaxKind.StringLiteralExpression:
                return(((CSS.LiteralExpressionSyntax)node).ConvertLiteralString());

            case CS.SyntaxKind.TypeOfExpression:
                return(((CSS.TypeOfExpressionSyntax)node).ConvertTypeOf());

            case CS.SyntaxKind.IsExpression:                 // Is
            case CS.SyntaxKind.AddExpression:                // +
            case CS.SyntaxKind.SubtractExpression:           // -
            case CS.SyntaxKind.MultiplyExpression:           // *
            case CS.SyntaxKind.DivideExpression:             // /
            case CS.SyntaxKind.ModuloExpression:             // %
            case CS.SyntaxKind.LeftShiftExpression:          // <<
            case CS.SyntaxKind.RightShiftExpression:         // >>
            case CS.SyntaxKind.BitwiseAndExpression:         //&
            case CS.SyntaxKind.BitwiseOrExpression:          //|
            case CS.SyntaxKind.ExclusiveOrExpression:        // ^
            case CS.SyntaxKind.LogicalAndExpression:         //&&
            case CS.SyntaxKind.LogicalOrExpression:          //||
            case CS.SyntaxKind.EqualsExpression:             // ==
            case CS.SyntaxKind.NotEqualsExpression:          // !=
            case CS.SyntaxKind.GreaterThanExpression:        // >
            case CS.SyntaxKind.GreaterThanOrEqualExpression: // >=
            case CS.SyntaxKind.LessThanExpression:           // <
            case CS.SyntaxKind.LessThanOrEqualExpression:    // <=
            case CS.SyntaxKind.CoalesceExpression:           // ??
                return(ConvertBinaryExpression((CSS.BinaryExpressionSyntax)node));

            case CS.SyntaxKind.BitwiseNotExpression: // !
            case CS.SyntaxKind.LogicalNotExpression: // ~
                return(((CSS.PrefixUnaryExpressionSyntax)node).ConvertNot());

            case CS.SyntaxKind.PreIncrementExpression: // ++A
                return(((CSS.PrefixUnaryExpressionSyntax)node).ConvertPreIncrement());

            case CS.SyntaxKind.PreDecrementExpression: // --A
                return(((CSS.PrefixUnaryExpressionSyntax)node).ConvertPreDecrement());

            case CS.SyntaxKind.PostIncrementExpression: // A++
                return(((CSS.PostfixUnaryExpressionSyntax)node).ConvertPostIncrement());

            case CS.SyntaxKind.PostDecrementExpression: // A--
                return(((CSS.PostfixUnaryExpressionSyntax)node).ConvertPostDecrement());

            case CS.SyntaxKind.ConditionalExpression: // ?:
                return(((CSS.ConditionalExpressionSyntax)node).ConvertConditional());


            case CS.SyntaxKind.AnonymousObjectCreationExpression:
                return(((CSS.AnonymousObjectCreationExpressionSyntax)node).ConvertAnonymousObjectCreationExpressionSyntax());

            case CS.SyntaxKind.AnonymousObjectMemberDeclarator:
                return(((CSS.AnonymousObjectMemberDeclaratorSyntax)node).ConvertAnonymousObjectMemberDeclaratorSyntax());

                #endregion

            case CS.SyntaxKind.ExplicitInterfaceSpecifier:
                return(((CSS.ExplicitInterfaceSpecifierSyntax)node).ConvertExplicitInterfaceSpecifier());

            case CS.SyntaxKind.UsingStatement:
                return(((CSS.UsingStatementSyntax)node).ConvertUsingBlock());

            case CS.SyntaxKind.LockStatement:
                return(((CSS.LockStatementSyntax)node).ConvertLock());

            case CS.SyntaxKind.EmptyStatement:
                return(VB.SyntaxFactory.EmptyStatement());

                #region Lambda

            case CS.SyntaxKind.ConversionOperatorDeclaration:
                return(((CSS.ConversionOperatorDeclarationSyntax)node).ConvertConversionOperator());

            case CS.SyntaxKind.ParenthesizedLambdaExpression:
            case CS.SyntaxKind.SimpleLambdaExpression:
                return(((CSS.LambdaExpressionSyntax)node).ConvertLambdaExpression());

                #endregion

            case CS.SyntaxKind.InterpolatedStringExpression:
                if (true)
                {
                    //Convert to flat Interpolate
                    return(((CSS.InterpolatedStringExpressionSyntax)node).ConvertInterpolatedStringExpression());
                }
                else
                {
                    //Convert to nested Interpolate
                    var nodex      = (CSS.InterpolatedStringExpressionSyntax)node;
                    var vbContents = nodex.Contents.ConvertSyntaxNodes <VBS.InterpolatedStringContentSyntax>();
                    return(VB.SyntaxFactory.InterpolatedStringExpression().AddContents(vbContents.ToArray()));
                }

            case CS.SyntaxKind.InterpolationAlignmentClause:
                return(((CSS.InterpolationAlignmentClauseSyntax)node).ConvertInterpolationAlignmentClause());

            case CS.SyntaxKind.InterpolatedStringText:
                return(((CSS.InterpolatedStringTextSyntax)node).ConvertInterpolatedStringText());

            case CS.SyntaxKind.Interpolation:
                return(((CSS.InterpolationSyntax)node).ConvertInterpolation());

            case CS.SyntaxKind.InterpolationFormatClause:
                return(((CSS.InterpolationFormatClauseSyntax)node).ConvertInterpolationFormatClause());


            case CS.SyntaxKind.AnonymousMethodExpression:
            {
                var xx = ((CSS.AnonymousMethodExpressionSyntax)node);
                //public event EventHandler EV = delegate{};
                var y = xx.Body.Convert() as VBS.WithBlockSyntax;
                if (y != null)
                {
                    var end = VB.SyntaxFactory.EndBlockStatement(VB.SyntaxKind.EndFunctionStatement, VB.SyntaxFactory.Token(VB.SyntaxKind.FunctionKeyword));
                    return(VB.SyntaxFactory.MultiLineFunctionLambdaExpression(VB.SyntaxFactory.FunctionLambdaHeader(), end)
                           .WithStatements(new SyntaxList <VBS.StatementSyntax>().Add(y)));
                }
            }
            break;

            default:
                System.Diagnostics.Debug.WriteLine(node.Kind());
                break;
            }
            return(null);
        }
コード例 #30
0
        /// <summary>
        /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS.
        /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type.
        /// Returns null if a merged tuple type could not be fabricated.
        /// </summary>
        private static TypeSymbol?MakeMergedTupleType(ArrayBuilder <DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, CSharpCompilation compilation, DiagnosticBag?diagnostics)
        {
            int leftLength  = lhsVariables.Count;
            int rightLength = rhsLiteral.Arguments.Length;

            var typesWithAnnotationsBuilder = ArrayBuilder <TypeWithAnnotations> .GetInstance(leftLength);

            var locationsBuilder = ArrayBuilder <Location?> .GetInstance(leftLength);

            for (int i = 0; i < rightLength; i++)
            {
                BoundExpression element    = rhsLiteral.Arguments[i];
                TypeSymbol?     mergedType = element.Type;

                if (i < leftLength)
                {
                    var variable = lhsVariables[i];
                    if (variable.NestedVariables is object)
                    {
                        if (element.Kind == BoundKind.TupleLiteral)
                        {
                            // (variables) on the left and (elements) on the right
                            mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, compilation, diagnostics);
                        }
                        else if ((object?)mergedType == null && diagnostics is object)
                        {
                            // (variables) on the left and null on the right
                            Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax);
                        }
                    }
                    else
                    {
                        Debug.Assert(variable.Single is object);
                        if ((object?)variable.Single.Type != null)
                        {
                            // typed-variable on the left
                            mergedType = variable.Single.Type;
                        }
                    }
                }
                else
                {
                    if ((object?)mergedType == null && diagnostics is object)
                    {
                        // a typeless element on the right, matching no variable on the left
                        Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax);
                    }
                }

                typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(mergedType));
                locationsBuilder.Add(element.Syntax.Location);
            }

            if (typesWithAnnotationsBuilder.Any(t => !t.HasType))
            {
                typesWithAnnotationsBuilder.Free();
                locationsBuilder.Free();
                return(null);
            }

            // The tuple created here is not identical to the one created by
            // DeconstructionVariablesAsTuple. It represents a smaller
            // tree of types used for figuring out natural types in tuple literal.
            return(NamedTypeSymbol.CreateTuple(
                       locationOpt: null,
                       elementTypesWithAnnotations: typesWithAnnotationsBuilder.ToImmutableAndFree(),
                       elementLocations: locationsBuilder.ToImmutableAndFree(),
                       elementNames: default(ImmutableArray <string?>),
                       compilation: compilation,
                       diagnostics: diagnostics,
                       shouldCheckConstraints: true,
                       includeNullability: false,
                       errorPositions: default(ImmutableArray <bool>),
                       syntax: syntax));
        }