Exemplo n.º 1
0
        private ITypeElement GetRelatedTypeElementFromAttributeUsage(ICSharpLiteralExpression literalExpression)
        {
            var attribute = AttributeNavigator.GetByConstructorArgumentExpression(literalExpression);
              if (attribute == null)
            return null;

              var argument = (ICSharpArgument) literalExpression.Parent.AssertNotNull();
              if (argument.MatchingParameter == null)
            return null;

              var parameter = argument.MatchingParameter.Element;
              if (parameter.HasAttributeInstance(s_memberReferenceAttribute, false))
            return null;

              var constructor = attribute.ConstructorReference.GetResolved<IConstructor>().AssertNotNull();
              var literalArgumentIndex = constructor.Parameters.IndexOf(parameter);
              if (literalArgumentIndex == 0)
            return null;

              var typeofExpression = attribute.Arguments[literalArgumentIndex - 1].Expression as ITypeofExpression;
              if (typeofExpression == null)
            return null;

              return ((IDeclaredType) typeofExpression.ArgumentType).GetTypeElement();
        }
        private ITypeElement GetRelatedTypeElementFromAttributeUsage(ICSharpLiteralExpression literalExpression)
        {
            var attribute = AttributeNavigator.GetByConstructorArgumentExpression(literalExpression);

            if (attribute == null)
            {
                return(null);
            }

            var argument = (ICSharpArgument)literalExpression.Parent.NotNull();

            if (argument.MatchingParameter == null)
            {
                return(null);
            }

            var parameter            = argument.MatchingParameter.Element;
            var constructor          = attribute.ConstructorReference.GetResolved <IConstructor>().NotNull();
            var literalArgumentIndex = constructor.Parameters.IndexOf(parameter);

            if (literalArgumentIndex == 0)
            {
                return(null);
            }

            var typeofExpression = attribute.Arguments[literalArgumentIndex - 1].Expression as ITypeofExpression;

            if (typeofExpression == null)
            {
                return(null);
            }

            return(((IDeclaredType)typeofExpression.ArgumentType).GetTypeElement());
        }
        private static IAssignableExpression ToConst(ICSharpLiteralExpression lit, bool isPositive)
        {
            var isNull = lit.ConstantValue.IsPureNull(CSharpLanguage.Instance);

            if (isNull)
            {
                return(new ConstantValueExpression {
                    Value = ConstantValueExpression.Null
                });
            }

            var val = lit.ConstantValue.Value;

            if (val is string)
            {
                return(new ConstantValueExpression());
            }

            if (val is int)
            {
                var i = (int)val;
                if (!isPositive)
                {
                    i = -1 * i;
                }
                var v = i == -1 || i == 0 || i == 1 || i == 2 ? i.ToString() : null;
                return(new ConstantValueExpression {
                    Value = v
                });
            }

            if (val is double)
            {
                var d = (double)val;
                if (!isPositive)
                {
                    d = -1 * d;
                }
                string v = null;
                Func <double, double, bool> isEq = (a, b) => Math.Abs(a - b) < 0.000001;
                if (isEq(d, 0) || isEq(d, -1) || isEq(d, 1))
                {
                    v = string.Format("{0:0.0}", d).Replace(',', '.');
                }
                return(new ConstantValueExpression {
                    Value = v
                });
            }

            if (val is bool)
            {
                var b = (bool)val;
                return(new ConstantValueExpression
                {
                    Value = b ? ConstantValueExpression.True : ConstantValueExpression.False
                });
            }

            return(new ConstantValueExpression());
        }
 public LogIntroducerContextAction(ICSharpContextActionDataProvider provider)
 {
     factory           = provider.ElementFactory;
     classDeclaration  = provider.GetSelectedElement <IClassDeclaration>();
     literalExpression = provider.GetSelectedElement <ICSharpLiteralExpression>();
     file = classDeclaration?.GetContainingFile() as ICSharpFile;
 }
