public override void VisitInvocationExpression(IInvocationExpression invocation, IHighlightingConsumer consumer)
        {
            if (IsCallWithTheSameContextAsFunctionOwner(invocation))
                consumer.AddHighlighting(new CallWithSameContextWarning(invocation), invocation.GetHighlightingRange(), File);

            base.VisitInvocationExpression(invocation, consumer);
        }
        public override void VisitNode(ITreeNode element, IHighlightingConsumer consumer)
        {
            var tokenNode = element as ITokenNode;
            if (tokenNode != null && tokenNode.GetTokenType().IsWhitespace) return;

            var colorInfo = CreateColorHighlightingInfo(element);
            if (colorInfo != null)
                consumer.AddHighlighting(colorInfo.Highlighting, colorInfo.Range);
        }
 private void AddHighLighting(DocumentRange range, ITreeNode element, IHighlightingConsumer consumer, IHighlighting highlighting)
 {
   var info = new HighlightingInfo(range, highlighting, new Severity?());
   IFile file = element.GetContainingFile();
   if (file != null)
   {
     consumer.AddHighlighting(info.Highlighting, file);
   }
 }
 private void AddFactsSuggestionHighlighting(
     IHighlightingConsumer consumer, string message, IFact startElement, IFact endElement)
 {
     var highlighting = new HintRangeHighlighting<IFact>(startElement, endElement, message);
     IFile file = startElement.GetContainingFile();
     if (file != null)
     {
         consumer.AddHighlighting(highlighting, file);
     }
 }
		public override void VisitNode(ITreeNode node, IHighlightingConsumer context) {
			base.VisitNode(node, context);
			
			DocumentRange highlightingRange = node.GetHighlightingRange();
			//context.AddHighlighting(new PredefinedHighlighting(VsPredefinedHighlighterIds.RazorCode), highlightingRange);

			string attributeId = GetHighlightingAttributeId(node);
			if (attributeId != null)
				context.AddHighlighting(new PredefinedHighlighting(attributeId, highlightingRange));
		}
        /// <summary>
        /// Visits the element.
        /// </summary>
        /// <param name="element">The param.</param>
        /// <param name="consumer">The context.</param>
        /// <returns></returns>
        public override object VisitElement(IElement element, IHighlightingConsumer consumer)
        {
            var tokenType = element as ITokenNode;
              if (tokenType != null)
              {
            AddHighlighting(consumer, this.stringEmptyAnalyzer.Analyze(tokenType));
              }

              return base.VisitElement(element, consumer);
        }
        public void VisitLeaf(ITreeNode treeNode, IHighlightingConsumer consumer)
        {
            ICollection<DocumentRange> colorConstantRange = treeNode.UserData.GetData(Constants.Ranges);

            if (colorConstantRange == null)
                return;

            colorConstantRange.ForEach(
                range =>
                AddHighLighting(range, consumer, new TokenHighlighting(treeNode)));
        }
        public ExceptionalDaemonStageProcess(ICSharpFile file, IContextBoundSettingsStore settings)
            : base(ServiceLocator.Process, file)
        {
            _settings = settings;

            #if R2016_1 || R2016_2
            _consumer = new FilteringHighlightingConsumer(this, _settings, file);
            #else
            _consumer = new DefaultHighlightingConsumer(this, _settings);
            #endif
        }
 public override void VisitStatement(IStatement statementParam, IHighlightingConsumer consumer)
 {
     var canBeSimplified = statementParam.FactsEnumerable.GroupBy(x => x.Predicate.GetText()).Any(x => x.Count() >= 2);
     if (canBeSimplified)
     {
         this.AddFactsSuggestionHighlighting(
             consumer,
             "Facts can be simplified",
             statementParam.FactsEnumerable.First(),
             statementParam.FactsEnumerable.Last());
     }
 }
 public override void VisitRuleDeclaredName(IRuleDeclaredName ruleDeclaredName, IHighlightingConsumer consumer)
 {
   string name = ruleDeclaredName.GetText();
   if (myDeclarations.ContainsKey(name))
   {
     List<IDeclaration> list = myDeclarations.GetValue(name);
     if (list.Count > 1)
     {
       consumer.AddHighlighting(new DuplicatingLocalDeclarationError(ruleDeclaredName), File);
     }
   }
   base.VisitRuleDeclaredName(ruleDeclaredName, consumer);
 }
 public override void VisitNode(ITreeNode node, IHighlightingConsumer consumer)
 {
     // Tree level highlighting
     //
     const string prefixHighlighting = HighlightingAttributeIds.NAMESPACE_IDENTIFIER_ATTRIBUTE;
     if (node is IPrefix || node is IPrefixName)
     {
         this.AddSyntaxHighlighting(consumer, node, prefixHighlighting);
     }
     else if (node is ILocalName)
     {
         this.AddSyntaxHighlighting(consumer, node, HighlightingAttributeIds.METHOD_IDENTIFIER_ATTRIBUTE);
     }
     else if (node is IVariableIdentifier)
     {
         this.AddSyntaxHighlighting(consumer, node, HighlightingAttributeIds.FIELD_IDENTIFIER_ATTRIBUTE);
     }
     else if (node is ITokenNode)
     {
         // Token level highlighting
         // 
         var token = node as ITokenNode;
         if (token.GetTokenType().IsStringLiteral)
         {
             if (token.Parent is IDataLiteral && token.Parent.LastChild != token)
             {
                 this.AddSyntaxHighlighting(consumer, node, VsPredefinedHighlighterIds.String);
             }
             else
             {
                 this.AddSyntaxHighlighting(consumer, node, VsPredefinedHighlighterIds.String);
             }
         }
         else if (token.GetTokenType().IsComment)
         {
             this.AddSyntaxHighlighting(consumer, node, VsPredefinedHighlighterIds.Comment);
         }
         else if (token.GetTokenType().IsKeyword)
         {
             this.AddSyntaxHighlighting(consumer, node, VsPredefinedHighlighterIds.Keyword);
         }
         else if (token.GetTokenType().IsConstantLiteral)
         {
             //this.AddSyntaxHighlighting(consumer, node, VsPredefinedHighlighterIds.Literal);
         }
         else if (token.GetTokenType() == NTriplesTokenType.NAMESPACE_SEPARATOR)
         {
             this.AddSyntaxHighlighting(consumer, node, prefixHighlighting);
         }
     }
 }
 public override void VisitRuleDeclaration(IRuleDeclaration ruleDeclaration, IHighlightingConsumer consumer)
 {
   IRuleBody body = ruleDeclaration.Body;
   ITreeNode child = PsiTreeUtil.GetFirstChild<IRuleName>(body);
   var ruleName = child as IRuleName;
   if (ruleName != null)
   {
     if (ruleName.GetText().Equals(ruleDeclaration.DeclaredName))
     {
       consumer.AddHighlighting(new LeftRecursionWarning(ruleName), File);
     }
   }
   base.VisitRuleDeclaration(ruleDeclaration, consumer);
 }
        protected override void Run(IDllImportMethodDeclaration importMethod, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            var element = importMethod.MethodDeclaration;
            var libraryName = importMethod.ImportedDll;
            var factory = new LibraryFactory();
            var library = factory.LoadLibrary(libraryName);
            var export = library[element.NameIdentifier.Name];
            if (export == null || export.Parameters.Count != element.ParameterDeclarations.Count)
            {
                return;
            }

            for (var i = 0; i < element.ParameterDeclarations.Count; i++ )
            {
                var parameter = element.ParameterDeclarations[i];
                var knownParameter = export.Parameters[i];
                var exportedType = new ClrTypeName(knownParameter.CLRType.FullName);
                if (parameter.Type.IsInt() && exportedType.Equals(IntPtrClrType))
                {
                    consumer.AddHighlighting(new DllImportInt32ForIntPtrHighlighting(parameter));
                }
                var marshalAs = parameter.Attributes.GetAttibuteOfCLRType(MarshalAsAttribute);
                if (knownParameter.UnmanagedType.HasValue && marshalAs != null && marshalAs.ConstructorArgumentExpressions.Count == 1)
                {
                    var argumentExpression = marshalAs.ConstructorArgumentExpressions[0];
                    if (!argumentExpression.IsConstantValue())
                    {
                        continue;
                    }
                    var shortType = argumentExpression.ConstantValue.IsShort();
                    UnmanagedType unmanagedType;
                    if (shortType)
                    {
                        unmanagedType = (UnmanagedType)(short)argumentExpression.ConstantValue.Value;
                    }
                    else
                    {
                        unmanagedType = (UnmanagedType)argumentExpression.ConstantValue.Value;
                    }
                    if (knownParameter.UnmanagedType.Value != unmanagedType)
                    {
                        consumer.AddHighlighting(new DllImportIncorrectParameterMarshalHighlighting(parameter, argumentExpression, knownParameter.UnmanagedType.Value));
                    }
                }
            }
        }
    public override void VisitPsiExpression(IPsiExpression psiExpression, IHighlightingConsumer consumer)
    {
      ITreeNode child = psiExpression.FirstChild;
      IList<ISequence> list = new List<ISequence>();
      while (child != null)
      {
        if (child is ISequence)
        {
          list.Add(child as ISequence);
        }
        if (child is IChoiceTail)
        {
          list.Add((child as IChoiceTail).Sequence);
        }
        child = child.NextSibling;
      }

      if (list.Count > 1)
      {
        ISequence[] sequences = list.ToArray();
        var isRepeated = new bool[sequences.Count()];
        for (int i = 0 ; i < sequences.Count() - 1 ; ++i)
        {
          if (!isRepeated[i])
          {
            ISequence sequence1 = sequences[i];
            for (int j = i + 1 ; j < sequences.Count() ; ++j)
            {
              ISequence sequence2 = sequences[j];
              if (PsiTreeUtil.EqualsElements(sequence1, sequence2))
              {
                if (!isRepeated[i])
                {
                  consumer.AddHighlighting(new RepeatedChoiceWarning(sequence1), File);
                  isRepeated[i] = true;
                }
                consumer.AddHighlighting(new RepeatedChoiceWarning(sequence2), File);
                isRepeated[j] = true;
              }
            }
          }
        }
      }
      base.VisitPsiExpression(psiExpression, consumer);
    }
    public override void VisitRuleName(IRuleName ruleName, IHighlightingConsumer consumer)
    {
      DocumentRange colorConstantRange = ruleName.GetDocumentRange();

      ResolveResultWithInfo resolve = ruleName.RuleNameReference.Resolve();

      bool isRuleResolved = resolve.Result.DeclaredElement != null || (resolve.Result.Candidates.Count > 0);
      if (isRuleResolved)
      {
        AddHighLighting(colorConstantRange, ruleName, consumer, new PsiRuleHighlighting(ruleName));
      }
      else
      {
        AddHighLighting(colorConstantRange, ruleName, consumer, new PsiUnresolvedRuleReferenceHighlighting(ruleName));
      }

      base.VisitRuleName(ruleName, consumer);
    }
        private void VisitLoop(ITreeNode loop, IHighlightingConsumer consumer)
        {
            var function = loop.GetContainingNode<IJsFunctionLike>();
            var accessAnalizer = new VariableCollector();
            loop.ProcessThisAndDescendants(accessAnalizer);
            var accessToExternalModifiedClosure = accessAnalizer.Variables
                .GroupBy(r => r.DeclaredElement)
                .Select(g => g.ToArray())
                .Where(l => HasExternallyModifiedClosure(function, l))
                .SelectMany(l => l)
                .Where(r => r.FunctionLike != function)
                .Select(info => info.Node);

            foreach (var expression in accessToExternalModifiedClosure)
            {
                consumer.AddHighlighting(new AccessToModifiedClosureWarning(expression), expression.GetHighlightingRange(), File);
            }
        }
