Esempio n. 1
0
        public static void Write(CodeWriter writer, LongRunningOperation operation)
        {
            var responseVariable = "response";

            void WriteResultFunction(bool async)
            {
                if (operation.ResultSerialization != null)
                {
                    writer.WriteDeserializationForMethods(
                        operation.ResultSerialization,
                        async: async,
                        (w, v) => w.Line($"return {v};"),
                        responseVariable);
                }
                else
                {
                    if (async)
                    {
                        writer.Line($"return await new {typeof(ValueTask<Response>)}({responseVariable}).ConfigureAwait(false);");
                    }
                    else
                    {
                        writer.Line($"return {responseVariable};");
                    }
                }
            }

            var cs         = operation.Type;
            var @namespace = cs.Namespace;

            using (writer.Namespace(@namespace))
            {
                writer.WriteXmlDocumentationSummary(operation.Description);
                var interfaceType         = new CSharpType(typeof(IOperationSource <>), operation.ResultType);
                var baseType              = new CSharpType(typeof(Operation <>), operation.ResultType);
                var waitForCompletionType = new CSharpType(typeof(ValueTask <>), new CSharpType(typeof(Response <>), operation.ResultType));
                var helperType            = new CSharpType(typeof(ArmOperationHelpers <>), operation.ResultType);

                using (writer.Scope($"{operation.Declaration.Accessibility} partial class {cs.Name}: {baseType}, {interfaceType}"))
                {
                    writer.Line($"private readonly {helperType} _operation;");

                    using (writer.Scope($"internal {cs.Name}({typeof(ClientDiagnostics)} clientDiagnostics, {typeof(HttpPipeline)} pipeline, {typeof(Request)} request, {typeof(Response)} response)"))
                    {
                        writer.Line($"_operation = new {helperType}(this, clientDiagnostics, pipeline, request, response, {typeof(OperationFinalStateVia)}.{operation.FinalStateVia}, {operation.Diagnostics.ScopeName:L});");
                    }

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override string Id => _operation.Id;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {operation.ResultType} Value => _operation.Value;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override bool HasCompleted => _operation.HasCompleted;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override bool HasValue => _operation.HasValue;");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(Response)} GetRawResponse() => _operation.GetRawResponse();");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(Response)} UpdateStatus({typeof(CancellationToken)} cancellationToken = default) => _operation.UpdateStatus(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {typeof(ValueTask<Response>)} UpdateStatusAsync({typeof(CancellationToken)} cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {waitForCompletionType} WaitForCompletionAsync({typeof(CancellationToken)} cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Line($"public override {waitForCompletionType} WaitForCompletionAsync({typeof(TimeSpan)} pollingInterval, {typeof(CancellationToken)} cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);");
                    writer.Line();

                    using (writer.Scope($"{operation.ResultType} {interfaceType}.CreateResult({typeof(Response)} {responseVariable:D}, {typeof(CancellationToken)} cancellationToken)"))
                    {
                        WriteResultFunction(false);
                    }
                    writer.Line();

                    using (writer.Scope($"async {new CSharpType(typeof(ValueTask<>), operation.ResultType)} {interfaceType}.CreateResultAsync({typeof(Response)} {responseVariable:D}, {typeof(CancellationToken)} cancellationToken)"))
                    {
                        WriteResultFunction(true);
                    }
                }
            }
        }
Esempio n. 2
0
        public static CodeWriter WriteInitialization(this CodeWriter writer, ObjectType objectType, IEnumerable <ObjectPropertyInitializer> initializers)
        {
            ObjectPropertyInitializer?FindInitializerForParameter(ObjectTypeConstructor constructor, Parameter constructorParameter)
            {
                var property = constructor.FindPropertyInitializedByParameter(constructorParameter);

                return(initializers.SingleOrDefault(i => i.Property == property));
            }

            // Checks if constructor parameters can be satisfied by the provided initializer list
            List <ObjectPropertyInitializer>?TryGetParameters(ObjectTypeConstructor constructor)
            {
                List <ObjectPropertyInitializer> constructorInitializers = new List <ObjectPropertyInitializer>();

                foreach (var constructorParameter in constructor.Parameters)
                {
                    var objectPropertyInitializer = FindInitializerForParameter(constructor, constructorParameter);
                    if (objectPropertyInitializer == null)
                    {
                        return(null);
                    }

                    constructorInitializers.Add(objectPropertyInitializer);
                }

                return(constructorInitializers);
            }

            // Find longest satisfiable ctor
            List <ObjectPropertyInitializer>?selectedCtorInitializers = null;

            foreach (var constructor in objectType.Constructors)
            {
                var newInitializers = TryGetParameters(constructor);
                if (newInitializers != null &&
                    newInitializers.Count > (selectedCtorInitializers?.Count ?? -1))
                {
                    selectedCtorInitializers = newInitializers;
                }
            }

            Debug.Assert(selectedCtorInitializers != null);

            writer.Append($"new {objectType.Type}(");
            foreach (var initializer in selectedCtorInitializers)
            {
                writer.WriteReferenceOrConstant(initializer.Value);
                writer.WriteConversion(initializer.Value.Type, initializer.Property.Declaration.Type);
                writer.Append($", ");
            }
            writer.RemoveTrailingComma();
            writer.Append($")");

            // Find properties that would have to be initialized via property initializers
            var restOfInitializers = initializers.Except(selectedCtorInitializers).ToArray();

            if (restOfInitializers.Any())
            {
                using (writer.Scope($"", newLine: false))
                {
                    foreach (var propertyInitializer in restOfInitializers)
                    {
                        writer.Append($"{propertyInitializer.Property.Declaration.Name} = ")
                        .WriteReferenceOrConstant(propertyInitializer.Value);

                        writer.WriteConversion(propertyInitializer.Value.Type, propertyInitializer.Property.Declaration.Type);

                        writer.Line($",");
                    }

                    writer.RemoveTrailingComma();
                }
            }

            return(writer);
        }
Esempio n. 3
0
 private void WriteEditorBrowsableFalse(CodeWriter writer)
 {
     writer.Line($"[{typeof(EditorBrowsableAttribute)}({typeof(EditorBrowsableState)}.{nameof(EditorBrowsableState.Never)})]");
 }
Esempio n. 4
0
        private void WriteObjectSchema(CodeWriter writer, ObjectType schema)
        {
            using (writer.Namespace(schema.Declaration.Namespace))
            {
                List <CSharpType> implementsTypes = new List <CSharpType>();
                if (schema.Inherits != null)
                {
                    implementsTypes.Add(schema.Inherits);
                }

                if (schema.ImplementsDictionaryType != null)
                {
                    implementsTypes.Add(schema.ImplementsDictionaryType);
                }

                writer.WriteXmlDocumentationSummary(schema.Description);

                if (schema.IsStruct)
                {
                    writer.Append($"{schema.Declaration.Accessibility} readonly partial struct {schema.Declaration.Name}");
                }
                else
                {
                    writer.Append($"{schema.Declaration.Accessibility} partial class {schema.Declaration.Name}");
                }

                if (implementsTypes.Any())
                {
                    writer.AppendRaw(" : ");
                    foreach (var type in implementsTypes)
                    {
                        writer.Append($"{type} ,");
                    }
                    writer.RemoveTrailingComma();
                }

                writer.Line();
                using (writer.Scope())
                {
                    WriteConstructor(writer, schema);

                    foreach (var property in schema.Properties)
                    {
                        writer.WriteXmlDocumentationSummary(property.Description);

                        CSharpType propertyType = property.Declaration.Type;
                        writer.Append($"{property.Declaration.Accessibility} {propertyType} {property.Declaration.Name:D}");
                        writer.AppendRaw(property.IsReadOnly ? "{ get; }" : "{ get; set; }");

                        writer.Line();
                    }

                    if (schema.AdditionalPropertiesProperty is ObjectTypeProperty additionalPropertiesProperty)
                    {
                        var dictionaryType = schema.ImplementsDictionaryType;
                        Debug.Assert(dictionaryType != null);

                        var keyType                     = typeof(string);
                        var isReadonly                  = dictionaryType.FrameworkType == typeof(IReadOnlyDictionary <,>);
                        var itemType                    = dictionaryType.Arguments[1];
                        var keyValuePairType            = new CSharpType(typeof(KeyValuePair <,>), keyType, itemType);
                        var iEnumeratorKeyValuePairType = new CSharpType(typeof(IEnumerator <>), keyValuePairType);

                        var collectionType = isReadonly ? typeof(IReadOnlyCollection <>) : typeof(ICollection <>);

                        var iCollectionKeyValuePairType = new CSharpType(collectionType, keyValuePairType);

                        var keyValueCollectionType = isReadonly ? typeof(IEnumerable <>) : typeof(ICollection <>);
                        var iCollectionKeyType     = new CSharpType(keyValueCollectionType, keyType);
                        var iCollectionItemType    = new CSharpType(keyValueCollectionType, itemType);
                        var iEnumerator            = typeof(IEnumerator);
                        var iEnumerable            = typeof(IEnumerable);

                        string additionalProperties = additionalPropertiesProperty.Declaration.Name;

                        writer
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"public {iEnumeratorKeyValuePairType} GetEnumerator() => {additionalProperties}.GetEnumerator();")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"{iEnumerator} {iEnumerable}.GetEnumerator() => {additionalProperties}.GetEnumerator();")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"public bool TryGetValue(string key, out {itemType} value) => {additionalProperties}.TryGetValue(key, out value);")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"public bool ContainsKey({keyType} key) => {additionalProperties}.ContainsKey(key);")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"public {iCollectionKeyType} Keys => {additionalProperties}.Keys;")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"public {iCollectionItemType} Values => {additionalProperties}.Values;")
                        .WriteXmlDocumentationInheritDoc()
                        .Line($"int {iCollectionKeyValuePairType}.Count => {additionalProperties}.Count;");

                        if (!isReadonly)
                        {
                            writer
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"public void Add({keyType} key, {itemType} value) => {additionalProperties}.Add(key, value);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"public bool Remove({keyType} key) => {additionalProperties}.Remove(key);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"bool {iCollectionKeyValuePairType}.IsReadOnly => {additionalProperties}.IsReadOnly;")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"void {iCollectionKeyValuePairType}.Add({keyValuePairType} value) => {additionalProperties}.Add(value);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"bool {iCollectionKeyValuePairType}.Remove({keyValuePairType} value) => {additionalProperties}.Remove(value);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"bool {iCollectionKeyValuePairType}.Contains({keyValuePairType} value) => {additionalProperties}.Contains(value);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"void {iCollectionKeyValuePairType}.CopyTo({keyValuePairType}[] destination, int offset) => {additionalProperties}.CopyTo(destination, offset);")
                            .WriteXmlDocumentationInheritDoc()
                            .Line($"void {iCollectionKeyValuePairType}.Clear() => {additionalProperties}.Clear();");
                        }

                        using (writer
                               .WriteXmlDocumentationInheritDoc()
                               .Scope($"public {itemType} this[{keyType} key]"))
                        {
                            writer.Line($"get => {additionalProperties}[key];");
                            if (!isReadonly)
                            {
                                writer.Line($"set => {additionalProperties}[key] = value;");
                            }
                        }
                    }
                }
            }
        }