Exemplo n.º 5
0
        private ReferenceCollection CreateTypeNameReferences(ICSharpLiteralExpression literal,
                                                             ExpectedObjectTypeReferenceKind kind)
        {
            var literalValue = (string)literal.ConstantValue.Value;

            if (literalValue == null)
            {
                return(ReferenceCollection.Empty);
            }

            var symbolCache = literal.GetPsiServices().Symbols;

            IQualifier qualifier    = null;
            var        references   = new LocalList <IReference>();
            var        startIndex   = 0;
            var        nextDotIndex = literalValue.IndexOf('.');

            while (true)
            {
                var endIndex = nextDotIndex != -1 ? nextDotIndex : literalValue.Length;

                // startIndex + 1 to skip leading quote in tree node, which doesn't exist in literalValue
                var rangeWithin = TextRange.FromLength(startIndex + 1, endIndex - startIndex);

                // Behaviour and resolution is almost identical for each part.
                // For a single component, it is either a Unity object with an inferred namespace, a type in the global
                // namespace, or the namespace for an as yet uncompleted qualified type name
                // For a trailing component, it is a qualified reference, and could be a type, or a continuation of the
                // namespace qualification
                // For a middle component, it could be a namespace, or the user typing a new type, with the trailing
                // text being the old component
                // When there is no qualifier, resolve should match:
                // * inferred type, with expected type check
                // * type in global namespace, with expected type check
                // * namespace, with expected type check (so namespace won't be the last thing)
                // When there is a qualifier, resolve should match
                // * namespaces
                // * qualified type with expected type check
                // For the final component, resolve should match namespaces, but with the expected type check
                // At all times, completion should show both namespaces and qualified types
                // Leading and trailing space are treated as part of a name, and will cause resolve to fail
                // TODO: Handle trailing dot
                var isFinalPart = nextDotIndex == -1;
                var reference   = new UnityObjectTypeOrNamespaceReference(literal, qualifier, literal.Literal, rangeWithin,
                                                                          kind, symbolCache, isFinalPart);

                references.Add(reference);
                if (nextDotIndex == -1)
                {
                    break;
                }

                startIndex   = nextDotIndex + 1;
                nextDotIndex = literalValue.IndexOf('.', startIndex);
                qualifier    = reference;
            }

            return(new ReferenceCollection(references.ReadOnlyList()));
        }
Exemplo n.º 6
0
        protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
        {
            var ranges = context.CompletionRanges;
            IEnumerable <string>     completionItems = null;
            ICSharpLiteralExpression argumentLiteral = null;

            // scene completion
            if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsLoadSceneMethod, IsCorrespondingArgument("sceneName")))
            {
                var cache = context.NodeInFile.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                completionItems = cache.GetAllPossibleSceneNames();
            } // tag completion, tag == "..."
            else if (IsTagEquality(context, out argumentLiteral))
            {
                var cache = context.NodeInFile.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                completionItems = cache.GetAllTags();
            } //// tag completion, CompareTag("...")
            else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsCompareTagMethod, IsCorrespondingArgument("tag")))
            {
                var cache = context.NodeInFile.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                completionItems = cache.GetAllTags();
            } // layer completion
            else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsLayerMaskNameToLayer,
                                                        IsCorrespondingArgument("layerName")) || IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsLayerMaskGetMask,
                                                                                                                                    (_, __) => true))
            {
                var cache = context.NodeInFile.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                completionItems = cache.GetAllLayers();
            }  // input completion
            else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsInputButtonMethod, IsCorrespondingArgument("buttonName")) ||
                     IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsInputAxisMethod, IsCorrespondingArgument("axisName")))
            {
                var cache = context.NodeInFile.GetSolution().TryGetComponent <UnityProjectSettingsCache>();
                completionItems = cache.GetAllInput();
            }

            var any = false;

            if (argumentLiteral != null)
            {
                var offset = argumentLiteral.GetDocumentRange().EndOffset;
                ranges = ranges.WithInsertRange(ranges.InsertRange.SetEndTo(offset)).WithReplaceRange(ranges.ReplaceRange.SetEndTo(offset));
            }

            if (completionItems != null)
            {
                foreach (var sceneName in completionItems)
                {
                    any = true;
                    var item = new StringLiteralItem($"\"{sceneName}\"");
                    item.InitializeRanges(ranges, context.BasicContext);
                    collector.Add(item);
                }
            }
            return(any);
        }
