public void GetWinnerProbability_DummyResult_EvenOdds()
        {
            EvaluationResult evaluationResult = new EvaluationResult();

            double first = evaluationResult.GetWinnerProbability(Winner.FirstTeam);
            double second = evaluationResult.GetWinnerProbability(Winner.SecondTeam);

            Assert.AreEqual(first, second);
        }
        public void GetWinnerProbability_AnyResult_AlwaysAddsToOne()
        {
            EvaluationResult evaluationResult = new EvaluationResult();

            double first = evaluationResult.GetWinnerProbability(Winner.FirstTeam);
            double second = evaluationResult.GetWinnerProbability(Winner.SecondTeam);
            double draw = evaluationResult.GetWinnerProbability(Winner.Draw);

            Assert.AreEqual(1d, first + second + draw);
        }
		protected override Task<EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
		{
			if (IsEmptyFinalizer(node, semanticModel))
			{
				var result = new EvaluationResult
								 {
									 Snippet = node.ToFullString()
								 };

				return Task.FromResult(result);
			}

			return Task.FromResult<EvaluationResult>(null);
		}
		private static ModelNode CreateProjectNode(
			IProjectMetric projectMetric,
			IProjectMetric[] projectMetrics,
			EvaluationResult[] evaluationResults)
		{
			var children = projectMetric.Dependencies.Select(
				y =>
				{
					var couplings =
						projectMetric.NamespaceMetrics.SelectMany(x => x.ClassCouplings)
							.Where(x => x.Assembly == y.GetFileNameWithoutExtension())
							.Select(x => new ModelNode(x.Namespace, NodeKind.Namespace, CodeQuality.Good, 0, 100, 0))
							.Cast<IModelNode>()
							.ToList();
					return new ModelNode(
						y.GetFileNameWithoutExtension(),
						NodeKind.Assembly,
						CodeQuality.Good,
						0,
						100,
						0,
						couplings);
				})
				.Concat(
					projectMetric.NamespaceMetrics.Select(
						namespaceMetric =>
						CreateNamespaceNode(
							namespaceMetric,
							projectMetrics,
							evaluationResults.Where(r => r.Namespace == namespaceMetric.Name))))
				.Merge()
				.ToList();
			return new ModelNode(
				projectMetric.Name,
				NodeKind.Assembly,
				evaluationResults.Where(x => x.ProjectName == projectMetric.Name).GetQuality(),
				projectMetric.LinesOfCode,
				projectMetric.MaintainabilityIndex,
				projectMetric.CyclomaticComplexity,
				children);
		}
 public string FormatEvaluationErrorMessage(EvaluationResult evaluationResult)
 {
     if (evaluationResult.Location == 0)
         return evaluationResult.ErrorMessage;
     return string.Format("{0} (позиция {1})", evaluationResult.ErrorMessage, evaluationResult.Location + 1);
 }
 public override void VisitConditionalChoiceExpression([NotNull] IConditionalChoiceExpression operation)
 {
     Result = owner.AnalyzeConditionalChoice(operation);
 }
Exemple #7
0
        private static EvaluationResult RemoveRange(Context context, OrderedMap receiver, EvaluationResult arg, EvaluationStackFrame captures)
        {
            var argArray = Converter.ExpectArrayLiteral(arg, new ConversionContext(pos: 1));

            for (int i = 0; i < argArray.Length; ++i)
            {
                if (argArray[i].IsUndefined)
                {
                    throw new UndefinedMapKeyException(new ErrorContext(objectCtx: argArray, pos: i));
                }
            }

            return(EvaluationResult.Create(receiver.RemoveRange(argArray.Values)));
        }
Exemple #8
0
        private static EvaluationResult Add(Context context, OrderedMap receiver, EvaluationResult arg1, EvaluationResult arg2, EvaluationStackFrame captures)
        {
            if (arg1.IsUndefined)
            {
                throw new UndefinedMapKeyException(new ErrorContext(pos: 1));
            }

            return(EvaluationResult.Create(receiver.Add(arg1, arg2)));
        }
Exemple #9
0
 private static EvaluationResult TrimEnd(Context context, string receiver, EvaluationResult arg, EvaluationStackFrame captures)
 {
     return(arg.IsUndefined
         ? EvaluationResult.Create(receiver.TrimEnd())
         : EvaluationResult.Create(receiver.TrimEnd(Converter.ExpectString(arg, new ConversionContext(objectCtx: arg.Value, pos: 1)).ToCharArray())));
 }
