Esempio n. 1
0
        public static string GetTrackerClassName(TypeSyntax type)
        {
            // NOTE: it's naive approach because we don't know semantic type information here.
            var genericType = type as GenericNameSyntax;

            if (genericType == null)
            {
                if (type.ToString().StartsWith("Trackable"))
                {
                    return($"TrackablePocoTracker<I{type.ToString().Substring(9)}>");
                }
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableDictionary"))
            {
                return($"TrackableDictionaryTracker{genericType.TypeArgumentList}");
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableSet"))
            {
                return($"TrackableSetTracker{genericType.TypeArgumentList}");
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableList"))
            {
                return($"TrackableListTracker{genericType.TypeArgumentList}");
            }

            throw new Exception("Cannot resolve tracker class of " + type);
        }
Esempio n. 2
0
        /// <summary>
        /// Returns a fully-qualified name for the type inside the syntax node.
        /// </summary>
        /// <param name="typeUsed">Identifier of the type to rewrite</param>
        /// <param name="succeeded">Whether the fully qualified name was found</param>
        /// <returns>The fully qualified name</returns>
        internal string GetQualifiedName(TypeSyntax typeUsed, out bool succeeded)
        {
            var typeName           = typeUsed.ToString();
            var fullyQualifiedName = this.GetFullyQualifiedStateName(typeName);

            succeeded = fullyQualifiedName != typeUsed.ToString();
            return(fullyQualifiedName);
        }
        private static string GetMethodSignature(
            string name, SyntaxList <AttributeListSyntax> attributeLists, TypeSyntax returnType, ParameterListSyntax parameterList)
        {
            StringBuilder ret = new StringBuilder();

            foreach (var list in attributeLists)
            {
                if (list.Target != null && list.Target.Identifier.Text == "return")
                {
                    continue;
                }

                foreach (var attr in list.Attributes)
                {
                    if (attr.ToString().StartsWith("return:"))
                    {
                        continue;
                    }

                    ret.Append($"[{attr}]");
                }
            }

            var retType = GetTypeName(returnType.ToString(), attributeLists);

            if (retType == null)
            {
                retType = returnType.ToString();
            }

            ret.Append(retType);
            ret.Append(' ');
            ret.Append(name);
            ret.Append('(');

            bool firstParam = true;

            foreach (var param in parameterList.Parameters)
            {
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    ret.Append(',');
                }

                var typeName = GetTypeName(param.Type.ToString(), param.AttributeLists);
                ret.Append(typeName);
                ret.Append(' ');
                ret.Append(param.Identifier.ValueText);
            }

            ret.Append(')');

            return(ret.ToString());
        }
Esempio n. 4
0
 private void RegisterMakeCollectionActions(CodeRefactoringContext context, SyntaxNode root, TypeSyntax type)
 {
     context.RegisterRefactoring(CodeAction.Create(
                                     "Make collection",
                                     ImmutableArray.Create(
                                         CodeAction.Create(ienumerableType(type.ToString()), token => Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(type, SyntaxFactory.IdentifierName(ienumerableType(type.ToString())))))),
                                         CodeAction.Create(listType(type.ToString()), token => Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(type, SyntaxFactory.IdentifierName(listType(type.ToString()))))))),
                                     isInlinable: true));
 }
        public static TRoot ReplaceType <TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
        {
            string value = HlslKnownTypes.GetMappedName(type.ToString());

            if (value == type.ToString())
            {
                return(node);
            }
            else
            {
                return(node.ReplaceNode(type, SyntaxFactory.ParseTypeName(value).WithTriviaFrom(type)));
            }
        }
        /// <summary>
        /// Synthesize the concrete type that should be used to initialize a collection-
        /// valued property in the implementation of the generated class's <code>Init</code>
        /// method.
        /// </summary>
        /// <remarks>
        /// For array-valued properties, the property type stored in the
        /// PropertyInfoDictionary is <see cref="IList{T}" />. But in the implementation
        /// of the <code>Init</code> method, the concrete type used to initialize the
        /// property is <see cref="List{T}" />.
        /// </remarks>
        internal TypeSyntax GetConcreteListType(string propertyName)
        {
            TypeSyntax type = this[propertyName].Type;

            string typeName = type.ToString();

            if (typeName.StartsWith("IList"))
            {
                typeName = Regex.Replace(type.ToString(), "^IList<", "List<");
            }

            return(SyntaxFactory.ParseTypeName(typeName));
        }
