This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
/
FormattedCodeBlockBuilder.cs
385 lines (357 loc) · 12.4 KB
/
FormattedCodeBlockBuilder.cs
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Rubberduck.Parsing.Grammar;
using Rubberduck.SmartIndenter;
namespace RubberduckWeb.VBA
{
public class FormattedCodeBlockBuilder
{
private static readonly string KeywordClass = "keyword";
private static readonly string StringLiteralClass = "string-literal";
public string Format(string code)
{
var indenter = new Indenter(null, () => new IndenterSettings(true));
var indentedCode = indenter.Indent(code.Split('\n').Select(line => line.Replace("\r", string.Empty))).ToArray();
var builder = new StringBuilder();
var tokens = Tokenize(string.Join("\n", indentedCode));
var parser = new VBAParser(tokens)
{
Interpreter = {PredictionMode = PredictionMode.Ll}
};
var listeners = new IntervalListener[]
{
new CommentIntervalsListener(),
new AnnotationIntervalsListener(),
new AttributeIntervalsListener(),
new AttributeValueIntervalsListener(),
};
foreach (var listener in listeners)
{
parser.AddParseListener(listener);
}
parser.startRule();
for (var i = 0; i < tokens.Size; i++)
{
var token = tokens.Get(i);
var listener = listeners
.Select(e =>
new
{
IsValidInterval = e.IsValidInterval(token, out var interval),
Interval = interval,
Class = e.Class
})
.FirstOrDefault(e => e.IsValidInterval);
if (listener != null)
{
builder.Append($"<span class=\"{listener.Class}\">{tokens.GetText(listener.Interval)}</span>");
i = listener.Interval.b;
}
else
{
if (StringLiteralTokens.Contains(token.Type))
{
builder.Append($"<span class=\"{StringLiteralClass}\">{token.Text}</span>");
}
else if (KeywordTokens.Contains(token.Type))
{
builder.Append($"<span class=\"{KeywordClass}\">{token.Text}</span>");
}
else if (token.Type != VBAParser.Eof)
{
builder.Append(token.Text);
}
}
}
var lines = builder.ToString().Split('\n')
.Where(line => !string.IsNullOrWhiteSpace(line))
.ToArray();
var indent = lines.Last().TakeWhile(char.IsWhiteSpace).Count();
var formattedLines = from line in lines
let trimmed = line.Substring(indent)
select FormatIndents(trimmed);
return string.Join("<br/>", formattedLines);
}
private static string FormatIndents(string line)
{
var formatted = line;
var indent = line.TakeWhile(char.IsWhiteSpace).Count();
if (indent > 0)
{
formatted = line.Substring(0, indent).Replace(" ", " ")
+ line.Substring(indent);
}
return formatted;
}
private ITokenStream Tokenize(string code)
{
AntlrInputStream input;
using (var reader = new StringReader(code))
{
input = new AntlrInputStream(reader);
}
var lexer = new VBALexer(input);
return new CommonTokenStream(lexer);
}
#region token classes
private static readonly HashSet<int> StringLiteralTokens = new HashSet<int>
{
VBAParser.STRINGLITERAL,
VBAParser.DATELITERAL,
};
private static readonly HashSet<int> KeywordTokens = new HashSet<int> {
VBAParser.ANY,
VBAParser.CURRENCY,
VBAParser.DEBUG,
VBAParser.DOEVENTS,
VBAParser.EXIT,
VBAParser.FIX,
VBAParser.INPUTB,
VBAParser.LBOUND,
VBAParser.LONGLONG,
VBAParser.LONGPTR,
VBAParser.OPTION,
VBAParser.PSET,
VBAParser.SCALE,
VBAParser.SGN,
VBAParser.UBOUND,
VBAParser.ACCESS,
VBAParser.ADDRESSOF,
VBAParser.ALIAS,
VBAParser.AND,
VBAParser.ATTRIBUTE,
VBAParser.APPEND,
VBAParser.AS,
VBAParser.BEGINPROPERTY,
VBAParser.BEGIN,
VBAParser.BINARY,
VBAParser.BOOLEAN,
VBAParser.BYVAL,
VBAParser.BYREF,
VBAParser.BYTE,
VBAParser.CALL,
VBAParser.CASE,
VBAParser.CDECL,
VBAParser.CLASS,
VBAParser.CLOSE,
VBAParser.CONST,
VBAParser.CONST,
VBAParser.DATABASE,
VBAParser.DATE,
VBAParser.DECLARE,
VBAParser.DEFBOOL,
VBAParser.DEFBYTE,
VBAParser.DEFDATE,
VBAParser.DEFDBL,
VBAParser.DEFCUR,
VBAParser.DEFINT,
VBAParser.DEFLNG,
VBAParser.DEFLNGLNG,
VBAParser.DEFLNGPTR,
VBAParser.DEFOBJ,
VBAParser.DEFSNG,
VBAParser.DEFSTR,
VBAParser.DEFVAR,
VBAParser.DIM,
VBAParser.DO,
VBAParser.DOUBLE,
VBAParser.EACH,
VBAParser.ELSE,
VBAParser.ELSEIF,
VBAParser.EMPTY,
VBAParser.END_ENUM,
VBAParser.END_FUNCTION,
VBAParser.END_IF,
VBAParser.ENDPROPERTY,
VBAParser.END_SELECT,
VBAParser.END_SUB,
VBAParser.END_TYPE,
VBAParser.END_WITH,
VBAParser.END,
VBAParser.ENUM,
VBAParser.EQV,
VBAParser.ERASE,
VBAParser.ERROR,
VBAParser.EVENT,
VBAParser.EXIT_DO,
VBAParser.EXIT_FOR,
VBAParser.EXIT_FUNCTION,
VBAParser.EXIT_PROPERTY,
VBAParser.EXIT_SUB,
VBAParser.FALSE,
VBAParser.FRIEND,
VBAParser.FOR,
VBAParser.FUNCTION,
VBAParser.GET,
VBAParser.GLOBAL,
VBAParser.GOSUB,
VBAParser.GOTO,
VBAParser.IF,
VBAParser.IMP,
VBAParser.IMPLEMENTS,
VBAParser.IN,
VBAParser.INPUT,
VBAParser.IS,
VBAParser.INTEGER,
VBAParser.LOCK,
VBAParser.LONG,
VBAParser.LOOP,
VBAParser.LET,
VBAParser.LIB,
VBAParser.LIKE,
VBAParser.LINE_INPUT,
VBAParser.LOCK_READ,
VBAParser.LOCK_WRITE,
VBAParser.LOCK_READ_WRITE,
VBAParser.LSET,
VBAParser.MOD,
VBAParser.NAME,
VBAParser.NEXT,
VBAParser.NEW,
VBAParser.NOT,
VBAParser.NOTHING,
VBAParser.NULL,
VBAParser.OBJECT,
VBAParser.ON_ERROR,
VBAParser.ON_LOCAL_ERROR,
VBAParser.OPEN,
VBAParser.OPTIONAL,
VBAParser.OPTION_BASE,
VBAParser.OPTION_EXPLICIT,
VBAParser.OPTION_COMPARE,
VBAParser.OPTION_PRIVATE_MODULE,
VBAParser.OR,
VBAParser.OUTPUT,
VBAParser.PARAMARRAY,
VBAParser.PRESERVE,
VBAParser.PRINT,
VBAParser.PRIVATE,
VBAParser.PROPERTY_GET,
VBAParser.PROPERTY_LET,
VBAParser.PROPERTY_SET,
VBAParser.PTRSAFE,
VBAParser.PUBLIC,
VBAParser.PUT,
VBAParser.RANDOM,
VBAParser.RANDOMIZE,
VBAParser.RAISEEVENT,
VBAParser.READ,
VBAParser.READ_WRITE,
VBAParser.REDIM,
VBAParser.REM,
VBAParser.RESET,
VBAParser.RESUME,
VBAParser.RETURN,
VBAParser.RSET,
VBAParser.SEEK,
VBAParser.SELECT,
VBAParser.SET,
VBAParser.SHARED,
VBAParser.SINGLE,
VBAParser.STATIC,
VBAParser.STEP,
VBAParser.STOP,
VBAParser.STRING,
VBAParser.SUB,
VBAParser.TAB,
VBAParser.TEXT,
VBAParser.THEN,
VBAParser.TO,
VBAParser.TRUE,
VBAParser.TYPE,
VBAParser.TYPEOF,
VBAParser.UNLOCK,
VBAParser.UNTIL,
VBAParser.VARIANT,
VBAParser.VERSION,
VBAParser.WEND,
VBAParser.WHILE,
VBAParser.WITH,
VBAParser.WITHEVENTS,
VBAParser.WRITE,
VBAParser.XOR
};
#endregion
public abstract class IntervalListener : VBAParserBaseListener
{
private readonly IList<Interval> _intervals = new List<Interval>();
protected IntervalListener(string cssClass)
{
Class = cssClass;
}
public string Class { get; }
public bool IsValidInterval(IToken token, out Interval interval)
{
if (!_intervals.Any())
{
interval = Interval.Invalid;
return false;
}
interval = ExistsIn(_intervals, token);
return !interval.Equals(default(Interval));
}
private static Interval ExistsIn(IList<Interval> source, IToken token)
{
var tokenInterval = new Interval(token.TokenIndex, token.TokenIndex);
return source.SingleOrDefault(e => e.ProperlyContains(tokenInterval));
}
protected void AddInterval(Interval interval)
{
if (!_intervals.Any(e => e.ProperlyContains(interval)))
{
_intervals.Add(interval);
}
}
}
public class CommentIntervalsListener : IntervalListener
{
public CommentIntervalsListener() : base("comment") { }
public override void ExitCommentOrAnnotation(VBAParser.CommentOrAnnotationContext context)
{
if (context.annotationList() == null)
{
// exclude the line-ending token
AddInterval(new Interval(context.SourceInterval.a, context.SourceInterval.b - 1));
}
}
}
public class AnnotationIntervalsListener : IntervalListener
{
public AnnotationIntervalsListener() : base("annotation") { }
public override void ExitAnnotationList(VBAParser.AnnotationListContext context)
{
// exclude the line-ending token at the end
AddInterval(new Interval(context.SourceInterval.a, context.SourceInterval.b - 1));
}
}
public class AttributeIntervalsListener : IntervalListener
{
public AttributeIntervalsListener() : base("attribute") { }
public override void ExitAttributeStmt(VBAParser.AttributeStmtContext context)
{
// exclude the line-ending token
AddInterval(new Interval(context.SourceInterval.a, context.SourceInterval.b - 1));
}
}
public class AttributeValueIntervalsListener : IntervalListener
{
public AttributeValueIntervalsListener() : base("attribute-value") { }
public override void ExitAttributeStmt(VBAParser.AttributeStmtContext context)
{
var value = context.attributeValue();
if (value != null)
{
// exclude the line-ending token
AddInterval(new Interval(value.First().SourceInterval.a, value.Last().SourceInterval.b - 1));
}
}
}
}
}