Exemple #10
0
 /// <summary>
 /// 無參數建構式
 /// </summary>
 public OrEval()
 {
     _evals  = new List <IEvaluative>();
     _result = new EvaluationResult();
 }
Exemple #11
0
        private static EvaluationResult IsUndefinedOrWhitespace(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var str = Args.AsStringOrUndefined(args, 0);

            return(EvaluationResult.Create(string.IsNullOrWhiteSpace(str)));
        }
Exemple #12
0
 private static EvaluationResult StartsWith(Context context, string receiver, EvaluationResult arg, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.StartsWith(Converter.ExpectString(arg), StringComparison.Ordinal)));
 }
Exemple #13
0
        /// <summary>
        /// This method will be deprecated soon.
        /// </summary>
        private static EvaluationResult HasFlag(Context context, EnumValue receiver, EvaluationResult arg, EvaluationStackFrame captures)
        {
            var enumValueArg = Converter.ExpectEnumValue(arg);

            return(EvaluationResult.Create((enumValueArg.Value & receiver.Value) == enumValueArg.Value));
        }
Exemple #14
0
 private static EvaluationResult ValueOf(Context context, EnumValue receiver, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.Value));
 }
Exemple #15
0
        public static ObjectValue CreateObject(IObjectValueSource source, ObjectPath path, string typeName, EvaluationResult value, ObjectValueFlags flags, ObjectValue[] children)
        {
            ObjectValue ob = Create(source, path, typeName);

            ob.path         = path;
            ob.flags        = flags | ObjectValueFlags.Object;
            ob.value        = value.Value;
            ob.displayValue = value.DisplayValue;
            if (children != null)
            {
                ob.children = new List <ObjectValue> ();
                ob.children.AddRange(children);
            }
            return(ob);
        }
