public void ABarOnTheLine_ABarOnTheLine_ReturnTrue()
        {
            var aLine  = GenerateALine(Symbol.Bar, Symbol.DoubleBar, Symbol.TripleBar);
            var result = SymbolHelpers.ABarOnTheLine(aLine);

            Assert.That(result, Is.EqualTo(true));
        }
        public void ABarOnTheLine_NoBarOnTheLine_ReturnFalse()
        {
            var aLine  = GenerateALine(Symbol.DoubleBar, Symbol.TripleBar, Symbol.Seven);
            var result = SymbolHelpers.ABarOnTheLine(aLine);

            Assert.That(result, Is.EqualTo(false));
        }
        public void CherryAndSevenOnTheSameLine_CherryAndSevenOnTheSameLine_ReturnTrue()
        {
            var aLine  = GenerateALine(Symbol.Cherry, Symbol.Seven, Symbol.TripleBar);
            var result = SymbolHelpers.CherryAndSevenOnTheSameLine(aLine);

            Assert.That(result, Is.EqualTo(true));
        }
        public void CherryAndSevenOnTheSameLine_NoCherryAndSevenOnTheSameLine_ReturnFalse()
        {
            var aLine  = GenerateALine(Symbol.TripleBar, Symbol.DoubleBar, Symbol.DoubleBar);
            var result = SymbolHelpers.CherryAndSevenOnTheSameLine(aLine);

            Assert.That(result, Is.EqualTo(false));
        }
        public void ThreeSymbolsOnTheSameLine_ThreeDiffirentSymbosOnTheSameLine_ReturnFalse()
        {
            var aLine  = GenerateALine(Symbol.Seven, Symbol.Cherry, Symbol.DoubleBar);
            var result = SymbolHelpers.ThreeSymbolsOnTheSameLine(aLine, Symbol.Cherry);

            Assert.That(result, Is.EqualTo(false));
        }
        public void ThreeSymbolsOnTheSameLine_ThreeCherriesOnTheSameLine_ReturnTrue()
        {
            var aLine  = GenerateALine(Symbol.Cherry, Symbol.Cherry, Symbol.Cherry);
            var result = SymbolHelpers.ThreeSymbolsOnTheSameLine(aLine, Symbol.Cherry);

            Assert.That(result, Is.EqualTo(true));
        }
Exemple #7
0
        private IType BindType()
        {
            if (!Condition.Type.Equals(Primitive.Bool))
            {
                _diagnostics.Add(new Diagnostic(
                                     new Location(_context.expression(0)),
                                     ErrorCode.NonBooleanCondition,
                                     ImmutableArray.Create <object?>(Condition.Type)));
            }
            if (SymbolHelpers.TryFindBestType(IfTrue.Type, IfFalse.Type, out var type))
            {
                return(type);
            }

            _diagnostics.Add(new Diagnostic(
                                 new Location(_context.expression(0)),
                                 ErrorCode.NoBestType,
                                 ImmutableArray.Create <object?>(IfTrue.Type, IfFalse.Type)));

            return(ErrorType.Instance);
        }
Exemple #8
0
        private static bool TryGetSourceInfo(CompetitionTarget competitionTarget, out string fileName, out int firstCodeLine)
        {
            fileName      = null;
            firstCodeLine = 0;
            var methodSymbols = SymbolHelpers.TryGetSymbols(competitionTarget.Target.Method);

            if (methodSymbols != null)
            {
                var count      = methodSymbols.SequencePointCount;
                var docs       = new ISymbolDocument[count];
                var offsets    = new int[count];
                var lines      = new int[count];
                var columns    = new int[count];
                var endlines   = new int[count];
                var endcolumns = new int[count];
                methodSymbols.GetSequencePoints(offsets, docs, lines, columns, endlines, endcolumns);

                fileName      = docs[0].URL;
                firstCodeLine = lines.Min();
            }
            return(fileName != null);
        }
        public async Task GenericReplace()
        {
            var root          = await trees[0].GetRootAsync();
            var semanticModel = compilation.GetSemanticModel(trees[0], false);
            var nodes         = root.DescendantNodes();

            var declaredTypeSymbols
                = nodes
                  .OfType <TypeDeclarationSyntax>()
                  .Select(sy => semanticModel.GetDeclaredSymbol(sy))
                  .OfType <INamedTypeSymbol>()
                  .ToArray();

            var constraintGenericsSymbol = declaredTypeSymbols
                                           .Single(s => s.ToString() == "TestAssembly.TA.ConstraintGenerics<R, S, Op>");

            var constraint = (INamedTypeSymbol)constraintGenericsSymbol.TypeParameters[2].ConstraintTypes.Single();

            var builder = ImmutableDictionary.CreateBuilder <ITypeParameterSymbol, ITypeSymbol>(SymbolEqualityComparer.Default);

            builder.Add(constraintGenericsSymbol.TypeParameters[0],
                        declaredTypeSymbols.Single(s => s.ToString() == "TestAssembly.TA.Foo"));
            builder.Add(constraintGenericsSymbol.TypeParameters[1],
                        declaredTypeSymbols.Single(s => s.ToString() == "TestAssembly.TA.Bar"));

            var got = SymbolHelpers.ReplaceGenericType(constraint, builder.ToImmutable());

            Assert.Equal(nodes
                         .OfType <TypeDeclarationSyntax>()
                         .Single(sy => sy.Identifier.Text == "Foo")
                         .DescendantNodes()
                         .OfType <FieldDeclarationSyntax>()
                         .Where(sy => sy.Declaration.Variables.Single().Identifier.Text == "field2")
                         .Select(sy => semanticModel.GetSymbolInfo(sy.Declaration.Type).Symbol)
                         .OfType <INamedTypeSymbol>()
                         .Single()
                         , got, SymbolEqualityComparer.Default);
        }
