AdditionalTextFile.cs 2.2 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Represents a non source code file.
    /// </summary>
    internal sealed class AdditionalTextFile : AdditionalText
    {
17 18 19 20
        private readonly CommandLineSourceFile _sourceFile;
        private readonly CommonCompiler _compiler;
        private SourceText _text;
        private IList<DiagnosticInfo> _diagnostics;
21

22
        private readonly object _lockObject = new object();
23 24 25 26 27 28 29 30

        public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler)
        {
            if (compiler == null)
            {
                throw new ArgumentNullException(nameof(compiler));
            }

31 32 33
            _sourceFile = sourceFile;
            _compiler = compiler;
            _diagnostics = SpecializedCollections.EmptyList<DiagnosticInfo>();
34 35 36 37 38
        }

        /// <summary>
        /// Path to the file.
        /// </summary>
39
        public override string Path => _sourceFile.Path;
40 41 42 43 44 45 46

        /// <summary>
        /// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
        /// there were errors reading the file.
        /// </summary>
        public override SourceText GetText(CancellationToken cancellationToken = default(CancellationToken))
        {
47
            lock (_lockObject)
48
            {
49
                if (_text == null)
50 51
                {
                    var diagnostics = new List<DiagnosticInfo>();
52
                    _text = _compiler.TryReadFileContent(_sourceFile, diagnostics);
53
                    _diagnostics = diagnostics;
54 55 56
                }
            }

57
            return _text;
58 59 60 61 62 63
        }

        /// <summary>
        /// Errors encountered when trying to read the additional file. Always empty if
        /// <see cref="GetText(CancellationToken)"/> has not been called.
        /// </summary>
64
        internal IList<DiagnosticInfo> Diagnostics => _diagnostics;
65 66
    }
}