From 65c7618c2a8834616b009195f10c6cd762f43b8a Mon Sep 17 00:00:00 2001 From: Mincho Paskalev Date: Wed, 7 Nov 2018 10:31:59 +0200 Subject: Добавяне на второ домашно (#30) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add 1st hw * --amend * moving readme for 1st hw to designated folder * renamed TokenType enum to TokenClass * fixed character constant lexing. added sampe output file * add new line at end-of-file. added gitignore * a bit of refactoring * adding cyclomatic complexity * refactored * adding cyclomatic complexity * refactored --- homework/81568/c2html/html_utils.cpp | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 homework/81568/c2html/html_utils.cpp (limited to 'homework/81568/c2html/html_utils.cpp') diff --git a/homework/81568/c2html/html_utils.cpp b/homework/81568/c2html/html_utils.cpp new file mode 100644 index 0000000..6ca91c6 --- /dev/null +++ b/homework/81568/c2html/html_utils.cpp @@ -0,0 +1,87 @@ +#include "html_utils.h" +#include "lexconst.h" + +namespace HTMLUtils { + +std::string escapeHTML(const std::string &lexeme) { + std::string result; + for (auto c : lexeme) { + switch(c) { + case '<': + result.append("<"); + break; + case '>': + result.append(">"); + break; + case '&': + result.append("&"); + break; + default: + result.push_back(c); + break; + } + } + return result; +} + +bool writeToOutput(FILE *out, Token token) { + if (token.type == TokenClass::Eof) { + printf("End of file!\n"); + fputc('\n', out); + return false; + } + + if (token.type == TokenClass::Skip) { + if (fputs(token.lexeme.c_str(), out) == EOF) { + printf("Error while writing to output"); + return false; + } + return true; + } + + printf("Token of type %s at line %d: ", LexCer::tokenToClass.at(token.type).c_str(), token.line); + if (token.type == TokenClass::Number) + printf("%f\n", token.number); + else + printf("%s\n", token.lexeme.c_str()); + + auto lexeme = escapeHTML(token.lexeme); + + std::string output; + output.append(LexCer::spanBegin).append(LexCer::tokenToClass.at(token.type)).append("\">").append(lexeme).append(LexCer::spanEnd); + + if (fputs(output.c_str(), out) == EOF) { + printf("Error while writing to output"); + return false; + } + return true; +} + +std::string getOutputFileName(const std::string &name) { + auto pos = name.find_last_of('.'); + if (pos == std::string::npos) { + return name + ".html"; + } + + return name.substr(0, pos) + ".html"; +} + +void lexCit(FILE *in, FILE *out) { + Tokenizer hl {in, out}; + + std::string lexeme; + double number; + TokenClass type; + Token token; + do { + token = hl.nextToken(&lexeme, &number); + type = token.type; + + if (!writeToOutput(out, token)) + break; + lexeme = ""; + number = 0.0; + } while(type != TokenClass::Eof || type != TokenClass::Invalid); +} + +} /* Namespace HTMLUtils */ -- cgit v1.3.1-23-gd82d