Exemple #10
0
        public static CompetitionTarget[] TryAnnotateBenchmarkFiles(
            [NotNull] CompetitionTarget[] targetsToAnnotate,
            [NotNull] CompetitionState competitionState)
        {
            Code.NotNull(targetsToAnnotate, nameof(targetsToAnnotate));
            Code.NotNull(competitionState, nameof(competitionState));

            var annotatedTargets = new List <CompetitionTarget>();
            var annContext       = new AnnotateContext();
            var logger           = competitionState.Logger;

            foreach (var targetToAnnotate in targetsToAnnotate)
            {
                var target            = targetToAnnotate.Target;
                var targetMethodTitle = target.MethodTitle;

                logger.WriteLineInfo(
                    $"{LogVerbosePrefix} Method {targetMethodTitle}: updating time limits {targetToAnnotate}.");

                // DONTTOUCH: the source should be loaded for checksum validation even if target uses resource annotation.
                string fileName;
                int    firstCodeLine;
                bool   hasSource = SymbolHelpers.TryGetSourceInfo(target.Method, competitionState, out fileName, out firstCodeLine);

                if (!hasSource)
                {
                    continue;
                }

                var competitionMetadata = targetToAnnotate.CompetitionMetadata;
                if (competitionMetadata != null)
                {
                    var resourceFileName = GetResourceFileName(fileName, competitionMetadata);

                    logger.WriteLineInfo(
                        $"{LogVerbosePrefix} Method {targetMethodTitle}: annotating resource file '{resourceFileName}'.");
                    var annotated = TryFixBenchmarkXmlAnnotation(annContext, resourceFileName, targetToAnnotate, competitionState);
                    if (!annotated)
                    {
                        competitionState.WriteMessage(
                            MessageSource.Analyser, MessageSeverity.Warning,
                            $"Method {targetMethodTitle}: could not annotate resource file '{resourceFileName}'.", null);
                        continue;
                    }
                }
                else
                {
                    logger.WriteLineInfo(
                        $"{LogVerbosePrefix} Method {targetMethodTitle}: annotating file '{fileName}', line {firstCodeLine}.");
                    var annotated = TryFixBenchmarkAttribute(annContext, fileName, firstCodeLine, targetToAnnotate, competitionState);
                    if (!annotated)
                    {
                        competitionState.WriteMessage(
                            MessageSource.Analyser, MessageSeverity.Warning,
                            $"Method {targetMethodTitle}: could not annotate source file '{fileName}'.");
                        continue;
                    }
                }

                logger.WriteLineInfo(
                    $"{LogImportantInfoPrefix} Method {targetMethodTitle} updated time limits: {targetToAnnotate}.");
                annotatedTargets.Add(targetToAnnotate);
            }

            annContext.Save();
            return(annotatedTargets.ToArray());
        }
Exemple #11
0
 // Return 10 score when three Bars on any line
 private void ThreeBarOnAnyLine()
 {
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_winLines.TopLine, Symbol.Bar) ? 10 : 0;
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_winLines.CenterLine, Symbol.Bar) ? 10 : 0;
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_winLines.BottomLine, Symbol.Bar) ? 10 : 0;
 }
 // Return 4000 score when 3 cherry symbols on the bottom line
 private void ThreeCherryOnBottomLine()
 {
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_winLines.BottomLine, Symbol.Cherry) ? 4000 : 0;
 }
 // Return 1000 score when 3 cherry symbols on the center line
 private void ThreeCherryOnCenterLine()
 {
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_winLines.CenterLine, Symbol.Cherry) ? 1000 : 0;
 }
