AbstractOptionsSerializationService.cs 16.5 KB
Newer Older
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3
using System;
4 5 6 7
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
8 9 10
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
11 12 13 14
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Execution
{
H
Heejae Chang 已提交
15
    internal abstract class AbstractOptionsSerializationService : IOptionsSerializationService
16 17 18
    {
        public abstract void WriteTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken);
        public abstract void WriteTo(ParseOptions options, ObjectWriter writer, CancellationToken cancellationToken);
19
        public abstract void WriteTo(OptionSet options, ObjectWriter writer, CancellationToken cancellationToken);
20 21 22

        public abstract CompilationOptions ReadCompilationOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
        public abstract ParseOptions ReadParseOptionsFrom(ObjectReader reader, CancellationToken cancellationToken);
23
        public abstract OptionSet ReadOptionSetFrom(ObjectReader reader, CancellationToken cancellationToken);
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

        protected void WriteCompilationOptionsTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            writer.WriteInt32((int)options.OutputKind);
            writer.WriteBoolean(options.ReportSuppressedDiagnostics);
            writer.WriteString(options.ModuleName);
            writer.WriteString(options.MainTypeName);
            writer.WriteString(options.ScriptClassName);
            writer.WriteInt32((int)options.OptimizationLevel);
            writer.WriteBoolean(options.CheckOverflow);

            // REVIEW: is it okay this being not part of snapshot?
            writer.WriteString(options.CryptoKeyContainer);
            writer.WriteString(options.CryptoKeyFile);

41
            writer.WriteValue(options.CryptoPublicKey.ToArray());
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            writer.WriteBoolean(options.DelaySign.HasValue);
            if (options.DelaySign.HasValue)
            {
                writer.WriteBoolean(options.DelaySign.Value);
            }

            writer.WriteInt32((int)options.Platform);
            writer.WriteInt32((int)options.GeneralDiagnosticOption);

            writer.WriteInt32(options.WarningLevel);

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            writer.WriteInt32(options.SpecificDiagnosticOptions.Count);
            foreach (var kv in options.SpecificDiagnosticOptions.OrderBy(o => o.Key))
            {
                writer.WriteString(kv.Key);
                writer.WriteInt32((int)kv.Value);
            }

            writer.WriteBoolean(options.ConcurrentBuild);
            writer.WriteBoolean(options.Deterministic);
            writer.WriteBoolean(options.PublicSign);

            // REVIEW: What should I do with these. we probably need to implement either out own one
            //         or somehow share these as service....
            //
            // XmlReferenceResolver xmlReferenceResolver
            // SourceReferenceResolver sourceReferenceResolver
            // MetadataReferenceResolver metadataReferenceResolver
            // AssemblyIdentityComparer assemblyIdentityComparer
            // StrongNameProvider strongNameProvider
        }

        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray<byte> cryptoPublicKey,
            out bool? delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile = reader.ReadString();

            cryptoPublicKey = reader.ReadArray<byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List<KeyValuePair<string, ReportDiagnostic>>(count);

                for (var i = 0; i < count; i++)
                {
                    var key = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, ReportDiagnostic>>();

            concurrentBuild = reader.ReadBoolean();
            deterministic = reader.ReadBoolean();
            publicSign = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver = XmlFileResolver.Default;
            sourceReferenceResolver = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider = new DesktopStrongNameProvider();
        }

        protected void WriteParseOptionsTo(ParseOptions options, ObjectWriter writer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            writer.WriteInt32((int)options.Kind);
            writer.WriteInt32((int)options.DocumentationMode);

            // REVIEW: I don't think there is a guarantee on ordering of elements in the readonly dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            writer.WriteInt32(options.Features.Count);
            foreach (var kv in options.Features.OrderBy(o => o.Key))
            {
                writer.WriteString(kv.Key);
                writer.WriteString(kv.Value);
            }
        }

        protected void ReadParseOptionsFrom(
            ObjectReader reader,
            out SourceCodeKind kind,
            out DocumentationMode documentationMode,
            out IEnumerable<KeyValuePair<string, string>> features,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            kind = (SourceCodeKind)reader.ReadInt32();
            documentationMode = (DocumentationMode)reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why ParseOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List<KeyValuePair<string, string>> featuresList = null;

            if (count > 0)
            {
                featuresList = new List<KeyValuePair<string, string>>(count);

                for (var i = 0; i < count; i++)
                {
                    var key = reader.ReadString();
                    var value = reader.ReadString();

                    featuresList.Add(KeyValuePair.Create(key, value));
                }
            }

            features = featuresList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, string>>();
        }
