Пример #1
0
		private string GetTypeStringFromAnnotation(AnnotatedType type, bool wrappedContext, bool dropGenerics)
		{
			string output;

			if (type.Name == "Array")
			{
				output = this.GetTypeStringFromAnnotation(type.Generics[0], false, dropGenerics);
				output += "[]";
			}
			else
			{
				output = TranslateType(type.Name, wrappedContext);
				if (type.Generics.Length > 0 && !dropGenerics)
				{
					output += "<";
					for (int i = 0; i < type.Generics.Length; ++i)
					{
						if (i > 0) output += ", ";
						output += this.GetTypeStringFromAnnotation(type.Generics[i], true, false);
					}
					output += ">";
				}
			}
			return output;
		}
 private async Task <MappingElement> FindMappingSource(AnnotatedType targetType, MappingContext mappingContext, MappingPath mappingPath)
 {
     return(new MappingElement
     {
         ExpressionType = targetType,
         Expression = (ExpressionSyntax)(await GetDefaultExpression(targetType.Type, mappingContext, mappingPath).ConfigureAwait(false))
     });
 }
Пример #3
0
        static void TestObjectGetTypeValue(AnnotatedType instance = null)
        {
            string type = instance.GetType().AssemblyQualifiedName;

            // Currently Object.GetType is unimplemented in the analyzer, but
            // this still shouldn't warn.
            RequirePublicConstructors(type);
            RequireNothing(type);
        }
        public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel, MappingContext mappingContext)
        {
            var cloneMappingEngine = new CloneMappingEngine(semanticModel, generator);
            var sourceParameter    = methodSymbol.Parameters[0];
            var sourceType         = new AnnotatedType(sourceParameter.Type);
            var targetType         = new AnnotatedType(methodSymbol.ReturnType);
            var newExpression      = cloneMappingEngine.MapExpression((ExpressionSyntax)generator.IdentifierName(sourceParameter.Name), sourceType, targetType, mappingContext);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
Пример #5
0
        public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine   = new MappingEngine(semanticModel, generator);
            var destinationType = new AnnotatedType(methodSymbol.ReturnType);
            var sourceType      = new AnnotatedType(methodSymbol.ContainingType);
            var newExpression   = mappingEngine.MapExpression((ExpressionSyntax)generator.ThisExpression(), sourceType, destinationType, mappingContext);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
        public async Task <IReadOnlyList <SyntaxNode> > GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator,
                                                                               SemanticModel semanticModel, MappingContext mappingContext)
        {
            var mappingEngine = new MappingEngine(semanticModel, generator);
            var source        = methodSymbol.Parameters[0];
            var sourceType    = new AnnotatedType(source.Type);
            var targetType    = new AnnotatedType(methodSymbol.ReturnType);
            var newExpression = await mappingEngine.MapExpression((ExpressionSyntax)generator.IdentifierName(source.Name), sourceType, targetType, mappingContext).ConfigureAwait(false);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
Пример #7
0
        public ObjectMembersMappingSourceFinder(AnnotatedType sourceType, SyntaxNode sourceGlobalAccessor)
        {
            this.sourceType           = sourceType;
            this.sourceGlobalAccessor = sourceGlobalAccessor;
            potentialPrefix           = NameHelper.ToLocalVariableName(sourceGlobalAccessor.ToFullString());
            var sourceAllMembers = sourceType.Type.GetAllMembers();

            sourceProperties       = new Lazy <IReadOnlyList <IObjectField> >(() => ObjectFieldExtensions.GetObjectFields(sourceAllMembers).ToList());
            sourceMethods          = new Lazy <IReadOnlyList <IMethodSymbol> >(() => ObjectHelper.GetWithGetPrefixMethods(sourceAllMembers).ToList());
            isSourceTypeEnumerable = new Lazy <bool>(() => sourceType.Type.Interfaces.Any(x => x.ToDisplayString().StartsWith("System.Collections.Generic.IEnumerable<")));
        }
Пример #8
0
        public MappingElement FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            foreach (var sourceFinder in sourceFinders)
            {
                var mappingElement = sourceFinder.FindMappingSource(targetName, targetType, mappingContext);
                if (mappingElement != null)
                {
                    return(mappingElement);
                }
            }

            return(null);
        }
        public async Task <MappingElement> FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            foreach (var sourceFinder in sourceFinders)
            {
                var mappingElement = await sourceFinder.FindMappingSource(targetName, targetType, mappingContext).ConfigureAwait(false);

                if (mappingElement != null)
                {
                    return(mappingElement);
                }
            }

            return(null);
        }