Exemple #16
0
        public static ObjectValue CreatePrimitive(IObjectValueSource source, ObjectPath path, string typeName, EvaluationResult value, ObjectValueFlags flags)
        {
            ObjectValue ob = Create(source, path, typeName);

            ob.flags        = flags | ObjectValueFlags.Primitive;
            ob.value        = value.Value;
            ob.displayValue = value.DisplayValue;
            return(ob);
        }
        /// <inheritdoc />
        protected override EvaluationResult DoEval(Context context, ModuleLiteral env, EvaluationStackFrame frame)
        {
            Contract.Assume(frame.Length > Index);

            // By construction, the above preconditions should hold.
            var value = RightExpression.Eval(context, env, frame);

            if (value.IsErrorValue)
            {
                return(EvaluationResult.Error);
            }

            if (OperatorKind == AssignmentOperator.Assignment)
            {
                frame[Index] = value;
                return(frame[Index]);
            }

            try
            {
                // All operations should be in the checked context to fail on overflow!
                checked
                {
                    var arg = frame[Index];

                    switch (OperatorKind)
                    {
                    case AssignmentOperator.AdditionAssignment:
                        if (Converter.TryGet <int>(arg, out int lIntValue) && Converter.TryGet <int>(value, out int rIntValue))
                        {
                            frame[Index] = NumberLiteral.Box(lIntValue + rIntValue);
                            break;
                        }
                        else if (Converter.TryGet <string>(arg, out string lStrValue) && Converter.TryGet <string>(value, out string rStrValue))
                        {
                            frame[Index] = EvaluationResult.Create(lStrValue + rStrValue);
                            break;
                        }

                        throw Converter.CreateException <int>(value, context: new ConversionContext(pos: Index));

                    case AssignmentOperator.SubtractionAssignment:
                        frame[Index] = NumberLiteral.Box(Converter.ExpectNumber(arg, position: 0) - Converter.ExpectNumber(value, position: 1));
                        break;

                    case AssignmentOperator.MultiplicationAssignment:
                        frame[Index] = NumberLiteral.Box(Converter.ExpectNumber(arg, position: 0) * Converter.ExpectNumber(value, position: 1));
                        break;

                    case AssignmentOperator.RemainderAssignment:
                        frame[Index] = NumberLiteral.Box(Converter.ExpectNumber(arg, position: 0) % Converter.ExpectNumber(value, position: 1));
                        break;

                    case AssignmentOperator.ExponentiationAssignment:
                        frame[Index] = NumberOperations.Power(
                            context,
                            Converter.ExpectNumber(arg, position: 0),
                            Converter.ExpectNumber(value, position: 1), LocationForLogging(context, env));
                        break;

                    case AssignmentOperator.LeftShiftAssignment:
                        frame[Index] = NumberLiteral.Box(Converter.ExpectNumber(frame[Index], position: 0) << Converter.ExpectNumber(value, position: 1));
                        break;

                    case AssignmentOperator.RightShiftAssignment:
                        frame[Index] = NumberLiteral.Box(NumberOperations.SignPropagatingRightShift(
                                                             Converter.ExpectNumber(arg, position: 0),
                                                             Converter.ExpectNumber(value, position: 1)).Value);
                        break;

                    case AssignmentOperator.UnsignedRightShiftAssignment:
                        frame[Index] = NumberLiteral.Box(NumberOperations.ZeroFillingRightShift(
                                                             Converter.ExpectNumber(arg, position: 0),
                                                             Converter.ExpectNumber(value, position: 1)).Value);
                        break;

                    case AssignmentOperator.BitwiseAndAssignment:
                        frame[Index] =
                            Converter.ToEnumValueIfNeeded(
                                arg.GetType(),
                                Converter.ExpectNumberOrEnum(arg, position: 0) & Converter.ExpectNumberOrEnum(value, position: 1));
                        break;

                    case AssignmentOperator.BitwiseXorAssignment:
                        frame[Index] =
                            Converter.ToEnumValueIfNeeded(
                                arg.GetType(),
                                Converter.ExpectNumberOrEnum(arg, position: 0) ^ Converter.ExpectNumberOrEnum(value, position: 1));
                        break;

                    case AssignmentOperator.BitwiseOrAssignment:
                        frame[Index] =
                            Converter.ToEnumValueIfNeeded(
                                arg.GetType(),
                                Converter.ExpectNumberOrEnum(arg, position: 0) | Converter.ExpectNumberOrEnum(value, position: 1));
                        break;

                    default:
                        var message = I($"Unknown operator kind '{OperatorKind}'");
                        Contract.Assert(false, message);
                        throw new InvalidOperationException(message);
                    }
                }

                return(frame[Index]);
            }
            catch (OverflowException)
            {
                context.Logger.ReportArithmeticOverflow(context.LoggingContext, LocationForLogging(context, env), this.ToDisplayString(context));
            }
            catch (ConvertException exception)
            {
                if (exception.ErrorContext.Pos == 0)
                {
                    context.Errors.ReportUnexpectedValueTypeForName(env, LeftExpression, exception.ExpectedTypesToString(context), exception.Value, Location);
                }
                else
                {
                    context.Errors.ReportUnexpectedValueType(env, RightExpression, exception.Value, exception.ExpectedTypesToString(context));
                }
            }

            return(EvaluationResult.Error);
        }
Exemple #18
0
        private static EvaluationResult NumberToStringMethod(Context context, int receiver, EvaluationResult radixAsObject, EvaluationStackFrame captures)
        {
            int?   radix = radixAsObject.IsUndefined ? (int?)null : (int)radixAsObject.Value;
            string result;

            if (radix != null)
            {
                ValidateRadix(radix.Value);
                result = Convert.ToString(receiver, radix.Value);
            }
            else
            {
                result = receiver.ToString(CultureInfo.InvariantCulture);
            }

            return(EvaluationResult.Create(result));
        }
Exemple #19
0
 private static EvaluationResult CharCodeAt(Context context, string receiver, EvaluationResult arg, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(CharAtCore(receiver, arg)[0]));
 }
Exemple #20
0
        private static EvaluationResult Split(Context context, string receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
        {
            var separator    = Converter.ExpectString(arg0, new ConversionContext(pos: 1));
            var resultAsStrs = receiver.Split(new[] { separator }, int.MaxValue, StringSplitOptions.None);

            // Here, C# and ECMAScript semantics differ:
            // ECMAScript: ";aa;;bb;".split(";", 3) will yield ["", "aa", ""]
            // C#: ";aa;;bb;".split(";", 3) will yield ["", "aa", ";bb;"]
            // (i.e., C# stops splitting, and ECMAScript truncates)
            var len = arg1.IsUndefined ? resultAsStrs.Length : Converter.ExpectNumber(arg1, context: new ConversionContext(pos: 2));

            var result = new EvaluationResult[len];

            for (int i = 0; i < len; i++)
            {
                result[i] = EvaluationResult.Create(resultAsStrs[i]);
            }

            var entry = context.TopStack;

            return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(result, entry.InvocationLocation, entry.Path)));
        }