Exemplo n.º 17
0
		public override void VisitClassDeclaration(IClassDeclaration classDeclarationParam, IHighlightingConsumer context) {
			base.VisitClassDeclaration(classDeclarationParam, context);

			if (!classDeclarationParam.IsSynthetic()
			|| !T4CSharpCodeGenerator.ClassName.Equals(classDeclarationParam.DeclaredName, StringComparison.Ordinal))
				return;

			IDeclaredTypeUsage superTypeUsage = classDeclarationParam.SuperTypeUsageNodes.FirstOrDefault();
			if (superTypeUsage == null
			|| T4CSharpCodeGenerator.DefaultBaseClassName.Equals(superTypeUsage.GetText(), StringComparison.Ordinal))
				return;

			ITypeElement typeElement = CSharpTypeFactory.CreateDeclaredType(superTypeUsage).GetTypeElement();
			if (typeElement == null)
				return;

			if (!typeElement.Methods.Any(IsTransformTextMethod))
				context.AddHighlighting(new MissingTransformTextMethodHighlighting(superTypeUsage));
		}
 public override void VisitPrefix(IPrefix prefixParam, IHighlightingConsumer consumer)
 {
     DocumentRange range = prefixParam.GetDocumentRange();
     var prefix = prefixParam as Prefix;
     if (prefix != null)
     {
         ResolveResultWithInfo resolve = prefix.Resolve();
         if (resolve == null ||
             resolve.Result.DeclaredElement is UnresolvedNamespacePrefixDeclaredElement ||
             ((resolve.Result.DeclaredElement == null) && (resolve.Result.Candidates.Count == 0)))
         {
             this.AddHighLighting(
                 range,
                 prefixParam,
                 consumer,
                 new NTriplesUnresolvedReferenceHighlighting<NTriplesPrefixReference>(
                     prefix, prefix.PrefixReference, string.Format("Unresolved prefix '{0}'", prefix.GetText())));
         }
     }
 }
        public override void VisitSentences(ISentences sentencesParam, IHighlightingConsumer consumer)
        {
            string lastText = null;
            ISentence lastSentence = null;
            ISentence startSentence = null;
            const string message = "Statements can be simplified";
            foreach (var sentence in sentencesParam.SentenceListEnumerable)
            {
                string text;
                if (sentence.Statement != null && sentence.Statement.Subject != null &&
                    !string.IsNullOrEmpty(text = sentence.Statement.Subject.GetText()))
                {
                    if (text.Equals(lastText, StringComparison.Ordinal))
                    {
                        if (startSentence == null)
                        {
                            startSentence = lastSentence;
                        }
                    }
                    else
                    {
                        if (startSentence != null)
                        {
                            this.AddSentenceSuggestionHighlighting(consumer, message, startSentence, lastSentence);
                            startSentence = null;
                        }
                    }

                    lastSentence = sentence;
                    lastText = text;
                }
            }

            if (startSentence != null)
            {
                this.AddSentenceSuggestionHighlighting(consumer, message, startSentence, lastSentence);
            }
        }
 public override void VisitNode(ITreeNode node, IHighlightingConsumer consumer)
 {
   String s = node.GetText();
   if (PsiLexer.IsKeyword(s))
   {
     AddHighlighting(consumer, node);
   }
   else
   {
     var token = node as PsiGenericToken;
     if (token != null)
     {
       if (token.GetTokenType().IsStringLiteral)
       {
         AddHighlighting(consumer, new PsiStringLiteralHighlighting(node));
       }
       else if (token.GetTokenType().IsComment)
       {
         AddHighlighting(consumer, new PsiCommentHighlighting(node));
       }
     }
   }
 }
 public override void VisitNode(ITreeNode node, IHighlightingConsumer consumer)
 {
     var element = node as IErrorElement;
     if (element != null)
     {
         if (element.GetTextLength() == 0)
         {
             ITreeNode parent = element.Parent;
             while ((parent != null) && (parent.GetTextLength() == 0))
             {
                 parent = parent.Parent;
             }
             if (parent != null)
             {
                 this.AddHighlighting(consumer, parent);
             }
         }
         else
         {
             this.AddHighlighting(consumer, element);
         }
     }
 }
    public override void VisitNode(ITreeNode element, IHighlightingConsumer consumer)
    {
      DocumentRange colorConstantRange = element.GetDocumentRange();

      if ((element is ITokenNode) && ((ITokenNode)element).GetTokenType().IsWhitespace)
      {
        return;
      }

      var variableName = element as VariableName;
      if (variableName != null)
      {
        ResolveResultWithInfo resolve = variableName.Resolve();
        if ((resolve != null) && ((resolve.Result.DeclaredElement != null) || (resolve.Result.Candidates.Count > 0)))
        {
          AddHighLighting(colorConstantRange, element, consumer, new PsiVariableHighlighting(element));
        }
        else
        {
          AddHighLighting(colorConstantRange, element, consumer, new PsiUnresolvedVariableReferenceHighlighting(variableName));
          return;
        }
      }
      var pathName = element as PathName;
      if (pathName != null)
      {
        ResolveResultWithInfo resolve = pathName.Resolve();
        if ((resolve != null) && ((resolve.Result.DeclaredElement != null) || (resolve.Result.Candidates.Count > 0)))
        {
          AddHighLighting(colorConstantRange, element, consumer, new PsiRuleHighlighting(element));
        }
        else
        {
          AddHighLighting(colorConstantRange, element, consumer, new PsiUnresolvedPathReferenceHighlighting(pathName));
        }
      }
    }
