Example #1
0
 public static SmallDictionary<CSharpSyntaxNode, Binder> BuildMap(MethodSymbol method, CSharpSyntaxNode syntax, Binder enclosing, out bool sawYield)
 {
     var builder = new LocalBinderFactory(method, enclosing);
     builder.Visit(syntax);
     sawYield = builder._sawYield;
     return builder._map;
 }
 protected override void ReportUnassigned(Symbol symbol, CSharpSyntaxNode node)
 {
     if (node.Parent.Kind() == SyntaxKind.AddressOfExpression)
     {
         _result.Add((PrefixUnaryExpressionSyntax)node.Parent);
     }
 }
Example #3
0
        private BoundExpression MakeLiteral(CSharpSyntaxNode syntax, ConstantValue constantValue, TypeSymbol type, BoundLiteral oldNodeOpt = null)
        {
            Debug.Assert(constantValue != null);

            if (constantValue.IsDecimal)
            {
                //  Rewrite decimal literal
                Debug.Assert((object)type != null);
                Debug.Assert(type.SpecialType == SpecialType.System_Decimal);

                return MakeDecimalLiteral(syntax, constantValue);
            }
            else if (constantValue.IsDateTime)
            {
                // C# does not support DateTime constants but VB does; we might have obtained a 
                // DateTime constant by calling a method with an optional parameter with a DateTime
                // for its default value.
                Debug.Assert((object)type != null);
                Debug.Assert(type.SpecialType == SpecialType.System_DateTime);
                return MakeDateTimeLiteral(syntax, constantValue);
            }
            else if (oldNodeOpt != null)
            {
                return oldNodeOpt.Update(constantValue, type);
            }
            else
            {
                return new BoundLiteral(syntax, constantValue, type, hasErrors: constantValue.IsBad);
            }
        }
        public static bool TryGet(CSharpSyntaxNode node, SemanticModel semanticModel, out IControlFlowGraph cfg)
        {
            cfg = null;
            try
            {
                if (node != null)
                {
                    cfg = Create(node, semanticModel);
                }
                else
                {
                    return false;
                }
            }
            catch (Exception exc) when (exc is InvalidOperationException ||
                                        exc is ArgumentException ||
                                        exc is NotSupportedException)
            {
                // These are expected
            }
            catch (Exception exc) when (exc is NotImplementedException)
            {
                Debug.Fail(exc.ToString());
            }

            return cfg != null;
        }
 internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax)
 {
     var method = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetObjectAtAddressMethodName,
         (c, n, s) =>
         {
             var parameterType = compilation.GetSpecialType(SpecialType.System_UInt64);
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 this.Type,
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)));
         });
     var argument = new BoundLiteral(
         syntax,
         Microsoft.CodeAnalysis.ConstantValue.Create(_address),
         method.Parameters[0].Type);
     var call = BoundCall.Synthesized(
         syntax,
         receiverOpt: null,
         method: method,
         arguments: ImmutableArray.Create<BoundExpression>(argument));
     Debug.Assert(call.Type == this.Type);
     return call;
 }
 /// <summary>
 /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors.
 /// </summary>
 internal static bool Add(
     this DiagnosticBag diagnostics,
     CSharpSyntaxNode node,
     HashSet<DiagnosticInfo> useSiteDiagnostics)
 {
     return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(node.Location, useSiteDiagnostics);
 }
 private void VisitNodeToBind(CSharpSyntaxNode node)
 {
     var previousNodeToBind = _nodeToBind;
     _nodeToBind = node;
     Visit(node);
     _nodeToBind = previousNodeToBind;
 }
 protected override void ReportUnassigned(FieldSymbol fieldSymbol, int unassignedSlot, CSharpSyntaxNode node)
 {
     if (node.Parent.Kind == SyntaxKind.AddressOfExpression)
     {
         result.Add((PrefixUnaryExpressionSyntax)node.Parent);
     }
 }
Example #9
0
 private static BoundExpression RewriteLocalInternal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax, LocalSymbol local)
 {
     var parameterType = compilation.GetSpecialType(SpecialType.System_String);
     var getValueMethod = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetVariableValueMethodName,
         (c, n, s) =>
         {
             var returnType = compilation.GetSpecialType(SpecialType.System_Object);
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 returnType,
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)));
         });
     var getAddressMethod = container.GetOrAddSynthesizedMethod(
         ExpressionCompilerConstants.GetVariableAddressMethodName,
         (c, n, s) =>
         {
             return new PlaceholderMethodSymbol(
                 c,
                 s,
                 n,
                 m => ImmutableArray.Create<TypeParameterSymbol>(new SimpleTypeParameterSymbol(m, 0, "<>T")),
                 m => m.TypeParameters[0], // return type is <>T&
                 m => ImmutableArray.Create<ParameterSymbol>(new SynthesizedParameterSymbol(m, parameterType, ordinal: 0, refKind: RefKind.None)),
                 returnValueIsByRef: true);
         });
     return new BoundPseudoVariable(
         syntax,
         local,
         new ObjectIdExpressions(compilation, getValueMethod, getAddressMethod),
         local.Type);
 }
 internal ResetPoint(int resetCount, LexerMode mode, int position, CSharpSyntaxNode prevTokenTrailingTrivia)
 {
     this.ResetCount = resetCount;
     this.Mode = mode;
     this.Position = position;
     this.PrevTokenTrailingTrivia = prevTokenTrailingTrivia;
 }
Example #11
0
        public void EmbedAllMembersOfImplementedInterface(CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
        {
            Debug.Assert(UnderlyingNamedType.IsInterfaceType());

            if (embeddedAllMembersOfImplementedInterface)
            {
                return;
            }

            embeddedAllMembersOfImplementedInterface = true;

            // Embed all members
            foreach (MethodSymbol m in UnderlyingNamedType.GetMethodsToEmit())
            {
                if ((object)m != null)
                {
                    TypeManager.EmbedMethod(this, m, syntaxNodeOpt, diagnostics);
                }
            }

            // We also should embed properties and events, but we don't need to do this explicitly here
            // because accessors embed them automatically.

            // Do the same for implemented interfaces.
            foreach (NamedTypeSymbol @interface in UnderlyingNamedType.GetInterfacesToEmit())
            {
                TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true);
            }
        }
 public WithConstructorInitializerLocalsBinder(Binder enclosing, ArgumentListSyntax initializerArgumentList)
     : base(enclosing, enclosing.Flags)
 {
     Debug.Assert(initializerArgumentList != null);
     this.scope = initializerArgumentList;
     this.initializerArgumentList = initializerArgumentList;
 }
 public WithConstructorInitializerLocalsBinder(Binder enclosing, ConstructorDeclarationSyntax declaration)
     : base(enclosing, enclosing.Flags)
 {
     Debug.Assert(declaration.Initializer != null);
     this.scope = declaration;
     this.initializerArgumentList = declaration.Initializer.ArgumentList;
 }
Example #14
0
 public override BoundExpression Replacement(CSharpSyntaxNode node, Func<NamedTypeSymbol, BoundExpression> makeFrame)
 {
     // By returning the same replacement each time, it is possible we
     // are constructing a DAG instead of a tree for the translation.
     // Because the bound trees are immutable that is usually harmless.
     return _replacement;
 }
        private static BoundExpression RewriteConditionalOperator(
            CSharpSyntaxNode syntax,
            BoundExpression rewrittenCondition,
            BoundExpression rewrittenConsequence,
            BoundExpression rewrittenAlternative,
            ConstantValue constantValueOpt,
            TypeSymbol rewrittenType)
        {
            // NOTE: This optimization assumes that a constant has no side effects. In the future we 
            // might wish to represent nodes that are known to the optimizer as having constant
            // values as a sequence of side effects and a constant value; in that case the result
            // of this should be a sequence containing the side effect and the consequence or alternative.

            ConstantValue conditionConstantValue = rewrittenCondition.ConstantValue;
            if (conditionConstantValue == ConstantValue.True)
            {
                return rewrittenConsequence;
            }
            else if (conditionConstantValue == ConstantValue.False)
            {
                return rewrittenAlternative;
            }
            else
            {
                return new BoundConditionalOperator(
                    syntax,
                    rewrittenCondition,
                    rewrittenConsequence,
                    rewrittenAlternative,
                    constantValueOpt,
                    rewrittenType);
            }
        }
        private static IEnumerable<CodeAction> GetActions(Document document, SyntaxNode root, SyntaxNode node, CSharpSyntaxNode nullableType, CSharpSyntaxNode objectType)
        {
            var returnType = (CSharpSyntaxNode)nullableType ?? objectType;
            if (returnType == null)
                yield break;

            var bodyStatement = node.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
            if (bodyStatement == null)
                yield break; 

            if (HasReturnContract(bodyStatement, returnType.ToString()))
                yield break;

            yield return CreateAction(
                node.Span
                ,t2 => {
                    var newBody = bodyStatement.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { CreateContractEnsuresCall(returnType.ToString()) }.Concat(bodyStatement.Statements)));

                    var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);

                    if (UsingStatementNotPresent(newRoot)) newRoot = AddUsingStatement(node, newRoot);

                    return Task.FromResult(document.WithSyntaxRoot(newRoot));
                }
                ,"Add a Contract to specify the return value must not be null"
            );
        }
Example #17
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);
        }
Example #18
0
        // insert the implicit "return" statement at the end of the method body
        // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these
        // ones are going to have sequence points.
        internal static BoundBlock AppendImplicitReturn(BoundStatement node, MethodSymbol method = null, CSharpSyntaxNode syntax = null)
        {
            if (syntax == null)
            {
                syntax = node.Syntax;
            }

            BoundStatement ret =
                (object)method != null && (object)method.IteratorElementType != null
                ? BoundYieldBreakStatement.Synthesized(syntax) as BoundStatement
                : BoundReturnStatement.Synthesized(syntax, null);

            if (syntax.Kind == SyntaxKind.Block)
            {
                var blockSyntax = (BlockSyntax)syntax;

                ret = new BoundSequencePointWithSpan(
                    blockSyntax,
                    ret,
                    blockSyntax.CloseBraceToken.Span)
                { WasCompilerGenerated = true };
            }

            switch (node.Kind)
            {
                case BoundKind.Block:
                    var block = (BoundBlock)node;
                    return block.Update(block.LocalsOpt, block.Statements.Add(ret));

                default:
                    return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(ret, node));
            }
        }
Example #19
0
        private BoundExpression MakeFieldAccess(
            CSharpSyntaxNode syntax,
            BoundExpression rewrittenReceiver,
            FieldSymbol fieldSymbol,
            ConstantValue constantValueOpt,
            LookupResultKind resultKind,
            TypeSymbol type,
            BoundFieldAccess oldNodeOpt = null)
        {

            if (fieldSymbol.IsTupleField)
            {
                return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver, constantValueOpt, resultKind);
            }
            
            BoundExpression result = oldNodeOpt != null ?
                oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) :
                new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type);

            if (fieldSymbol.IsFixed)
            {
                // a reference to a fixed buffer is translated into its address
                result = new BoundConversion(syntax,
                    new BoundAddressOfOperator(syntax, result, syntax != null && SyntaxFacts.IsFixedStatementExpression(syntax), type, false),
                    new Conversion(ConversionKind.PointerToPointer), false, false, default(ConstantValue), type, false);
            }

            return result;
        }
Example #20
0
        public BoundLambda(CSharpSyntaxNode syntax, BoundBlock body, ImmutableArray<Diagnostic> diagnostics, Binder binder, TypeSymbol delegateType, bool inferReturnType)
            : this(syntax, (LambdaSymbol)binder.ContainingMemberOrLambda, body, diagnostics, binder, delegateType)
        {
            if (inferReturnType)
            {
                this._inferredReturnType = InferReturnType(
                    this.Body,
                    this.Binder,
                    delegateType,
                    this.Symbol.IsAsync,
                    ref this._inferredReturnTypeUseSiteDiagnostics,
                    out this._refKind,
                    out this._inferredFromSingleType);

#if DEBUG
                _hasInferredReturnType = true;
#endif
            }

            Debug.Assert(
                syntax.IsAnonymousFunction() ||                                                                 // lambda expressions
                syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas
                LambdaUtilities.IsQueryPairLambda(syntax)                                                       // "pair" lambdas in queries
            );
        }
Example #21
0
 internal override BoundExpression Replacement(CSharpSyntaxNode node, FramePointerMaker makeFrame)
 {
     // By returning the same replacement each time, it is possible we
     // are constructing a DAG instead of a tree for the translation.
     // Because the bound trees are immutable that is usually harmless.
     return replacement;
 }
 private static void ReportDiagnostic(
     SyntaxNodeAnalysisContext context,
     CSharpSyntaxNode syntaxNode,
     string propertyName)
 {
     context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.GetConfigurationEntryKey, syntaxNode.GetLocation(), propertyName));
 }
        private BoundExpression MakePropertyGetAccess(
            CSharpSyntaxNode syntax,
            BoundExpression rewrittenReceiver,
            PropertySymbol property,
            ImmutableArray<BoundExpression> rewrittenArguments,
            MethodSymbol getMethodOpt = null,
            BoundPropertyAccess oldNodeOpt = null)
        {
            if (_inExpressionLambda && rewrittenArguments.IsEmpty)
            {
                return oldNodeOpt != null ?
                    oldNodeOpt.Update(rewrittenReceiver, property, LookupResultKind.Viable, property.Type) :
                    new BoundPropertyAccess(syntax, rewrittenReceiver, property, LookupResultKind.Viable, property.Type);
            }
            else
            {
                var getMethod = getMethodOpt ?? property.GetOwnOrInheritedGetMethod();

                Debug.Assert((object)getMethod != null);
                Debug.Assert(getMethod.ParameterCount == rewrittenArguments.Length);
                Debug.Assert(((object)getMethodOpt == null) || ReferenceEquals(getMethod, getMethodOpt));

                return BoundCall.Synthesized(
                    syntax,
                    rewrittenReceiver,
                    getMethod,
                    rewrittenArguments);
            }
        }