Exemplo n.º 7
0
            public override Expression VisitCSharpLiteralExpression(ICSharpLiteralExpression expression, IMetadataResolver context)
            {
                var declaredType = expression.ConstantValue.Type as IDeclaredType;

                if (declaredType != null)
                {
                    Type type = Type.GetType(declaredType.GetClrName().FullName);
                    Assertion.Assert(type != null, "type != null");
                    return(Expression.Constant(expression.ConstantValue.Value, type));
                }

                return(Expression.Constant(expression.ConstantValue.Value));
            }
        private bool IsValid(ICSharpLiteralExpression literalExpression, [CanBeNull] IReference[] oldReferences)
        {
            if (oldReferences == null)
            {
                return(false);
            }

            var oldReference = oldReferences.Cast <MemberReference>().SingleOrDefault();

            if (oldReference == null)
            {
                return(false);
            }

            var referenceName = literalExpression.ConstantValue.Value as string;

            return(oldReference.IsValid() && oldReference.GetName() == referenceName);
        }
Exemplo n.º 9
0
        private static void CheckMessageExpression(
            ICSharpExpression conditionExpression,
            ICSharpLiteralExpression messageExpression,
            string message,
            int messagePostfixLength,
            IHighlightingConsumer consumer)
        {
            var conditionExpressionText = conditionExpression.GetText();

            var messageConditionPart = message.Substring(0, message.Length - messagePostfixLength);

            if (!EqualsIgnoringWhitespace(messageConditionPart, conditionExpressionText))
            {
                consumer.AddHighlighting(new InvalidAssertionMessageHighlighting(
                                             messageExpression,
                                             messagePostfixLength,
                                             conditionExpressionText));
            }
        }
        public void CheckString(
            ICSharpLiteralExpression literalExpression,
            IHighlightingConsumer highlightingConsumer, StringSettings settings)
        {
            //ConstantValue val = literalExpression.ConstantValue;

            // Ignore it unless it's something we're re-evalutating
            if (!this._daemonProcess.IsRangeInvalidated(literalExpression.GetDocumentRange()))
            {
                return;
            }



            // Ignore verbatim strings.
            if (settings.IgnoreVerbatimStrings &&
                LiteralService.Get(CSharpLanguage.Instance).IsVerbatimStringLiteral(literalExpression))
            {
                return;
            }

            ITokenNode tokenNode = literalExpression.Literal;

            if (tokenNode == null)
            {
                return;
            }

            if (tokenNode.GetTokenType() == CSharpTokenType.STRING_LITERAL)
            {
                ISpellChecker spellChecker = SpellCheckManager.GetSpellChecker(this._settingsStore, this._solution, settings.DictionaryNames);

                StringSpellChecker.SpellCheck(
                    literalExpression.GetDocumentRange().Document,
                    tokenNode,
                    spellChecker,
                    this._solution, highlightingConsumer, this._settingsStore, settings);
            }
        }
        public static void CheckString(ICSharpLiteralExpression literalExpression,
                                       DefaultHighlightingConsumer consumer, StringSettings settings, ISolution _solution, IContextBoundSettingsStore _settingsStore, IDaemonProcess _daemonProcess = null)
        {
            //ConstantValue val = literalExpression.ConstantValue;

            // Ignore it unless it's something we're re-evalutating
            if (_daemonProcess != null && !_daemonProcess.IsRangeInvalidated(literalExpression.GetDocumentRange()))
            {
                return;
            }

            ITokenNode tokenNode = literalExpression.Literal;

            if (tokenNode == null)
            {
                return;
            }

            if (tokenNode.GetTokenType() == CSharpTokenType.STRING_LITERAL_VERBATIM)
            {
                if (settings.IgnoreVerbatimStrings)
                {
                    return;
                }
            }
            else if (tokenNode.GetTokenType() != CSharpTokenType.STRING_LITERAL_REGULAR)
            {
                return;
            }

            ISpellChecker spellChecker = SpellCheckManager.GetSpellChecker(_settingsStore, _solution, settings.DictionaryNames);

            StringSpellChecker.SpellCheck(
                literalExpression.GetDocumentRange()
                .Document,
                tokenNode,
                spellChecker,
                _solution, consumer, _settingsStore, settings);
        }
        public static string GetScenePathFromArgument(ICSharpLiteralExpression literalExpression)
        {
            // There are 3 ways to present scene name in unity
            // Consider scene : Assets/Scenes/myScene.unity
            // User could use "myScene", "Scenes/myScene" and "Assets/Scenes/myScene.unity" to load scene
            // Internally, we work only with first and second format (see UnityProjectSettingsCache)

            var constantValue = literalExpression.ConstantValue.Value as string;

            if (constantValue == null)
            {
                return(null);
            }

            var sceneName = constantValue;

            if (sceneName.StartsWith("Assets/") && sceneName.EndsWith(UnityYamlFileExtensions.SceneFileExtensionWithDot))
            {
                sceneName = GetUnityScenePathRepresentation(sceneName);
            }

            return(sceneName);
        }
