Docsity

CSE-3528 Compiler Lab, Lab Reports of Compilers

Partial preview of the text

Download CSE-3528 Compiler Lab and more Lab Reports Compilers in PDF only on Docsity!

Department of Computer Science and Engineering

LAB REPORT

Course Title: Compiler Lab

Course Code: CSE- 3528

Experiment no: 1 - 11

Submitted by:

Name: Mahiah Kulsum

ID: C

Sec: 5BF

Submitted to:

Mrs. Israt Binte Habib

Lecturer, CSE, IIUC

Experiment 1 : Remove comment from line from the given input.

Code explanation:

  1. Function removeComments:
    • This function takes a string (prgm) representing the input C++ program and removes the comments from it.
    • It iterates through the input string character by character.
    • The flags s_cmt (single-line comment flag) and m_cmt (multi-line comment flag) are used to keep track of comment blocks.
    • If a single-line comment is encountered (//), the s_cmt flag is set to true, and the loop skips until a newline character is found to indicate the end of the comment.
    • If a multi-line comment is encountered (/*), the m_cmt flag is set to true, and the loop continues until */ is found to indicate the end of the comment block.
    • Characters within comments are skipped; otherwise, they are added to the result string (res).
  2. Function main:
    • It initializes an empty string prgm to store the input program.
    • It continuously reads lines of input from the user until the user types "end" on a new line, concatenating the lines to form the input program.
    • The removeComments function is called with the input program, and the modified program (without comments) is printed to the console. Code: #include using namespace std; string removeComments(string prgm) { int n = prgm.length(); string res; bool s_cmt = false; bool m_cmt = false; for (int i=0; i<n; i++) { if (s_cmt == true && prgm[i] == '\n') s_cmt = false;

Output:

Experiment 2 : Token identification.

Code explanation: Sure! This C++ program examines an input string and classifies the substrings into categories like keywords, integers, real numbers, operators, and valid identifiers. Here's a simpler summary of the code:

  1. Function isDelimiter(char ch):
    • Determines if a character is a delimiter (space, operators, commas, etc.).
  2. Function isOperator(char ch):
    • Finds out if a character is an operator.
  3. Function validIdentifier(char* str):
    • Verifies if a string is a valid identifier. Identifiers must not start with a digit or delimiter.
  1. Function isKeyword(char* str):
    • Checks whether a string is a C++ keyword.
  2. Function isInteger(char* str):
    • Determines if a string is an integer.
  3. Function isRealNumber(char* str):
    • Verifies if a string is a real number.
  4. Function subString(char* str, int left, int right):
    • Takes out a substring from the supplied string from index left to index right.
  5. Function parse(char* str):
    • Goes through the input string and recognizes substrings.
    • Figures out keywords, integers, real numbers, and valid identifiers using helper functions.
    • Displays the recognized substrings and their categories.
  6. Function main():
    • Receives an input string utilizing cin.getline().
    • Invokes the parse function to examine the input string and sort substrings.
    • Presents results showing the category of each substring. Code: #include <bits/stdc++.h> using namespace std; bool isDelimiter(char ch) { if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == ',' || ch == ';' || ch == '>' || ch == '<' || ch == '=' || ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '{' || ch == '}') return (true);

|| !strcmp(str, "short") || !strcmp(str, "typedef") || !strcmp(str, "switch") || !strcmp(str, "unsigned") || !strcmp(str, "void") || !strcmp(str, "static") || !strcmp(str, "struct") || !strcmp(str, "goto")) return (true); return (false); } bool isInteger(char* str) { int i, len = strlen(str); if (len == 0) return (false); for (i = 0; i < len; i++) { if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5' && str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' || (str[i] == '-' && i > 0)) return (false); } return (true); } bool isRealNumber(char* str) { int i, len = strlen(str); bool hasDecimal = false; if (len == 0) return (false); for (i = 0; i < len; i++) {

if (str[i] != '0' && str[i] != '1' && str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5' && str[i] != '6' && str[i] != '7' && str[i] != '8' && str[i] != '9' && str[i] != '.' || (str[i] == '-' && i > 0)) return (false); if (str[i] == '.') hasDecimal = true; } return (hasDecimal); } char* subString(char* str, int left, int right) { int i; char* subStr = (char)malloc( sizeof(char) * (right - left + 2)); for (i = left; i <= right; i++) subStr[i - left] = str[i]; subStr[right - left + 1] = '\0'; return (subStr); } void parse(char str) { int left = 0, right = 0; int len = strlen(str); while (right <= len && left <= right) { if (isDelimiter(str[right]) == false) right++;

int main() { char str[100]; cin.getline(str,20); cout<<endl; parse(str); return (0); } Input: Output:

Experiment 3 : L={w|w=a^ib^j c^k where i,j,k>=1 and i=j+k) accept those

string which fill up the following condition.

Code explanation:

  1. Header Inclusion:
    • The program incorporates the <bits/stdc++.h> header, a GCC-specific header that encompasses all standard C++ libraries, offering a handy method to include them all simultaneously.
  2. Function bool isValidString(const char* str):
    • This function determines if a given string is valid based on these criteria:
      • Only the characters 'a', 'b', and 'c' are allowed.
      • 'a' must be at the start of the string.
      • 'b' can only follow 'a' and precede 'c'.
  • 'c' can only appear after 'a' and 'b'.
  • At least one occurrence of each character is required.
  • The total of 'a's in the string must equal the sum of 'b's and 'c's.
  • The function returns true if these conditions are met, otherwise false.
  1. Function int main():
  • The main function starts by creating a character array inputString of length 100.
  • It retrieves user input with scanf.
  • It then invokes the isValidString function with this input string.
  • If the input string is deemed valid by the isValidString function, it displays "Accepted!". If not, it displays "Not accepted!". Code: #include <bits/stdc++.h> bool isValidString(const char* str) { int aCount = 0, bCount = 0, cCount = 0; int length = strlen(str); for (int i = 0; i < length; i++) { if (str[i] == 'a') { aCount++; if (bCount > 0 || cCount > 0) { return false; } } else if (str[i] == 'b') { bCount++; if (cCount > 0) { return false; } } else if (str[i] == 'c') { cCount++; } else {
  • Creates an enumeration called State for the finite automaton states.
  • Lists the states: q0, q1, q2, q3, q4.
  1. Function bool isBaba(string str, State currentState):
  • A recursive function to see if "baba" is in the input string using finite automaton.
  • Parameters: str (the substring being checked), currentState (automaton's current state).
  • Base cases:
  • Returns true if state is q4 (found "baba").
  • Returns false if string is empty.
  • Recursive cases:
  • Checks current character (currentChar) and moves to next state based on character and current state.
  • Continues recursion with new substring and state if character matches expected transition.
  1. Function int main():
  • Creates a string variable str for user input.
  • Gets input from the user with cin.
  • Sets initial state as q0.
  • Calls isBaba function with the input and starting state.
  • Prints whether "baba" is in the input or not based on the returned value from isBaba. Code: #include <bits/stdc++.h> using namespace std; enum State { q0, q1, q2, q3, q }; bool isBaba(string str, State currentState) {

if (currentState == q4) { return true; } if (str.length() == 0) { return false; } char currentChar = str[0]; switch (currentState) { case q0: if (currentChar == 'b') { return isBaba(str.substr(1), q1); } else { return isBaba(str.substr(1), q0); } case q1: if (currentChar == 'a') { return isBaba(str.substr(1), q2); } else { return isBaba(str.substr(1), q0); } case q2: if (currentChar == 'b') { return isBaba(str.substr(1), q3); } else { return isBaba(str.substr(1), q0); } case q3: if (currentChar == 'a') { return isBaba(str.substr(1), q4); } else { return isBaba(str.substr(1), q0);

  • The function verifies if the input automaton, expressed by its transition table, is a DFA.
  • By iterating through each state and symbol, it confirms there are no transitions to undefined states (marked as -1).
  • It also looks for repeated transitions in every row, which would suggest non-deterministic behavior.
  • If all transitions are properly defined with no duplicates, the function returns true (DFA). If not, it returns false.
  1. Function explanation: int main():
  • Variables n (state count) and s (symbol count) are declared.
  • The program collects user input for the number of states and symbols.
  • A 2D array a[MAX_STATE][MAX_SYMBOL] is declared to store the transition table data.
  • The transition table is populated using user input.
  • The function DFA is called with the relevant transition table, state count, and symbol count parameters.
  • The program outputs whether the automaton is a DFA or NFA based on the result from the DFA function. Code: #include using namespace std; #define MAX_STATE 100 #define MAX_SYMBOL 100 bool DFA(int a[MAX_STATE][MAX_SYMBOL], int n, int s) { for (int i = 0; i < n; i++) { for (int j = 0; j < s; j++) { if (a[i][j] == - 1) { return false; } for (int k = j + 1; k < s; k++)

if (a[i][j] == a[i][k]) { return false; } } } } return true; } int main() { int n, s; cout << "Enter the number of states: "; cin >> n; cout << "Enter the number of symbols: "; cin >> s; int a[MAX_STATE][MAX_SYMBOL]; cout << "Enter the transition table:\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < s; j++) { cin >> a[i][j]; } } if (DFA(a, n, s)) {

  • It creates two new rules:
    • One non-recursive rule: non_terminal - > beta non_terminal'
    • One for recursive scenarios: non_terminal - > sym alpha non_terminal' | epsilon
  • If no left recursion exists, it displays "not recursive."
  1. The main() function:
  • Reads input for the number of test cases (t).
  • Calls solve() for each test to process grammar rules and remove left recursion.
  • The solve() function tackles one production rule at a time. Code: #include <bits/stdc++.h> using namespace std; void solve() { string pro; while (cin >> pro) { char non_terminal, beta, alpha, sym; int index = 3; cout << "GRAMMAR IS : " << pro<< endl; non_terminal = pro[0]; if (non_terminal == pro[index]) { sym = pro[index + 1]; alpha = pro[index + 2]; while (pro[index] != '\0' && pro[index] != '|') { index++; } if (pro[index] != 0) {

beta = pro[index + 1]; cout<< "Grammar without left recursion:"<<endl; cout<<non_terminal<<"->"<<beta<<non_terminal<<"'"<<endl; cout<<non_terminal<<"->"<<sym<< alpha<< non_terminal<<"'"<<"|#"; } else cout<<"can't be reduced"<<endl; } else cout<<"not recursive."<<endl; index = 3; } } int main() { long long t; cin>>t; while(t--) { solve(); } } Input: Output: