Website Summary Files Commits Branches @commit @diff @stats
path: root / homework / 81270 / js2html / Highlighter.cpp
blob: cd56496a7e18ac684fe54804ec5433e77e72bc06 (plain) (blame)
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
//
// Created by bmestanov on 25.10.18.
//

#include "Highlighter.h"
#include <fstream>
#include <sstream>
#include <iostream>

Highlighter::Highlighter(const char *outputPath, const char *stylePath) :
        outputPath(outputPath), stylePath(stylePath) {}

void Highlighter::highlight(const IPLVector<Token> &tokens) {
    std::stringstream ss;

    ss << "<!doctype html>\n";
    ss << "<html>\n";
    ss << " <head>\n";
    ss << "     <title>hello.js</title>\n";
    ss << "     <link rel=\"stylesheet\" href=\"" << stylePath << "\">\n";
    ss << " </head>\n";
    ss << " <body>\n";
    ss << "     <pre class=\"code\">\n";

    for (auto &token : tokens) {
        IPLString cssClass = getClass(token);
        if (cssClass.empty()) {
            // Print with no formatting
            ss << token.lexeme;
        } else {
            ss << "<span class=\"" << cssClass << "\">" << token.lexeme << "</span>";
        }
    }

    ss << " </body>\n";
    ss << "</html>\n";

    std::ofstream fs(outputPath);
    if (fs) {
        fs << ss.rdbuf();
    } else {
        std::cout << ss.rdbuf();
    }
}

IPLString Highlighter::getClass(const Token &token) {
    switch (token.type) {
        case Whitespace:
        case NewLine:
        case Raw:
            return "";
        case Comment:
            return "comment";
        case Keyword:
            return "keyword";
        case NumericLiteral:
            return "numeric";
        case StringLiteral:
            return "string";
        case TemplateLiteral:
            return "template";
        case Regex:
            return "regex";
        case Identifier:
            return "identifier";
        case BooleanLiteral:
            return "boolean";
        case Global:
            return "global";
    }
}