Exemplo n.º 23
0
        protected override void Analyze(IInvocationExpression invocationExpression, ElementProblemAnalyzerData data,
                                        IHighlightingConsumer consumer)
        {
            if (!myAssetSerializationMode.IsForceText)
            {
                return;
            }

            if (!myUnityYamlSupport.IsParsingEnabled.Value)
            {
                return;
            }

            var argument = GetSceneNameArgument(invocationExpression);
            var literal  = argument?.Value as ICSharpLiteralExpression;

            if (literal == null)
            {
                return;
            }

            if (invocationExpression.InvocationExpressionReference.IsSceneManagerSceneRelatedMethod())
            {
                var cache = invocationExpression.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                if (cache == null)
                {
                    return;
                }

                var sceneName = GetScenePathFromArgument(literal);
                if (sceneName != null)
                {
                    // check build settings warnings
                    if (cache.IsScenePresentedAtEditorBuildSettings(sceneName,
                                                                    out var ambiguousDefinition))
                    {
                        if (cache.IsSceneDisabledAtEditorBuildSettings(sceneName))
                        {
                            consumer.AddHighlighting(new LoadSceneDisabledSceneNameWarning(argument, sceneName));
                        }
                        else if (ambiguousDefinition)
                        {
                            consumer.AddHighlighting(
                                new LoadSceneAmbiguousSceneNameWarning(argument, sceneName));
                        }
                    }
                    else
                    {
                        if (cache.IsSceneExists(sceneName))
                        {
                            consumer.AddHighlighting(new LoadSceneUnknownSceneNameWarning(argument, sceneName));
                        }
                        else
                        {
                            consumer.AddHighlighting(new LoadSceneUnexistingSceneNameWarning(argument));
                        }
                    }
                }
                else if (literal.ConstantValue.IsInteger())
                {
                    var value = (int)literal.ConstantValue.Value;
                    if (value >= cache.SceneCount)
                    {
                        consumer.AddHighlighting(new LoadSceneWrongIndexWarning(argument));
                    }
                }
            }

            if (invocationExpression.InvocationExpressionReference.IsEditorSceneManagerSceneRelatedMethod())
            {
                var cache = invocationExpression.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                if (cache == null)
                {
                    return;
                }

                var sceneName = GetScenePathFromArgument(literal);
                if (sceneName != null)
                {
                    if (!cache.IsSceneExists(sceneName))
                    {
                        consumer.AddHighlighting(new LoadSceneUnexistingSceneNameWarning(argument));
                    }
                }
            }
        }