Example #24
0
        protected BoundNode(BoundKind kind, CSharpSyntaxNode syntax)
        {
            Debug.Assert(kind == BoundKind.SequencePoint || kind == BoundKind.SequencePointExpression || syntax != null);

            this.kind = kind;
            this.Syntax = syntax;
        }
Example #25
0
 internal ExecutableCodeBinder(CSharpSyntaxNode root, Symbol memberSymbol, Binder next, BinderFlags additionalFlags)
     : base(next, (next.Flags | additionalFlags) & ~BinderFlags.AllClearedAtExecutableCodeBoundary)
 {
     this.memberSymbol = memberSymbol;
     this.root = root;
     this.owner = memberSymbol as MethodSymbol;
 }
Example #26
0
        internal PlaceholderLocalBinder(
            CSharpSyntaxNode syntax,
            ImmutableArray<Alias> aliases,
            MethodSymbol containingMethod,
            EETypeNameDecoder typeNameDecoder,
            Binder next) :
            base(next)
        {
            _syntax = syntax;
            _containingMethod = containingMethod;

            var compilation = next.Compilation;
            var sourceAssembly = compilation.SourceAssembly;

            var aliasesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(aliases.Length);
            var lowercaseBuilder = ImmutableDictionary.CreateBuilder<string, LocalSymbol>();
            foreach (Alias alias in aliases)
            {
                var local = PlaceholderLocalSymbol.Create(
                    typeNameDecoder,
                    containingMethod,
                    sourceAssembly,
                    alias);
                aliasesBuilder.Add(local);

                if (alias.Kind == DkmClrAliasKind.ReturnValue)
                {
                    lowercaseBuilder.Add(local.Name.ToLower(), local);
                }
            }
            _lowercaseReturnValueAliases = lowercaseBuilder.ToImmutableDictionary();
            _aliases = aliasesBuilder.ToImmutableAndFree();
        }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MethodASTWalker"/> class.
        /// </summary>
        protected MethodASTWalker(CSharpSyntaxNode node)
        {
            var methodDeclarationSyntaxNode = node as MethodDeclarationSyntax;
            if (methodDeclarationSyntaxNode == null)
            {
                throw new ArgumentException(
                    string.Format("Specified node is not of type {0}",
                    typeof(MethodDeclarationSyntax).Name));
            }

            this.node = node;
            MethodDeclaration methodHelper = new MethodDeclaration(methodDeclarationSyntaxNode);

            this.methodDeclaration = MethodDeclarationTranslationUnit.Create(
                methodHelper.Visibility,
                IdentifierTranslationUnit.Create(methodHelper.ReturnType),
                IdentifierTranslationUnit.Create(methodHelper.Name));

            foreach (TypedIdentifier parameter in methodHelper.Parameters)
            {
                this.methodDeclaration.AddArgument(ArgumentDefinitionTranslationUnit.Create(
                    IdentifierTranslationUnit.Create(parameter.TypeName),
                    IdentifierTranslationUnit.Create(parameter.IdentifierName)));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExpressionStatementASTWalker"/> class.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="statement"></param>
        /// <param name="semanticModel">The semantic model.</param>
        protected ExpressionStatementASTWalker(CSharpSyntaxNode node, ExpressionStatementTranslationUnit expressionStatement, SemanticModel semanticModel)
            : base(node, semanticModel)
        {
            var returnSyntaxNode = node as ReturnStatementSyntax;
            var throwSyntaxNode = node as ThrowStatementSyntax;
            var expressionSyntaxNode = node as ExpressionStatementSyntax;

            if (returnSyntaxNode == null && throwSyntaxNode == null && expressionSyntaxNode == null)
            {
                throw new ArgumentException(
                    string.Format("Specified node ({0}) is not one of these types: {1}, {2}, {3}!",
                    node.GetType().Name,
                    typeof(ReturnStatementSyntax).Name,
                    typeof(ThrowStatementSyntax).Name),
                    typeof(ExpressionStatementSyntax).Name);
            }

            if (expressionStatement == null)
            {
                throw new ArgumentNullException(nameof(expressionStatement));
            }

            // Node assigned in base, no need to assign it here
            this.statement = expressionStatement;
        }
Example #29
0
        /// <summary>
        /// Create a context to compile expressions within a method scope.
        /// </summary>
        internal CompilationContext(
            CSharpCompilation compilation,
            MethodSymbol currentFrame,
            ImmutableArray<LocalSymbol> locals,
            InScopeHoistedLocals inScopeHoistedLocals,
            MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo,
            CSharpSyntaxNode syntax)
        {
            Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));

            // TODO: syntax.SyntaxTree should probably be added to the compilation,
            // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
            _currentFrame = currentFrame;
            _syntax = syntax;
            _methodNotType = !locals.IsDefault;

            // NOTE: Since this is done within CompilationContext, it will not be cached.
            // CONSIDER: The values should be the same everywhere in the module, so they
            // could be cached.  
            // (Catch: what happens in a type context without a method def?)
            this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);

            // Each expression compile should use a unique compilation
            // to ensure expression-specific synthesized members can be
            // added (anonymous types, for instance).
            Debug.Assert(this.Compilation != compilation);

            this.NamespaceBinder = CreateBinderChain(
                this.Compilation,
                (PEModuleSymbol)currentFrame.ContainingModule,
                currentFrame.ContainingNamespace,
                methodDebugInfo.ImportRecordGroups);

            if (_methodNotType)
            {
                _locals = locals;
                ImmutableArray<string> displayClassVariableNamesInOrder;
                GetDisplayClassVariables(
                    currentFrame,
                    _locals,
                    inScopeHoistedLocals,
                    out displayClassVariableNamesInOrder,
                    out _displayClassVariables,
                    out _hoistedParameterNames);
                Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
                _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
            }
            else
            {
                _locals = ImmutableArray<LocalSymbol>.Empty;
                _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
                _localsForBinding = ImmutableArray<LocalSymbol>.Empty;
            }

            // Assert that the cheap check for "this" is equivalent to the expensive check for "this".
            Debug.Assert(
                _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
                _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
        }
        public static void WriteIt(OutputWriter writer, SyntaxToken operatorToken, CSharpSyntaxNode rightExpression,
            CSharpSyntaxNode leftExpression)
        {
            if (operatorToken.IsKind(SyntaxKind.AsKeyword))
            {
                writer.Write("AsCast!(");
                writer.Write(TypeProcessor.ConvertType(rightExpression));
                writer.Write(")(");
                Core.Write(writer, leftExpression);
                writer.Write(")");
            }
            else if (operatorToken.IsKind(SyntaxKind.IsKeyword)) // isCast
            {
                var leftSymbolType = TypeProcessor.GetTypeInfo(leftExpression);
                var rightSymbolType = TypeProcessor.GetTypeInfo(rightExpression);

                if (leftSymbolType.Type.IsValueType)
                {
                    writer.Write("IsCast!(Boxed!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write("))");
                    writer.Write("(");
                    Core.Write(writer, leftExpression);
                    writer.Write(")");
                }
                else if (rightSymbolType.Type.IsValueType)
                {
                    writer.Write("IsCast!(Boxed!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write("))");
                    writer.Write("(");
                    Core.Write(writer, leftExpression);
                    writer.Write(")");
                }
                else
                {
                    writer.Write("(IsCast!(");
                    writer.Write(TypeProcessor.ConvertType(rightExpression));
                    writer.Write(")(");
                    Core.Write(writer, leftExpression);
                    writer.Write("))");
                }
            }
            else if (operatorToken.IsKind(SyntaxKind.QuestionQuestionToken))
            {
                writer.Write("((");
                Core.Write(writer, leftExpression);
                writer.Write(")!is null?(");
                Core.Write(writer, leftExpression);
                writer.Write("):(");
                Core.Write(writer, rightExpression);
                writer.Write("))");
            }
            else
            {

                ProcessExpression(writer, operatorToken, rightExpression, leftExpression);
            }
        }