Esempio n. 5
0
        private void WriteChoiceSchema(CodeWriter writer, EnumType schema)
        {
            var    cs       = schema.Type;
            string name     = schema.Declaration.Name;
            var    isString = schema.BaseType.FrameworkType == typeof(string);

            using (writer.Namespace(schema.Declaration.Namespace))
            {
                writer.WriteXmlDocumentationSummary(schema.Description);

                var implementType = new CSharpType(typeof(IEquatable <>), cs);
                using (writer.Scope($"{schema.Declaration.Accessibility} readonly partial struct {name}: {implementType}"))
                {
                    writer.Line($"private readonly {schema.BaseType} _value;");
                    writer.Line();

                    writer.WriteXmlDocumentationSummary($"Determines if two <see cref=\"{name}\"/> values are the same.");
                    using (writer.Scope($"public {name}({schema.BaseType} value)"))
                    {
                        writer.Append($"_value = value");
                        if (isString)
                        {
                            writer.Append($"?? throw new {typeof(ArgumentNullException)}(nameof(value))");
                        }
                        writer.Line($";");
                    }
                    writer.Line();

                    foreach (var choice in schema.Values)
                    {
                        writer.Line($"private const {schema.BaseType} {choice.Declaration.Name}Value = {choice.Value.Value:L};");
                    }
                    writer.Line();

                    foreach (var choice in schema.Values)
                    {
                        writer.WriteXmlDocumentationSummary(choice.Description);
                        writer.Append($"public static {cs} {choice.Declaration.Name}").AppendRaw("{ get; }").Append($" = new {cs}({choice.Declaration.Name}Value);").Line();
                    }

                    writer.WriteXmlDocumentationSummary($"Determines if two <see cref=\"{name}\"/> values are the same.");
                    writer.Line($"public static bool operator ==({cs} left, {cs} right) => left.Equals(right);");

                    writer.WriteXmlDocumentationSummary($"Determines if two <see cref=\"{name}\"/> values are not the same.");
                    writer.Line($"public static bool operator !=({cs} left, {cs} right) => !left.Equals(right);");

                    writer.WriteXmlDocumentationSummary($"Converts a string to a <see cref=\"{name}\"/>.");
                    writer.Line($"public static implicit operator {cs}({schema.BaseType} value) => new {cs}(value);");
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    WriteEditorBrowsableFalse(writer);
                    writer.Line($"public override bool Equals({typeof(object)} obj) => obj is {cs} other && Equals(other);");

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Append($"public bool Equals({cs} other) => ");
                    if (isString)
                    {
                        writer.Line($"{schema.BaseType}.Equals(_value, other._value, {typeof(StringComparison)}.InvariantCultureIgnoreCase);");
                    }
                    else
                    {
                        writer.Line($"{schema.BaseType}.Equals(_value, other._value);");
                    }
                    writer.Line();

                    writer.WriteXmlDocumentationInheritDoc();
                    WriteEditorBrowsableFalse(writer);
                    writer.Append($"public override int GetHashCode() => ");
                    if (isString)
                    {
                        writer.Line($"_value?.GetHashCode() ?? 0;");
                    }
                    else
                    {
                        writer.Line($"_value.GetHashCode();");
                    }

                    writer.WriteXmlDocumentationInheritDoc();
                    writer.Append($"public override {typeof(string)} ToString() => ");

                    if (isString)
                    {
                        writer.Line($"_value;");
                    }
                    else
                    {
                        writer.Line($"_value.ToString({typeof(CultureInfo)}.InvariantCulture);");
                    }
                }
            }
        }