Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Rewrite/HTMLRewrite.cpp
Line
Count
Source (jump to first uncovered line)
1
//== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the HTMLRewriter class, which is used to translate the
10
//  text of a source file into prettified HTML.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Rewrite/Core/HTMLRewrite.h"
15
#include "clang/Basic/SourceManager.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "clang/Lex/TokenConcatenation.h"
18
#include "clang/Rewrite/Core/Rewriter.h"
19
#include "llvm/ADT/SmallString.h"
20
#include "llvm/Support/ErrorHandling.h"
21
#include "llvm/Support/MemoryBuffer.h"
22
#include "llvm/Support/raw_ostream.h"
23
#include <memory>
24
using namespace clang;
25
26
27
/// HighlightRange - Highlight a range in the source code with the specified
28
/// start/end tags.  B/E must be in the same file.  This ensures that
29
/// start/end tags are placed at the start/end of each line if the range is
30
/// multiline.
31
void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E,
32
                          const char *StartTag, const char *EndTag,
33
570
                          bool IsTokenRange) {
34
570
  SourceManager &SM = R.getSourceMgr();
35
570
  B = SM.getExpansionLoc(B);
36
570
  E = SM.getExpansionLoc(E);
37
570
  FileID FID = SM.getFileID(B);
38
570
  assert(SM.getFileID(E) == FID && "B/E not in the same file!");
39
570
40
570
  unsigned BOffset = SM.getFileOffset(B);
41
570
  unsigned EOffset = SM.getFileOffset(E);
42
570
43
570
  // Include the whole end token in the range.
44
570
  if (IsTokenRange)
45
570
    EOffset += Lexer::MeasureTokenLength(E, R.getSourceMgr(), R.getLangOpts());
46
570
47
570
  bool Invalid = false;
48
570
  const char *BufferStart = SM.getBufferData(FID, &Invalid).data();
49
570
  if (Invalid)
50
0
    return;
51
570
52
570
  HighlightRange(R.getEditBuffer(FID), BOffset, EOffset,
53
570
                 BufferStart, StartTag, EndTag);
54
570
}
55
56
/// HighlightRange - This is the same as the above method, but takes
57
/// decomposed file locations.
58
void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E,
59
                          const char *BufferStart,
