Write a Program to Detect Keyword and Identifier using JavaScript in Compiler Design

Write a Program to Check Keyword and Identifier using JavaScript in Compiler Design

What is Keyword and Identifiers?

Keywords and identifiers play crucial roles in programming languages. Keywords are predefined reserved words with special meanings to the compiler, while identifiers are names given to entities like variables, functions, and structures. In this article, we will explore how to detect keywords and identifiers in a given program using JavaScript.


Detecting Keywords and Identifiers in JavaScript:

To detect keywords and identifiers, we can use a combination of techniques such as string manipulation, comparison, and regular expressions. Let's dive into the code example:

let keywords = ["auto", "double", "int", "struct", "break", "else", "long",
    "switch", "case", "enum", "register", "typedef", "char",
    "extern", "return", "union", "const", "float", "short",
    "unsigned", "continue", "for", "signed", "void", "default",
    "goto", "sizeof", "voltile", "do", "if", "static", "while"
];

let expression = "int 9int = float(b) + double(c) + $text = char(ABC)";
let separators = ["=", ",", "+", "-", "*", "/", "%", "{", "}", "(", ")"];

function hasSeparators(separators) {
    for (let separator of separators) {
        if (expression.includes(separator)) {
            expression = expression.replaceAll(`${separator}`, ' ');
        }
    }
    return expression;
}

function detectKeyword(keywords, newExpression) {
    let resultKeywords = [];
    for (let expression of newExpression) {
        for (let keyword of keywords) {
            if (keyword == expression) {
                console.log(`${keyword} is a keyword`);
                resultKeywords.push(keyword);
            }
        }
    }
    return resultKeywords;
}

function detectIdentifier(keywordList, newExpression) {
    let resultIdentifiers = newExpression.filter(keyword => {
        let regex = "^([a-zA-Z_$][a-zA-Z\\d_$]*)$";
        return !keywordList.includes(keyword) && keyword.match(regex);
    });

    console.log(`\n`);
    resultIdentifiers.forEach(element => {
        console.log(`${element} is an identifier`);
    });
}

function detectKeywordIdentifier() {
    console.log(`The given expression:\n ${expression}\n`);
    let newExpression = hasSeparators(separators).split(" ")
        .filter(e => e != "");

    let keywordList = detectKeyword(keywords, newExpression);
    detectIdentifier(keywordList, newExpression);
}

detectKeywordIdentifier();

 

0 Response to Write a Program to Detect Keyword and Identifier using JavaScript in Compiler Design

Post a Comment