New paste Repaste Download
**Compiler final lab test preparation**
Code 1:
/*
Eikhane input nah neye kisu expression er output dekhate bola hoyeche je eigulo valid naki invalid. Tai amra oigulo ekhta vector er moddhe rekhe dibo.
*/
#include<bits/stdc++.h>
using namespace std;
bool isValidExpression(const string& expr) {
    int balance = 0;
    bool expectOperand = true;
    for (size_t i = 0; i < expr.size(); i++) {
        char c = expr[i];
        if (isspace(c)) {
            continue;
        }
        else if (isdigit(c)) {
            while (i < expr.size() && isdigit(expr[i])){
                i++;
            }
            if((expr[i]=='+' && expr[i+1]=='+') || (expr[i]=='-' && expr[i+1]=='-')){
                i+=2;
            }
            i--;
            expectOperand = false;
        }
        else if (c == '(') {
            balance++;
            expectOperand = true;
        }
        else if (c == ')') {
            balance--;
            if (balance < 0) {
                return false;
            }
            expectOperand = false;
        }
        else if (c == '{') {
            balance++;
            expectOperand = true;
        }
        else if (c == '}') {
            balance--;
            if (balance < 0) {
                return false;
            }
            expectOperand = false;
        }
        else if (c == '[') {
            balance++;
            expectOperand = true;
        }
        else if (c == ']') {
            balance--;
            if (balance < 0) {
                return false;
            }
            expectOperand = false;
        }
        else if (c == '+' || c == '-' || c == '*' || c == '/' || c=='%') {
            if (expectOperand) {
                return false;
            }
            expectOperand = true;
        }
        else {
            return false;
        }
    }
    return (balance == 0 && !expectOperand);
}
int main() {
    vector<string> v = {
        "(4+5)*{6-(8-4)}",
        "##[4-{6-(5*8)}]",
        "3++",
        "5+*6",
        "6%2"
    };
    for(int i=0;i<v.size();i++){
        string expr=v[i];
        if(expr[0]=='#' && expr[1]=='#'){
            cout<<"Line "<<i+1<<": Comment detected, skip validation"<<endl;
            continue;
        }
        if((expr[0]=='+' && expr[1]=='+') || (expr[0]=='-' && expr[1]=='-')){
               cout<<"Line "<<i+1<<": Valid expression"<<endl;
               continue;
        }
        if(isValidExpression(expr)){
            cout<<"Line "<<i+1<<": Valid expression"<<endl;
        }
        else{
            cout<<"Line "<<i+1<<": Invalid expression"<<endl;
        }
    }
}
Code 2: (Calculator with bracket)
/*
    Amra normally jei expression gulo lekhi seigulo calculate kore dibe.
    Input sample : [{(4+7+8-8)}]
          Output : 11
    Input sample : [{(4+7+8-8)}
          Output : Missing Third Bracket
    Input sample : [{(4+7+8-8)]
          Output : Missing second Bracket
*/
#include <bits/stdc++.h>
using namespace std;
string input;
int pos = 0;
void skipWhitespace() {
    while (pos < (int)input.size() && isspace(input[pos])) pos++;
}
char peek() {
    skipWhitespace();
    if (pos < (int)input.size()) return input[pos];
    return '\0';
}
char get() {
    skipWhitespace();
    if (pos < (int)input.size()) return input[pos++];
    return '\0';
}
double parseTerm();
double parseExpression();
double parseNumber() {
    skipWhitespace();
    char op=peek();
    if (op == '[') {
        get();
        double val = parseExpression();
        if (get() != ']') {
            cout<<"Missing third bracket "<<endl;
            exit(1);
        }
        return val;
    }
    if (op == '{') {
        get();
        double val = parseExpression();
        if (get() != '}') {
            cout<<"Missing second bracket "<<endl;
            exit(1);
        }
        return val;
    }
    if (op == '(') {
        get();
        double val = parseExpression();
        if (get() != ')') {
            cout<<"Missing first bracket "<<endl;
            exit(1);
        }
        return val;
    }
    string num;
    while (isdigit(peek()) || peek() == '.') {
        num += get();
    }
    return stod(num);
}
double parseTerm() {
    double val = parseNumber();
    while (true) {
        char op = peek();
        if (op == '*') {
            get();
            val *= parseNumber();
        } else if (op == '/') {
            get();
            double divisor = parseNumber();
            if (divisor == 0) {
                cerr << "Error: Division by zero\n";
                exit(1);
            }
            val /= divisor;
        } else {
            break;
        }
    }
    return val;
}
double parseExpression() {
    double val = parseTerm();
    while (true) {
        char op = peek();
        if (op == '+') {
            get();
            val += parseTerm();
        } else if (op == '-') {
            get();
            val -= parseTerm();
        } else {
            break;
        }
    }
    return val;
}
int main() {
    cout << "Enter expression (no brackets): ";
    getline(cin, input);
    double result = parseExpression();
    cout << "Result: " << result << endl;
}
Code 3:(Calculator without bracket)
/*
Amra normally jei expression gulo lekhi seigulo calculate kore dibe.
Input sample : 4+7+8-8
Output : 11
*/
#include <bits/stdc++.h>
using namespace std;
string input;
int pos = 0;
void skipWhitespace() {
    while (pos < (int)input.size() && isspace(input[pos])) pos++;
}
char peek() {
    skipWhitespace();
    if (pos < (int)input.size()) return input[pos];
    return '\0';
}
char get() {
    skipWhitespace();
    if (pos < (int)input.size()) return input[pos++];
    return '\0';
}
double parseTerm();
double parseExpression();
double parseNumber() {
    skipWhitespace();
    string num;
    while (isdigit(peek()) || peek() == '.') {
        num += get();
    }
    return stod(num);
}
double parseTerm() {
    double val = parseNumber();
    while (true) {
        char op = peek();
        if (op == '*') {
            get();
            val *= parseNumber();
        } else if (op == '/') {
            get();
            double divisor = parseNumber();
            if (divisor == 0) {
                cerr << "Error: Division by zero\n";
                exit(1);
            }
            val /= divisor;
        } else {
            break;
        }
    }
    return val;
}
double parseExpression() {
    double val = parseTerm();
    while (true) {
        char op = peek();
        if (op == '+') {
            get();
            val += parseTerm();
        } else if (op == '-') {
            get();
            val -= parseTerm();
        } else {
            break;
        }
    }
    return val;
}
int main() {
    cout << "Enter expression (no brackets): ";
    getline(cin, input);
    double result = parseExpression();
    cout << "Result: " << result << endl;
}
Code 4:
/*
Input sample :  int a,b,c;
Output       :  Data type: int
                Variable: a
                Variable: b
                Variable: c
                Declaration is valid.
eikhan ami int, float, double, string, DEF, DEFINE, char shob data type use korte parbo.
*/
#include<bits/stdc++.h>
using namespace std;
bool alpha(char ch) {
    return(ch>='a' && ch<='z') || (ch >='A' && ch<='Z') || (ch >='[' && ch<=']' || (ch=='='));
}
bool isDigit(char ch) {
    return(ch>='0' && ch<='9');
}
bool v_identi(char word[]) {
    if(!alpha(word[0]) || word[0]=='_'){
         return false;
    }
    for(int i=1;word[i]!='\0';i++) {
        if(!alpha(word[i]) && !isDigit(word[i]) && word[i]!='_') {
            return false;
        }
    }
    return true;
}
bool v_datatype(char word[]) {
    return strcmp(word,"int")==0 || strcmp(word,"float")==0 ||
           strcmp(word,"double")==0 || strcmp(word,"string")==0 || strcmp(word, "DEF")==0 || strcmp(word, "DEFINE")==0 || strcmp(word, "char")==0;
}
int main() {
    char line[100];
    cout<<"Enter declaration (Like, int a, b, c;): ";
    cin.getline(line,100);
    int len=strlen(line);
    if (line[len - 1] != ';') {
        cout<<"Invalid: Missing semicolon.\n";
        return 0;
    }
    line[len - 1]='\0';
    char *token=strtok(line," ,");
    if(token==NULL || !v_datatype(token)) {
        cout<< "Invalid: Declaration must start with a supported data type.\n";
        return 0;
    }
    cout<<"Data type: "<<token<<endl;
    bool valid=true;
    token=strtok(NULL, " ,");
    while(token != NULL) {
        if(!v_identi(token)) {
            cout<<"Invalid identifier: "<<token<<endl;
            valid=false;
        } else {
            cout<<"Variable: "<<token<<endl;
        }
        token=strtok(NULL, " ,");
    }
    if(valid) cout<<"Declaration is valid.\n"<<endl;
    else cout<<"Declaration contains invalid identifiers."<<endl;
    return 0;
}
Code 5:
/*
Input sample :  first e ami koyte testcase neye kaj korte cacchi seita input dete hobe.
                int a,b,c;
                int a=9,a=5,a=9;
                eikhan ami int, float, double, string, DEF, DEFINE, char shob data type use korte parbo.
*/
#include<bits/stdc++.h>
using namespace std;
bool alpha(char ch) {
    return(ch>='a' && ch<='z') || (ch >='A' && ch<='Z') || (ch >='[' && ch<=']' || (ch=='='));
}
bool isDigit(char ch) {
    return(ch>='0' && ch<='9');
}
bool v_identi(char word[]) {
    if(!alpha(word[0]) || word[0]=='_'){
         return false;
    }
    for(int i=1;word[i]!='\0';i++) {
        if(!alpha(word[i]) && !isDigit(word[i]) && word[i]!='_') {
            return false;
        }
    }
    return true;
}
bool v_datatype(char word[]) {
    return strcmp(word,"int")==0 || strcmp(word,"float")==0 ||
           strcmp(word,"double")==0 || strcmp(word,"string")==0 || strcmp(word, "DEF")==0 || strcmp(word, "DEFINE")==0 || strcmp(word, "char")==0;
}
int main() {
    int n;
    cin>>n;
    //cout<<endl;
    cin.ignore();
    while(n--){
    char line[100];
    cout<<"Enter declaration (Like, int a, b, c;): ";
    cin.getline(line,100);
    int len=strlen(line);
    if (line[len - 1] != ';') {
        cout<<"Invalid: Missing semicolon.\n";
        return 0;
    }
    line[len - 1]='\0';
    char *token=strtok(line," ,");
    if(token==NULL || !v_datatype(token)) {
        cout<< "Invalid: Declaration must start with a supported data type.\n";
        return 0;
    }
    cout<<"Data type: "<<token<<endl;
    bool valid=true;
    token=strtok(NULL, " ,");
    while(token != NULL) {
        if(!v_identi(token)) {
            cout<<"Invalid identifier: "<<token<<endl;
            valid=false;
        } else {
            cout<<"Variable: "<<token<<endl;
        }
        token=strtok(NULL, " ,");
    }
    if(valid) cout<<"Declaration is valid.\n"<<endl;
    else cout<<"Declaration contains invalid identifiers."<<endl;
    }
    return 0;
}
Code 6:(Line comment(single and multi line comment))
/*
Input sample:
Ei code ta mainly konta single line comment & konta multi line comment seita dekhabe.
Jodi ami single line er jonno Input dei:
        //Rifat Hassan  othoba ##Rifat Hassan
        Output : It's a single-line comment.
Jodi ami multi line er jonno input dei:
        /*Rifat Hassan end closing multi line
        Output : Total Length of text : ---
                It's a multi-line comment
*/
#include <bits/stdc++.h>
using namespace std;
bool isSingleLineComment(const string line) {
    for (int i=0;i<line.length();i++)
    {
      if((line[i]=='/' && line[i+1]=='/') || (line[i]=='#' && line[i+1]=='#'))
      {
          return true;
          break;
      }
    }
}
bool isMultiComment(const string text) {
    cout<<"Total Length of this text : ";
    cout<<text.length();
    cout<<endl;
    int check=0;
    int yes=0;
    for (int i=0;i<text.length();i++)
    {
      if((text[i]=='/'&&text[i+1]=='*') || (text[i]==';'&&text[i+1]==';') && check==0)
      {
          check=1;
          i=i+1;
      }
      if ((text[i]=='*'&&text[i+1]=='/') || (text[i]==';'&&text[i+1]==';') &&check==1)
      {
          yes=1;
          check=0;
          break;
      }
    }
    if(yes==1)
    {
        return true;
    }
    else
        return false;
}
int main() {
    string line, fullInput;
    cout << "Enter text (type END to finish):\n";
    while (true) {
        getline(cin, line);
        if (line == "END") break;
        fullInput += line + "\n";
    }
    if (isSingleLineComment(fullInput)) {
        cout << "It's a single-line comment.\n";
    }
    else if (isMultiComment(fullInput)) {
        cout << "It's a multi-line comment.\n";
    }
    else {
        cout << "Not a comment.\n";
    }
    return 0;
}
Code 7: (Math Expression)
/*
Amra normally operator use kore jei expression make kori seigulo valid naki invalid seita check kore ei code deye.
Input sample : first e test-case input nete hobe
then,
Sample Input 1  : 8+9+(8*5*4)
Output          : Valid Expression
Sample Input 2  : 8*9-{(8*5*4)
Output          : Invalid Expression
*/
#include <bits/stdc++.h>
using namespace std;
bool isValidExpression(const string& expr) {
    int balance = 0;
    bool expectOperand = true;
    for (size_t i = 0; i < expr.size(); i++) {
        char c = expr[i];
        if (isspace(c)) {
            continue;
        }
        else if (isdigit(c)) {
            while (i < expr.size() && isdigit(expr[i])) i++;
            i--;
            expectOperand = false;
        }
        else if (c == '(') {
            balance++;
            expectOperand = true;
        }
        else if (c == ')') {
            balance--;
            if (balance < 0) return false;
            expectOperand = false;
        }
        else if (c == '{') {
            balance++;
            expectOperand = true;
        }
        else if (c == '}') {
            balance--;
            if (balance < 0) return false;
            expectOperand = false;
        }
        else if (c == '[') {
            balance++;
            expectOperand = true;
        }
        else if (c == ']') {
            balance--;
            if (balance < 0) return false;
            expectOperand = false;
        }
        else if (c == '+' || c == '-' || c == '*' || c == '/') {
            if (expectOperand) return false;
            expectOperand = true;
        }
        else {
            return false;
        }
    }
    return (balance == 0 && !expectOperand);
}
int main() {
    int n;
    cin>>n;
    cin.ignore();
    while(n--){
        string expr;
        cout << "Enter mathematical expression: ";
        getline(cin, expr);
        if (isValidExpression(expr))
            cout << "Valid expression." << endl;
        else
            cout << "Invalid expression." << endl;
    }
    return 0;
}
Code 8: Multiple Line declaration (Onekgulo expression input hisabe nete pari, jhokon end press korbo thkn code theke ber hoye jabo)
//Multiple line declaration, jhokon ami end press korbo thokon code theke ber hoye jabe
#include <iostream>
#include <cstring>
using namespace std;
bool isAlphabet(char ch) {
    return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
bool isDigit(char ch) {
    return (ch >= '0' && ch <= '9');
}
bool isValidIdentifier(char word[]) {
    if (!isAlphabet(word[0]) && word[0] != '_') return false;
    for (int i = 1; word[i] != '\0'; i++) {
        if (!isAlphabet(word[i]) && !isDigit(word[i]) && word[i] != '_') return false;
    }
    return true;
}
bool isValidDataType(char word[]) {
    return strcmp(word, "int") == 0 || strcmp(word, "float") == 0 ||
           strcmp(word, "double") == 0 || strcmp(word, "string") == 0;
}
// simple integer-only checker
bool isNumber(const char* str) {
    for (int i = 0; str[i] != '\0'; i++) {
        if (!isdigit(str[i])) return false;
    }
    return true;
}
int main() {
    char line[200];
    cout << "Enter declarations (type 'end' to stop):" << endl;
    // Loop to handle multiple lines
    while (true) {
        cin.getline(line, 200);   // read one full line
        if (strcmp(line, "end") == 0) break; // stop if user types 'end'
        int len = strlen(line);
        if (line[len - 1] != ';') {
           cout << "Invalid: Missing semicolon.\n";
           return 0;
        }
        line[len - 1] = '\0';
        char* token = strtok(line, " ,");
        if (token == NULL || !isValidDataType(token)) {
            cout << "Invalid: Declaration must start with a supported data type.\n";
            continue; // skip this line, but don't exit program
        }
        cout << "Data type: " << token << endl;
        bool valid = true; // reset for each line
        token = strtok(NULL, " ,");
        while (token != NULL) {
            char* equalSign = strchr(token, '=');
            if (equalSign != NULL) {
                *equalSign = '\0';
                char* var = token;
                char* val = equalSign + 1;
                if (!isValidIdentifier(var)) {
                    cout << "Invalid identifier: " << var << endl;
                    valid = false;
                } else if (!isNumber(val)) {
                    cout << "Invalid assignment value: " << val << endl;
                    valid = false;
                } else {
                    cout << "Valid assignment: " << var << " = " << val << endl;
                }
            } else {
                if (!isValidIdentifier(token)) {
                    cout << "Invalid identifier: " << token << endl;
                    valid = false;
                } else {
                    cout << "Valid variable: " << token << endl;
                }
            }
            token = strtok(NULL, " ,");
        }
        if (valid) cout << "Declaration is valid.\n";
        else cout << "Declaration contains errors.\n";
    }
    return 0;
}
Code 9: Recursive descent parser
/*
E → T E'
E' → + T E' | ε
T → F T'
T' → * F T' | ε
F → id
*/
#include <iostream>
#include <string>
using namespace std;
string input;
int i = 0;
bool E(), Eprime(), T(), Tprime(), F();
bool E() { return T() && Eprime(); }
bool Eprime() {
    if (input[i] == '+') {
        i++;
        return T() && Eprime();
    }
    return true; // epsilon
}
bool T() { return F() && Tprime(); }
bool Tprime() {
    if (input[i] == '*') {
        i++;
        return F() && Tprime();
    }
    return true; // epsilon
}
bool F() {
    if (input[i] == 'i' && input[i+1] == 'd') {
        i += 2;
        return true;
    }
    return false;
}
int main() {
    cout << "Enter expression (use id for identifiers): ";
    cin >> input;
    input += "$";
    if (E() && input[i] == '$')
        cout << "Parsing Successful\n";
    else
        cout << "Parsing Error\n";
}
Code 10: Recursive descent parser(First calculation)
/*
E → T E'
E' → + T E' | ε
T → F T'
T' → * F T' | ε
F → id
*/
#include <bits/stdc++.h>
using namespace std;
set<char> E;
set<char> Eprime;
set<char> T;
set<char> Tprime;
set<char> F;
void F_Function() {
    F.insert('i');
}
void Tprime_Function() {
    Tprime.insert('*');
}
void Eprime_Function() {
    Eprime.insert('+');
}
void T_Function() {
    T.insert(F.begin(), F.end());
}
void E_Function() {
    E.insert(T.begin(), T.end());
}
void print(const string& name, const set<char>& s) {
    cout << "First(" << name << ") = { ";
    bool first = true;
    for (char c : s) {
        if (!first) {
            cout << ", ";
        }
        if (c == 'i') cout << "id";
        else cout << c;
        first = false;
    }
    cout << " }" << endl;
}
int main() {
    F_Function();
    Tprime_Function();
    Eprime_Function();
    T_Function();
    E_Function();
    cout << "--- First Set Calculation Results (Terminals Only) ---" << endl;
    print("F", F);
    print("T'", Tprime);
    print("E'", Eprime);
    print("T", T);
    print("E", E);
}
Filename: None. Size: 20kb. View raw, , hex, or download this file.

This paste expires on 2025-12-15 18:03:50.536769+00:00. Pasted through web.