213 214 215 216 217 218 219 220 221 222 223 224

        protected void WriteOptionSetTo(OptionSet options, string language, ObjectWriter writer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // order of options we serialize should be static so that we get deterministic checksum for options
            WriteOptionTo(options, language, CodeStyleOptions.QualifyFieldAccess, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.QualifyPropertyAccess, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.QualifyMethodAccess, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.QualifyEventAccess, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, writer, cancellationToken);
225 226 227 228 229 230 231 232

            WriteOptionTo(options, language, CodeStyleOptions.PreferCoalesceExpression, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferCollectionInitializer, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferExplicitTupleNames, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferInlinedVariableDeclaration, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferNullPropagation, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferObjectInitializer, writer, cancellationToken);
            WriteOptionTo(options, language, CodeStyleOptions.PreferThrowExpression, writer, cancellationToken);
233 234 235 236 237 238 239 240 241 242 243 244 245
        }

        protected OptionSet ReadOptionSetFrom(OptionSet options, string language, ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            options = ReadOptionFrom(options, language, CodeStyleOptions.QualifyFieldAccess, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.QualifyPropertyAccess, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.QualifyMethodAccess, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.QualifyEventAccess, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, reader, cancellationToken);

246 247 248 249 250 251 252 253
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferCoalesceExpression, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferCollectionInitializer, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferExplicitTupleNames, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferInlinedVariableDeclaration, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferNullPropagation, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferObjectInitializer, reader, cancellationToken);
            options = ReadOptionFrom(options, language, CodeStyleOptions.PreferThrowExpression, reader, cancellationToken);

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            return options;
        }

        protected void WriteOptionTo<T>(OptionSet options, Option<CodeStyleOption<T>> option, ObjectWriter writer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var value = options.GetOption(option);
            writer.WriteString(value.ToXElement().ToString());
        }

        protected OptionSet ReadOptionFrom<T>(OptionSet options, Option<CodeStyleOption<T>> option, ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var xmlText = reader.ReadString();
            var value = CodeStyleOption<T>.FromXElement(XElement.Parse(xmlText));

            return options.WithChangedOption(option, value);
        }

        private void WriteOptionTo<T>(OptionSet options, string language, PerLanguageOption<CodeStyleOption<T>> option, ObjectWriter writer, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var value = options.GetOption(option, language);
            writer.WriteString(value.ToXElement().ToString());
        }

        private OptionSet ReadOptionFrom<T>(OptionSet options, string language, PerLanguageOption<CodeStyleOption<T>> option, ObjectReader reader, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var xmlText = reader.ReadString();
            var value = CodeStyleOption<T>.FromXElement(XElement.Parse(xmlText));

            return options.WithChangedOption(option, language, value);
        }

        /// <summary>
        /// this is not real option set. it doesn't have all options defined in host. but only those
        /// we pre-selected.
        /// </summary>
        protected class SerializedPartialOptionSet : OptionSet
        {
            private readonly ImmutableDictionary<OptionKey, object> _values;

            public SerializedPartialOptionSet()
            {
                _values = ImmutableDictionary<OptionKey, object>.Empty;
            }

            private SerializedPartialOptionSet(ImmutableDictionary<OptionKey, object> values)
            {
                _values = values;
            }

            public override object GetOption(OptionKey optionKey)
            {
                object value;
                Contract.ThrowIfFalse(_values.TryGetValue(optionKey, out value));

                return value;
            }

            public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object value)
            {
                return new SerializedPartialOptionSet(_values.SetItem(optionAndLanguage, value));
            }

            internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet)
            {
                foreach (var kvp in _values)
                {
                    var currentValue = optionSet.GetOption(kvp.Key);
                    if (!object.Equals(currentValue, kvp.Value))
                    {
                        yield return kvp.Key;
                    }
                }
            }
        }
336 337
    }
}