private Function bracketsOpener(Function e)
        {
            IExpressionType add = null;

            foreach (var op in e.getOperands())
            {
                if (op.getType() == Types.Addition)
                {
                    add = op;
                    break;
                }
            }

            if (add == null)
            {
                return(e);
            }

            e.getOperands().Remove(add);
            List <IExpressionType> mulList        = new List <IExpressionType>();
            Simplification         simplification = new Simplification();

            foreach (var a in add.getOperands())
            {
                List <IExpressionType> list = new List <IExpressionType>();
                list.AddRange(e.getOperands());
                list.Add(a);
                IMathExpression mul = new Function(Types.Multiplication, list, "");
                mul = simplification.simplify((Function)mul);
                mulList.Add(mul);
            }

            return(new Function(Types.Addition, mulList, ""));
        }
Beispiel #2
0
        private IMethod FindAssertionMethod([NotNull] string assertionMethodName, [NotNull] IExpressionType parameterType, [NotNull] IPsiModule module)
        {
            var symbolScope = module.GetPsiServices().Symbols.GetSymbolScope(module, true, true);

            IClass typeDecl = null;

            if (this.CachedAssertClassTypeName != null)
            {
                typeDecl = symbolScope.GetTypeElementByCLRName(this.CachedAssertClassTypeName) as IClass;
            }
            else
            {
                var candidates = symbolScope.GetElementsByShortName(AssertTypeName).OfType <IClass>().Where(c => c.CanBeVisibleToSolution()).ToArray();
                if (candidates.Length == 1)
                {
                    typeDecl = candidates[0];
                }
                if (typeDecl != null)
                {
                    this.CachedAssertClassTypeName = typeDecl.GetClrName();
                }
            }

            return(typeDecl?
                   .EnumerateMembers(assertionMethodName, true)
                   .OfType <IMethod>()
                   .FirstOrDefault(m => m.Parameters.Count > 1 && (m.Parameters[0].Type.IsOpenType || parameterType.IsImplicitlyConvertibleTo(m.Parameters[0].Type, module.GetTypeConversionRule()))));
        }
Beispiel #3
0
 public WhileUnit(List <IExpressionType> expressions, IExpressionType condition, int position)
 {
     _expressions = expressions;
     _ctx         = getType().ToString() + position;
     _condition   = condition;
     _position    = position;
 }
        // FORMAT TO MATH MODEL PARSER
        public IExpressionType UnitImportFromFormatToModel(IFormat input, int listPosition)
        {
            Context ctx = Context.getInstance();

            ctx.getIn(input.getType().ToString() + listPosition); //спускаемся в контекст блока

            List <IExpressionType> unitExpressions = new List <IExpressionType>();

            for (int o = 0; o < input.getOperands().Count; o++) // преобразуем все выражения внутри блока
            {
                switch (input.getOperands()[o].getType())
                {
                case Types.FuncDefinition:
                case Types.WhileU:
                case Types.ConditionU:
                    unitExpressions.Add(UnitImportFromFormatToModel(input.getOperands()[o], o));
                    break;

                default:
                    unitExpressions.Add(ExpressionImportFromFormatToModel(input.getOperands()[o]));
                    break;
                }
            }

            // преобразуем выражение - условие
            IExpressionType options = null;

            if (input.getType() != Types.FuncDefinition)
            {
                options = input.getOptions() == null ? null : ExpressionImportFromFormatToModel(input.getOptions());
            }

            ctx.getOut();

            // построение самого блока
            switch (input.getType())
            {
            case Types.GlobalU:
                return(new GlobalUnit(unitExpressions, listPosition));

            case Types.WhileU:
                return(new WhileUnit(unitExpressions, options, listPosition));

            case Types.FuncDefinition:
                string name = input.getOptions().getOptions().getValue();

                List <Variable> lst = new List <Variable>();
                foreach (var v in input.getOptions().getOperands())
                {
                    lst.Add(new Variable(v.getValue()));
                }

                FunctionDefenition fd = new FunctionDefenition(unitExpressions, name, lst, listPosition);
                ctx.addFunction(name, ctx.getCurrPath(), fd);
                return(fd);

            default:
                throw new Exception("Error in importing" + input.getType());
            }
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CSharpUnaryOperatorExpression"/> class.
        /// </summary>
        /// <param name="context">The creation context.</param>
        /// <param name="source">The Easly expression from which the C# expression is created.</param>
        protected CSharpUnaryOperatorExpression(ICSharpContext context, IUnaryOperatorExpression source)
            : base(context, source)
        {
            RightExpression = Create(context, (IExpression)source.RightExpression);

            Operator = context.GetFeature(source.SelectedFeature.Item) as ICSharpFunctionFeature;
            Debug.Assert(Operator != null);

            FeatureCall = new CSharpFeatureCall(context, new FeatureCall());

            IResultType     ResolvedRightResult  = RightExpression.Source.ResolvedResult.Item;
            IExpressionType PreferredRightResult = ResolvedRightResult.Preferred;

            Debug.Assert(PreferredRightResult != null);

            if (PreferredRightResult.ValueType is IClassType AsClassType)
            {
                if (AsClassType.BaseClass.ClassGuid == LanguageClasses.Number.Guid)
                {
                    IsCallingNumberFeature = true;
                }
            }

            if (IsCallingNumberFeature)
            {
                Debug.Assert(ResolvedRightResult.Count == 1);
            }

            Debug.Assert(Source.SelectedOverload.IsAssigned);
            IQueryOverload     Overload = Source.SelectedOverload.Item;
            IQueryOverloadType ResolvedAssociatedType = Overload.ResolvedAssociatedType.Item;

            SelectedOverloadType = CSharpQueryOverloadType.Create(context, ResolvedAssociatedType, Operator.Owner);
        }
        public IFormat UnitImportFromModelToFormat(IExpressionType output, int listPosition)
        {
            List <IFormat> lst = new List <IFormat>();

            if (output.getType() == Types.FuncDefinition)
            {
                lst.Add(new XML(((FunctionDefenition)output).getName()));
            }
            foreach (var outp in output.getOperands())
            {
                if (outp.getType() == Types.FuncDefinition ||
                    outp.getType() == Types.WhileU ||
                    outp.getType() == Types.ConditionU)
                {
                    lst.Add(UnitImportFromModelToFormat(outp, 0));
                }
                else
                {
                    lst.Add(ExpressionImportFromModelToFormat(outp));
                }
            }

            //IFormat options;
            return(new XML(output.getType(), lst, null));
        }
        public IFormat ExpressionImportFromModelToFormat(IExpressionType outp)
        {
            switch (outp.getType())
            {
            case Types.Variable:
                return(new XML(((Variable)outp).getValue()));

            case Types.Number:
                return(new XML(Convert.ToDouble(((Number)outp).getValue())));

            case Types.FuncExpression:
                List <IFormat> list = new List <IFormat>();
                foreach (var o in outp.getOperands())
                {
                    list.Add(ExpressionImportFromModelToFormat(o));
                }
                return(new XML(outp.getType(), list, new XML(((Function)outp).getName())));

            default:
                List <IFormat> lst = new List <IFormat>();
                foreach (var o in outp.getOperands())
                {
                    lst.Add(ExpressionImportFromModelToFormat(o));
                }
                return(new XML(outp.getType(), lst, null));
            }
        }
        public XmlDocument parseToInputFromMathModel(IExpressionType model)
        {
            XmlParser xp = new XmlParser();
            IFormat   nf = xp.UnitImportFromModelToFormat((IUnit)model, 0);

            return(xp.ParseFormatToInput(nf));
        }
        /// <summary>
        /// Applies the rule.
        /// </summary>
        /// <param name="node">The node instance to modify.</param>
        /// <param name="data">Private data from CheckConsistency().</param>
        public override void Apply(IAttachmentInstruction node, object data)
        {
            IExpression AttachmentSource = (IExpression)node.Source;
            IResultType SourceTypeList   = AttachmentSource.ResolvedResult.Item;
            IClass      EmbeddingClass   = node.EmbeddingClass;

            IList <IList <ITypeName> >     FullAttachmentTypeNameList = ((Tuple <IList <IList <ITypeName> >, IList <IList <ICompiledType> > >)data).Item1;
            IList <IList <ICompiledType> > FullAttachmentTypeList     = ((Tuple <IList <IList <ITypeName> >, IList <IList <ICompiledType> > >)data).Item2;

            for (int i = 0; i < node.EntityNameList.Count; i++)
            {
                IExpressionType       Item      = SourceTypeList.At(i);
                IName                 ItemName  = node.EntityNameList[i];
                string                ValidText = ItemName.ValidText.Item;
                IList <ITypeName>     AttachmentTypeNameList = FullAttachmentTypeNameList[i];
                IList <ICompiledType> AttachmentTypeList     = FullAttachmentTypeList[i];

                for (int j = 0; j < node.AttachmentList.Count; j++)
                {
                    IAttachment   Attachment         = node.AttachmentList[j];
                    ITypeName     AttachmentTypeName = AttachmentTypeNameList[j];
                    ICompiledType AttachmentType     = AttachmentTypeList[j];

                    IScopeAttributeFeature TypeFixedEntity = Attachment.FullScope[ValidText];
                    TypeFixedEntity.FixFeatureType(AttachmentTypeName, AttachmentType);

                    Attachment.ResolvedLocalEntitiesList.Add(TypeFixedEntity);
                }
            }

            node.ResolvedInitResult.Item = ResultType.Empty;
        }
        public IExpressionType parseFromInputToMathModel(List <string> input)
        {
            LatexParser     ll        = new LatexParser();
            IFormat         result    = ll.ParseInputToFormat(input, Types.GlobalU, "");
            IExpressionType mathModel = ll.UnitImportFromFormatToModel(result, 0);

            return(mathModel);
        }
        /// <summary>
        /// Checks for errors before applying a rule.
        /// </summary>
        /// <param name="node">The node instance to check.</param>
        /// <param name="dataList">Optional data collected during inspection of sources.</param>
        /// <param name="data">Private data to give to Apply() upon return.</param>
        /// <returns>True if an error occured.</returns>
        public override bool CheckConsistency(IAttachmentInstruction node, IDictionary <ISourceTemplate, object> dataList, out object data)
        {
            data = null;
            bool Success = true;

            IExpression AttachmentSource = (IExpression)node.Source;
            IResultType SourceTypeList   = AttachmentSource.ResolvedResult.Item;
            IClass      EmbeddingClass   = node.EmbeddingClass;

            IList <IList <ITypeName> >     FullAttachmentTypeNameList = new List <IList <ITypeName> >();
            IList <IList <ICompiledType> > FullAttachmentTypeList     = new List <IList <ICompiledType> >();

            if (SourceTypeList.Count < node.EntityNameList.Count)
            {
                AddSourceError(new ErrorInvalidInstruction(node));
                Success = false;
            }
            else
            {
                for (int i = 0; i < node.EntityNameList.Count; i++)
                {
                    IList <ITypeName>     AttachmentTypeNameList = new List <ITypeName>();
                    IList <ICompiledType> AttachmentTypeList     = new List <ICompiledType>();

                    FullAttachmentTypeNameList.Add(AttachmentTypeNameList);
                    FullAttachmentTypeList.Add(AttachmentTypeList);
                }

                for (int i = 0; i < node.EntityNameList.Count; i++)
                {
                    IExpressionType       Item     = SourceTypeList.At(i);
                    IName                 ItemName = node.EntityNameList[i];
                    IList <ITypeName>     AttachmentTypeNameList = FullAttachmentTypeNameList[i];
                    IList <ICompiledType> AttachmentTypeList     = FullAttachmentTypeList[i];

                    foreach (IAttachment Attachment in node.AttachmentList)
                    {
                        IObjectType AttachedType = Attachment.AttachTypeList[i];
                        ISealableDictionary <string, IScopeAttributeFeature> CheckedScope = Attachment.FullScope;

                        IList <IClass> AssignedSingleClassList = new List <IClass>();
                        IErrorList     CheckErrorList          = new ErrorList();
                        if (ScopeHolder.HasConflictingSingleAttributes(CheckedScope, node.InnerScopes, AssignedSingleClassList, node, CheckErrorList))
                        {
                            AddSourceErrorList(CheckErrorList);
                            Success = false;
                        }

                        AttachmentTypeNameList.Add(AttachedType.ResolvedTypeName.Item);
                        AttachmentTypeList.Add(AttachedType.ResolvedType.Item);
                    }
                }

                data = new Tuple <IList <IList <ITypeName> >, IList <IList <ICompiledType> > >(FullAttachmentTypeNameList, FullAttachmentTypeList);
            }

            return(Success);
        }
Beispiel #12
0
    public static Boxing TryFind(
        Conversion conversion, [NotNull] IExpressionType sourceExpressionType, [NotNull] IType targetType, [NotNull] ITreeNode correspondingNode)
    {
        switch (conversion.Kind)
        {
        case ConversionKind.Boxing:
        {
            return(RefineBoxingConversionResult());
        }

        case ConversionKind.Unboxing:
        {
            return(RefineUnboxingConversionResult());
        }

        case ConversionKind.ImplicitTuple:
        case ConversionKind.ImplicitTupleLiteral:
        case ConversionKind.ExplicitTuple:
        case ConversionKind.ExplicitTupleLiteral:
        {
            var components = new LocalList <Boxing>();

            foreach (var(nested, componentIndex) in conversion.GetTopLevelNestedConversionsWithTypeInfo().WithIndexes())
            {
                var componentNode = TryGetComponentNode(correspondingNode, componentIndex) ?? correspondingNode;

                var nestedBoxing = TryFind(nested.Conversion, nested.SourceType, nested.TargetType, componentNode);
                if (nestedBoxing != null)
                {
                    components.Add(nestedBoxing);
                }
            }

            if (components.Count > 0)
            {
                return(new InsideTupleConversion(components.ReadOnlyList(), correspondingNode));
            }

            break;
        }

        case ConversionKind.ImplicitUserDefined:
        case ConversionKind.ExplicitUserDefined:
        {
            foreach (var nested in conversion.GetTopLevelNestedConversionsWithTypeInfo())
            {
                var nestedBoxing = TryFind(nested.Conversion, nested.SourceType, nested.TargetType, correspondingNode);
                if (nestedBoxing != null)
                {
                    return(nestedBoxing);
                }
            }

            break;
        }
        }

        return(null);
        /// <summary>
        /// Applies the rule.
        /// </summary>
        /// <param name="node">The node instance to modify.</param>
        /// <param name="data">Private data from CheckConsistency().</param>
        public override void Apply(IFunctionType node, object data)
        {
            IResultType CommonResults = (IResultType)data;

            int             Index            = CommonResults.ResultNameIndex >= 0 ? CommonResults.ResultNameIndex : 0;
            IExpressionType MostCommonResult = CommonResults.At(Index);

            node.MostCommonResult.Item = MostCommonResult;
        }
        private IExpressionType doCustomFunc(Function f, FunctionDefenition fd)
        {
            Context        ctx  = Context.getInstance();
            Computator     comp = new Computator();
            Simplification s    = new Simplification();

            // вычисления кастомных функций
            if (f.getOperands().Count != fd.getParams().Count)
            {
                throw new Exception("Not equal number of params");
            }

            ctx.getIn(fd.getContext()); // get into right context

            bool[]            wasBefore   = new bool[fd.getParams().Count];
            IExpressionType[] expressions = new IExpressionType[fd.getParams().Count];

            for (int p = 0; p < fd.getParams().Count; p++) // add params to scope
            {
                if (ctx.exists(fd.getParams()[p].getValue(), ctx.getCurrPath()) == -1)
                {
                    wasBefore[p] = false;
                    ctx.addVariable(fd.getParams()[p].getValue(), ctx.getCurrPath(), f.getOperands()[p]);
                }
                else
                {
                    wasBefore[p]   = true;
                    expressions[p] = ctx.getVariableValue(fd.getParams()[p].getValue(), ctx.getCurrPath());
                    ctx.changeVariable(fd.getParams()[p].getValue(), ctx.getCurrPath(), f.getOperands()[p]);
                }
            }

            List <IExpressionType> nl = new List <IExpressionType>();

            foreach (var op in fd.getOperands())
            {
                nl.Add(op.doOperation(comp));
            }

            for (int p = 0; p < fd.getParams().Count; p++) //remove params from scope
            {
                if (!wasBefore[p])
                {
                    ctx.removeVariable(fd.getParams()[p].getValue(), ctx.getCurrPath());
                }
                else
                {
                    ctx.changeVariable(fd.getParams()[p].getValue(), ctx.getCurrPath(), expressions[p]);
                }
            }

            //OUT
            ctx.getOut();
            IExpressionType n = nl[nl.Count - 1];

            return((IMathExpression)(n.getType() == Types.FuncExpression ? s.simplify((Function)n) : n));
        }
Beispiel #15
0
 public void changeVariable(string name, string currentPath, IExpressionType exp)
 {
     if (exists(name, currentPath) != -1)
     {
         Table tmp = variables.Find(x => x.name == name && x.path == currentPath);
         variables.Remove(tmp);
         tmp.varReference = exp;
         variables.Add(tmp);
     }
 }
Beispiel #16
0
        private bool IsMatrixType([NotNull] IExpressionType expression)
        {
            var clrType = (expression as IDeclaredType)?.GetClrName();

            if (clrType == null)
            {
                return(false);
            }
            return(knownTypes.ContainsKey(clrType));
        }
Beispiel #17
0
        public Ordinary(IExpressionType sourceExpressionType, IType targetType, ITreeNode correspondingNode, bool isPossible = false)
            : base(correspondingNode)
        {
            IsPossible = isPossible;

            var sourceTypeText = sourceExpressionType.GetPresentableName(CorrespondingNode.Language, TypePresentationStyle.Default).Text;
            var targetTypeText = targetType.GetPresentableName(CorrespondingNode.Language, TypePresentationStyle.Default).Text;

            Reason = $"conversion from '{sourceTypeText}' to '{targetTypeText}'";
        }
Beispiel #18
0
        private static bool ValidateAssignmentStyle(IList <IArgument> argumentList, List <IExpressionType> mergedArgumentList, IErrorList errorList)
        {
            ISealableDictionary <string, IArgument> DuplicateNameTable = new SealableDictionary <string, IArgument>();

            for (int i = 0; i < argumentList.Count; i++)
            {
                IAssignmentArgument Argument = argumentList[i] as IAssignmentArgument;
                Debug.Assert(Argument != null);
                IExpression         Source        = (IExpression)Argument.Source;
                IList <IIdentifier> ParameterList = Argument.ParameterList;

                if (ParameterList.Count > 1 && Argument.ResolvedResult.Item.Count == 1)
                {
                    IExpressionType Item = Argument.ResolvedResult.Item.At(0);

                    for (int j = 0; j < ParameterList.Count; j++)
                    {
                        IExpressionType ItemJ = new ExpressionType(Item.ValueTypeName, Item.ValueType, ParameterList[j].ValidText.Item);
                        ItemJ.SetSource(Source, 0);
                        mergedArgumentList.Add(ItemJ);
                    }
                }
                else
                {
                    for (int j = 0; j < Argument.ResolvedResult.Item.Count; j++)
                    {
                        IExpressionType Item = Argument.ResolvedResult.Item.At(j);
                        Item.SetName(ParameterList[j].ValidText.Item);

                        if (mergedArgumentList.Exists((IExpressionType other) => { return(Item.Name == other.Name); }))
                        {
                            if (!DuplicateNameTable.ContainsKey(Item.Name))
                            {
                                DuplicateNameTable.Add(Item.Name, Argument);
                            }
                        }

                        Item.SetSource(Source, j);
                        mergedArgumentList.Add(Item);
                    }
                }
            }

            if (DuplicateNameTable.Count > 0)
            {
                foreach (KeyValuePair <string, IArgument> Entry in DuplicateNameTable)
                {
                    errorList.AddError(new ErrorDuplicateName(Entry.Value, Entry.Key));
                }

                return(false);
            }

            return(true);
        }
        protected override void AppendTooltip(IncorrectArrayElementTypeError highlighting, CSharpColorizer colorizer)
        {
            IExpressionType sourceType       = highlighting.InitializerExpression.GetExpressionType();
            bool            appendModuleName = sourceType.HasSameFullNameAs(highlighting.TargetType);

            colorizer.AppendPlainText("Cannot convert expression of type '");
            colorizer.AppendExpressionType(sourceType, appendModuleName, PresenterOptions.FullWithoutParameterNames);
            colorizer.AppendPlainText("' to type '");
            colorizer.AppendExpressionType(highlighting.TargetType, appendModuleName, PresenterOptions.FullWithoutParameterNames);
            colorizer.AppendPlainText("'");
        }
Beispiel #20
0
        /// <summary>
        /// Applies the rule.
        /// </summary>
        /// <param name="node">The node instance to modify.</param>
        /// <param name="data">Private data from CheckConsistency().</param>
        public override void Apply(IFunctionFeature node, object data)
        {
            IResultType CommonResults = (IResultType)data;

            int             Index            = CommonResults.ResultNameIndex >= 0 ? CommonResults.ResultNameIndex : 0;
            IExpressionType MostCommonResult = CommonResults.At(Index);

            node.MostCommonResult.Item          = MostCommonResult;
            node.ResolvedEffectiveTypeName.Item = MostCommonResult.ValueTypeName;
            node.ResolvedEffectiveType.Item     = MostCommonResult.ValueType;
        }
Beispiel #21
0
        private int GetElementCount(IExpressionType expression)
        {
            var clrType = (expression as IDeclaredType)?.GetClrName();

            if (clrType == null || !knownTypes.ContainsKey(clrType))
            {
                return(0);
            }

            return(knownTypes[clrType]);
        }
Beispiel #22
0
 public void addVariable(string variableName, string currentPath, IExpressionType expression)
 {
     if (exists(variableName, currentPath) == -1)
     {
         Table nt = new Table();
         nt.name         = variableName;
         nt.path         = currentPath;
         nt.varReference = expression;
         variables.Add(nt);
     }
 }
Beispiel #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QualifiedName"/> class.
        /// </summary>
        /// <param name="source">The pre-constructed source.</param>
        /// <param name="sourceType">The qualified name resolved type.</param>
        public QualifiedName(BaseNode.IQualifiedName source, IExpressionType sourceType)
        {
            Debug.Assert(source.Path.Count == 1);

            BaseNode.IIdentifier Identifier    = source.Path[0];
            IIdentifier          NewIdentifier = new Identifier(Identifier.Text);

            ValidPath.Item = new List <IIdentifier>();
            ValidPath.Item.Add(NewIdentifier);
            ValidResultTypePath.Item = new List <IExpressionType>();
            ValidResultTypePath.Item.Add(sourceType);
        }
        public IExpressionType doFunction(Function f)
        {
            Context ctx = Context.getInstance();

            // определяем вид функции: встроенная или пользовательская
            IExpressionType me = ctx.getVariableValue(f.getName(), ctx.getCurrPath());

            if (me == null)
            {
                return(doPredefinedFunc(f));
            }
            return(doCustomFunc(f, (FunctionDefenition)me));
        }
        // This will be called multiple times in the case of chained method calls.
        public override void VisitInvocationExpression(IInvocationExpression invocationExpressionParam)
        {
            // TODO: Loop through here somehow and work up through the string calls like ToLower().ToUpper() et et.
            //do
//          {
            IReferenceExpression expression = invocationExpressionParam.InvokedExpression as IReferenceExpression;

            if (expression == null)
            {
                return;
            }

            // As I understand it this takes the abstract syntax element that is e.ToString() and resolves it such that
            // we know it's the System.Enum.ToString() method call.
            IResolveResult resolveResult = expression.Reference.Resolve();

            IDeclaredElement e = resolveResult.DeclaredElement;

            if (e == null)
            {
                return;
            }

            ITypeElement containingType = e.GetContainingType();


            // work up through the string calls
            //invocationExpressionParam = invocationExpressionParam.InvocationExpressionReference as IInvocationExpression;
            //var allowed = new[] { "ToUpper", "ToLower", "ToString" };
            //if (!new List<string>(allowed).Contains(e.ShortName))
            //    return;
//          }
            //while (containingType != null && containingType.CLRName == "System.String");

            if (containingType == null)
            {
                return;
            }

            if (containingType.CLRName == "System.Enum" && e.ShortName == "ToString")
            {
                Found = true;

                // Save the enum declaration so we can implement the fix.
                this.FoundEnumReference = invocationExpressionParam.Reference;
                this.EnumReferenceName  = expression.QualifierExpression.GetText();

                IExpressionType qe = expression.QualifierExpression.GetExpressionType();
                this.EnumDeclaredName = ((IDeclaredType)qe).GetPresentableName(PsiLanguageType.GetByProjectFile(invocationExpressionParam.GetProjectFile()));
            }
        }
            private void CheckNullComparisonWithUnityObject([NotNull] IEqualityExpression equalityExpressionParam, HotMethodAnalyzerContext context)
            {
                var reference = equalityExpressionParam.Reference;

                if (reference == null)
                {
                    return;
                }

                var isNullFound  = false;
                var leftOperand  = equalityExpressionParam.LeftOperand;
                var rightOperand = equalityExpressionParam.RightOperand;

                if (leftOperand == null || rightOperand == null)
                {
                    return;
                }

                IExpressionType expressionType = null;

                if (leftOperand.ConstantValue.IsNull())
                {
                    isNullFound    = true;
                    expressionType = rightOperand.GetExpressionType();
                }
                else if (rightOperand.ConstantValue.IsNull())
                {
                    isNullFound    = true;
                    expressionType = leftOperand.GetExpressionType();
                }

                if (!isNullFound)
                {
                    return;
                }

                var typeElement = expressionType.ToIType()?.GetTypeElement();

                if (typeElement == null)
                {
                    return;
                }

                if (typeElement.GetAllSuperTypes().Any(t => t.GetClrName().Equals(KnownTypes.Object)))
                {
                    context.MarkCurrentAsCostlyReachable();
                    myConsumer.AddHighlighting(new PerformanceCriticalCodeInvocationHighlighting(reference));
                }
            }
Beispiel #27
0
            public SuitableStaticMethodsFilter(
                [NotNull] IExpressionType expressionType, [NotNull] ICSharpExpression expression, int argumentsCount)
            {
                myExpressionType         = expressionType;
                myExistingArgumentsCount = argumentsCount;
                myConversionRule         = expression.GetTypeConversionRule();

                var reference = expression as IReferenceExpression;

                if (reference != null && reference.QualifierExpression == null)
                {
                    var element = reference.Reference.Resolve().DeclaredElement;
                    myAllowRefParameters = (element is ILocalVariable || element is IParameter);
                }
            }
Beispiel #28
0
        private bool IsForLoopTypeAvailable(IForLoopInstruction node)
        {
            bool IsBooleanTypeAvailable = Expression.IsLanguageTypeAvailable(LanguageClasses.Boolean.Guid, node, out ITypeName BooleanTypeName, out ICompiledType BooleanType);
            bool IsNumberTypeAvailable  = Expression.IsLanguageTypeAvailable(LanguageClasses.Number.Guid, node, out ITypeName NumberTypeName, out ICompiledType NumberType);

            if (node.Variant.IsAssigned && !IsNumberTypeAvailable)
            {
                AddSourceError(new ErrorNumberTypeMissing(node));
                return(false);
            }

            if (!IsBooleanTypeAvailable)
            {
                AddSourceError(new ErrorBooleanTypeMissing(node));
                return(false);
            }

            IExpression     WhileCondition = (IExpression)node.WhileCondition;
            IResultType     ResolvedResult = WhileCondition.ResolvedResult.Item;
            IExpressionType ContractType   = ResolvedResult.At(0);

            if (ContractType.ValueType != BooleanType)
            {
                AddSourceError(new ErrorInvalidExpression(WhileCondition));
                return(false);
            }

            bool Success = true;

            if (node.Variant.IsAssigned)
            {
                IExpression VariantCondition = (IExpression)node.Variant.Item;

                foreach (IExpressionType Item in VariantCondition.ResolvedResult.Item)
                {
                    if (Item.ValueType != NumberType)
                    {
                        AddSourceError(new ErrorInvalidExpression(VariantCondition));
                        Success = false;
                    }
                }
            }

            return(Success);
        }
        /// <summary>
        /// Check number types.
        /// </summary>
        /// <param name="isChanged">True upon return if a number type was changed.</param>
        public void CheckNumberType(ref bool isChanged)
        {
            foreach (IArgument Argument in ArgumentList)
            {
                Argument.CheckNumberType(ref isChanged);
            }

            if (SelectedOverload.IsAssigned)
            {
                ResolvedResult.Item.UpdateNumberKind(SelectedOverload.Item.NumberKind, ref isChanged);

                IDictionary <IParameter, IList <NumberKinds> > NumberArgumentTable = SelectedOverload.Item.NumberArgumentTable;

                for (int i = 0; i < FeatureCall.Item.ArgumentList.Count && i < FeatureCall.Item.ParameterList.Count; i++)
                {
                    IArgument  Argument  = FeatureCall.Item.ArgumentList[i];
                    IParameter Parameter = FeatureCall.Item.ParameterList[i];

                    Debug.Assert(NumberArgumentTable.ContainsKey(Parameter));
                    IList <NumberKinds> NumberKindList = NumberArgumentTable[Parameter];

                    IExpression SourceExpression = null;
                    switch (Argument)
                    {
                    case IPositionalArgument AsPositionalArgument:
                        SourceExpression = (IExpression)AsPositionalArgument.Source;
                        break;

                    case IAssignmentArgument AsAssignmentArgument:
                        SourceExpression = (IExpression)AsAssignmentArgument.Source;
                        break;
                    }

                    Debug.Assert(SourceExpression != null);

                    IExpressionType PreferredArgumentType = SourceExpression.ResolvedResult.Item.Preferred;
                    if (PreferredArgumentType != null && PreferredArgumentType.ValueType is ICompiledNumberType AsNumberArgumentType)
                    {
                        Debug.Assert(AsNumberArgumentType.NumberKind != NumberKinds.NotChecked);

                        NumberKindList.Add(AsNumberArgumentType.NumberKind);
                    }
                }
            }
        }
        /// <summary>
        /// Applies the rule.
        /// </summary>
        /// <param name="node">The node instance to modify.</param>
        /// <param name="data">Private data from CheckConsistency().</param>
        public override void Apply(IBinaryOperatorExpression node, object data)
        {
            ILanguageConstant ExpressionConstant = NeutralLanguageConstant.NotConstant;

            Debug.Assert(node.ConstantSourceList.Count == 2);

            IExpression LeftConstantSource = node.ConstantSourceList[0];

            Debug.Assert(LeftConstantSource == node.LeftExpression);

            IExpression RightConstantSource = node.ConstantSourceList[1];

            Debug.Assert(RightConstantSource == node.RightExpression);

            Debug.Assert(LeftConstantSource.ExpressionConstant.IsAssigned);
            ILanguageConstant LeftExpressionConstant = LeftConstantSource.ExpressionConstant.Item;

            Debug.Assert(RightConstantSource.ExpressionConstant.IsAssigned);
            ILanguageConstant RightExpressionConstant = RightConstantSource.ExpressionConstant.Item;

            if (LeftExpressionConstant != NeutralLanguageConstant.NotConstant && RightExpressionConstant != NeutralLanguageConstant.NotConstant)
            {
                Debug.Assert(node.ResolvedResult.IsAssigned);
                IResultType ResolvedResult = node.ResolvedResult.Item;

                if (ResolvedResult.Count == 1)
                {
                    IExpressionType ConstantType = ResolvedResult.At(0);

                    bool IsBooleanTypeAvailable = Expression.IsLanguageTypeAvailable(LanguageClasses.Boolean.Guid, node, out ITypeName BooleanTypeName, out ICompiledType BooleanType);
                    bool IsNumberTypeAvailable  = Expression.IsLanguageTypeAvailable(LanguageClasses.Number.Guid, node, out ITypeName NumberTypeName, out ICompiledType NumberType);

                    if (IsBooleanTypeAvailable && ConstantType.ValueType == BooleanType)
                    {
                        ExpressionConstant = new BooleanLanguageConstant();
                    }
                    else if (IsNumberTypeAvailable && ConstantType.ValueType == NumberType)
                    {
                        ExpressionConstant = new NumberLanguageConstant();
                    }
                }
            }

            node.ExpressionConstant.Item = ExpressionConstant;
        }