1)Design a lexer and grammar for a simple programming language that includes the following features:
- Integer and floating-point number literals
- String literals enclosed in double quotes
- Single-line comments starting with
//
- Multi-line comments enclosed in
/* */
- Basic arithmetic operators:
+, - , *, /
- Comparison operators:
<, >, <=, >=, ==, !=
- Logical operators:
&& (AND), || (OR), ! (NOT)
- Assignment operator:
=
- Keywords:
if, else, while, for, return
- Identifiers starting with a letter or underscore, followed by letters, digits, or underscores
- Parentheses, braces, and semicolons for grouping and statement termination
Answer
lexer grammar Hello;
// Numbers
INT: [0-9]+ {System.out.println("Integer");};
FLOAT: [0-9]* '.' [0-9]+ {System.out.println("Float");};
// String
STRING: '"' .*? '"' {System.out.println("String");};
// Comments
SINGLE_LINE_COMMENT: '//' .*? '\\n' {System.out.println("Single Line Comment");};
MULTI_LINE_COMMENT: '/*' .+? '*/' {System.out.println("Multi Line Comment");};
// Arithmetic Operators
PLUS: '+' {System.out.println("Plus");};
MINUS: '-' {System.out.println("Minus");};
MULT: '*' {System.out.println("Multiply");};
DIV: '/' {System.out.println("Divide");};
// Comparison Operators
LT: '<' {System.out.println("Less Than");};
GT: '>' {System.out.println("Greater Than");};
LE: '<=' {System.out.println("Less Than or Equal");};
GE: '>=' {System.out.println("Greater Than or Equal");};
EQ: '==' {System.out.println("Equal");};
NE: '!=' {System.out.println("Not Equal");};
// Logical Operators
AND: '&&' {System.out.println("Logical AND");};
OR: '||' {System.out.println("Logical OR");};
NOT: '!' {System.out.println("Logical NOT");};
// Assignment Operator
ASSIGN: '=' {System.out.println("Assign");};
// Keywords
IF: 'if' {System.out.println("If");};
ELSE: 'else' {System.out.println("Else");};
WHILE: 'while' {System.out.println("While");};
FOR: 'for' {System.out.println("For");};
RETURN: 'return' {System.out.println("Return");};
// Identifier
ID: [a-zA-Z_][a-zA-Z0-9_]* {System.out.println("Identifier");};
// Separators
LPAREN: '(' {System.out.println("Left Parenthesis");};
RPAREN: ')' {System.out.println("Right Parenthesis");};
LBRACE: '{' {System.out.println("Left Brace");};
RBRACE: '}' {System.out.println("Right Brace");};
SEMICOLON: ';' {System.out.println("Semicolon");};
// Whitespace
WS: [ \\t\\r\\n]+ -> skip;