summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Razor/RazorDebugHelpers.cs
blob: 46fb75dc644a973a9fc66cb332e2b1cdec4676be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

#if DEBUG

using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web.Razor.Parser.SyntaxTree;
using System.Web.Razor.Text;

namespace System.Web.Razor
{
    internal static class RazorDebugHelpers
    {
        private static bool _outputDebuggingEnabled = IsDebuggingEnabled();

        private static readonly Dictionary<char, string> _printableEscapeChars = new Dictionary<char, string>
        {
            { '\0', "\\0" },
            { '\\', "\\\\" },
            { '\'', "'" },
            { '\"', "\\\"" },
            { '\a', "\\a" },
            { '\b', "\\b" },
            { '\f', "\\f" },
            { '\n', "\\n" },
            { '\r', "\\r" },
            { '\t', "\\t" },
            { '\v', "\\v" },
        };

        internal static bool OutputDebuggingEnabled
        {
            get { return _outputDebuggingEnabled; }
        }

        [SuppressMessage("Microsoft.Security", "CA2141:TransparentMethodsMustNotSatisfyLinkDemandsFxCopRule", Justification = "This is debug only")]
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is debug only")]
        [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.IO.StringWriter.#ctor", Justification = "This is debug only")]
        internal static void WriteGeneratedCode(string sourceFile, CodeCompileUnit codeCompileUnit)
        {
            if (!OutputDebuggingEnabled)
            {
                return;
            }

            RunTask(() =>
            {
                string extension = Path.GetExtension(sourceFile);
                RazorCodeLanguage language = RazorCodeLanguage.GetLanguageByExtension(extension);
                CodeDomProvider provider = CodeDomProvider.CreateProvider(language.LanguageName);

                using (var writer = new StringWriter())
                {
                    // Trim the html part of cshtml or vbhtml
                    string outputExtension = extension.Substring(0, 3);
                    string outputFileName = Normalize(sourceFile) + "_generated" + outputExtension;
                    string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName);

                    // REVIEW: Do these options need to be tweaked?
                    provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions());
                    File.WriteAllText(outputPath, writer.ToString());
                }
            });
        }

        internal static void WriteDebugTree(string sourceFile, Block document, PartialParseResult result, TextChange change, RazorEditorParser parser, bool treeStructureChanged)
        {
            if (!OutputDebuggingEnabled)
            {
                return;
            }

            RunTask(() =>
            {
                string outputFileName = Normalize(sourceFile) + "_tree";
                string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName);

                var treeBuilder = new StringBuilder();
                WriteTree(document, treeBuilder);
                treeBuilder.AppendLine();
                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, "Last Change: {0}", change);
                treeBuilder.AppendLine();
                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, "Normalized To: {0}", change.Normalize());
                treeBuilder.AppendLine();
                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, "Partial Parse Result: {0}", result);
                treeBuilder.AppendLine();
                if (result.HasFlag(PartialParseResult.Rejected))
                {
                    treeBuilder.AppendFormat(CultureInfo.CurrentCulture, "Tree Structure Changed: {0}", treeStructureChanged);
                    treeBuilder.AppendLine();
                }
                if (result.HasFlag(PartialParseResult.AutoCompleteBlock))
                {
                    treeBuilder.AppendFormat(CultureInfo.CurrentCulture, "Auto Complete Insert String: \"{0}\"", parser.GetAutoCompleteString());
                    treeBuilder.AppendLine();
                }
                File.WriteAllText(outputPath, treeBuilder.ToString());
            });
        }

        private static void WriteTree(SyntaxTreeNode node, StringBuilder treeBuilder, int depth = 0)
        {
            if (node == null)
            {
                return;
            }
            if (depth > 1)
            {
                WriteIndent(treeBuilder, depth);
            }

            if (depth > 0)
            {
                treeBuilder.Append("|-- ");
            }

            treeBuilder.AppendLine(ConvertEscapseSequences(node.ToString()));
            if (node.IsBlock)
            {
                foreach (SyntaxTreeNode child in ((Block)node).Children)
                {
                    WriteTree(child, treeBuilder, depth + 1);
                }
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This is debug only")]
        [SuppressMessage("Microsoft.WebAPI", "CR4000:DoNotUseProblematicTaskTypes", Justification = "This rule is not applicable to this assembly.")]
        [SuppressMessage("Microsoft.WebAPI", "CR4001:DoNotCallProblematicMethodsOnTask", Justification = "This rule is not applicable to this assembly.")]
        private static void RunTask(Action action)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    action();
                }
                catch
                {
                    // Catch all errors since this is just a debug helper
                }
            });
        }

        private static void WriteIndent(StringBuilder sb, int depth)
        {
            for (int i = 0; i < (depth - 1) * 4; ++i)
            {
                if (i % 4 == 0)
                {
                    sb.Append("|");
                }
                else
                {
                    sb.Append(" ");
                }
            }
        }

        private static string Normalize(string path)
        {
            return Path.GetFileName(path).Replace('.', '_');
        }

        private static string ConvertEscapseSequences(string value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var ch in value)
            {
                sb.Append(GetCharValue(ch));
            }
            return sb.ToString();
        }

        private static string GetCharValue(char ch)
        {
            string value;
            if (_printableEscapeChars.TryGetValue(ch, out value))
            {
                return value;
            }
            return ch.ToString();
        }

        private static bool IsDebuggingEnabled()
        {
            bool enabled;
            return Boolean.TryParse(Environment.GetEnvironmentVariable("RAZOR_DEBUG"), out enabled) && enabled;
        }
    }
}

#endif