Exemple #14
0
 // Return 150 score when 3 seven on any line
 private void ThreeSeventOnAnyLine()
 {
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_WinLines.TopLine, Symbol.Seven) ? 150 : 0;
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_WinLines.CenterLine, Symbol.Seven) ? 150 : 0;
     _score += SymbolHelpers.ThreeSymbolsOnTheSameLine(_WinLines.BottomLine, Symbol.Seven) ? 150 : 0;
 }
 // Return 75 score when cherry and seven on the same line
 private void CherryAndSevenOnAnyLine()
 {
     _score += SymbolHelpers.CherryAndSevenOnTheSameLine(_winLines.TopLine) ? 75 : 0;
     _score += SymbolHelpers.CherryAndSevenOnTheSameLine(_winLines.CenterLine) ? 75 : 0;
     _score += SymbolHelpers.CherryAndSevenOnTheSameLine(_winLines.BottomLine) ? 75 : 0;
 }
 // Return 5 score when one or two bars on any line
 private void OneOrTwoBarsOnAnyLine()
 {
     _score += SymbolHelpers.ABarOnTheLine(_winLines.TopLine) ? 5 : 0;
     _score += SymbolHelpers.ABarOnTheLine(_winLines.CenterLine) ? 5 : 0;
     _score += SymbolHelpers.ABarOnTheLine(_winLines.BottomLine) ? 5 : 0;
 }
Exemple #17
0
 public static void CannotCallGetPropertyNameWithNullPropertyExpression()
 {
     Assert.Throws <ArgumentNullException>(() => SymbolHelpers.GetPropertyName <T>(default(Expression <Func <T> >)));
 }
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false)
                is not CompilationUnitSyntax root)
            {
                return;
            }
            var config         = AtCoderAnalyzerConfig.Parse(context.Document.Project.AnalyzerOptions.AnalyzerConfigOptionsProvider.GlobalOptions);
            var diagnostic     = context.Diagnostics[0];
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            if (root.FindNode(diagnosticSpan)
                is not GenericNameSyntax genericNode)
            {
                return;
            }

            var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            ImmutableArray <ITypeParameterSymbol> originalTypes;
            ImmutableArray <ITypeSymbol>          writtenTypes;

            switch (semanticModel.GetSymbolInfo(genericNode, context.CancellationToken).Symbol)
            {
            case INamedTypeSymbol symbol:
                originalTypes = symbol.TypeParameters;
                writtenTypes  = symbol.TypeArguments;
                break;

            case IMethodSymbol symbol:
                originalTypes = symbol.TypeParameters;
                writtenTypes  = symbol.TypeArguments;
                break;

            default:
                return;
            }


            var writtenTypeSyntaxes = genericNode.TypeArgumentList.Arguments;

            if (originalTypes.Length != writtenTypes.Length)
            {
                return;
            }

            if (!OperatorTypesMatcher.TryParseTypes(semanticModel.Compilation, out var types))
            {
                return;
            }

            var defaultSet           = ImmutableHashSet.Create <ITypeSymbol>(SymbolEqualityComparer.Default);
            var genericDicBuilder    = ImmutableDictionary.CreateBuilder <ITypeParameterSymbol, ITypeSymbol>(SymbolEqualityComparer.Default);
            var constraintDicBuilder = ImmutableDictionary.CreateBuilder <string, ImmutableHashSet <ITypeSymbol> >();

            for (int i = 0; i < originalTypes.Length; i++)
            {
                var writtenTypeSyntax = writtenTypeSyntaxes[i];
                var originalType      = originalTypes[i];
                var constraintTypes   = originalType.ConstraintTypes;
                var writtenType       = writtenTypes[i];

                if (!constraintTypes
                    .OfType <INamedTypeSymbol>()
                    .Select(ty => ty.ConstructedFrom)
                    .Any(ty => types.IsMatch(ty)))
                {
                    genericDicBuilder.Add(originalType, writtenType);
                    continue;
                }

                if (writtenType.TypeKind == TypeKind.Error)
                {
                    var name        = writtenType.Name;
                    var typeSymbols = constraintDicBuilder.GetValueOrDefault(name, defaultSet);
                    constraintDicBuilder[name] = typeSymbols.Union(constraintTypes);
                }
            }
            if (constraintDicBuilder.Count == 0)
            {
                return;
            }

            var genericDic         = genericDicBuilder.ToImmutable();
            var constraintArrayDic = ImmutableDictionary.CreateBuilder <string, ImmutableArray <ITypeSymbol> >();

            foreach (var p in constraintDicBuilder)
            {
                constraintArrayDic[p.Key]
                    = p.Value.Select(sy => SymbolHelpers.ReplaceGenericType(sy, genericDic))
                      .OrderBy(sy => sy.ToDisplayString())
                      .ToImmutableArray();
            }

            var action = CodeAction.Create(title: title,
                                           createChangedDocument: c => new OperatorTypeSyntaxBuilder(semanticModel, config).AddOperatorType(
                                               context.Document,
                                               root,
                                               constraintArrayDic.ToImmutable()),
                                           equivalenceKey: title);

            context.RegisterCodeFix(action, diagnostic);
        }