?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  
  3.   SjASMPlus Z80 Cross Compiler - modified - error/warning module
  4.  
  5.   Copyright (c) 2006 Sjoerd Mastijn (original SW)
  6.   Copyright (c) 2020 Peter Ped Helcmanovsky (error/warning module)
  7.  
  8.   This software is provided 'as-is', without any express or implied warranty.
  9.   In no event will the authors be held liable for any damages arising from the
  10.   use of this software.
  11.  
  12.   Permission is granted to anyone to use this software for any purpose,
  13.   including commercial applications, and to alter it and redistribute it freely,
  14.   subject to the following restrictions:
  15.  
  16.   1. The origin of this software must not be misrepresented; you must not claim
  17.          that you wrote the original software. If you use this software in a product,
  18.          an acknowledgment in the product documentation would be appreciated but is
  19.          not required.
  20.  
  21.   2. Altered source versions must be plainly marked as such, and must not be
  22.          misrepresented as being the original software.
  23.  
  24.   3. This notice may not be removed or altered from any source distribution.
  25.  
  26. */
  27.  
  28. // io_err.cpp
  29.  
  30. #include "sjdefs.h"
  31. #include <vector>
  32. #include <unordered_map>
  33. #include <algorithm>
  34.  
  35. TextFilePos skipEmitMessagePos;
  36. const char* extraErrorWarningPrefix = nullptr;
  37.  
  38. static bool IsSkipErrors = false;
  39. static char ErrorLine[LINEMAX2], ErrorLine2[LINEMAX2];
  40. static aint PreviousErrorLine = -1L;
  41.  
  42. static const char* nullptr_message_txt = "<nullptr>";
  43.  
  44. static void initErrorLine() {           // adds filename + line of definition if possible
  45.         *ErrorLine = 0;
  46.         *ErrorLine2 = 0;
  47.         // when OpenFile is reporting error, the filename is still nullptr, but pass==1 already
  48.         if (pass < 1 || LASTPASS < pass || sourcePosStack.empty()) return;
  49.         SPRINTF2(ErrorLine, LINEMAX2, "%s(%d): ", sourcePosStack.back().filename, sourcePosStack.back().line);
  50.         // if the error filename:line is not identical with current source line, add ErrorLine2 about emit
  51.         if (std::max(1, aint(IncludeLevel + 1)) < aint(sourcePosStack.size())) {
  52.                 auto previous = sourcePosStack.end() - 2;
  53.                 if (*previous == skipEmitMessagePos && previous != sourcePosStack.begin()) --previous;
  54.                 if (*previous != skipEmitMessagePos && *previous != sourcePosStack.back()) {
  55.                         SPRINTF2(ErrorLine2, LINEMAX2, "%s(%d): ^ emitted from here\n", previous->filename, previous->line);
  56.                 }
  57.         }
  58. }
  59.  
  60. static void trimAndAddEol(char* lineBuffer) {
  61.         if (!lineBuffer[0]) return;             // ignore empty line buffer
  62.         char* lastChar = lineBuffer + strlen(lineBuffer) - 1;
  63.         while (lineBuffer < lastChar && (' ' == *lastChar || '\t' == *lastChar)) --lastChar;    // trim ending whitespace
  64.         if ('\n' != *lastChar) lastChar[1] = '\n', lastChar[2] = 0;     // add EOL character if not present
  65. }
  66.  
  67. static void outputErrorLine(const EOutputVerbosity errorLevel, int keywordPos, int keywordSz) {
  68.         assert(0 <= keywordPos && 1 <= keywordSz && keywordPos + keywordSz <= int(strlen(ErrorLine)));  // keyword is mandatory
  69.         auto lstFile = GetListingFile();
  70.         if (!lstFile && errorLevel < Options::OutputVerbosity) return;  // no output required
  71.         // trim end of error/warning line and add EOL char if needed
  72.         trimAndAddEol(ErrorLine);
  73.         trimAndAddEol(ErrorLine2);
  74.         // always print the message into listing file (the OutputVerbosity does not apply to listing)
  75.         if (lstFile) {
  76.                 fputs(ErrorLine, lstFile);
  77.                 if (*ErrorLine2) fputs(ErrorLine2, lstFile);
  78.         }
  79.         // print the error into stderr if OutputVerbosity allows this type of message
  80.         if (Options::OutputVerbosity <= errorLevel) {
  81.                 if (keywordPos) cerr.write(ErrorLine, keywordPos);      // output filename and line position
  82.                 // colorize the keyword in message
  83.                 if (OV_ERROR == errorLevel) _CERR Options::tcols->error _END;
  84.                 if (OV_WARNING == errorLevel) _CERR Options::tcols->warning _END;
  85.                 cerr.write(ErrorLine + keywordPos, keywordSz);
  86.                 // switch color off for rest of message
  87.                 _CERR Options::tcols->end _END;
  88.                 _CERR ErrorLine + keywordPos + keywordSz _END;
  89.                 if (*ErrorLine2) _CERR ErrorLine2 _END;
  90.         }
  91. }
  92.  
  93. void Error(const char* message, const char* badValueMessage, EStatus type) {
  94.         // check if it is correct pass by the type of error
  95.         if (type == EARLY && LASTPASS <= pass) return;
  96.         if ((type == SUPPRESS || type == IF_FIRST || type == PASS3) && pass < LASTPASS) return;
  97.         if (PASS03 == type && 0 < pass && pass < LASTPASS) return;
  98.         // check if this one should be skipped due to type constraints and current-error-state
  99.         if (FATAL != type && PreviousErrorLine == CompiledCurrentLine) {
  100.                 // non-fatal error, on the same line as previous, maybe skip?
  101.                 if (IsSkipErrors || IF_FIRST == type) return;
  102.         }
  103.         // update current-error-state (reset "skip" on new parsed-line, set "skip" by SUPPRESS type)
  104.         IsSkipErrors = (IsSkipErrors && (PreviousErrorLine == CompiledCurrentLine)) || (SUPPRESS == type);
  105.         PreviousErrorLine = CompiledCurrentLine;
  106.         ++ErrorCount;                                                   // number of non-skipped (!) errors
  107.  
  108.         DefineTable.Replace("__ERRORS__", ErrorCount);
  109.  
  110.         initErrorLine();
  111.         const int errorTxtPos = strlen(ErrorLine);
  112.         STRCAT(ErrorLine, LINEMAX2-1, "error: ");
  113.         if (extraErrorWarningPrefix) STRCAT(ErrorLine, LINEMAX2-1, extraErrorWarningPrefix);
  114.         STRCAT(ErrorLine, LINEMAX2-1, message ? message : nullptr_message_txt);
  115.         if (badValueMessage) {
  116.                 STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage);
  117.         }
  118.         outputErrorLine(OV_ERROR, errorTxtPos, 5);
  119.         // terminate whole assembler in case of fatal error
  120.         if (type == FATAL) {
  121.                 ExitASM(1);
  122.         }
  123. }
  124.  
  125. void ErrorInt(const char* message, aint badValue, EStatus type) {
  126.         char numBuf[24];
  127.         SPRINTF1(numBuf, 24, "%d", badValue);
  128.         Error(message, numBuf, type);
  129. }
  130.  
  131. void ErrorOOM() {               // out of memory
  132.         Error("Not enough memory!", nullptr, FATAL);
  133. }
  134.  
  135. static void WarningImpl(const char* id, const char* message, const char* badValueMessage, EWStatus type) {
  136.         // turn the warning into error if "Warnings as errors" is switched on
  137.         if (Options::syx.WarningsAsErrors) switch (type) {
  138.                 case W_EARLY:   Error(message, badValueMessage, EARLY); return;
  139.                 case W_PASS3:   Error(message, badValueMessage, PASS3); return;
  140.                 case W_PASS03:  Error(message, badValueMessage, PASS03); return;
  141.                 case W_ALL:             Error(message, badValueMessage, ALL); return;
  142.         }
  143.  
  144.         ++WarningCount;
  145.         DefineTable.Replace("__WARNINGS__", WarningCount);
  146.  
  147.         initErrorLine();
  148.         const int warningTxtPos = strlen(ErrorLine);
  149.         if (id) {
  150.                 STRCAT(ErrorLine, LINEMAX2-1, "warning[");
  151.                 STRCAT(ErrorLine, LINEMAX2-1, id);
  152.                 STRCAT(ErrorLine, LINEMAX2-1, "]: ");
  153.         } else {
  154.                 STRCAT(ErrorLine, LINEMAX2-1, "warning: ");
  155.         }
  156.         if (extraErrorWarningPrefix) STRCAT(ErrorLine, LINEMAX2-1, extraErrorWarningPrefix);
  157.         STRCAT(ErrorLine, LINEMAX2-1, message ? message : nullptr_message_txt);
  158.         if (badValueMessage) {
  159.                 STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage);
  160.         }
  161.         outputErrorLine(OV_WARNING, warningTxtPos, 7);
  162. }
  163.  
  164. struct WarningEntry {
  165.         bool enabled;
  166.         const char* txt;
  167.         const char* help;
  168. };
  169.  
  170. typedef std::unordered_map<const char*, WarningEntry> messages_map;
  171.  
  172. const char* W_NO_RAMTOP = "noramtop";
  173. const char* W_DEV_RAMTOP = "devramtop";
  174. const char* W_DISPLACED_ORG = "displacedorg";
  175. const char* W_ORG_PAGE = "orgpage";
  176. const char* W_FWD_REF = "fwdref";
  177. const char* W_LUA_MC_PASS = "luamc";
  178. const char* W_NEX_STACK = "nexstack";
  179. const char* W_SNA_48 = "sna48";
  180. const char* W_SNA_128 = "sna128";
  181. const char* W_TRD_EXT_INVALID = "trdext";
  182. const char* W_TRD_EXT_3 = "trdext3";
  183. const char* W_TRD_EXT_B = "trdextb";
  184. const char* W_TRD_DUPLICATE = "trddup";
  185. const char* W_RELOCATABLE_ALIGN = "relalign";
  186. const char* W_READ_LOW_MEM = "rdlow";
  187. const char* W_REL_DIVERTS = "reldiverts";
  188. const char* W_REL_UNSTABLE = "relunstable";
  189. const char* W_DISP_MEM_PAGE = "dispmempage";
  190. const char* W_BP_FILE = "bpfile";
  191. const char* W_OUT0 = "out0";
  192. const char* W_BACKSLASH = "backslash";
  193. const char* W_OPKEYWORD = "opkeyword";
  194. const char* W_BE_HOST = "behost";
  195. const char* W_FAKE = "fake";
  196. const char* W_ENABLE_ALL = "all";
  197. const char* W_ZERO_DECIMAL = "decimalz";
  198. const char* W_NON_ZERO_DECIMAL = "decimaln";
  199.  
  200. static messages_map w_texts = {
  201.         { W_NO_RAMTOP,
  202.                 { true,
  203.                         "current device doesn't init memory in any way (RAMTOP is ignored)",
  204.                         "Warn when device ignores <ramtop> argument."
  205.                 }
  206.         },
  207.         { W_DEV_RAMTOP,
  208.                 { true,
  209.                         "[DEVICE] this device was already opened with different RAMTOP value",
  210.                         "Warn when different <ramtop> is used for same device."
  211.                 }
  212.         },
  213.         { W_DISPLACED_ORG,
  214.                 { true,
  215.                         "ORG-address set inside displaced block, the physical address is not modified, only displacement address",
  216.                         "Warn about ORG-address used inside DISP block."
  217.                 }
  218.         },
  219.         { W_ORG_PAGE,
  220.                 { true,
  221.                         "[ORG] page argument affects current slot while address is outside",
  222.                         "Warn about ORG address vs page argument mismatch."
  223.                 }
  224.         },
  225.         { W_FWD_REF,
  226.                 { true,
  227.                         "forward reference of symbol",
  228.                         "Warn about using undefined symbol in risky way."
  229.                 }
  230.         },
  231.         { W_LUA_MC_PASS,
  232.                 { true,
  233.                         "When lua script emits machine code bytes, use \"ALLPASS\" modifier",
  234.                         "Warn when lua script is not ALLPASS, but emits bytes."
  235.                 }
  236.         },
  237.         { W_NEX_STACK,
  238.                 { true,
  239.                         "[SAVENEX] non-zero data are in stackAddress area, may get overwritten by NEXLOAD",
  240.                         "Warn when NEX stack points into non-empty memory."
  241.                 }
  242.         },
  243.         { W_SNA_48,
  244.                 { true,
  245.                         "[SAVESNA] RAM <0x4000-0x4001> will be overwritten due to 48k snapshot imperfect format.",
  246.                         "Warn when 48k SNA does use screen for stack."
  247.                 }
  248.         },
  249.         { W_SNA_128,
  250.                 { true,
  251.                         "only 128kb will be written to snapshot",
  252.                         "Warn when saving snapshot from 256+ki device."
  253.                 }
  254.         },
  255.         { W_TRD_EXT_INVALID,
  256.                 { true,
  257.                         "invalid file extension, TRDOS official extensions are B, C, D and #.",
  258.                         "Warn when TRD file uses unofficial/invalid extension."
  259.                 }
  260.         },
  261.         { W_TRD_EXT_3,
  262.                 { true,
  263.                         "3-letter extension of TRDOS file (unofficial extension)",
  264.                         "Warn when TRD file does use 3-letter extension."
  265.                 }
  266.         },
  267.         { W_TRD_EXT_B,
  268.                 { true,
  269.                         "the \"B\" extension is always single letter",
  270.                         "Warn when long extension starts with letter B (can not)."
  271.                 }
  272.         },
  273.         { W_TRD_DUPLICATE,
  274.                 { true,
  275.                         "TRD file already exists, creating one more!",
  276.                         "Warn when second file with same name is added to disk."
  277.                 }
  278.         },
  279.         { W_RELOCATABLE_ALIGN,
  280.                 { true,
  281.                         "[ALIGN] inside relocation block: may become misaligned when relocated",
  282.                         "Warn when align is used inside relocatable code."
  283.                 }
  284.         },
  285.         { W_READ_LOW_MEM,
  286.                 { false,
  287.                         "Reading memory at low address",
  288.                         "Warn when reading memory from addresses 0..255."
  289.                 }
  290.         },
  291.         { W_REL_DIVERTS,
  292.                 { true,
  293.                         "Expression can't be relocated by simple \"+offset\" mechanics, value diverts differently.",
  294.                         "Warn when relocated expression differs non-trivially."
  295.                 }
  296.         },
  297.         { W_REL_UNSTABLE,
  298.                 { true,
  299.                         "Relocation makes one of the expressions unstable, resulting machine code is not relocatable",
  300.                         "Warn when expression result can't be relocated."
  301.                 }
  302.         },
  303.         { W_DISP_MEM_PAGE,
  304.                 { true,
  305.                         "DISP memory page differs from current mapping",
  306.                         "Warn when DISP page differs from current mapping."
  307.                 }
  308.         },
  309.         { W_BP_FILE,
  310.                 { true,
  311.                         "breakpoints file was not specified",
  312.                         "Warn when SETBREAKPOINT is used without breakpoint file."
  313.                 }
  314.         },
  315.         { W_OUT0,
  316.                 { true,
  317.                         "'out (c),0' is unstable, on CMOS based chips it does `out (c),255`",
  318.                         "Warn when instruction `out (c),0` is used."
  319.                 }
  320.         },
  321.         { W_BACKSLASH,
  322.                 { true,
  323.                         "File name contains \\, use / instead (\\ fails on most of the supported platforms)",
  324.                         "Warn when file name contains backslash."
  325.                 }
  326.         },
  327.         { W_OPKEYWORD,
  328.                 { true,
  329.                         "Label collides with one of the operator keywords, try capitalizing it or other name",
  330.                         "Warn when symbol name collides with operator keyword."
  331.                 }
  332.         },
  333.         { W_BE_HOST,
  334.                 { true,
  335.                         "Big-endian host detected: support is experimental, please report any issues",
  336.                         "Warn when big-endian host runs sjasmplus (experimental)."
  337.                 }
  338.         },
  339.         { W_FAKE,
  340.                 { true, // fake-warnings are enabled/disabled through --syntax, this value here is always true
  341.                                 // the main reason is that fake warning enabled can be reset/push/pop by OPT
  342.                         "Fake instruction",
  343.                         "Warn when fake instruction is used in the source."
  344.                 }
  345.         },
  346.         { W_ZERO_DECIMAL,
  347.                 { false,
  348.                         "decimal part is ignored",
  349.                         "Warn when numeric constant has decimal part (equal to zero)"
  350.                 }
  351.         },
  352.         { W_NON_ZERO_DECIMAL,
  353.                 { true,
  354.                         "decimal part is ignored",
  355.                         "Warn when numeric constant has non zero decimal part"
  356.                 }
  357.         },
  358.         { W_ENABLE_ALL,
  359.                 { false,
  360.                         "",             // not emitted by code, just command-line option
  361.                         "Enable/disable all id-warnings"
  362.                 }
  363.         },
  364. };
  365.  
  366. static messages_map::iterator findWarningByIdText(const char* id) {
  367.         // like w_texts.find(id) but compares id content (string), not pointer
  368.         return std::find_if(w_texts.begin(), w_texts.end(), [id](const auto& v){ return !strcmp(id, v.first); } );
  369. }
  370.  
  371. static bool & warning_state(messages_map::value_type & v) {
  372.         // W_FAKE (ID "fake") stores enabled/disabled state in Options::syx to handle reset/push/pop of the state
  373.         if (W_FAKE == v.first) return Options::syx.FakeWarning;
  374.         // other warnings have global state stored in w_texts map
  375.         return v.second.enabled;
  376. }
  377.  
  378. bool suppressedById(const char* id) {
  379.         assert(id);
  380.         if (nullptr == eolComment) return false;
  381.         const size_t idLength = strlen(id);
  382.         assert(0 < idLength);
  383.         const char* commentToCheck = eolComment;
  384.         while (const char* idPos = strstr(commentToCheck, id)) {
  385.                 if (!strcmp(id, W_FAKE)) return true;                           // "fake" only is enough to suppress those
  386.                 commentToCheck = idPos + idLength;
  387.                 if ('-' == commentToCheck[0] && 'o' == commentToCheck[1] && 'k' == commentToCheck[2]) {
  388.                         return true;
  389.                 }
  390.         }
  391.         return false;
  392. }
  393.  
  394. static bool isInactiveTypeInCurrentPass(EWStatus type) {
  395.         switch (type) {
  396.                 case W_EARLY:   // "early" is inactive during pass3+
  397.                         return LASTPASS <= pass;
  398.                 case W_PASS3:   // "pass3" is inactive during 0..2 pass
  399.                         return pass < LASTPASS;
  400.                 case W_PASS03:  // "pass03" is inactive during 1..2 pass
  401.                         return 0 < pass && pass < LASTPASS;
  402.                 default:                // never inactive for other types (W_ALL)
  403.                         return false;
  404.         }
  405. }
  406.  
  407. void Warning(const char* message, const char* badValueMessage, EWStatus type) {
  408.         if (isInactiveTypeInCurrentPass(type)) return;
  409.         WarningImpl(nullptr, message, badValueMessage, type);
  410. }
  411.  
  412. void WarningById(const char* id, const char* badValueMessage, EWStatus type) {
  413.         if (isInactiveTypeInCurrentPass(type)) return;
  414.  
  415.         // id-warnings could be suppressed by "id-ok" anywhere in eol comment
  416.         if (suppressedById(id)) return;
  417.  
  418.         const messages_map::const_iterator idMessage = w_texts.find(id);        // searching by id POINTER!
  419.         assert(idMessage != w_texts.end());
  420.  
  421.         if (!idMessage->second.enabled) return;
  422.         WarningImpl(id, idMessage->second.txt, badValueMessage, type);
  423. }
  424.  
  425. void WarningById(const char* id, int badValue, EWStatus type) {
  426.         char buf[32];
  427.         SPRINTF1(buf, 32, "%d", badValue);
  428.         WarningById(id, buf, type);
  429. }
  430.  
  431. void CliWoption(const char* option) {
  432.         if (!option[0]) {
  433.                 // from command line 0 == pass, from source by OPT the pass is above zero
  434.                 Error("no argument after -W", (0 == pass) ? nullptr : bp, PASS03);
  435.                 return;
  436.         }
  437.         // check for specific id, with possible "no-" prefix ("-Wabs" vs "-Wno-abs")
  438.         const bool enable = strncmp("no-", option, 3);
  439.         const char* id = enable ? option : option + 3;
  440.         // handle ID "all"
  441.         if (!strcmp(id, W_ENABLE_ALL)) {
  442.                 for (auto & warning_entry : w_texts) warning_state(warning_entry) = enable;
  443.                 return;
  444.         }
  445.         auto warning_it = findWarningByIdText(id);
  446.         if (w_texts.end() == warning_it) {
  447.                 Warning("unknown warning id in -W option", id, W_PASS03);
  448.                 return;
  449.         }
  450.         warning_state(*warning_it) = enable;
  451. }
  452.  
  453. static const char* spaceFiller = "               ";
  454. static const char* txt_on       = "on";
  455. static const char* txt_off      = "off";
  456. static const char* txt_none     = "      ";
  457. static constexpr const int STATE_TXT_BUFFER_SIZE = 64;
  458.  
  459. static void initWarningStateTxt(char* buffer, const char* id) {
  460.         if (W_ENABLE_ALL == id) {
  461.                 STRCPY(buffer, STATE_TXT_BUFFER_SIZE, txt_none);
  462.                 return;
  463.         }
  464.         const bool state = warning_state(*w_texts.find(id));
  465.         buffer[0] = '[';
  466.         STRCPY(buffer + 1, STATE_TXT_BUFFER_SIZE-1, state ? Options::tcols->display : Options::tcols->warning);
  467.         STRCAT(buffer, STATE_TXT_BUFFER_SIZE, state ? txt_on : txt_off);
  468.         STRCAT(buffer, STATE_TXT_BUFFER_SIZE, Options::tcols->end);
  469.         STRCAT(buffer, STATE_TXT_BUFFER_SIZE, "] ");
  470.         if (state) STRCAT(buffer, STATE_TXT_BUFFER_SIZE, " ");
  471. }
  472.  
  473. void PrintHelpWarnings() {
  474.         char state_txt[STATE_TXT_BUFFER_SIZE+1];
  475.         _COUT "The following options control compiler warning messages:" _ENDL;
  476.         std::vector<const char*> ids;
  477.         ids.reserve(w_texts.size());
  478.         for (const auto& w_text : w_texts) ids.push_back(w_text.first);
  479.         std::sort(ids.begin(), ids.end(), [](const char* a, const char* b) -> bool { return (strcmp(a,b) < 0); } );
  480.         for (const auto& id : ids) {
  481.                 assert(strlen(id) < strlen(spaceFiller));
  482.                 initWarningStateTxt(state_txt, id);
  483.                 _COUT " -W" _CMDL Options::tcols->bold _CMDL Options::tcols->warning _CMDL id _CMDL Options::tcols->end _CMDL spaceFiller+strlen(id) _CMDL state_txt _CMDL w_texts[id].help _ENDL;
  484.         }
  485.         _COUT "Use -W" _CMDL Options::tcols->bold _CMDL Options::tcols->warning _CMDL "no-" _CMDL Options::tcols->end;
  486.         _COUT " prefix to disable specific warning, example: " _CMDL Options::tcols->display _CMDL "-Wno-out0" _CMDL Options::tcols->end _ENDL;
  487.         _COUT "Use -ok suffix in comment to suppress it per line, example: ";
  488.         _COUT Options::tcols->display _CMDL "out (c),0 ; out0-ok" _CMDL Options::tcols->end _ENDL;
  489. }
  490.  
  491. //eof io_err.cpp
  492.