//return char except comments static int getChar(SrcFile *sf) { int c = getChar_(sf); if(c == '\\'){ int nc = getChar_(sf); if(nc == '"'){ //escaped double-quotation sf->inStrLiteral = !sf->inStrLiteral; } ungetChar_(nc, sf); }else if(sf->inStrLiteral){ if(c == '"'){ sf->inStrLiteral = 0; } }else{ if(c == '/'){ int nc = getChar_(sf); if(nc == '*'){ // block comment sf->numCommentedLFs += skipBlockComment(sf); c = ' '; }else if(nc == '/'){ // single-line comment skipSingleLineComment(sf); c = '\n'; }else{ ungetChar_(nc, sf); } }else if(c == '"'){ sf->inStrLiteral = 1; } } if(c == '\n'){ while(sf->numCommentedLFs > 0){ ungetChar_('\n', sf); sf->numCommentedLFs--; } } return c; }
char * removeComments(char* source) { /*char* rez = stradd("as\0", 'b');*/ /*printf("[%s]", rez);*/ /*return 1;*/ const int DEBUG = 0; const char FIRST_COMMENT_SYMBOL = '/'; const char SINGLELINE = '/'; const char MULTILINE = '*'; const char IS_NOT_COMMENT = -1; char* result = "\0"; int matchedPreviously = 0, i = 0; if (DEBUG) { printf("ORIGINAL:[%s]\n", source); } int sourceLen = strlen(source); for(i = 0; i < sourceLen; i++) { // printf("\n[%s]\n", source); char curChar = source[i]; char typeOfComment = IS_NOT_COMMENT; if (matchedPreviously) { matchedPreviously = 0; if (curChar == MULTILINE) { typeOfComment = MULTILINE; }else if (curChar == SINGLELINE) { typeOfComment = SINGLELINE; } if (typeOfComment == IS_NOT_COMMENT) { //if comment was not matched add first comment symbol(/) to string result = stradd(result, FIRST_COMMENT_SYMBOL); }else { if (typeOfComment == SINGLELINE) { i = skipSingleLineComment(i+1, sourceLen, source); }else if (typeOfComment == MULTILINE) { int rez = skipMultilineComment(i+1, sourceLen, source); //if end of comment was not recognized if (rez == -1) { //return first two charackter that were skipped result = stradd(result, FIRST_COMMENT_SYMBOL); result = stradd(result, MULTILINE); }else { i = rez; } } } }else { int isFirstCommentSymbol = curChar == FIRST_COMMENT_SYMBOL; if (!isFirstCommentSymbol) { result = stradd(result, curChar); } matchedPreviously = isFirstCommentSymbol; } if (DEBUG == 2) { printf("RESULT:[%s]\n", result); } } if (DEBUG) { printf("RESULT:[%s]", result); } return result; }