Пример #10
0
        private IAnnotatedType ProcessAnnotatedType(Type type)
        {
            var annotated = new AnnotatedType(type);

            if (annotated.Annotations.Any <VetoAttribute>())
            {
                return(annotated);
            }

            var e = new ProcessAnnotatedType(annotated);

            _manager.FireEvent(e, Qualifiers.Empty);
            return(e.AnnotatedType);
        }
Пример #11
0
        public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedType type, TypeSyntax optionalSyntax, Extraction.Entities.Location exprLocation, Extraction.Entities.Location declLocation, bool isVar, IExpressionParentEntity parent, int child)
        {
            var ret = new VariableDeclaration(new ExpressionInfo(cx, type, exprLocation, ExprKind.LOCAL_VAR_DECL, parent, child, false, null));

            cx.Try(null, null, () =>
            {
                LocalVariable.Create(cx, symbol, ret, isVar, declLocation);
                if (optionalSyntax != null)
                {
                    TypeMention.Create(cx, optionalSyntax, parent, type);
                }
            });
            return(ret);
        }
        public ArgumentListSyntax ToArgumentListSyntax(MappingEngine mappingEngine, MappingContext mappingContext, bool generateNamedParameters = true)
        {
            return(Matches.Aggregate(SyntaxFactory.ArgumentList(), (list, match) =>
            {
                if (match.Source?.Expression == null && match.Parameter.IsOptional)
                {
                    generateNamedParameters = true;
                    return list;
                }

                var parameterType = new AnnotatedType(match.Parameter.Type);
                var expression = mappingEngine.MapExpression(match.Source, parameterType, mappingContext)?.Expression ?? mappingEngine.CreateDefaultExpression(parameterType.Type);
                var argument = generateNamedParameters
                    ? SyntaxFactory.Argument(SyntaxFactory.NameColon(match.Parameter.Name), SyntaxFactory.Token(SyntaxKind.None), expression)
                    : SyntaxFactory.Argument(expression);
                return list.AddArguments(argument);
            }));
        }
        public async System.Threading.Tasks.Task <ArgumentListSyntax> ToArgumentListSyntaxAsync(MappingEngine mappingEngine, MappingContext mappingContext, bool generateNamedParameters = true)
        {
            var resultList = SyntaxFactory.ArgumentList();

            foreach (var match in Matches)
            {
                if (match.Source?.Expression == null && match.Parameter.IsOptional)
                {
                    generateNamedParameters = true;
                    continue;
                }

                var parameterType = new AnnotatedType(match.Parameter.Type);
                var mapExpression = await mappingEngine.MapExpression(match.Source, parameterType, mappingContext).ConfigureAwait(false);

                var expression = mapExpression?.Expression ?? mappingEngine.CreateDefaultExpression(parameterType.Type);
                var argument   = generateNamedParameters
                    ? SyntaxFactory.Argument(SyntaxFactory.NameColon(match.Parameter.Name), SyntaxFactory.Token(SyntaxKind.None), expression)
                    : SyntaxFactory.Argument(expression);
                resultList = resultList.AddArguments(argument);
            }

            return(resultList);
        }
Пример #14
0
        public async Task <MappingElement> FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            var candidate = localSymbols.FirstOrDefault(x => x.Name.Equals(targetName, StringComparison.OrdinalIgnoreCase));

            if (candidate != null)
            {
                var type = semanticModel.GetTypeForSymbol(candidate);
                if (type != null)
                {
                    return(new MappingElement
                    {
                        ExpressionType = new AnnotatedType(type),
                        Expression = CreateIdentifierName(candidate)
                    });
                }
            }

            if (AllowMatchOnlyByTypeWhenSingleCandidate)
            {
                var byTypeCandidates = localSymbols.Where(x => semanticModel.MatchType(x, targetType.Type)).ToList();
                if (byTypeCandidates.Count == 1)
                {
                    var byTypeCandidate = byTypeCandidates[0];
                    var type            = semanticModel.GetTypeForSymbol(byTypeCandidate);
                    if (type != null)
                    {
                        return(new MappingElement()
                        {
                            ExpressionType = new AnnotatedType(type),
                            Expression = CreateIdentifierName(byTypeCandidate)
                        });
                    }
                }
            }
            return(null);
        }