60
16.1k
                          const char *StartTag, const char *EndTag) {
61
16.1k
  // Insert the tag at the absolute start/end of the range.
62
16.1k
  RB.InsertTextAfter(B, StartTag);
63
16.1k
  RB.InsertTextBefore(E, EndTag);
64
16.1k
65
16.1k
  // Scan the range to see if there is a \r or \n.  If so, and if the line is
66
16.1k
  // not blank, insert tags on that line as well.
67
16.1k
  bool HadOpenTag = true;
68
16.1k
69
16.1k
  unsigned LastNonWhiteSpace = B;
70
247k
  for (unsigned i = B; i != E; 
++i231k
) {
71
231k
    switch (BufferStart[i]) {
72
49
    case '\r':
73
49
    case '\n':
74
49
      // Okay, we found a newline in the range.  If we have an open tag, we need
75
49
      // to insert a close tag at the first non-whitespace before the newline.
76
49
      if (HadOpenTag)
77
49
        RB.InsertTextBefore(LastNonWhiteSpace+1, EndTag);
78
49
79
49
      // Instead of inserting an open tag immediately after the newline, we
80
49
      // wait until we see a non-whitespace character.  This prevents us from
81
49
      // inserting tags around blank lines, and also allows the open tag to
82
49
      // be put *after* whitespace on a non-blank line.
83
49
      HadOpenTag = false;
84
49
      break;
85
16.6k
    case '\0':
86
16.6k
    case ' ':
87
16.6k
    case '\t':
88
16.6k
    case '\f':
89
16.6k
    case '\v':
90
16.6k
      // Ignore whitespace.
91
16.6k
      break;
92
16.6k
93
214k
    default:
94
214k
      // If there is no tag open, do it now.
95
214k
      if (!HadOpenTag) {
96
49
        RB.InsertTextAfter(i, StartTag);
97
49
        HadOpenTag = true;
98
49
      }
99
214k
100
214k
      // Remember this character.
101
214k
      LastNonWhiteSpace = i;
102
214k
      break;
103
231k
    }
104
231k
  }
105
16.1k
}
106
107
void html::EscapeText(Rewriter &R, FileID FID,
108
100
                      bool EscapeSpaces, bool ReplaceTabs) {
109
100
110
100
  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
111
100
  const char* C = Buf->getBufferStart();
112
100
  const char* FileEnd = Buf->getBufferEnd();
113
100
114
100
  assert (C <= FileEnd);
115
100
116
100
  RewriteBuffer &RB = R.getEditBuffer(FID);
117
100
118
100
  unsigned ColNo = 0;
119
525k
  for (unsigned FilePos = 0; C != FileEnd ; 
++C, ++FilePos525k
) {
120
525k
    switch (*C) {
121
428k
    default: ++ColNo; break;
122
22.2k
    case '\n':
123
22.2k
    case '\r':
124
22.2k
      ColNo = 0;
125
22.2k
      break;
126
22.2k
127
71.3k
    case ' ':
128
71.3k
      if (EscapeSpaces)
129
0
        RB.ReplaceText(FilePos, 1, "&nbsp;");
130
71.3k
      ++ColNo;
131
71.3k
      break;
132
22.2k
    case '\f':
133
0
      RB.ReplaceText(FilePos, 1, "<hr>");
134
0
      ColNo = 0;
135
0
      break;
136
22.2k
137
22.2k
    case '\t': {
138
80
      if (!ReplaceTabs)
139
80
        break;
140
0
      unsigned NumSpaces = 8-(ColNo&7);
141
0
      if (EscapeSpaces)
142
0
        RB.ReplaceText(FilePos, 1,
143
0
                       StringRef("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
144
0
                                       "&nbsp;&nbsp;&nbsp;", 6*NumSpaces));
145
0
      else
146
0
        RB.ReplaceText(FilePos, 1, StringRef("        ", NumSpaces));
147
0
      ColNo += NumSpaces;
148
0
      break;
149
0
    }
150
883
    case '<':
151
883
      RB.ReplaceText(FilePos, 1, "&lt;");
152
883
      ++ColNo;
153
883
      break;
154
0
155
628
    case '>':
156
628
      RB.ReplaceText(FilePos, 1, "&gt;");
157
628
      ++ColNo;
158
628
      break;
159
0
160
1.89k
    case '&':
161
1.89k
      RB.ReplaceText(FilePos, 1, "&amp;");
162
1.89k
      ++ColNo;
163
1.89k
      break;
164
525k
    }
165
525k
  }
166
100
}
167
168
1.20k
std::string html::EscapeText(StringRef s, bool EscapeSpaces, bool ReplaceTabs) {
169
1.20k
170
1.20k
  unsigned len = s.size();
171
1.20k
  std::string Str;
172
1.20k
  llvm::raw_string_ostream os(Str);
173
1.20k
174
92.1k
  for (unsigned i = 0 ; i < len; 
++i90.9k
) {
175
90.9k
176
90.9k
    char c = s[i];
177
90.9k
    switch (c) {
178
88.2k
    default:
179
88.2k
      os << c; break;
180
0
181
2.69k
    case ' ':
182
2.69k
      if (EscapeSpaces) 
os << "&nbsp;"0
;
183
2.69k
      else os << ' ';
184
2.69k
      break;
185
0
186
17
    case '\t':
187
17
      if (ReplaceTabs) {
188
0
        if (EscapeSpaces)
189
0
          for (unsigned i = 0; i < 4; ++i)
190
0
            os << "&nbsp;";
191
0
        else
192
0
          for (unsigned i = 0; i < 4; ++i)
193
0
            os << " ";
194
0
      }
195
17
      else
196
17
        os << c;
197
17
198
17
      break;
199
0
200
13
    case '<': os << "&lt;"; break;
201
15
    case '>': os << "&gt;"; break;
202
1
    case '&': os << "&amp;"; break;
203
90.9k
    }
204
90.9k
  }
205
1.20k
206
1.20k
  return os.str();
207
1.20k
}
208
209
static void AddLineNumber(RewriteBuffer &RB, unsigned LineNo,
210
22.2k
                          unsigned B, unsigned E) {
211
22.2k
  SmallString<256> Str;
212
22.2k
  llvm::raw_svector_ostream OS(Str);
213
22.2k
214
22.2k
  OS << "<tr class=\"codeline\" data-linenumber=\"" << LineNo << "\">"
215
22.2k
     << "<td class=\"num\" id=\"LN" << LineNo << "\">" << LineNo
216
22.2k
     << "</td><td class=\"line\">";
217
22.2k
218
22.2k
  if (B == E) { // Handle empty lines.
219
3.62k
    OS << " </td></tr>";
220
3.62k
    RB.InsertTextBefore(B, OS.str());
221
18.6k
  } else {
222
18.6k
    RB.InsertTextBefore(B, OS.str());
223
18.6k
    RB.InsertTextBefore(E, "</td></tr>");
224
18.6k
  }
225
22.2k
}
226
227
100
void html::AddLineNumbers(Rewriter& R, FileID FID) {
228
100
229
100
  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
230
100
  const char* FileBeg = Buf->getBufferStart();
231
100
  const char* FileEnd = Buf->getBufferEnd();
232
100
  const char* C = FileBeg;
233
100
  RewriteBuffer &RB = R.getEditBuffer(FID);
234
100
235
100
  assert (C <= FileEnd);
236
100
237
100
  unsigned LineNo = 0;
238
100
  unsigned FilePos = 0;
239
100
240
22.3k
  while (C != FileEnd) {
241
22.2k
242
22.2k
    ++LineNo;
243
22.2k
    unsigned LineStartPos = FilePos;
244
22.2k
    unsigned LineEndPos = FileEnd - FileBeg;
245
22.2k
246
22.2k
    assert (FilePos <= LineEndPos);
247
22.2k
    assert (C < FileEnd);
248
22.2k
249
22.2k
    // Scan until the newline (or end-of-file).
250
22.2k
251
525k
    while (C != FileEnd) {
252
525k
      char c = *C;
253
525k
      ++C;
254
525k
255
525k
      if (c == '\n') {
256
22.2k
        LineEndPos = FilePos++;
257
22.2k
        break;
258
22.2k
      }
259
503k
260
503k
      ++FilePos;
261
503k
    }
262
22.2k
263
22.2k
    AddLineNumber(RB, LineNo, LineStartPos, LineEndPos);
264
22.2k
  }
265
100
266
100
  // Add one big table tag that surrounds all of the code.
267
100
  std::string s;
268
100
  llvm::raw_string_ostream os(s);
269
100
  os << "<table class=\"code\" data-fileid=\"" << FID.getHashValue() << "\">\n";
270
100
  RB.InsertTextBefore(0, os.str());
271
100
  RB.InsertTextAfter(FileEnd - FileBeg, "</table>");
272
100
}
273
274
void html::AddHeaderFooterInternalBuiltinCSS(Rewriter &R, FileID FID,
275
96
                                             StringRef title) {
276
96
277
96
  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
278
96
  const char* FileStart = Buf->getBufferStart();
279
96
  const char* FileEnd = Buf->getBufferEnd();
280
96
281
96
  SourceLocation StartLoc = R.getSourceMgr().getLocForStartOfFile(FID);
282
96
  SourceLocation EndLoc = StartLoc.getLocWithOffset(FileEnd-FileStart);
283
96
284
96
  std::string s;
285
96
  llvm::raw_string_ostream os(s);
286
96
  os << "<!doctype html>\n" // Use HTML 5 doctype
287
96
        "<html>\n<head>\n";
288
96
289
96
  if (!title.empty())
290
96
    os << "<title>" << html::EscapeText(title) << "</title>\n";
291
96
292
96
  os << R"<<<(
293
96
<style type="text/css">
294
96
body { color:#000000; background-color:#ffffff }
295
96
body { font-family:Helvetica, sans-serif; font-size:10pt }
296
96
h1 { font-size:14pt }
297
96
.FileName { margin-top: 5px; margin-bottom: 5px; display: inline; }
298
96
.FileNav { margin-left: 5px; margin-right: 5px; display: inline; }
299
96
.FileNav a { text-decoration:none; font-size: larger; }
300
96
.divider { margin-top: 30px; margin-bottom: 30px; height: 15px; }
301
96
.divider { background-color: gray; }
302
96
.code { border-collapse:collapse; width:100%; }
303
96
.code { font-family: "Monospace", monospace; font-size:10pt }
304
96
.code { line-height: 1.2em }
305
96
.comment { color: green; font-style: oblique }
306
96
.keyword { color: blue }
307
96
.string_literal { color: red }
308
96
.directive { color: darkmagenta }
309
96
310
96
/* Macros and variables could have pop-up notes hidden by default.
311
96
  - Macro pop-up:    expansion of the macro
312
96
  - Variable pop-up: value (table) of the variable */
313
96
.macro_popup, .variable_popup { display: none; }
314
96
315
96
/* Pop-up appears on mouse-hover event. */
316
96
.macro:hover .macro_popup, .variable:hover .variable_popup {
317
96
  display: block;
318
96
  padding: 2px;
319
96
  -webkit-border-radius:5px;
320
96
  -webkit-box-shadow:1px 1px 7px #000;
321
96
  border-radius:5px;
322
96
  box-shadow:1px 1px 7px #000;
323
96
  position: absolute;
324
96
  top: -1em;
325
96
  left:10em;
326
96
  z-index: 1
327
96
}
328
96
329
96
.macro_popup {
330
96
  border: 2px solid red;
331
96
  background-color:#FFF0F0;
332
96
  font-weight: normal;
333
96
}
334
96
335
96
.variable_popup {
336
96
  border: 2px solid blue;
337
96
  background-color:#F0F0FF;
338
96
  font-weight: bold;
339
96
  font-family: Helvetica, sans-serif;
340
96
  font-size: 9pt;
341
96
}
342
96
343
96
/* Pop-up notes needs a relative position as a base where they pops up. */
344
96
.macro, .variable {
345
96
  background-color: PaleGoldenRod;
346
96
  position: relative;
347
96
}
348
96
.macro { color: DarkMagenta; }
349
96
350
96
#tooltiphint {
351
96
  position: fixed;
352
96
  width: 50em;
353
96
  margin-left: -25em;
354
96
  left: 50%;
355
96
  padding: 10px;
356
96
  border: 1px solid #b0b0b0;
357
96
  border-radius: 2px;
358
96
  box-shadow: 1px 1px 7px black;
359
96
  background-color: #c0c0c0;
360
96
  z-index: 2;
361
96
}
362
96
363
96
.num { width:2.5em; padding-right:2ex; background-color:#eeeeee }
364
96
.num { text-align:right; font-size:8pt }
365
96
.num { color:#444444 }
366
96
.line { padding-left: 1ex; border-left: 3px solid #ccc }
367
96
.line { white-space: pre }
368
96
.msg { -webkit-box-shadow:1px 1px 7px #000 }
369
96
.msg { box-shadow:1px 1px 7px #000 }
370
96
.msg { -webkit-border-radius:5px }
371
96
.msg { border-radius:5px }
372
96
.msg { font-family:Helvetica, sans-serif; font-size:8pt }
373
96
.msg { float:left }
374
96
.msg { padding:0.25em 1ex 0.25em 1ex }
375
96
.msg { margin-top:10px; margin-bottom:10px }
376
96
.msg { font-weight:bold }
377
96
.msg { max-width:60em; word-wrap: break-word; white-space: pre-wrap }
378
96
.msgT { padding:0x; spacing:0x }
379
96
.msgEvent { background-color:#fff8b4; color:#000000 }
380
96
.msgControl { background-color:#bbbbbb; color:#000000 }
381
96
.msgNote { background-color:#ddeeff; color:#000000 }
382
96
.mrange { background-color:#dfddf3 }
383
96
.mrange { border-bottom:1px solid #6F9DBE }
384
96
.PathIndex { font-weight: bold; padding:0px 5px; margin-right:5px; }
385
96
.PathIndex { -webkit-border-radius:8px }
386
96
.PathIndex { border-radius:8px }
387
96
.PathIndexEvent { background-color:#bfba87 }
388
96
.PathIndexControl { background-color:#8c8c8c }
389
96
.PathIndexPopUp { background-color: #879abc; }
390
96
.PathNav a { text-decoration:none; font-size: larger }
391
96
.CodeInsertionHint { font-weight: bold; background-color: #10dd10 }
392
96
.CodeRemovalHint { background-color:#de1010 }
393
96
.CodeRemovalHint { border-bottom:1px solid #6F9DBE }
394
96
.selected{ background-color:orange !important; }
395
96
396
96
table.simpletable {
397
96
  padding: 5px;
398
96
  font-size:12pt;
399
96
  margin:20px;
400
96
  border-collapse: collapse; border-spacing: 0px;
401
96
}
402
96
td.rowname {
403
96
  text-align: right;
404
96
  vertical-align: top;
405
96
  font-weight: bold;
406
96
  color:#444444;
407
96
  padding-right:2ex;
408
96
}
409
96
410
96
/* Hidden text. */
411
96
input.spoilerhider + label {
412
96
  cursor: pointer;
413
96
  text-decoration: underline;
414
96
  display: block;
415
96
}
416
96
input.spoilerhider {
417
96
 display: none;
418
96
}
419
96
input.spoilerhider ~ .spoiler {
420
96
  overflow: hidden;
421
96
  margin: 10px auto 0;
422
96
  height: 0;
423
96
  opacity: 0;
424
96
}
425
96
input.spoilerhider:checked + label + .spoiler{
426
96
  height: auto;
427
96
  opacity: 1;
428
96
}
429
96
</style>
430
96
</head>
431
96
<body>)<<<";
432
96
433
96
  // Generate header
434
96
  R.InsertTextBefore(StartLoc, os.str());
435
96
  // Generate footer
436
96
437
96
  R.InsertTextAfter(EndLoc, "</body></html>\n");
438
96
}
439
440
/// SyntaxHighlight - Relex the specified FileID and annotate the HTML with
441
/// information about keywords, macro expansions etc.  This uses the macro
442
/// table state from the end of the file, so it won't be perfectly perfect,
443
/// but it will be reasonably close.
444
100
void html::SyntaxHighlight(Rewriter &R, FileID FID, const Preprocessor &PP) {
445
100
  RewriteBuffer &RB = R.getEditBuffer(FID);
446
100
447
100
  const SourceManager &SM = PP.getSourceManager();
448
100
  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
449
100
  Lexer L(FID, FromFile, SM, PP.getLangOpts());
450
100
  const char *BufferStart = L.getBuffer().data();
451
100
452
100
  // Inform the preprocessor that we want to retain comments as tokens, so we
453
100
  // can highlight them.
454
100
  L.SetCommentRetentionState(true);
455
100
456
100
  // Lex all the tokens in raw mode, to avoid entering #includes or expanding
457
100
  // macros.
458
100
  Token Tok;
459
100
  L.LexFromRawLexer(Tok);
460
100
461
92.8k
  while (Tok.isNot(tok::eof)) {
462
92.7k
    // Since we are lexing unexpanded tokens, all tokens are from the main
463
92.7k
    // FileID.
464
92.7k
    unsigned TokOffs = SM.getFileOffset(Tok.getLocation());
465
92.7k
    unsigned TokLen = Tok.getLength();
466
92.7k
    switch (Tok.getKind()) {
467
53.7k
    default: break;
468
0
    case tok::identifier:
469
0
      llvm_unreachable("tok::identifier in raw lexing mode!");
470
33.8k
    case tok::raw_identifier: {
471
33.8k
      // Fill in Result.IdentifierInfo and update the token kind,
472
33.8k
      // looking up the identifier in the identifier table.
473
33.8k
      PP.LookUpIdentifierInfo(Tok);
474
33.8k
475
33.8k
      // If this is a pp-identifier, for a keyword, highlight it as such.
476
33.8k
      if (Tok.isNot(tok::identifier))
477
10.2k
        HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
478
10.2k
                       "<span class='keyword'>", "</span>");
479
33.8k
      break;
480
0
    }
481
2.95k
    case tok::comment:
482
2.95k
      HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
483
2.95k
                     "<span class='comment'>", "</span>");
484
2.95k
      break;
485
0
    case tok::utf8_string_literal:
486
0
      // Chop off the u part of u8 prefix
487
0
      ++TokOffs;
488
0
      --TokLen;
489
0
      // FALL THROUGH to chop the 8
490
0
      LLVM_FALLTHROUGH;
491
0
    case tok::wide_string_literal:
492
0
    case tok::utf16_string_literal:
493
0
    case tok::utf32_string_literal:
494
0
      // Chop off the L, u, U or 8 prefix
495
0
      ++TokOffs;
496
0
      --TokLen;
497
0
      LLVM_FALLTHROUGH;
498
38
    case tok::string_literal:
499
38
      // FIXME: Exclude the optional ud-suffix from the highlighted range.
500
38
      HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
501
38
                     "<span class='string_literal'>", "</span>");
502
38
      break;
503
2.26k
    case tok::hash: {
504
2.26k
      // If this is a preprocessor directive, all tokens to end of line are too.
505
2.26k
      if (!Tok.isAtStartOfLine())
506
0
        break;
507
2.26k
508
2.26k
      // Eat all of the tokens until we get to the next one at the start of
509
2.26k
      // line.
510
2.26k
      unsigned TokEnd = TokOffs+TokLen;
511
2.26k
      L.LexFromRawLexer(Tok);
512
5.78k
      while (!Tok.isAtStartOfLine() && 
Tok.isNot(tok::eof)3.52k
) {
513
3.52k
        TokEnd = SM.getFileOffset(Tok.getLocation())+Tok.getLength();
514
3.52k
        L.LexFromRawLexer(Tok);
515
3.52k
      }
516
2.26k
517
2.26k
      // Find end of line.  This is a hack.
518
2.26k
      HighlightRange(RB, TokOffs, TokEnd, BufferStart,
519
2.26k
                     "<span class='directive'>", "</span>");
520
2.26k
521
2.26k
      // Don't skip the next token.
522
2.26k
      continue;
523
2.26k
    }
524
90.5k
    }
525
90.5k
526
90.5k
    L.LexFromRawLexer(Tok);
527
90.5k
  }
528
100
}
529
530
/// HighlightMacros - This uses the macro table state from the end of the
531
/// file, to re-expand macros and insert (into the HTML) information about the
532
/// macro expansions.  This won't be perfectly perfect, but it will be
533
/// reasonably close.
534
100
void html::HighlightMacros(Rewriter &R, FileID FID, const Preprocessor& PP) {
535
100
  // Re-lex the raw token stream into a token buffer.
536
100
  const SourceManager &SM = PP.getSourceManager();
537
100
  std::vector<Token> TokenStream;
538
100
539
100
  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
540
100
  Lexer L(FID, FromFile, SM, PP.getLangOpts());
541
100
542
100
  // Lex all the tokens in raw mode, to avoid entering #includes or expanding
543
100
  // macros.
544
93.4k
  while (1) {
545
93.4k
    Token Tok;
546
93.4k
    L.LexFromRawLexer(Tok);
547
93.4k
548
93.4k
    // If this is a # at the start of a line, discard it from the token stream.
549
93.4k
    // We don't want the re-preprocess step to see #defines, #includes or other
550
93.4k
    // preprocessor directives.
551
93.4k
    if (Tok.is(tok::hash) && 
Tok.isAtStartOfLine()2.26k
)
552
2.26k
      continue;
553
91.1k
554
91.1k
    // If this is a ## token, change its kind to unknown so that repreprocessing
555
91.1k
    // it will not produce an error.
556
91.1k
    if (Tok.is(tok::hashhash))
557
1
      Tok.setKind(tok::unknown);
558
91.1k
559
91.1k
    // If this raw token is an identifier, the raw lexer won't have looked up
560
91.1k
    // the corresponding identifier info for it.  Do this now so that it will be
561
91.1k
    // macro expanded when we re-preprocess it.
562
91.1k
    if (Tok.is(tok::raw_identifier))
563
37.2k
      PP.LookUpIdentifierInfo(Tok);
564
91.1k
565
91.1k
    TokenStream.push_back(Tok);
566
91.1k
567
91.1k
    if (Tok.is(tok::eof)) 
break100
;
568
91.1k
  }
569
100
570
100
  // Temporarily change the diagnostics object so that we ignore any generated
571
100
  // diagnostics from this pass.
572
100
  DiagnosticsEngine TmpDiags(PP.getDiagnostics().getDiagnosticIDs(),
573
100
                             &PP.getDiagnostics().getDiagnosticOptions(),
574
100
                      new IgnoringDiagConsumer);
575
100
576
100
  // FIXME: This is a huge hack; we reuse the input preprocessor because we want
577
100
  // its state, but we aren't actually changing it (we hope). This should really
578
100
  // construct a copy of the preprocessor.
579
100
  Preprocessor &TmpPP = const_cast<Preprocessor&>(PP);
580
100
  DiagnosticsEngine *OldDiags = &TmpPP.getDiagnostics();
581
100
  TmpPP.setDiagnostics(TmpDiags);
582
100
583
100
  // Inform the preprocessor that we don't want comments.
584
100
  TmpPP.SetCommentRetentionState(false, false);
585
100
586
100
  // We don't want pragmas either. Although we filtered out #pragma, removing
587
100
  // _Pragma and __pragma is much harder.
588
100
  bool PragmasPreviouslyEnabled = TmpPP.getPragmasEnabled();
589
100
  TmpPP.setPragmasEnabled(false);
590
100
591
100
  // Enter the tokens we just lexed.  This will cause them to be macro expanded
592
100
  // but won't enter sub-files (because we removed #'s).
593
100
  TmpPP.EnterTokenStream(TokenStream, false, /*IsReinject=*/false);
594
100
595
100
  TokenConcatenation ConcatInfo(TmpPP);
596
100
597
100
  // Lex all the tokens.
598
100
  Token Tok;
599
100
  TmpPP.Lex(Tok);
600
91.0k
  while (Tok.isNot(tok::eof)) {
601
90.9k
    // Ignore non-macro tokens.
602
90.9k
    if (!Tok.getLocation().isMacroID()) {
603
90.6k
      TmpPP.Lex(Tok);
604
90.6k
      continue;
605
90.6k
    }
606
372
607
372
    // Okay, we have the first token of a macro expansion: highlight the
608
372
    // expansion by inserting a start tag before the macro expansion and
609
372
    // end tag after it.
610
372
    CharSourceRange LLoc = SM.getExpansionRange(Tok.getLocation());
611
372
612
372
    // Ignore tokens whose instantiation location was not the main file.
613
372
    if (SM.getFileID(LLoc.getBegin()) != FID) {
614
0
      TmpPP.Lex(Tok);
615
0
      continue;
616
0
    }
617
372
618
372
    assert(SM.getFileID(LLoc.getEnd()) == FID &&
619
372
           "Start and end of expansion must be in the same ultimate file!");
620
372
621
372
    std::string Expansion = EscapeText(TmpPP.getSpelling(Tok));
622
372
    unsigned LineLen = Expansion.size();
623
372
624
372
    Token PrevPrevTok;
625
372
    Token PrevTok = Tok;
626
372
    // Okay, eat this token, getting the next one.
627
372
    TmpPP.Lex(Tok);
628
372
629
372
    // Skip all the rest of the tokens that are part of this macro
630
372
    // instantiation.  It would be really nice to pop up a window with all the
631
372
    // spelling of the tokens or something.
632
595
    while (!Tok.is(tok::eof) &&
633
595
           
SM.getExpansionLoc(Tok.getLocation()) == LLoc.getBegin()594
) {
634
223
      // Insert a newline if the macro expansion is getting large.
635
223
      if (LineLen > 60) {
636
0
        Expansion += "<br>";
637
0
        LineLen = 0;
638
0
      }
639
223
640
223
      LineLen -= Expansion.size();
641
223
642
223
      // If the tokens were already space separated, or if they must be to avoid
643
223
      // them being implicitly pasted, add a space between them.
644
223
      if (Tok.hasLeadingSpace() ||
645
223
          
ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok)192
)
646
31
        Expansion += ' ';
647
223
648
223
      // Escape any special characters in the token text.
649
223
      Expansion += EscapeText(TmpPP.getSpelling(Tok));
650
223
      LineLen += Expansion.size();
651
223
652
223
      PrevPrevTok = PrevTok;
653
223
      PrevTok = Tok;
654
223
      TmpPP.Lex(Tok);
655
223
    }
656
372
657
372
    // Insert the 'macro_popup' as the end tag, so that multi-line macros all
658
372
    // get highlighted.
659
372
    Expansion = "<span class='macro_popup'>" + Expansion + "</span></span>";
660
372
661
372
    HighlightRange(R, LLoc.getBegin(), LLoc.getEnd(), "<span class='macro'>",
662
372
                   Expansion.c_str(), LLoc.isTokenRange());
663
372
  }
664
100
665
100
  // Restore the preprocessor's old state.
666
100
  TmpPP.setDiagnostics(*OldDiags);
667
100
  TmpPP.setPragmasEnabled(PragmasPreviouslyEnabled);
668
100
}