Exemplo n.º 24
0
        protected override void Analyze(INullCoalescingExpression expression, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (!(expression.LeftOperand is IReferenceExpression leftOperand) || expression.RightOperand == null)
            {
                return;
            }
            var resolve = leftOperand.Reference.Resolve();

            if (resolve.ResolveErrorType != ResolveErrorType.OK)
            {
                return;
            }
            var unityObjectType = TypeFactory.CreateTypeByCLRName(KnownTypes.Object, expression.GetPsiModule());

            if (!leftOperand.Type().IsSubtypeOf(unityObjectType))
            {
                return;
            }

            consumer.AddHighlighting(new UnityObjectNullCoalescingWarning(expression));
        }
Exemplo n.º 25
0
 protected override bool CheckAndAnalyze(IMethodDeclaration methodDeclaration, IHighlightingConsumer consumer, IReadOnlyCallGraphContext context)
 {
     return(false);
 }
Exemplo n.º 26
0
            public override void VisitExpressionStatementNode(IExpressionStatement expressionStatementParam, IHighlightingConsumer context)
            {
                if (expressionStatementParam.FirstChild is IIdentifier identifier)
                {
                    context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.VARIABLE_IDENTIFIER, identifier.GetDocumentRange()));
                }

                base.VisitExpressionStatementNode(expressionStatementParam, context);
            }
 protected override void Analyze(IJavaScriptLiteralExpression element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
 {
     if (element.IsReferencesStringLiteralValue())
     {
         var nameCache           = data.Solution.GetComponent <AsmDefNameCache>();
         var nameDeclaredElement = nameCache.GetNameDeclaredElement(data.SourceFile);
         var reference           = element.FindReference <AsmDefNameReference>();
         if (reference != null && nameDeclaredElement != null &&
             Equals(reference.Resolve().DeclaredElement, nameDeclaredElement))
         {
             consumer.AddHighlighting(new ReferencingSelfError(reference));
         }
     }
 }
        protected override void Run(IStartRegion element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (element.EndRegion != null)
            {
                var nonWhitespaceNodes = 0;
                foreach (var node in TreeRange.Build(element, element.EndRegion).Skip(1).TakeWhile(n => n != element.EndRegion))
                {
                    if (node?.NodeType is TokenNodeType tokenNodeType && tokenNodeType.IsWhitespace)
                    {
                        continue;
                    }

                    nonWhitespaceNodes++;

                    if (nonWhitespaceNodes > 1)
                    {
                        break;
                    }
                }

                switch (nonWhitespaceNodes)
                {
                case 0:
                    consumer.AddHighlighting(new EmptyRegionHighlighting("The region is empty.", element));
                    break;

                case 1:
                    consumer.AddHighlighting(new RegionWithSingleElementHighlighting("The region contains a single element.", element));
                    break;
                }
            }

            if (element.GetContainingNode <IBlock>() != null)
            {
                consumer.AddHighlighting(new RegionWithinTypeMemberBodyHighlighting("The region is contained within a type member body.", element));
            }
        }
        protected override void Run(
            IInvocationExpression element,
            ElementProblemAnalyzerData data,
            IHighlightingConsumer consumer)
        {
            var templateArgument = element.GetTemplateArgument();

            if (templateArgument == null)
            {
                return;
            }

            var exceptionType = element.PsiModule.GetPredefinedType().TryGetType(PredefinedType.EXCEPTION_FQN, NullableAnnotation.Unknown);

            if (exceptionType == null)
            {
                return;
            }

            ICSharpArgument invalidExceptionArgument = FindInvalidExceptionArgument(element, templateArgument, exceptionType);

            if (invalidExceptionArgument == null)
            {
                return;
            }

            var overloadAvailable    = false;
            var candidates           = element.InvocationExpressionReference.GetCandidates().ToArray();
            var invalidArgumentIndex = invalidExceptionArgument.IndexOf();

            foreach (var candidate in candidates)
            {
                if (!(candidate.GetDeclaredElement() is IMethod declaredElement))
                {
                    continue;
                }

                foreach (var parameter in declaredElement.Parameters)
                {
                    if (invalidArgumentIndex <= parameter.IndexOf())
                    {
                        break;
                    }

                    if (parameter.Type.IsSubtypeOf(exceptionType))
                    {
                        overloadAvailable = true;
                        break;
                    }
                }

                if (overloadAvailable)
                {
                    break;
                }
            }

            if (!overloadAvailable)
            {
                return;
            }

            consumer.AddHighlighting(new ExceptionPassedAsTemplateArgumentWarning(invalidExceptionArgument.GetDocumentRange()));
        }
        /// <summary>
        /// Adds the highlighting.
        /// </summary>
        /// <param name="consumer">The consumer.</param>
        /// <param name="suggestions">The suggestions.</param>
        private static void AddHighlighting(IHighlightingConsumer consumer, IEnumerable<SuggestionBase> suggestions)
        {
            if (suggestions == null)
              {
            return;
              }

              foreach (var highlighting in suggestions)
              {
            AddHighlighting(consumer, highlighting);
              }
        }
 /// <summary>
 /// Visits the type member.
 /// </summary>
 /// <param name="typeMemberDeclaration">The type member declaration.</param>
 /// <param name="consumer">The consumer.</param>
 /// <returns></returns>
 private void VisitTypeMember(ITypeMemberDeclaration typeMemberDeclaration, IHighlightingConsumer consumer)
 {
     AddHighlighting(consumer, this.valueAnalysisAnalyzer.Analyze(typeMemberDeclaration));
 }
        protected override void Run(
            ICSharpFunctionDeclaration element,
            ElementProblemAnalyzerData data,
            IHighlightingConsumer consumer)
        {
            if (element.Body == null)
            {
                return;
            }

            var elementProcessor = new CognitiveComplexityElementProcessor(element);

            element.Body.ProcessDescendants(elementProcessor);

            var store                = data.SettingsStore;
            var baseThreshold        = store.GetValue((CognitiveComplexityAnalysisSettings s) => s.CSharpThreshold);
            var complexityPercentage = (int)(elementProcessor.ComplexityScore * 100.0 / baseThreshold);

            if (complexityPercentage > 100)
            {
                consumer.AddHighlighting(new CognitiveComplexityErrorHighlighting(
                                             element,
                                             elementProcessor.ComplexityScore - baseThreshold,
                                             complexityPercentage));
            }
            else
            {
                consumer.AddHighlighting(new CognitiveComplexityInfoHighlighting(
                                             element,
                                             elementProcessor.ComplexityScore,
                                             complexityPercentage));
            }

#if RIDER
            var lowThreshold    = store.GetValue((CognitiveComplexityAnalysisSettings s) => s.LowComplexityThreshold);
            var middleThreshold =
                store.GetValue((CognitiveComplexityAnalysisSettings s) => s.MiddleComplexityThreshold);
            var highThreshold = store.GetValue((CognitiveComplexityAnalysisSettings s) => s.HighComplexityThreshold);

            string codeLensText;
            IconId iconId;

            if (complexityPercentage >= highThreshold)
            {
                iconId       = ComplexityExtreme.Id;
                codeLensText = complexityPercentage >= highThreshold * 2
                    ? $"refactor me? ({complexityPercentage}%)"
                    : $"very complex ({complexityPercentage}%)";
            }
            else if (complexityPercentage >= middleThreshold)
            {
                iconId       = ComplexityHigh.Id;
                codeLensText = $"mildly complex ({complexityPercentage}%)";
            }
            else if (complexityPercentage >= lowThreshold)
            {
                iconId       = ComplexityAverage.Id;
                codeLensText = $"simple enough ({complexityPercentage}%)";
            }
            else
            {
                iconId       = ComplexityLow.Id;
                codeLensText = string.Empty;
            }

            var moreText =
                $"Cognitive complexity value of {elementProcessor.ComplexityScore} " +
                $"({complexityPercentage}% of threshold {baseThreshold})";
            consumer.AddHighlighting(
                new CodeInsightsHighlighting(
                    element.GetNameDocumentRange(),
                    codeLensText,
                    moreText,
                    moreText,
                    _codeInsightsProvider,
                    element.DeclaredElement,
                    _iconHost.Transform(iconId))
                );

            if (elementProcessor.Complexities != null)
            {
                var min = int.MaxValue;
                var max = int.MinValue;
                foreach (var(_, _, complexity) in elementProcessor.Complexities)
                {
                    min = Math.Min(min, complexity);
                    max = Math.Max(max, complexity);
                }

                foreach (var(node, offset, complexity) in elementProcessor.Complexities)
                {
                    if (complexityPercentage >= highThreshold && complexity == max)
                    {
                        consumer.AddHighlighting(new CognitiveComplexityErrorHint(node, offset, complexity));
                    }
                    else if (complexityPercentage >= middleThreshold && complexity >= min + (max - min) / 2)
                    {
                        consumer.AddHighlighting(new CognitiveComplexityWarningHint(node, offset, complexity));
                    }
                    else
                    {
                        consumer.AddHighlighting(new CognitiveComplexityInfoHint(node, offset, complexity));
                    }
                }
            }
#endif
        }
Exemplo n.º 33
0
 public override void VisitNode(ITreeNode node, IHighlightingConsumer consumer)
 {
     myElementAnalyzerDispatcher.Run(node, consumer);
 }
 private void HighlightNameNodes(IVariableDeclaration variableDeclaration, IHighlightingConsumer context, string highlightingAttributeId)
 {
     foreach (var name in variableDeclaration.NameNodes)
     {
         context.AddHighlighting(new CgHighlighting(highlightingAttributeId, name.GetDocumentRange()));
     }
 }
Exemplo n.º 35
0
        protected override void Run(IInvocationExpression element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            /*
             *  this.WhenAnyValue(
             *          x => x.Toggle,
             *          x => _settingsProvider.Settings.IsAdmin,
             *          (toggle, admin) => toggle && admin)
             *      .ToProperty(this, nameof(ShowAdmin), out _showAdmin);
             */
            var method = element.InvocationExpressionReference.Resolve().DeclaredElement as IMethod;

            if (method?.ShortName != "WhenAnyValue")
            {
                return;
            }

            var typeByClrName = TypeFactory.CreateTypeByCLRName("ReactiveUI.WhenAnyMixin", element.PsiModule);

            if (method.GetContainingType()?.Equals(typeByClrName.GetTypeElement()) ?? true)
            {
                return;
            }

            foreach (var argument in element.ArgumentsEnumerable)
            {
                // A.B.C
                //     -> A.B
                //         -> A
                var lambdaExpression    = argument.Expression as ILambdaExpression;
                var referenceExpression = lambdaExpression?.BodyExpression as IReferenceExpression;
                var qualifierExpression = referenceExpression?.TraverseAcross(x => x.QualifierExpression as IReferenceExpression)
                                          .Last();

                // var qualifierExpression = referenceExpression.QualifierExpression as IReferenceExpression;
                if (qualifierExpression == null)
                {
                    continue;
                }

                var parameter = lambdaExpression.ParameterDeclarations.FirstOrDefault();
                if (parameter == null)
                {
                    continue;
                }

                if (parameter.NameIdentifier.Name == qualifierExpression.NameIdentifier.Name)
                {
                    continue;
                }

                var field = qualifierExpression.Reference.Resolve().DeclaredElement as IField;
                var type  = field?.GetContainingType();

                // if (type?.GetClrName().FullName != (parameter.DeclaredElement.Type as IDeclaredType)?.GetClrName().FullName)
                if (!type?.Equals((parameter.DeclaredElement.Type as IDeclaredType)?.GetTypeElement()) ?? true)
                {
                    continue;
                }

                consumer.AddHighlighting(new SampleHighlighting(lambdaExpression));
            }
        }
Exemplo n.º 36
0
 protected override void Run(IReferenceExpression element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
 {
     if (element.QualifierExpression != null &&
         !element.HasConditionalAccessSign &&
         element.Reference.Resolve().DeclaredElement.IsDelegateInvokeMethod() &&
         element.GetNextMeaningfulSibling() is CSharpTokenBase token &&
         token.GetTokenType() == CSharpTokenType.LPARENTH)
     {
         consumer.AddHighlighting(new RedundantDelegateInvokeHighlighting($"Redundant '{nameof(Action.Invoke)}' expression.", element));
     }
 }
 protected override void Run(ISpecificCatchClause element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
 {
     if (element.ExceptionType.ToString() == "System.Exception" && element.ExceptionDeclaration == null)
     {
         consumer.AddHighlighting(new CatchClauseWithoutVariableSuggestion("Redundant declaration without exception variable.", element));
     }
 }
Exemplo n.º 38
0
        protected override void Analyze(IAttribute attribute, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (!(attribute.TypeReference?.Resolve().DeclaredElement is ITypeElement attributeTypeElement))
            {
                return;
            }

            if (!Equals(attributeTypeElement.GetClrName(), KnownTypes.HideInInspector))
            {
                return;
            }

            var fields = attribute.GetFieldsByAttribute();

            foreach (var field in fields)
            {
                if (!Api.IsSerialisedField(field))
                {
                    consumer.AddHighlighting(new RedundantHideInInspectorAttributeWarning(attribute));
                    return;
                }
            }
        }
Exemplo n.º 39
0
 protected virtual void AddHighlighting(IHighlightingConsumer consumer, ICSharpDeclaration element, string text,
                                        string tooltip, DaemonProcessKind kind)
 {
     consumer.AddImplicitConfigurableHighlighting(element);
     consumer.AddHotHighlighting(CallGraphSwaExtensionProvider, element, MarksProvider, Settings, text, tooltip, kind, GetActions(element), myProvider);
 }
Exemplo n.º 40
0
        protected override void Run(ICSharpTreeNode element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            IExpressionType exceptionType;

            switch (element)
            {
            case IThrowStatement throwStatement:
                exceptionType = throwStatement.Exception?.GetExpressionType();
                break;

            case IThrowExpression throwExpression:
                exceptionType = throwExpression.Exception?.GetExpressionType();
                break;

            default: return;
            }

            if (exceptionType == null)
            {
                return;
            }

            var location = TryGetLocation(element, data);

            if (location != null)
            {
                if (GetAllowedExceptions((Location)location, element.GetPsiModule()).Any(e => IsOrDerivesFrom(exceptionType, e)))
                {
                    return;
                }

                consumer.AddHighlighting(
                    new ThrowExceptionInUnexpectedLocationWarning($"Exceptions should never be thrown in {GetText((Location)location)}.", element));
            }
        }
Exemplo n.º 41
0
 public abstract bool AddDeclarationHighlighting(IDeclaration treeNode, IHighlightingConsumer consumer,
                                                 DaemonProcessKind kind);
Exemplo n.º 42
0
        protected override void Analyze(IInvocationExpression element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (!myAssetSerializationMode.IsForceText)
            {
                return;
            }

            if (!myUnityYamlSupport.IsParsingEnabled.Value)
            {
                return;
            }

            if (element.IsLayerMaskGetMaskMethod() || element.IsLayerMaskNameToLayerMethod())
            {
                foreach (var argument in element.ArgumentList.Arguments)
                {
                    var literal = (argument?.Value as ICSharpLiteralExpression)?.ConstantValue.Value as string;
                    if (literal == null)
                    {
                        return;
                    }

                    var cache = element.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                    if (cache != null && !cache.HasLayer(literal))
                    {
                        consumer.AddHighlighting(new UnknownLayerWarning(argument));
                    }
                }
            }
        }
 public override void VisitFieldOperatorNode(IFieldOperator fieldOperatorParam, IHighlightingConsumer context)
 {
     context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.FIELD_IDENTIFIER, fieldOperatorParam.FieldNode.GetDocumentRange()));
     base.VisitFieldOperatorNode(fieldOperatorParam, context);
 }
Exemplo n.º 44
0
        public override void VisitClassDeclaration(IClassDeclaration classDeclarationParam, IHighlightingConsumer context)
        {
            base.VisitClassDeclaration(classDeclarationParam, context);

            if (!classDeclarationParam.IsSynthetic() ||
                !T4CSharpCodeGenerator.ClassName.Equals(classDeclarationParam.DeclaredName, StringComparison.Ordinal))
            {
                return;
            }

            IDeclaredTypeUsage superTypeUsage = classDeclarationParam.SuperTypeUsageNodes.FirstOrDefault();

            if (superTypeUsage == null ||
                T4CSharpCodeGenerator.DefaultBaseClassName.Equals(superTypeUsage.GetText(), StringComparison.Ordinal))
            {
                return;
            }

            ITypeElement typeElement = CSharpTypeFactory.CreateDeclaredType(superTypeUsage).GetTypeElement();

            if (typeElement == null)
            {
                return;
            }

            if (!typeElement.Methods.Any(IsTransformTextMethod))
            {
                context.AddHighlighting(new MissingTransformTextMethodHighlighting(superTypeUsage));
            }
        }
Exemplo n.º 45
0
        protected sealed override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            var processKind = data.GetDaemonProcessKind();

            if (processKind != DaemonProcessKind.VISIBLE_DOCUMENT)
            {
                return;
            }

            Analyze(element, data, consumer);
        }
            public override void VisitPostfixExpressionNode(IPostfixExpression postfixExpressionParam, IHighlightingConsumer context)
            {
                if (postfixExpressionParam.OperatorNode.FirstOrDefault() is ICallOperator &&
                    postfixExpressionParam.OperandNode is IIdentifier functionName)
                {
                    context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.FUNCTION_IDENTIFIER, functionName.GetDocumentRange()));
                }

                base.VisitPostfixExpressionNode(postfixExpressionParam, context);
            }
        /// <summary>
        /// Visits the throw statement.
        /// </summary>
        /// <param name="throwStatement">The throw statement.</param>
        /// <param name="consumer">The consumer.</param>
        /// <returns></returns>
        public override object VisitThrowStatement(IThrowStatement throwStatement, IHighlightingConsumer consumer)
        {
            AddHighlighting(consumer, this.documentThrownExceptionAnalyzer.AnalyzeThrowStatement(throwStatement));

              return base.VisitThrowStatement(throwStatement, consumer);
        }
 public GlobalProcessor(PsiDaemonStageProcessBase process, IHighlightingConsumer consumer)
   : base(process, consumer)
 {
 }
        /// <summary>
        /// Adds the highlighting.
        /// </summary>
        ///<param name="consumer">The consumer.</param>
        ///<param name="highlighting">The highlighting.</param>
        private static void AddHighlighting(IHighlightingConsumer consumer, SuggestionBase highlighting)
        {
            var range = highlighting.Range;
              if (!range.IsValid())
              {
            return;
              }

              consumer.AddHighlighting(range, highlighting);
        }
        public BurstProblemSubAnalyzerStatus CheckAndAnalyze(IReferenceExpression referenceExpression, IHighlightingConsumer consumer)
        {
            var element = referenceExpression.Reference.Resolve().DeclaredElement;

            if (!(element is ITypeOwner typeOwner))
            {
                return(BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE);
            }

            if (typeOwner is IAttributesOwner attributesOwner &&
                attributesOwner.HasAttributeInstance(KnownTypes.NativeSetClassTypeToNullOnScheduleAttribute, AttributesSource.Self))
            {
                return(BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE);
            }

            if (BurstCodeAnalysisUtil.IsBurstPermittedType(typeOwner.Type()))
            {
                return(BurstProblemSubAnalyzerStatus.NO_WARNING_CONTINUE);
            }

            consumer?.AddHighlighting(new BurstLoadingManagedTypeWarning(
                                          referenceExpression,
                                          typeOwner.Type().GetTypeElement()?.ShortName));

            return(BurstProblemSubAnalyzerStatus.WARNING_PLACED_STOP);
        }
 /// <summary>
 /// Visits the constructor declaration.
 /// </summary>
 /// <param name="constructorDeclaration">The constructor declaration.</param>
 /// <param name="consumer">The consumer.</param>
 /// <returns></returns>
 public override object VisitConstructorDeclaration(IConstructorDeclaration constructorDeclaration, IHighlightingConsumer consumer)
 {
     this.VisitTypeMember(constructorDeclaration, consumer);
       return base.VisitConstructorDeclaration(constructorDeclaration, consumer);
 }
 public override void VisitStructDeclarationNode(IStructDeclaration structDeclarationParam, IHighlightingConsumer context)
 {
     context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.TYPE_IDENTIFIER, structDeclarationParam.NameNode.GetDocumentRange()));
     base.VisitStructDeclarationNode(structDeclarationParam, context);
 }
 public override void VisitRuleDeclaredName(IRuleDeclaredName ruleDeclaredName, IHighlightingConsumer consumer)
 {
   DocumentRange colorConstantRange = ruleDeclaredName.GetDocumentRange();
   AddHighLighting(colorConstantRange, ruleDeclaredName, consumer, new PsiRuleHighlighting(ruleDeclaredName));
   base.VisitRuleDeclaredName(ruleDeclaredName, consumer);
 }
            public override void VisitFunctionDeclarationNode(IFunctionDeclaration functionDeclarationParam, IHighlightingConsumer context)
            {
                var header = functionDeclarationParam.HeaderNode;

                if (header.TypeNode is IIdentifier userDeclaredType)
                {
                    context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.TYPE_IDENTIFIER, userDeclaredType.GetDocumentRange()));
                }

                try
                {
                    context.AddHighlighting(new CgHighlighting(CgHighlightingAttributeIds.FUNCTION_IDENTIFIER,
                                                               header.NameNode.GetDocumentRange()));
                }
                catch (InvalidCastException ex)
                {
                    // TODO: remove after PP implementation
                    myLogger.LogExceptionSilently(ex);
                }

                base.VisitFunctionDeclarationNode(functionDeclarationParam, context);
            }
 public static void AddImplicitConfigurableHighlighting(this IHighlightingConsumer consumer,
                                                        ICSharpDeclaration declaration)
 {
     consumer.AddHighlighting(new UnityImplicitlyUsedIdentifierHighlighting(declaration.NameIdentifier.GetDocumentRange()));
 }
 private void CreateHiglighting(IInvocationExpression expression, IHighlightingConsumer consumer)
 {
     consumer.AddHighlighting(new UnityPerformanceInvocationWarning(expression, (expression.InvokedExpression as IReferenceExpression)?.Reference));
 }
 public override void VisitVariableDeclarationNode(IVariableDeclaration variableDeclarationParam, IHighlightingConsumer context)
 {
     HighlightNameNodes(variableDeclarationParam, context, CgHighlightingAttributeIds.VARIABLE_IDENTIFIER);
     base.VisitVariableDeclarationNode(variableDeclarationParam, context);
 }
        protected override void Run(IInvocationExpression element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            var conditions = GetConditionsIfConditionalMethodInvoked(element);

            if (conditions.Count > 0)
            {
                consumer.AddHighlighting(
                    new ConditionalInvocationHighlighting(
                        conditions.Count == 1
                            ? string.Format("Method invocation will be skipped if the '{0}' condition is not defined.", conditions[0])
                            : string.Format(
                            "Method invocation will be skipped if none of the following conditions is defined: {0}.",
                            string.Join(", ", from condition in conditions orderby condition select $"'{condition}'")),
                        element));
            }
        }
 protected ProcessorBase(PsiDaemonStageProcessBase process, IHighlightingConsumer consumer)
 {
   myProcess = process;
   myConsumer = consumer;
 }
            public override void VisitFieldDeclarationNode(IFieldDeclaration fieldDeclarationParam, IHighlightingConsumer context)
            {
                var variableDeclaration = fieldDeclarationParam.ContentNode;

                if (variableDeclaration != null)
                {
                    HighlightNameNodes(variableDeclaration, context, CgHighlightingAttributeIds.FIELD_IDENTIFIER);
                }

                base.VisitFieldDeclarationNode(fieldDeclarationParam, context);
            }