Esempio n. 7
0
 private static TypeSyntax WrapInEnumerable(TypeSyntax type)
 {
     // very rough heuristic, if we have something like object[] make it IEnumerable<object[]>
     // as required by xunit. But if the data type is already enumerable, like object[][]
     // or IList<IList<object>> don't touch it
     if (type.ToString() == "IEnumerable<object[]>" ||
         type.ToString().EndsWith("[][]") ||
         type.ToString().Count(c => c == '<') >= 2)
     {
         return(type.WithoutLeadingTrivia());
     }
     return(ParseTypeName($"IEnumerable<{type}>").WithTrailingTrivia(Space));
 }
Esempio n. 8
0
        private static bool IsSimpleType(TypeSyntax type)
        {
            if (type.ToString() == "DateTime" || type.ToString().EndsWith(".DateTime"))
            {
                return(true);
            }

            if (type is PredefinedTypeSyntax)
            {
                return(true);
            }

            return(false);
        }
        public static TRoot ReplaceType <TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
        {
            string value = HlslKnownTypes.GetMappedName(type.ToString());

            // If the HLSL mapped full type name equals the original type, just return the input node
            if (value == type.ToString())
            {
                return(node);
            }

            // Process and return the type name
            TypeSyntax newType = SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia());

            return(node.ReplaceNode(type, newType));
        }