Пример #15
0
		public string GetTypeStringFromAnnotation(AnnotatedType type, bool wrappedContext, bool dropGenerics)
		{
			string output;

			if (type.Name == "Array")
			{
				output = this.GetTypeStringFromAnnotation(type.Generics[0], false, dropGenerics);
				output += "*";
			}
			else
			{
				// TODO: there's going to have to be massive changes here. 
				// I'm likely just going to autogenerate all the generic types used as separate types.
				if (type.Generics.Length == 0)
				{
					output = TranslateType(type.Name);
				}
				else
				{
					output = "void*";
				}
			}
			return output;
		}
Пример #16
0
		public string GetTypeStringFromAnnotation(Token stringToken, string value, bool wrappedContext, bool dropGenerics)
		{
			AnnotatedType type = new AnnotatedType(stringToken, Tokenizer.Tokenize("type proxy", value, -1, false));
			return GetTypeStringFromAnnotation(type, wrappedContext, dropGenerics);
		}
        public async Task <MappingElement> FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            var mapping = await wrappedFinder.FindMappingSource(targetName, targetType, mappingContext).ConfigureAwait(false);

            return(mapping == null || ignore(mapping) ? null : mapping);
        }
Пример #18
0
        public MappingElement FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            var mapping = wrappedFinder.FindMappingSource(targetName, targetType, mappingContext);

            return(mapping == null || ignore(mapping) ? null : mapping);
        }
Пример #19
0
 public MappingElement FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
 {
     return(TryFindSource(targetName, mappingContext, sourceType) ?? TryFindSourceForEnumerable(targetName, targetType.Type));
 }
Пример #20
0
        private MappingElement TryFindSource(string targetName, MappingContext mappingContext, AnnotatedType accessedVia)
        {
            //Direct 1-1 mapping
            var matchedSourceProperty = sourceProperties.Value
                                        .Where(x => x.Name.Equals(targetName, StringComparison.OrdinalIgnoreCase) || $"{potentialPrefix}{x.Name}".Equals(targetName, StringComparison.OrdinalIgnoreCase))
                                        .FirstOrDefault(p => p.CanBeGet(accessedVia.Type, mappingContext));

            if (matchedSourceProperty != null)
            {
                return(new MappingElement()
                {
                    Expression = SyntaxFactoryExtensions.CreateMemberAccessExpression((ExpressionSyntax)sourceGlobalAccessor, accessedVia.CanBeNull, matchedSourceProperty.Name),
                    ExpressionType = new AnnotatedType(matchedSourceProperty.Type.Type, accessedVia.CanBeNull || matchedSourceProperty.Type.CanBeNull)
                });
            }

            //Non-direct (mapping like y.UserName = x.User.Name)
            var source = FindSubPropertySource(targetName, sourceType.Type, sourceProperties.Value, sourceGlobalAccessor, mappingContext, accessedVia.CanBeNull);

            if (source != null)
            {
                return(source);
            }

            //Flattening with function eg. t.Total = s.GetTotal()
            var matchedSourceMethod = sourceMethods.Value.Where((x => x.Name.EndsWith(targetName, StringComparison.OrdinalIgnoreCase))).FirstOrDefault(m => mappingContext.AccessibilityHelper.IsSymbolAccessible(m, accessedVia.Type));

            if (matchedSourceMethod != null)
            {
                var sourceMethodAccessor = SyntaxFactoryExtensions.CreateMethodAccessExpression((ExpressionSyntax)sourceGlobalAccessor, sourceType.CanBeNull, matchedSourceMethod.Name);
                return(new MappingElement()
                {
                    Expression = sourceMethodAccessor,
                    ExpressionType = new AnnotatedType(matchedSourceMethod.ReturnType, sourceType.CanBeNull || matchedSourceMethod.CanBeNull())
                });
            }

            // HIGHLY SPECULATIVE: Expanding acronyms: UserName = u.Name
            if (string.IsNullOrWhiteSpace(potentialPrefix) == false && potentialPrefix == potentialPrefix.ToLowerInvariant() && targetName != potentialPrefix)
            {
                var acronym = GetAcronym(targetName).ToLowerInvariant();
                if (acronym.StartsWith(potentialPrefix))
                {
                    var rest      = acronymPattern.Split(targetName).Skip(potentialPrefix.Length);
                    var newTarget = $"{potentialPrefix}{string.Join("", rest)}";
                    return(TryFindSource(newTarget, mappingContext, accessedVia));
                }
            }
            return(null);
        }