Exemple #21
0
 private static EvaluationResult Contains(Context context, string receiver, EvaluationResult arg, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.Contains(Converter.ExpectString(arg))));
 }
Exemple #22
0
 private static EvaluationResult ToUpperCase(Context context, string receiver, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.ToUpperInvariant()));
 }
Exemple #23
0
        private static EvaluationResult IndexOf(Context context, string receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
        {
            var arg0Str = Converter.ExpectString(arg0, new ConversionContext(pos: 1));

            if (arg1.IsUndefined)
            {
                return(EvaluationResult.Create(receiver.IndexOf(arg0Str, StringComparison.Ordinal)));
            }

            return(EvaluationResult.Create(
                       receiver.IndexOf(arg0Str, Converter.ExpectNumber(arg1, context: new ConversionContext(pos: 2)),
                                        StringComparison.Ordinal)));
        }
Exemple #24
0
 private EvaluationResult CreateSourceFile(string path)
 {
     return(EvaluationResult.Create(FileArtifact.CreateSourceFile(CreateAbsolutePath(path))));
 }
Exemple #25
0
        private static EvaluationResult LastIndexOf(Context context, string receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
        {
            var arg0Str = Converter.ExpectString(arg0, new ConversionContext(pos: 1));
            var arg1Int = arg1.IsUndefined
                ? receiver.Length
                : Converter.ExpectNumber(arg1, context: new ConversionContext(pos: 2));

            if (arg1Int < 0)
            {
                arg1Int = 0;
            }

            if (arg1Int > receiver.Length)
            {
                arg1Int = receiver.Length;
            }

            return(EvaluationResult.Create(receiver.LastIndexOf(arg0Str, arg1Int, StringComparison.Ordinal)));
        }
Exemple #26
0
        private ObjectLiteral BuildExecuteOutputs(Context context, ModuleLiteral env, ProcessOutputs processOutputs, bool isService)
        {
            var entry = context.TopStack;

            using (var empty = EvaluationStackFrame.Empty())
            {
                var getOutputFile = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFile, m_getOutputFileSignature, GetOutputFile, m_getOutputFileStatistic),
                    frame: empty);

                var getOutputDirectory = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputDirectory, m_getOutputDirectorySignature, GetOutputDirectory, m_getOutputDirectoryStatistic),
                    frame: empty);

                var getOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFiles, m_getOutputFilesSignature, GetOutputFiles, m_getOutputFilesStatistic),
                    frame: empty);

                var getRequiredOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetRequiredOutputFiles, m_getRequiredOutputFilesSignature, GetRequiredOutputFiles, m_getRequiredOutputFilesStatistic),
                    frame: empty);

                var bindings = new List <Binding>(isService ? 5 : 4)
                {
                    new Binding(ExecuteResultGetOutputFile, getOutputFile, location: default),
                    new Binding(ExecuteResultGetOutputDirectory, getOutputDirectory, location: default),
                    new Binding(ExecuteResultGetOutputFiles, getOutputFiles, location: default),
                    new Binding(ExecuteResultGetRequiredOutputFiles, getRequiredOutputFiles, location: default),
                };
                if (isService)
                {
                    bindings.Add(new Binding(CreateServiceResultServiceId, processOutputs.ProcessPipId, location: default));
                }

                return(ObjectLiteral.Create(bindings, entry.InvocationLocation, entry.Path));
            }

            // Local functions
            EvaluationResult GetOutputFile(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputPath = Args.AsPathOrUndefined(args, 0, false);

                if (outputPath.IsValid && processOutputs.TryGetOutputFile(outputPath, out var file))
                {
                    return(EvaluationResult.Create(file));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputDirectory(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputDir = Args.AsDirectory(args, 0);

                if (outputDir.IsValid && processOutputs.TryGetOutputDirectory(outputDir.Path, out var output))
                {
                    return(EvaluationResult.Create(output));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }

            EvaluationResult GetRequiredOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetRequiredOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }
        }
Exemple #27
0
        private string CreateReprToString()
        {
            var ev = TaskExtensions.RunSynchronouslyOnUIThread(ct => EvaluationResult.EvaluateAsync(DebugEvaluationResultFields.Repr | DebugEvaluationResultFields.ReprToString, cancellationToken: ct));

            return((ev as DebugValueEvaluationResult)?.GetRepresentation().ToString);
        }
Exemple #28
0
 private static EvaluationResult AddRange(Context context, OrderedMap receiver, EvaluationResult arg, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.AddRange(ToKeyValuePairs(arg, pos: 1))));
 }