Esempio n. 10
0
        private void ParseTypeAndVariables(TypeSyntax type, SeparatedSyntaxList <VariableDeclaratorSyntax> variables)
        {
            string typeString     = type.ToString();
            string variableSuffix = String.Empty;

            int index = typeString.IndexOf("[");

            if (index != -1)
            {
                variableSuffix = typeString.Substring(index);
                typeString     = typeString.Substring(0, index);
            }

            _output.HandleLeadingTrivia(type);
            _output.Add(typeString);
            _output.HandleTrailingTrivia(type);

            foreach (var variable in variables)
            {
                _output.HandleLeadingTrivia(variable.Identifier);
                _output.Add(variable.Identifier.ToString() + variableSuffix);
                _output.HandleTrailingTrivia(variable.Identifier);

                if (variable.Initializer != null)
                {
                    HandleTokenAndTrivia(variable.Initializer.EqualsToken);
                    _expression.ParseExpressionSyntax(variable.Initializer.Value);
                }
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyInfo"/> class.
 /// </summary>
 /// <param name="description">
 /// The description of the property, for use in a summary comment.
 /// </param>
 /// <param name="serializedName">
 /// The name of the property as serialized in the JSON file.
 /// </param>
 /// <param name="comparisonKind">
 /// The kind of comparison code required by the property.
 /// </param>
 /// <param name="hashKind">
 /// The kind of hash value computation code required by the property.
 /// </param>
 /// <param name="initializationKind">
 /// The kind of initialization code required by the property.
 /// </param>
 /// <param name="type">
 /// The type of the property.
 /// </param>
 /// <param name="typeName">
 /// The name of the type of the property.
 /// </param>
 /// <param name="namespaceName">
 /// The qualified name of the namespace declaration required by this type,
 /// or <code>null</code> if no namespace declaration is required.
 /// </param>
 /// <param name="isRequired">
 /// <code>true</code> if this property is required by the schema;
 /// otherwise <code>false</code>.
 /// </param>
 /// <param name="isOfSchemaDefinedType">
 /// <code>true</code> if this property is of a type defined by the schema (or an;
 /// array of a schema-defined type otherwise <code>false</code>.
 /// </param>
 /// <param name="arrayRank">
 /// The array rank of the property type. 0 means the property is not an array.
 /// </param>
 /// <param name="declarationOrder">
 /// The 0-based order in which the property was declared in the schema.
 /// </param>
 public PropertyInfo(
     string description,
     string serializedName,
     ComparisonKind comparisonKind,
     HashKind hashKind,
     InitializationKind initializationKind,
     TypeSyntax type,
     string namespaceName,
     bool isRequired,
     bool isOfSchemaDefinedType,
     int arrayRank,
     int declarationOrder)
 {
     Description        = description;
     SerializedName     = serializedName;
     ComparisonKind     = comparisonKind;
     HashKind           = hashKind;
     InitializationKind = initializationKind;
     Type                  = type;
     TypeName              = type.ToString();
     NamespaceName         = namespaceName;
     IsRequired            = isRequired;
     IsOfSchemaDefinedType = isOfSchemaDefinedType;
     ArrayRank             = arrayRank;
     DeclarationOrder      = declarationOrder;
 }
Esempio n. 12
0
        private static string GetFunctionDescription(TypeSyntax returnType, SyntaxToken name, ParameterListSyntax parameterList, bool includeReturnType, bool includeParameterNames)
        {
            var result = new StringBuilder();

            if (includeReturnType)
            {
                result.Append($"{returnType.ToString(true)} ");
            }

            result.Append(name.GetFullyQualifiedName());
            result.Append("(");

            for (var i = 0; i < parameterList.Parameters.Count; i++)
            {
                var parameter = parameterList.Parameters[i];

                result.Append(parameter.GetDescription(includeParameterNames));

                if (i < parameterList.Parameters.Count - 1)
                {
                    result.Append(", ");
                }
            }

            result.Append(")");

            return(result.ToString().Replace(Environment.NewLine, string.Empty));
        }
Esempio n. 13
0
        /// <summary>
        /// Tries to resolve the given type name.
        /// </summary>
        /// <param name="type">The simple or full type name.</param>
        /// <param name="diagnostics">A diagnostics sink for resolution errors.</param>
        /// <param name="resolvedType">If this method returns true, the resolved type.</param>
        public static bool TryResolve(TypeSyntax type, IDiagnosticSink diagnostics,
                                      [NotNullWhen(true)] out TypeDefinition?resolvedType)
        {
            // TODO: Proper type resolution with a declaration provider
            switch (((TypeNameSyntax)type).TypeName)
            {
            case "bool":
                resolvedType = SimpleType.Bool;
                break;

            case "int32":
                resolvedType = SimpleType.Int32;
                break;

            case "void":
                resolvedType = SimpleType.Void;
                break;

            default:
                diagnostics.Add(DiagnosticCode.TypeNotFound, type.Position, type.ToString());
                resolvedType = null;
                return(false);
            }

            return(true);
        }
Esempio n. 14
0
        public static string translateType(TypeSyntax type_syntax)
        {
            string s = type_syntax.ToString();

            switch (s)
            {
            // basic types
            case "int":
            case "float":
            case "bool":
                return(s);

            // double -> float
            case "double":
                Translator.translatorWarning("translating \"double\" as \"float\"",
                                             "[uncertainty] type approximation");
                return("float");

            // void -> null
            case "void":
                return("null");
            }

            // enumerable types
            if (s.EndsWith("[]") || s.StartsWith("List<"))
            {
                return("list"); // NOT COOL !
            }

            return(Translator.translatorWarning("unknown type \"" + s + "\"", "[unsupported type] type approximation") + "auto");

            //throw new NotImplementedException("Unsupported type: " + s);
        }
Esempio n. 15
0
        private string GetTypeName(TypeSyntax typeSyntax)
        {
            if (typeSyntax is NullableTypeSyntax nullableTypeSyntax)
            {
                // string?
                typeSyntax = nullableTypeSyntax.ElementType;
            }

            if (typeSyntax is GenericNameSyntax genericNameSyntax)
            {
                // List<string>
                // Dictionary<string, string>
                return(genericNameSyntax.Identifier.ToString());
            }
            else if (typeSyntax is ArrayTypeSyntax)
            {
                // string[]
                return("[]");
            }
            else if (typeSyntax is PredefinedTypeSyntax predefinedTypeSyntax)
            {
                // string
                return(predefinedTypeSyntax.ToString());
            }
            else if (typeSyntax is QualifiedNameSyntax qualifiedNameSyntax)
            {
                // System.String
                return(qualifiedNameSyntax.ChildNodes().OfType <IdentifierNameSyntax>().Last().ToString());
            }
            else
            {
                // String
                return(typeSyntax.ToString());
            }
        }
        public static string ToTypescript(this TypeSyntax type)
        {
            switch (type)
            {
            case PredefinedTypeSyntax syntaxItem:
                return(syntaxItem.ToTypescript());

            case NullableTypeSyntax syntaxItem:
                return(syntaxItem.ElementType.ToTypescript());

            case GenericNameSyntax syntaxItem:
                return(syntaxItem.ToTypescript());

            case IdentifierNameSyntax syntaxItem:
                return(syntaxItem.ToTypescript());

            case ArrayTypeSyntax syntaxItem:
                if (syntaxItem.RankSpecifiers.IsMultiRankArray())
                {
                    Log.Info($"WARNING: To many ranks: {syntaxItem} returning any");
                    return("any");
                }
                return(syntaxItem.ElementType.ToTypescript() + syntaxItem.RankSpecifiers.ToTypescript());

            case QualifiedNameSyntax syntaxItem:
                return(syntaxItem.ToTypescript());
            }

            Log.Warn($"unknown type: {type}");
            return(type.ToString());
        }
Esempio n. 17
0
        public static NetType GetType(TypeSyntax typeSyntax)
        {
            if (typeSyntax is QualifiedNameSyntax)
            {
                typeSyntax = ((QualifiedNameSyntax)typeSyntax).Right;
            }

            if (typeSyntax is GenericNameSyntax)
            {
                var genericType = (GenericNameSyntax)typeSyntax;

                return(new NetType()
                {
                    Name = genericType.Identifier.ToString(),
                    GenericParameters = GetGenericParameters(genericType.TypeArgumentList)
                });
            }

            if (typeSyntax is NullableTypeSyntax)
            {
                return(new NetType
                {
                    Name = ((NullableTypeSyntax)typeSyntax).ElementType.ToString(),
                    IsNullable = true
                });
            }

            return(new NetType
            {
                Name = typeSyntax.ToString(),
            });
        }
        public IVariable SetupNewVariable(VariableKind variableKind, RDomBaseVariable newItem, TypeSyntax typeSyntax,
                                          SyntaxNode node, IDom parent, SemanticModel model)
        {
            CreateFromWorker.StandardInitialize(newItem, node, parent, model, OutputContext);
            newItem.Name = newItem.TypedSymbol.Name;
            var declaredType = typeSyntax.ToString();
            var returnType   = OutputContext.Corporation
                               .Create(typeSyntax, newItem, model)
                               .FirstOrDefault()
                               as IReferencedType;

            newItem.Type         = returnType;
            newItem.VariableKind = variableKind;

            newItem.IsImplicitlyTyped = (declaredType == "var");
            if (!newItem.IsImplicitlyTyped &&
                newItem.Type.TypeArguments.Count() == 0 &&
                declaredType != newItem.Type.Name)
            {
                var test = Mappings.AliasFromSystemType(newItem.Type.Name);
                if (declaredType == test)
                {
                    newItem.IsAliased = true;
                }
            }
            return(newItem);
        }
Esempio n. 19
0
        private static string Convert(TypeSyntax typeSyntax)
        {
            if (typeSyntax is IdentifierNameSyntax identifierNameSyntax)
            {
                switch (identifierNameSyntax.Identifier.ValueText)
                {
                case nameof(Boolean):
                    return("bool");

                case nameof(Byte):
                    return("int");

                case nameof(Char):
                    return("string");

                case nameof(Decimal):
                    return("decimal");

                case nameof(Double):
                    return("double");

                case nameof(Int16):
                case nameof(Int32):
                    return("int");

                case nameof(Int64):
                    return("long");

                case nameof(Object):
                    return("object");

                case nameof(SByte):
                    return("sbyte");

                case nameof(Single):
                    return("float");

                case nameof(String):
                    return("string");

                case nameof(UInt16):
                    return("int");

                case nameof(UInt32):
                    return("long");

                case nameof(UInt64):
                    return("ulong");

                case nameof(Byte) + "[]":
                    return("blob");

                case nameof(DateTime):
                    return("timestamp");
                }
            }

            return(typeSyntax.ToString().Trim());
        }
Esempio n. 20
0
        /// <summary>
        /// Synthesize the concrete type that should be used to initialize a dictionary-
        /// valued property in the implementation of the generated class's <code>Init</code>
        /// method.
        /// <remarks>
        /// For dictionary-valued properties, the property type stored in the
        /// PropertyInfoDictionary is <see cref="IDictionary{K,V}" />. But in the
        /// implementation of the <code>Init</code> method, the concrete type used to
        /// initialize the property is <see cref="Dictionary{K,V}" />.
        /// </remarks>
        internal TypeSyntax GetConcreteDictionaryType(string propertyName)
        {
            TypeSyntax type = this[propertyName].Type;

            string typeName = Regex.Replace(type.ToString(), "^IDictionary<", "Dictionary<");

            return(SyntaxFactory.ParseTypeName(typeName));
        }
Esempio n. 21
0
        public static bool IsTrackableType(TypeSyntax type)
        {
            // NOTE: it's naive approach because we don't know semantic type information here.
            var parts    = type.ToString().Split('.');
            var typeName = parts[parts.Length - 1];

            return(typeName.StartsWith("Trackable"));
        }
Esempio n. 22
0
        internal static bool IsCommand(this TypeSyntax value, SemanticModel semanticModel)
        {
            var name = value.ToString();

            return(name.Contains("Command") &&
                   semanticModel.LookupSymbols(value.GetLocation().SourceSpan.Start, name: name).FirstOrDefault() is ITypeSymbol symbol &&
                   symbol.IsCommand());
        }
        public static string GetClassName(this TypeSyntax classDec)
        {
            // Dong Xie: not really sure what's this for? REVIEW

            return(classDec.ToString());

            //return classDec.PlainName;
        }
        /// <summary>
        /// Heuristically identifies if typeSyntax is an interface
        /// </summary>
        /// <param name="typeSyntax">Type syntax to be analyzed</param>
        /// <returns>True if TypeSyntax looks like interface name</returns>
        private static bool IsInterfaceName(TypeSyntax typeSyntax)
        {
            var fullTypeName = typeSyntax.ToString();

            // zero if does not contain dot
            var typeName = fullTypeName.Substring(fullTypeName.LastIndexOf(".", StringComparison.Ordinal) + 1);

            return(typeName.StartsWith("I") && typeName.Length > 1 && char.IsUpper(typeName[1]));
        }
 public override string ToString()
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder(ElementType.ToString());
     for (int i = 0; i < Rank; i++)
     {
         sb.Append("[]");
     }
     return(sb.ToString());
 }
Esempio n. 26
0
        private static string getNodeServer(TypeSyntax type)
        {
            switch (type.ToString())
            {
            case "NetMQ.Node": return("NetMQNode");
            }

            throw new ArgumentException("type");
        }
Esempio n. 27
0
        private string ResolvePlainOrGenericType(TypeSyntax type)
        {
            if (Context.GetTypeInfo(type).Type is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsGenericType)
            {
                return(Context.TypeResolver.ResolveGenericType(namedTypeSymbol));
            }

            return(Context.TypeResolver.Resolve(type.ToString()));
        }
Esempio n. 28
0
        public static string Map(TypeSyntax type, bool useLongNames = false)
        {
            if (type == null)
            {
                return(string.Empty);
            }

            return(Map(type.ToString(), useLongNames));
        }
Esempio n. 29
0
        private ApexTypeSyntax ConvertType(TypeSyntax type)
        {
            if (type != null)
            {
                var apexType = GenericExpressionHelper.ConvertCSharpTypesToApex(type.ToString());
                return(new ApexTypeSyntax(apexType));
            }

            return(null);
        }
Esempio n. 30
0
        /// <summary>
        ///  变量类型的转换
        /// </summary>
        /// <param name="typeSyntax"></param>
        /// <returns></returns>
        private string CharpTypeToGolangType(TypeSyntax typeSyntax)
        {
            if (typeSyntax is PredefinedTypeSyntax)
            {
                string gotype;
                if (PrimitiveTypes.TryGetValue(typeSyntax.ToString(), out gotype))
                {
                    return(gotype);
                }

                return(typeSyntax.ToString());
            }

            if (typeSyntax is IdentifierNameSyntax)
            {
                return(typeSyntax.ToString());
            }

            if (typeSyntax is GenericNameSyntax)
            {
                var genericSyntax = typeSyntax as GenericNameSyntax;

                if (genericSyntax.Identifier.Text == DICTIONARY)
                {
                    var key   = genericSyntax.TypeArgumentList.Arguments[0];
                    var value = genericSyntax.TypeArgumentList.Arguments[1];
                    return($"map[{key}]{value}");
                }

                if (genericSyntax.Identifier.Text.IndexOf(LIST, StringComparison.Ordinal) != -1)
                {
                    var typeArgumen = genericSyntax.TypeArgumentList.ToString();
                    return("[]" + typeArgumen.Replace("<", "").Replace(">", ""));
                }
            }

            if (typeSyntax is ArrayTypeSyntax)
            {
                return("[]" + ((ArrayTypeSyntax)typeSyntax).ElementType);
            }

            return(typeSyntax.ToString());
        }