Exemplo n.º 13
0
        private bool IsTagEquality(CSharpCodeCompletionContext context, out ICSharpLiteralExpression stringLiteral)
        {
            stringLiteral = null;
            var nodeInFile   = context.NodeInFile;
            var eqExpression = nodeInFile.NextSibling as IEqualityExpression ??
                               nodeInFile.PrevSibling as IEqualityExpression;

            var possibleLiteral = context.NodeInFile.Parent;

            if (possibleLiteral is ICSharpLiteralExpression literalExpression)
            {
                stringLiteral = literalExpression;
                eqExpression  = possibleLiteral.Parent as IEqualityExpression;
            }

            if (eqExpression != null)
            {
                return(CompareTagProblemAnalyzer.IsTagReference(eqExpression.LeftOperand as IReferenceExpression) ||
                       CompareTagProblemAnalyzer.IsTagReference(eqExpression.RightOperand as IReferenceExpression));
            }

            stringLiteral = null;
            return(false);
        }
Exemplo n.º 14
0
        private bool IsSpecificArgumentInSpecificMethod(CSharpCodeCompletionContext context, out ICSharpLiteralExpression stringLiteral,
                                                        Func <IInvocationExpression, bool> methodChecker, Func <IArgumentList, ICSharpArgument, bool> argumentChecker)
        {
            stringLiteral = null;
            var nodeInFile = context.NodeInFile as ITokenNode;

            if (nodeInFile == null)
            {
                return(false);
            }

            var possibleInvocationExpression = nodeInFile.Parent;

            if (possibleInvocationExpression is ICSharpLiteralExpression literalExpression)
            {
                if (!literalExpression.Literal.IsAnyStringLiteral())
                {
                    return(false);
                }

                var argument     = CSharpArgumentNavigator.GetByValue(literalExpression);
                var argumentList = ArgumentListNavigator.GetByArgument(argument);
                if (argument == null || argumentList == null)
                {
                    return(false);
                }

                if (argumentChecker(argumentList, argument))
                {
                    stringLiteral = literalExpression;
                    possibleInvocationExpression = InvocationExpressionNavigator.GetByArgument(argument);
                }
            }


            if (possibleInvocationExpression is IInvocationExpression invocationExpression)
            {
                if (methodChecker(invocationExpression))
                {
                    return(true);
                }
            }

            stringLiteral = null;
            return(false);
        }
Exemplo n.º 15
0
        private bool IsValid(ICSharpLiteralExpression literalExpression, [CanBeNull] IReference[] oldReferences)
        {
            if (oldReferences == null)
            return false;

              var oldReference = oldReferences.Cast<MemberReference>().SingleOrDefault();
              if (oldReference == null)
            return false;

              var referenceName = literalExpression.ConstantValue.Value as string;
              return oldReference.IsValid() && oldReference.GetName() == referenceName;
        }
Exemplo n.º 16
0
 public NullReturnAsTaskHighlighting(ICSharpLiteralExpression cSharpLiteralExpression, IType returnType)
 {
     CSharpLiteralExpression = cSharpLiteralExpression;
     ReturnType = returnType;
 }
Exemplo n.º 17
0
 public MemberReference(ICSharpLiteralExpression literalExpression, ITypeElement typeElement)
     : base(literalExpression)
 {
     _literalExpression = literalExpression;
     _typeElement       = typeElement;
 }
Exemplo n.º 18
0
 public LocalizeStringSuggestion(ICSharpLiteralExpression declaration)
 {
     Declaration = declaration;
 }
 public override void VisitCSharpLiteralExpression(ICSharpLiteralExpression expr,
                                                   IList <IStatement> context)
 {
     // Do nothing!
 }
 public LocalizeStringSuggestion(ICSharpLiteralExpression declaration)
 {
     Declaration = declaration;
 }
 public override IAssignableExpression VisitCSharpLiteralExpression(ICSharpLiteralExpression litExpr,
                                                                    IList <IStatement> context)
 {
     return(ToConst(litExpr, true));
 }