Exemple #29
0
        /// <inheritdoc />
        protected override EvaluationResult DoEval(Context context, ModuleLiteral env, EvaluationStackFrame frame)
        {
            // There is some code duplication between this type and the CoerceQualifierTypeExpression.
            // But there is not clear how to reuse this because steps are 'slightly' different.
            var moduleCandidate = ModuleReference.Eval(context, env, frame);

            if (moduleCandidate.IsErrorValue || moduleCandidate.IsUndefined)
            {
                return(moduleCandidate);
            }

            // The type checker should make sure that 'this expression' evaluates to a module literal.
            var module = moduleCandidate.Value as ModuleLiteral;

            Contract.Assert(
                module != null,
                I($"The left hand-side of a withQualifier expression should evaluates to 'TypeOrNamespaceModuleLiteral' but got '{moduleCandidate.Value.GetType()}'"));

            Contract.Assert(module.CurrentFileModule != null, "module.CurrentFileModule != null");
            var currentQualifier = env.CurrentFileModule.Qualifier.Qualifier;

            // QualifierExpression can be an object literal or anything that ended up as an object literal.
            EvaluationResult objectQualifier;

            using (var emptyFrame = EvaluationStackFrame.Empty())
            {
                objectQualifier = QualifierExpression.Eval(context, env, emptyFrame);
            }

            if (objectQualifier.IsErrorValue)
            {
                // Error has been reported.
                return(EvaluationResult.Error);
            }

            var requestedQualifier = objectQualifier.Value as ObjectLiteral;

            Contract.Assert(
                requestedQualifier != null,
                I($"The right hand-side of a withQualifier expression should evaluates to 'ObjectLiteral' but got '{objectQualifier.Value.GetType()}'"));

            // TODO: This can be made more efficient by talking with the qualifier table directly
            // and maintaining a global map of qualifier id to object literal rather than have many copies of
            // object literal floating around, but that would be more changes than warranted at the moment
            // since withqualifier is not used that heavily at the moment, when this starts showing up on profiles
            // we should consider improving the logic here.
            var qualifierBindings = new Dictionary <StringId, Binding>();

            foreach (var member in currentQualifier.Members)
            {
                qualifierBindings[member.Key] = new Binding(member.Key, member.Value, requestedQualifier.Location);
            }

            foreach (var member in requestedQualifier.Members)
            {
                if (member.Value.IsUndefined)
                {
                    // setting a value to undefined implies explicitly removing they qualifier key.
                    qualifierBindings.Remove(member.Key);
                }
                else
                {
                    qualifierBindings[member.Key] = new Binding(member.Key, member.Value, requestedQualifier.Location);
                }
            }
            var qualifierToUse = ObjectLiteral.Create(qualifierBindings.Values.ToArray());


            if (!QualifierValue.TryCreate(context, env, qualifierToUse, out QualifierValue qualifierValue, requestedQualifier.Location))
            {
                // Error has been reported.
                return(EvaluationResult.Error);
            }

            // Coercing qualifier with a given value
            if (
                !QualifierUtilities.CoerceQualifierValueForV2(
                    context,
                    qualifierValue,
                    SourceQualifierSpaceId,
                    TargetQualifierSpaceId,
                    referencingLocation: Location.AsUniversalLocation(env, context),
                    referencedLocation: module.CurrentFileModule.Location.AsUniversalLocation(module.CurrentFileModule, context),
                    coercedQualifierValue: out QualifierValue coercedQualifierValue))
            {
                // Error has been reported
                return(EvaluationResult.Error);
            }

            var result = module.Instantiate(context.ModuleRegistry, coercedQualifierValue);

            return(EvaluationResult.Create(result));
        }
Exemple #30
0
        private static KeyValuePair <EvaluationResult, EvaluationResult>[] ToKeyValuePairs(EvaluationResult arg, int pos)
        {
            var argArray = Converter.ExpectArrayLiteral(arg, new ConversionContext(pos: pos));
            var range    = new KeyValuePair <EvaluationResult, EvaluationResult> [argArray.Length];

            for (int i = 0; i < argArray.Length; ++i)
            {
                var kvp = Converter.ExpectArrayLiteral(argArray[i], new ConversionContext(objectCtx: argArray, pos: i));

                if (kvp.Length != 2)
                {
                    throw new InvalidKeyValueMapException(new ErrorContext(objectCtx: argArray, pos: i));
                }

                if (kvp[0].IsUndefined)
                {
                    throw new UndefinedMapKeyException(new ErrorContext(objectCtx: argArray, pos: i));
                }

                range[i] = new KeyValuePair <EvaluationResult, EvaluationResult>(kvp[0], kvp[1]);
            }

            return(range);
        }