Example #31
0
        public static CSharpSyntaxNode SetAttributeLists(this CSharpSyntaxNode node, SyntaxList <AttributeListSyntax> attributeLists)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            switch (node.Kind())
            {
            case SyntaxKind.EnumDeclaration:
                return(((EnumDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.DelegateDeclaration:
                return(((DelegateDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.ClassDeclaration:
                return(((ClassDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.TypeParameter:
                return(((TypeParameterSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.StructDeclaration:
                return(((StructDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.PropertyDeclaration:
                return(((PropertyDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.Parameter:
                return(((ParameterSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.OperatorDeclaration:
                return(((OperatorDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.MethodDeclaration:
                return(((MethodDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.InterfaceDeclaration:
                return(((InterfaceDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.IndexerDeclaration:
                return(((IndexerDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.FieldDeclaration:
                return(((FieldDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.EventFieldDeclaration:
                return(((EventFieldDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.EventDeclaration:
                return(((EventDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.EnumMemberDeclaration:
                return(((EnumMemberDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.DestructorDeclaration:
                return(((DestructorDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.ConversionOperatorDeclaration:
                return(((ConversionOperatorDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.ConstructorDeclaration:
                return(((ConstructorDeclarationSyntax)node).WithAttributeLists(attributeLists));

            case SyntaxKind.GetAccessorDeclaration:
            case SyntaxKind.SetAccessorDeclaration:
            case SyntaxKind.AddAccessorDeclaration:
            case SyntaxKind.RemoveAccessorDeclaration:
                return(((AccessorDeclarationSyntax)node).WithAttributeLists(attributeLists));
            }

            return(node);
        }
 private ISymbol GetSymbol(CSharpSyntaxNode syntax)
 {
     return(syntax.SyntaxTree == _semanticModel.SyntaxTree
         ? _semanticModel.GetSymbolInfo(syntax).Symbol
         : null);
 }
 public new LambdaExpressionSyntax WithBody(CSharpSyntaxNode body)
 => body is BlockSyntax block
Example #34
0
        private static IEnumerable <CodeAction> GetActions(Document document, SyntaxNode root, SyntaxNode node, CSharpSyntaxNode nullableType, CSharpSyntaxNode objectType)
        {
            var returnType = (CSharpSyntaxNode)nullableType ?? objectType;

            if (returnType == null)
            {
                yield break;
            }

            var bodyStatement = node.ChildNodes().OfType <BlockSyntax>().FirstOrDefault();

            if (bodyStatement == null)
            {
                yield break;
            }

            if (HasReturnContract(bodyStatement, returnType.ToString()))
            {
                yield break;
            }

            yield return(CreateAction(
                             node.Span
                             , t2 => {
                var newBody = bodyStatement.WithStatements(SyntaxFactory.List <StatementSyntax>(new[] { CreateContractEnsuresCall(returnType.ToString()) }.Concat(bodyStatement.Statements)));

                var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);

                if (UsingStatementNotPresent(newRoot))
                {
                    newRoot = AddUsingStatement(node, newRoot);
                }

                return Task.FromResult(document.WithSyntaxRoot(newRoot));
            }
                             , "Add a Contract to specify the return value must not be null"
                             ));
        }
Example #35
0
 public BaseStateGenerator(Func <BaseStateGenerator, JsTransformer> transformer, CSharpSyntaxNode node, JsBlockStatement stateMachineBody, Idioms idioms, IMethodSymbol method, Action <BaseStateGenerator, JsTransformer> nodeAcceptor = null)
 {
     if (nodeAcceptor == null)
     {
         nodeAcceptor = (stateGenerator, jsTransformer) => node.Accept(stateGenerator);
     }
     this.transformer      = transformer(this);
     this.node             = node;
     this.stateMachineBody = stateMachineBody;
     this.method           = method;
     this.idioms           = idioms;
     this.nodeAcceptor     = nodeAcceptor;
 }
Example #36
0
        internal static SyntaxNodeOrToken ItemInternal(CSharpSyntaxNode node, int index)
#endif
        {
            Syntax.InternalSyntax.CSharpSyntaxNode greenChild;
            var green     = node.Green;
            var idx       = index;
            var slotIndex = 0;
            var position  = node.Position;

            // find a slot that contains the node or its parent list (if node is in a list)
            // we will be skipping whole slots here so we will not loop for long
            // the max possible number of slots is 11 (TypeDeclarationSyntax)
            // and typically much less than that
            //
            // at the end of this loop we will have
            // 1) slot index - slotIdx
            // 2) if the slot is a list, node index in the list - idx
            // 3) slot position - position
            while (true)
            {
                greenChild = green.GetSlot(slotIndex);
                if (greenChild != null)
                {
                    int currentOccupancy = Occupancy(greenChild);
                    if (idx < currentOccupancy)
                    {
                        break;
                    }

                    idx      -= currentOccupancy;
                    position += greenChild.FullWidth;
                }

                slotIndex++;
            }

            // get node that represents this slot
            var red = node.GetNodeSlot(slotIndex);

            if (!greenChild.IsList)
            {
                // this is a single node or token
                // if it is a node, we are done
                // otherwise will have to make a token with current gChild and position
                if (red != null)
                {
                    return(red);
                }
            }
            else if (red != null)
            {
                // it is a red list of nodes (separated or not), most common case
                var redChild = red.GetNodeSlot(idx);
                if (redChild != null)
                {
                    // this is our node
                    return(redChild);
                }

                // must be a separator
                // update gChild and position and let it be handled as a token
                greenChild = greenChild.GetSlot(idx);
                position   = red.GetChildPosition(idx);
            }
            else
            {
                // it is a token from a token list, uncommon case
                // update gChild and position and let it be handled as a token
                position  += greenChild.GetSlotOffset(idx);
                greenChild = greenChild.GetSlot(idx);
            }

#if DEBUG
            return(new SyntaxNodeOrToken(node, (Syntax.InternalSyntax.SyntaxToken)greenChild, position, index, fromTokenCtor));
#else
            return(new SyntaxNodeOrToken(node, (Syntax.InternalSyntax.SyntaxToken)greenChild, position, index));
#endif
        }
        internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, CSharpSyntaxNode syntax, DiagnosticBag diagnostics)
        {
            var method   = GetIntrinsicMethod(compilation, ExpressionCompilerConstants.GetObjectAtAddressMethodName);
            var argument = new BoundLiteral(
                syntax,
                Microsoft.CodeAnalysis.ConstantValue.Create(_address),
                method.Parameters[0].Type);
            var call = BoundCall.Synthesized(
                syntax,
                receiverOpt: null,
                method: method,
                arguments: ImmutableArray.Create <BoundExpression>(argument));

            Debug.Assert(call.Type == this.Type);
            return(call);
        }
Example #38
0
 /// <summary>
 /// Returns true if position is within the given node and before the first excluded token.
 /// </summary>
 private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded)
 {
     return(IsBeforeToken(position, firstExcluded) && position >= node.SpanStart);
 }
Example #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChildSyntaxList"/> struct.
 /// </summary>
 /// <param name="node">The underlying syntax node.</param>
 internal ChildSyntaxList(CSharpSyntaxNode node)
 {
     Debug.Assert(node == null || node.Kind != SyntaxKind.List);
     this.node  = node;
     this.count = CountNodes(node.Green);
 }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyDefinitionTranslationUnitFactory"/> class.
 /// </summary>
 /// <param name="node">The syntax node.</param>
 /// <param name="createWhenProtected">A value indicating whether the factory should create a <see cref="ITranslationUnit"/> when <see cref="node"/> is protected.</param>
 public PropertyDefinitionTranslationUnitFactory(CSharpSyntaxNode node, bool createWhenProtected = false)
     : this(node, null, createWhenProtected)
 {
 }
Example #41
0
 protected override Cci.ITypeReference GetType(PEModuleBuilder moduleBuilder, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
 {
     return(moduleBuilder.Translate(UnderlyingEvent.Type, syntaxNodeOpt, diagnostics));
 }
Example #42
0
 VisualBasicSyntaxNode Convert(CSharpSyntaxNode input, SemanticModel semanticModel, Document targetDocument)
 {
     return(CSharpConverter.Convert(input, semanticModel, targetDocument));
 }
Example #43
0
 private void EmitSymbolToken(MethodSymbol method, CSharpSyntaxNode syntaxNode, BoundArgListOperator optArgList)
 {
     _builder.EmitToken(_module.Translate(method, syntaxNode, _diagnostics, optArgList), syntaxNode, _diagnostics);
 }
Example #44
0
        /// <summary>
        /// internal indexer that does not verify index.
        /// Used when caller has already ensured that index is within bounds.
        /// </summary>
#if DEBUG
        internal static SyntaxNodeOrToken ItemInternal(CSharpSyntaxNode node, int index, bool fromTokenCtor = false)
Example #45
0
        public static Doc Print(CSharpSyntaxNode node)
        {
            SyntaxList <AttributeListSyntax>?attributeLists = null;
            SyntaxTokenList?modifiers  = null;
            TypeSyntax?     returnType = null;
            ExplicitInterfaceSpecifierSyntax?explicitInterfaceSpecifier = null;
            TypeParameterListSyntax?         typeParameterList          = null;
            Doc identifier        = Doc.Null;
            var constraintClauses = Enumerable.Empty <TypeParameterConstraintClauseSyntax>();
            ParameterListSyntax?         parameterList          = null;
            ConstructorInitializerSyntax?constructorInitializer = null;
            BlockSyntax?body = null;
            ArrowExpressionClauseSyntax?expressionBody = null;
            SyntaxToken?semicolonToken = null;
            string?     groupId        = null;

            if (node is BaseMethodDeclarationSyntax baseMethodDeclarationSyntax)
            {
                attributeLists = baseMethodDeclarationSyntax.AttributeLists;
                modifiers      = baseMethodDeclarationSyntax.Modifiers;
                parameterList  = baseMethodDeclarationSyntax.ParameterList;
                body           = baseMethodDeclarationSyntax.Body;
                expressionBody = baseMethodDeclarationSyntax.ExpressionBody;
                if (node is MethodDeclarationSyntax methodDeclarationSyntax)
                {
                    returnType = methodDeclarationSyntax.ReturnType;
                    explicitInterfaceSpecifier = methodDeclarationSyntax.ExplicitInterfaceSpecifier;
                    identifier        = Token.Print(methodDeclarationSyntax.Identifier);
                    typeParameterList = methodDeclarationSyntax.TypeParameterList;
                    constraintClauses = methodDeclarationSyntax.ConstraintClauses;
                }
                else if (node is DestructorDeclarationSyntax destructorDeclarationSyntax)
                {
                    identifier = Doc.Concat(
                        Token.Print(destructorDeclarationSyntax.TildeToken),
                        Token.Print(destructorDeclarationSyntax.Identifier)
                        );
                }
                else if (node is ConstructorDeclarationSyntax constructorDeclarationSyntax)
                {
                    identifier             = Token.Print(constructorDeclarationSyntax.Identifier);
                    constructorInitializer = constructorDeclarationSyntax.Initializer;
                }

                semicolonToken = baseMethodDeclarationSyntax.SemicolonToken;
            }
            else if (node is LocalFunctionStatementSyntax localFunctionStatementSyntax)
            {
                attributeLists    = localFunctionStatementSyntax.AttributeLists;
                modifiers         = localFunctionStatementSyntax.Modifiers;
                returnType        = localFunctionStatementSyntax.ReturnType;
                identifier        = Token.Print(localFunctionStatementSyntax.Identifier);
                typeParameterList = localFunctionStatementSyntax.TypeParameterList;
                parameterList     = localFunctionStatementSyntax.ParameterList;
                constraintClauses = localFunctionStatementSyntax.ConstraintClauses;
                body           = localFunctionStatementSyntax.Body;
                expressionBody = localFunctionStatementSyntax.ExpressionBody;
                semicolonToken = localFunctionStatementSyntax.SemicolonToken;
            }

            var docs = new List <Doc> {
                ExtraNewLines.Print(node)
            };

            if (attributeLists.HasValue)
            {
                docs.Add(AttributeLists.Print(node, attributeLists.Value));
            }

            var declarationGroup = new List <Doc>();

            if (modifiers.HasValue)
            {
                declarationGroup.Add(Modifiers.PrintWithoutLeadingTrivia(modifiers.Value));
            }

            if (returnType != null)
            {
                if (!(modifiers.HasValue && modifiers.Value.Count > 0))
                {
                    Token.ShouldSkipNextLeadingTrivia = true;
                }

                declarationGroup.Add(Node.Print(returnType), " ");
                Token.ShouldSkipNextLeadingTrivia = false;
            }

            if (explicitInterfaceSpecifier != null)
            {
                declarationGroup.Add(
                    Node.Print(explicitInterfaceSpecifier.Name),
                    Token.Print(explicitInterfaceSpecifier.DotToken)
                    );
            }

            if (identifier != Doc.Null)
            {
                declarationGroup.Add(identifier);
            }

            if (node is ConversionOperatorDeclarationSyntax conversionOperatorDeclarationSyntax)
            {
                declarationGroup.Add(
                    Token.PrintWithSuffix(
                        conversionOperatorDeclarationSyntax.ImplicitOrExplicitKeyword,
                        " "
                        ),
                    Token.PrintWithSuffix(conversionOperatorDeclarationSyntax.OperatorKeyword, " "),
                    Node.Print(conversionOperatorDeclarationSyntax.Type)
                    );
            }
            else if (node is OperatorDeclarationSyntax operatorDeclarationSyntax)
            {
                declarationGroup.Add(
                    Node.Print(operatorDeclarationSyntax.ReturnType),
                    " ",
                    Token.PrintWithSuffix(operatorDeclarationSyntax.OperatorKeyword, " "),
                    Token.Print(operatorDeclarationSyntax.OperatorToken)
                    );
            }

            if (typeParameterList != null)
            {
                declarationGroup.Add(TypeParameterList.Print(typeParameterList));
            }

            if (parameterList != null)
            {
                // if there are no parameters, but there is a super long method name, a groupId
                // will cause SpaceBrace when it isn't wanted.
                if (parameterList.Parameters.Count > 0)
                {
                    groupId = Guid.NewGuid().ToString();
                }
                declarationGroup.Add(ParameterList.Print(parameterList, groupId));
                declarationGroup.Add(Doc.IfBreak(Doc.Null, Doc.SoftLine));
            }

            if (constructorInitializer != null)
            {
                declarationGroup.Add(
                    groupId != null
                        ? ConstructorInitializer.PrintWithConditionalSpace(
                        constructorInitializer,
                        groupId
                        )
                        : ConstructorInitializer.Print(constructorInitializer)
                    );
            }

            if (modifiers.HasValue && modifiers.Value.Count > 0)
            {
                docs.Add(Token.PrintLeadingTrivia(modifiers.Value[0]));
            }
            else if (returnType != null)
            {
                docs.Add(Token.PrintLeadingTrivia(returnType.GetLeadingTrivia()));
            }

            docs.Add(Doc.Group(declarationGroup));

            docs.Add(
                groupId != null
                    ? ConstraintClauses.PrintWithConditionalSpace(constraintClauses, groupId)
                    : ConstraintClauses.Print(constraintClauses)
                );
            if (body != null)
            {
                docs.Add(
                    groupId != null
                        ? Block.PrintWithConditionalSpace(body, groupId)
                        : Block.Print(body)
                    );
            }
            else
            {
                if (expressionBody != null)
                {
                    docs.Add(ArrowExpressionClause.Print(expressionBody));
                }
            }

            if (semicolonToken.HasValue)
            {
                docs.Add(Token.Print(semicolonToken.Value));
            }

            return(Doc.Group(docs));
        }
 internal override ImmutableArray <LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
 {
     throw ExceptionUtilities.Unreachable;
 }
Example #47
0
 private static BaseFieldDeclarationSyntax GetFieldDeclaration(CSharpSyntaxNode declarator)
 {
     return((BaseFieldDeclarationSyntax)declarator.Parent.Parent);
 }
        public LambdaExpressionSyntax ConvertLambdaExpression(AnonymousFunctionExpressionSyntax node, CSharpSyntaxNode body, IEnumerable <ParameterSyntax> parameters, SyntaxTokenList modifiers)
        {
            var symbol        = ModelExtensions.GetSymbolInfo(_semanticModel, node).Symbol as IMethodSymbol;
            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;

            if (symbol.ReturnsVoid)
            {
                header = SyntaxFactory.SubLambdaHeader(SyntaxFactory.List <AttributeListSyntax>(),
                                                       ConvertModifiers(modifiers, SyntaxKindExtensions.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 BlockSyntax block)
            {
                statements = ConvertStatements(block.Statements);
            }
            else if (body.Kind() == Microsoft.CodeAnalysis.CSharp.SyntaxKind.ThrowExpression)
            {
                var csThrowExpression = (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
            {
                statements = InsertRequiredDeclarations(
                    SyntaxFactory.SingletonList <StatementSyntax>(
                        SyntaxFactory.ReturnStatement((ExpressionSyntax)body.Accept(_nodesVisitor))),
                    body);
            }

            if (statements.Count == 1 && UnpackExpressionFromStatement(statements[0], out var expression))
            {
                return(SyntaxFactory.SingleLineLambdaExpression(singleLineExpressionKind, header, expression));
            }

            return(SyntaxFactory.MultiLineLambdaExpression(multiLineExpressionKind, header, statements, endBlock));
        }
        /// <summary>
        /// Verify the default value matches the default value from any earlier attribute
        /// (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute).
        /// If not, report ERR_ParamDefaultValueDiffersFromAttribute.
        /// </summary>
        private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, CSharpSyntaxNode syntax, DiagnosticBag diagnostics)
        {
            var data = GetEarlyDecodedWellKnownAttributeData(diagnostics);

            if (data != null)
            {
                var attrValue = data.DefaultParameterValue;
                if ((attrValue != ConstantValue.Unset) &&
                    (value != attrValue))
                {
                    // CS8017: The parameter has multiple distinct default values.
                    diagnostics.Add(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, syntax.Location);
                }
            }
        }
        private async Task <CSharpSyntaxNode> GetInitializerFromNameAndTypeAsync(ITypeSymbol typeSymbol,
                                                                                 VBSyntax.ModifiedIdentifierSyntax name, CSharpSyntaxNode initializer)
        {
            if (!SyntaxTokenExtensions.IsKind(name.Nullable, SyntaxKind.None))
            {
                if (typeSymbol.IsArrayType())
                {
                    initializer = null;
                }
            }

            var rankSpecifiers = await ConvertArrayRankSpecifierSyntaxesAsync(name.ArrayRankSpecifiers, name.ArrayBounds, false);

            if (rankSpecifiers.Count > 0)
            {
                var rankSpecifiersWithSizes = await ConvertArrayRankSpecifierSyntaxesAsync(name.ArrayRankSpecifiers, name.ArrayBounds);

                var arrayTypeSyntax = ((ArrayTypeSyntax)GetTypeSyntax(typeSymbol)).WithRankSpecifiers(rankSpecifiersWithSizes);
                if (rankSpecifiersWithSizes.SelectMany(ars => ars.Sizes).Any(e => !e.IsKind(CSSyntaxKind.OmittedArraySizeExpression)))
                {
                    initializer = SyntaxFactory.ArrayCreationExpression(arrayTypeSyntax);
                }
                else if (initializer is CSSyntax.ImplicitArrayCreationExpressionSyntax iaces && iaces.Initializer != null)
                {
                    initializer = SyntaxFactory.ArrayCreationExpression(arrayTypeSyntax, iaces.Initializer);
                }
            }

            return(initializer);
        }
 private ITypeSymbol GetTypeSymbol(CSharpSyntaxNode syntax)
 {
     return(syntax.SyntaxTree == _semanticModel.SyntaxTree
         ? _semanticModel.GetTypeInfo(syntax).Type
         : null);
 }
Example #52
0
 private static void ReportDiagnostic(
     SyntaxNodeAnalysisContext context,
     CSharpSyntaxNode syntaxNode)
 {
     context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.ValueTuple, syntaxNode.GetLocation()));
 }
 public bool IsEventHandlerIdentifier(CSharpSyntaxNode syntax)
 {
     return(GetSymbol(syntax).IsKind(SymbolKind.Event));
 }
Example #54
0
 private void EmitSequencePoint(CSharpSyntaxNode syntax)
 {
     EmitSequencePoint(syntax.SyntaxTree, syntax.Span);
 }
        private static ReduceIfNestingAnalysis AnalyzeCore(
            IfStatementSyntax ifStatement,
            SemanticModel semanticModel,
            SyntaxKind jumpKind,
            ReduceIfNestingOptions options,
            INamedTypeSymbol taskSymbol         = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(ifStatement);

            if (!statementsInfo.Success)
            {
                return(Fail(ifStatement));
            }

            CSharpSyntaxNode node       = statementsInfo.Node;
            SyntaxNode       parent     = node.Parent;
            SyntaxKind       parentKind = parent.Kind();

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            if (statementsInfo.IsInSwitchSection ||
                parentKind == SyntaxKind.SwitchSection)
            {
                SyntaxNode switchSection = (statementsInfo.IsInSwitchSection) ? node : parent;

                if (!options.AllowSwitchSection())
                {
                    return(Fail(switchSection));
                }

                if (ifStatement != statements.LastButOneOrDefault())
                {
                    return(Fail(switchSection));
                }

                if (!IsFixableJumpStatement(statements.Last(), ref jumpKind))
                {
                    return(Fail(switchSection));
                }

                if (!options.AllowNestedFix() &&
                    IsNestedFix(switchSection.Parent, semanticModel, options, taskSymbol, cancellationToken))
                {
                    return(Fail(switchSection));
                }

                return(Success(jumpKind, switchSection));
            }

            if (parentKind.Is(
                    SyntaxKind.ForStatement,
                    SyntaxKind.ForEachStatement,
                    SyntaxKind.DoStatement,
                    SyntaxKind.WhileStatement))
            {
                if (!options.AllowLoop())
                {
                    return(Fail(parent));
                }

                StatementSyntax lastStatement = statements.Last();

                if (ifStatement == lastStatement)
                {
                    jumpKind = SyntaxKind.ContinueStatement;
                }
                else
                {
                    if (ifStatement != statements.LastButOneOrDefault())
                    {
                        return(Fail(parent));
                    }

                    if (!IsFixableJumpStatement(lastStatement, ref jumpKind))
                    {
                        return(Fail(parent));
                    }
                }

                if (!options.AllowNestedFix() &&
                    IsNestedFix(parent.Parent, semanticModel, options, taskSymbol, cancellationToken))
                {
                    return(Fail(parent));
                }

                return(Success(jumpKind, parent));
            }

            if (!IsFixable(ifStatement, statements, ref jumpKind))
            {
                return(Fail(node));
            }

            switch (parentKind)
            {
            case SyntaxKind.ConstructorDeclaration:
            case SyntaxKind.DestructorDeclaration:
            case SyntaxKind.SetAccessorDeclaration:
            case SyntaxKind.AddAccessorDeclaration:
            case SyntaxKind.RemoveAccessorDeclaration:
            {
                if (jumpKind == SyntaxKind.None)
                {
                    jumpKind = SyntaxKind.ReturnStatement;
                }
                else if (jumpKind != SyntaxKind.ReturnStatement)
                {
                    return(Fail(parent));
                }

                return(Success(jumpKind, parent));
            }

            case SyntaxKind.OperatorDeclaration:
            case SyntaxKind.ConversionOperatorDeclaration:
            case SyntaxKind.GetAccessorDeclaration:
            {
                if (jumpKind == SyntaxKind.None)
                {
                    return(Fail(parent));
                }

                return(Success(jumpKind, parent));
            }

            case SyntaxKind.MethodDeclaration:
            {
                var methodDeclaration = (MethodDeclarationSyntax)parent;

                if (jumpKind != SyntaxKind.None)
                {
                    return(Success(jumpKind, parent));
                }

                if (methodDeclaration.ReturnsVoid())
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                if (methodDeclaration.Modifiers.Contains(SyntaxKind.AsyncKeyword) &&
                    taskSymbol != null &&
                    semanticModel
                    .GetDeclaredSymbol(methodDeclaration, cancellationToken)?
                    .ReturnType
                    .Equals(taskSymbol) == true)
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                if (semanticModel
                    .GetDeclaredSymbol(methodDeclaration, cancellationToken)?
                    .ReturnType
                    .IsIEnumerableOrConstructedFromIEnumerableOfT() == true &&
                    methodDeclaration.ContainsYield())
                {
                    return(Success(SyntaxKind.YieldBreakStatement, parent));
                }

                break;
            }

            case SyntaxKind.LocalFunctionStatement:
            {
                var localFunction = (LocalFunctionStatementSyntax)parent;

                if (jumpKind != SyntaxKind.None)
                {
                    return(Success(jumpKind, parent));
                }

                if (localFunction.ReturnsVoid())
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                if (localFunction.Modifiers.Contains(SyntaxKind.AsyncKeyword) &&
                    taskSymbol != null &&
                    ((IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken))?
                    .ReturnType
                    .Equals(taskSymbol) == true)
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                if (((IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken))?
                    .ReturnType
                    .IsIEnumerableOrConstructedFromIEnumerableOfT() == true &&
                    localFunction.ContainsYield())
                {
                    return(Success(SyntaxKind.YieldBreakStatement, parent));
                }

                break;
            }

            case SyntaxKind.AnonymousMethodExpression:
            case SyntaxKind.SimpleLambdaExpression:
            case SyntaxKind.ParenthesizedLambdaExpression:
            {
                var anonymousFunction = (AnonymousFunctionExpressionSyntax)parent;

                if (jumpKind != SyntaxKind.None)
                {
                    return(Success(jumpKind, parent));
                }

                var methodSymbol = semanticModel.GetSymbol(anonymousFunction, cancellationToken) as IMethodSymbol;

                if (methodSymbol == null)
                {
                    return(Fail(parent));
                }

                if (methodSymbol.ReturnsVoid)
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) &&
                    methodSymbol.ReturnType.Equals(taskSymbol))
                {
                    return(Success(SyntaxKind.ReturnStatement, parent));
                }

                break;
            }

            case SyntaxKind.IfStatement:
            {
                ifStatement = (IfStatementSyntax)parent;

                if (ifStatement.Parent is ElseClauseSyntax elseClause)
                {
                    if (ifStatement.Else != null)
                    {
                        return(Fail(parent));
                    }

                    if (!options.AllowIfInsideIfElse())
                    {
                        return(Fail(parent));
                    }

                    return(AnalyzeCore(ifStatement.GetTopmostIf(), semanticModel, jumpKind, options, taskSymbol, cancellationToken));
                }
                else
                {
                    if (!IsFixable(ifStatement))
                    {
                        return(Fail(parent));
                    }

                    if (!options.AllowNestedFix())
                    {
                        return(Fail(parent));
                    }

                    return(AnalyzeCore(ifStatement, semanticModel, jumpKind, options, taskSymbol, cancellationToken));
                }
            }

            case SyntaxKind.ElseClause:
            {
                if (!options.AllowIfInsideIfElse())
                {
                    return(Fail(parent));
                }

                var elseClause = (ElseClauseSyntax)parent;

                return(AnalyzeCore(elseClause.GetTopmostIf(), semanticModel, jumpKind, options, taskSymbol, cancellationToken));
            }
            }

            return(Fail(parent));
        }
Example #56
0
 private void EmitSymbolToken(FieldSymbol symbol, CSharpSyntaxNode syntaxNode)
 {
     _builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics);
 }
        internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments <AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
        {
            Debug.Assert((object)arguments.AttributeSyntaxOpt != null);

            var attribute = arguments.Attribute;

            Debug.Assert(!attribute.HasErrors);
            Debug.Assert(arguments.SymbolPart == AttributeLocation.None);

            if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute))
            {
                arguments.GetOrCreateData <CommonFieldWellKnownAttributeData>().HasSpecialNameAttribute = true;
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.NonSerializedAttribute))
            {
                arguments.GetOrCreateData <CommonFieldWellKnownAttributeData>().HasNonSerializedAttribute = true;
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.FieldOffsetAttribute))
            {
                if (this.IsStatic || this.IsConst)
                {
                    // CS0637: The FieldOffset attribute is not allowed on static or const fields
                    arguments.Diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadField, arguments.AttributeSyntaxOpt.Name.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
                }
                else
                {
                    int offset = attribute.CommonConstructorArguments[0].DecodeValue <int>(SpecialType.System_Int32);
                    if (offset < 0)
                    {
                        // Dev10 reports CS0647: "Error emitting attribute ..."
                        CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt);
                        arguments.Diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
                        offset = 0;
                    }

                    // Set field offset even if the attribute specifies an invalid value, so that
                    // post-validation knows that the attribute is applied and reports better errors.
                    arguments.GetOrCreateData <CommonFieldWellKnownAttributeData>().SetFieldOffset(offset);
                }
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute))
            {
                MarshalAsAttributeDecoder <CommonFieldWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation> .Decode(ref arguments, AttributeTargets.Field, MessageProvider.Instance);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute))
            {
                // DynamicAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsReadOnlyAttribute))
            {
                // IsReadOnlyAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsReadOnlyAttribute.FullName);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsUnmanagedAttribute))
            {
                // IsUnmanagedAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsUnmanagedAttribute.FullName);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsByRefLikeAttribute))
            {
                // IsByRefLikeAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsByRefLikeAttribute.FullName);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute))
            {
                VerifyConstantValueMatches(attribute.DecodeDateTimeConstantValue(), ref arguments);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute))
            {
                VerifyConstantValueMatches(attribute.DecodeDecimalConstantValue(), ref arguments);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute))
            {
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute))
            {
                // NullableAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location);
            }
        }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyDefinitionTranslationUnitFactory"/> class.
 /// </summary>
 /// <param name="node">The syntax node.</param>
 /// <param name="semanticModel">The semantic model</param>
 /// <param name="createWhenProtected">A value indicating whether the factory should create a <see cref="ITranslationUnit"/> when <see cref="node"/> is protected.</param>
 public PropertyDefinitionTranslationUnitFactory(CSharpSyntaxNode node, SemanticModel semanticModel = null, bool createWhenProtected = false)
     : base(node, semanticModel)
 {
     this.createWhenProtected = createWhenProtected;
 }
Example #59
0
 public static IControlFlowGraph Create(CSharpSyntaxNode node, SemanticModel semanticModel)
 {
     return(new CSharpControlFlowGraphBuilder(node, semanticModel).Build());
 }
Example #60
0
 public abstract string GetCode(CSharpSyntaxNode Node);