Пример #21
0
        private async Task <SyntaxNode[]> CreateCloneExpressionAsync(SyntaxGenerator generator, SemanticModel semanticModel, AnnotatedType type, MappingContext mappingContext)
        {
            //TODO: If subtypes contains clone method use it, remember about casting
            var mappingEngine = new CloneMappingEngine(semanticModel, generator);
            var newExpression = await mappingEngine.MapExpression((ExpressionSyntax)generator.ThisExpression(), type, type, mappingContext).ConfigureAwait(false);

            return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) });
        }
Пример #22
0
        public string GetTypeStringFromAnnotation(Token stringToken, string value, bool wrappedContext, bool dropGenerics)
        {
            AnnotatedType type = new AnnotatedType(stringToken, new TokenStream(Tokenizer.Tokenize("type proxy", value, -1, false)));

            return(GetTypeStringFromAnnotation(type, wrappedContext, dropGenerics));
        }
Пример #23
0
		public string GetTypeStringFromAnnotation(Token stringToken, string value)
		{
			AnnotatedType type = new AnnotatedType(stringToken, Tokenizer.Tokenize("type proxy", value, -1, false));
			return GetTypeStringFromAnnotation(type);
		}
Пример #24
0
		private string GetTypeStringFromAnnotation(AnnotatedType type)
		{
			string output;

			if (type.Name == "Array")
			{
				output = this.GetTypeStringFromAnnotation(type.Generics[0]);
				output += "[]";
			}
			else
			{
				output = type.Name;
				if (type.Generics.Length > 0)
				{
					output += "<";
					for (int i = 0; i < type.Generics.Length; ++i)
					{
						if (i > 0) output += ", ";
						output += this.GetTypeStringFromAnnotation(type.Generics[i]);
					}
					output += ">";
				}
			}
			return output;
		}
Пример #25
0
        public Task <MappingElement> FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
        {
            var result = TryFindSource(targetName, mappingContext, sourceType) ?? TryFindSourceForEnumerable(targetName, targetType.Type);

            return(Task.FromResult(result));
        }
Пример #26
0
        public string GetTypeStringFromAnnotation(Token stringToken, string value)
        {
            AnnotatedType type = new AnnotatedType(stringToken, new TokenStream(Tokenizer.Tokenize("type proxy", value, -1, false)));

            return(GetTypeStringFromAnnotation(type));
        }
Пример #27
0
 public ObjectProperty(IPropertySymbol property)
 {
     this.property = property;
     Type          = new AnnotatedType(property.Type);
 }
Пример #28
0
 public static VariableDeclaration Create(Context cx, CSharpSyntaxNode c, AnnotatedType type, bool isVar, IExpressionParentEntity parent, int child) =>
 new VariableDeclaration(new ExpressionInfo(cx, type, cx.Create(c.FixedLocation()), ExprKind.LOCAL_VAR_DECL, parent, child, false, null));
Пример #29
0
 public static void TestNewConstraintOnTypeParameterInAnnotatedType()
 {
     AnnotatedType.Method();
 }
Пример #30
0
        public static VariableDeclaration CreateDeclarator(Context cx, VariableDeclaratorSyntax d, AnnotatedType type, bool isVar, IExpressionParentEntity parent, int child)
        {
            var ret = Create(cx, d, type, isVar, parent, child);

            cx.Try(d, null, () =>
            {
                var id         = d.Identifier;
                var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d);
                var location   = cx.Create(id.GetLocation());
                var localVar   = LocalVariable.Create(cx, declSymbol, ret, isVar, location);

                if (d.Initializer != null)
                {
                    Create(cx, d.Initializer.Value, ret, 0);

                    // Create an access
                    var access = new Expression(new ExpressionInfo(cx, type, location, ExprKind.LOCAL_VARIABLE_ACCESS, ret, 1, false, null));
                    cx.TrapWriter.Writer.expr_access(access, localVar);
                }

                var decl = d.Parent as VariableDeclarationSyntax;
                if (decl != null)
                {
                    TypeMention.Create(cx, decl.Type, ret, type);
                }
            });
            return(ret);
        }
 public MappingElement FindMappingSource(string targetName, AnnotatedType targetType, MappingContext mappingContext)
 {
     return(FindMappingSource(targetType, mappingContext, new MappingPath()));
 }