Exemple #31
0
		public Literal(EvaluationResult result)
		{
			m_result = result;
		}
Exemple #32
0
 private static EvaluationResult Length(Context context, string receiver, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(receiver.Length));
 }
 public override void VisitLocalReferenceExpression([NotNull] ILocalReferenceExpression operation)
 {
     Result = owner.AnalyzeLocalReference(operation);
 }
Exemple #34
0
        private static EvaluationResult LocaleCompare(Context context, string receiver, EvaluationResult arg, EvaluationStackFrame captures)
        {
            var rhsString = Converter.ExpectString(arg, new ConversionContext(allowUndefined: true, objectCtx: arg.Value));

            return(EvaluationResult.Create(rhsString == null
                ? -1
                : string.Compare(receiver, rhsString, StringComparison.CurrentCulture)));
        }
Exemple #35
0
 private static EvaluationResult Replace(Context context, string receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
 {
     return(EvaluationResult.Create(
                receiver.Replace(
                    Converter.ExpectString(arg0, new ConversionContext(pos: 1)),
                    Converter.ExpectString(arg1, new ConversionContext(pos: 2)))));
 }
		protected override Task<EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
		{
			//// TODO: For this to be correct, we need flow analysis to determine if a given method
			//// is actually invoked inside the current constructor. A method may be assigned to a
			//// delegate which can be called inside or outside the constructor. A method may also
			//// be called from within a lambda which is called inside or outside the constructor.
			//// Currently, FxCop does not produce a warning if a virtual method is called indirectly
			//// through a delegate or through a lambda.

			var constructor = (ConstructorDeclarationSyntax)node;
			var constructorSymbol = semanticModel.GetDeclaredSymbol(constructor);
			var containingType = constructorSymbol.ContainingType;

			if (
				constructor.Body.DescendantNodes()
				.Where(x => x.Kind() == SyntaxKind.InvocationExpression)
					.Any(x => CallVirtualMethod((InvocationExpressionSyntax)x, semanticModel, containingType)))
			{
				var result = new EvaluationResult
								 {
									 Snippet = node.ToFullString(),
									 LinesOfCodeAffected = GetLinesOfCode(node)
								 };
				return Task.FromResult(result);
			}

			return Task.FromResult<EvaluationResult>(null);
		}
Exemple #37
0
        private static EvaluationResult Slice(Context context, string receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
        {
            var start = arg0.IsUndefined
                ? 0
                : Converter.ExpectNumber(arg0, context: new ConversionContext(pos: 1));

            var end = arg1.IsUndefined
                ? receiver.Length
                : Converter.ExpectNumber(arg1, context: new ConversionContext(pos: 2));

            // this seems to be the semantics in JavaScript (if 'end' is greater than length,
            // it's trimmed down to length; but if 'start' is less than 0, the result is the empty string)
            if (end > receiver.Length)
            {
                end = receiver.Length;
            }

            return((start < 0 || start >= receiver.Length || end <= 0 || end > receiver.Length || end <= start)
                ? EvaluationResult.Create(string.Empty)
                : EvaluationResult.Create(receiver.Substring(start, end - start)));
        }
		protected override EvaluationResult EvaluateImpl(SyntaxNode node)
		{
			var catchClause = (CatchClauseSyntax)node;
			var catchesException = catchClause
				.DescendantNodesAndSelf()
				.OfType<CatchDeclarationSyntax>()
				.SelectMany(x => x.DescendantNodes())
				.OfType<IdentifierNameSyntax>()
				.Any(x => x.Identifier.ValueText == "Exception");
			var throwsSomething = catchClause
				.DescendantNodes()
				.OfType<ThrowStatementSyntax>()
				.Any(x => x.Expression != null);
			if (catchesException && throwsSomething)
			{
				var result = new EvaluationResult
							 {
								 Snippet = catchClause.ToFullString()
							 };
				return result;
			}

			return null;
		}
 public void AssignValue(Env env, EvaluationResult evaluationResult)
 {
     env.AssignValue(variable, evaluationResult.Result.ToString());
 }