Assignment-2 Setup

This commit is contained in:
Mann Patel
2025-10-10 12:57:07 -06:00
parent 9ceac201a3
commit 031e7e4a92
10 changed files with 1 additions and 0 deletions

Binary file not shown.

219
Assignment-1/ExprLexer.g4 Normal file
View File

@@ -0,0 +1,219 @@
lexer grammar ExprLexer;
fragment LineTerminator: '\r' '\n'? | '\n';
WhiteSpace: (' ' | '\t' | '\f' | LineTerminator) -> skip;
fragment EndOfLineComment: '//' ~('\r' | '\n')* LineTerminator?;
Comment: (TraditionalComment | EndOfLineComment) -> skip;
fragment TraditionalComment:
'/*' NotStar CommentTail;
fragment CommentTail: '*' CommentTailStar | NotStar ;
fragment CommentTailStar:
'/' | '*' CommentTailStar | NotStarNotSlash CommentTail;
fragment NotStar:
[^*] | LineTerminator;
fragment NotStarNotSlash:
[^*/] | LineTerminator;
Abstract: 'abstract';
Assert: 'assert';
Boolean: 'boolean';
Break: 'break';
Byte: 'byte';
Case: 'case';
Catch: 'catch';
Char: 'char';
Class: 'class';
Const: 'const';
Continue: 'continue';
Default: 'default';
Do: 'do';
Double: 'double';
Else: 'else';
Extends: 'extends';
Final: 'final';
Finally: 'finally';
Float: 'float';
For: 'for';
Goto: 'goto';
If: 'if';
Implements: 'implements';
Import: 'import';
InstanceOf: 'instanceof';
Int: 'int';
Interface: 'interface';
Long: 'long';
Native: 'native';
New: 'new';
Package: 'package';
Private: 'private';
Protected: 'protected';
Public: 'public';
Return: 'return';
Short: 'short';
Static: 'static';
Strictfp: 'strictfp';
Super: 'super';
Switch: 'switch';
Synchronized: 'synchronized';
This: 'this';
Throw: 'throw';
Throws: 'throws';
Transient: 'transient';
Try: 'try';
Void: 'void';
Volatile: 'volatile';
While: 'while';
Dot: '.';
IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral;
fragment DecimalIntegerLiteral:
DecimalNumeral IntegerTypeSuffix?;
fragment HexIntegerLiteral:
HexNumeral IntegerTypeSuffix?;
fragment OctalIntegerLiteral:
OctalNumeral IntegerTypeSuffix?;
fragment IntegerTypeSuffix:
[lL];
fragment DecimalNumeral:
'0' | NonZeroDigit Digits?;
fragment HexNumeral:
'0' 'x' HexDigits | '0' 'X' HexDigits;
fragment HexDigits:
HexDigit | HexDigit HexDigits;
fragment HexDigit:
[0-9a-fA-F];
FloatingPointLiteral: Digits '.' Digits? ExponentPart? FloatTypeSuffix?
| '.' Digits ExponentPart? FloatTypeSuffix?
| Digits ExponentPart FloatTypeSuffix?
| Digits ExponentPart? FloatTypeSuffix;
fragment ExponentPart:
ExponentIndicator SignedInteger;
fragment ExponentIndicator:
[eE];
fragment SignedInteger:
Sign? Digits;
fragment Digits:
Digit+;
fragment Digit:
'0' | NonZeroDigit;
fragment NonZeroDigit:
[1-9];
fragment Sign:
[+-];
fragment FloatTypeSuffix:
[fFdD];
CharacterLiteral: '\'' SingleCharacter '\'' | '\'' EscapeSequence '\'';
fragment SingleCharacter:
[^'\\];
StringLiteral: '"' StringCharacters? '"';
fragment StringCharacters:
StringCharacter+;
fragment StringCharacter:
SingleCharacter | EscapeSequence;
fragment EscapeSequence:
'\\' ('u0008' | 'u0009' | 'u000a' | 'u000c' | 'u000d' | 'u0022' | 'u0027' | 'u005c' | OctalEscape);
fragment OctalEscape:
'\\' OctalDigit | '\\' OctalDigit OctalDigit | '\\' ZeroToThree OctalDigit OctalDigit;
fragment OctalNumeral:
'0' OctalDigits;
fragment OctalDigits:
OctalDigit;
fragment OctalDigit:
[0-7];
fragment ZeroToThree:
[0-3];
BooleanLiteral: 'true' | 'false' ;
NullLiteral: 'null';
ParenthesesLeft: '(';
ParenthesesRight: ')';
CurlyBracketLeft: '{';
CurlyBracketRight: '}';
SquareBracketLeft: '[';
SquareBracketRight: ']';
Semicolon: ';';
Comma: ',';
UnsignedRightShiftAssign: '>>>=';
EqualTo: '==';
NotEqualTo: '!=';
LessThanEqualTo: '<=';
GreaterThanEqualTo: '>=';
ConditionalAND: '&&';
ConditionalOR: '||';
Increment: '++';
Decrement: '--';
LeftShift: '<<';
SignedRightShift: '>>';
UnsignedRightShift: '>>>';
AddAssign: '+=';
SubtractAssign: '-=';
MultiplyAssign: '*=';
DivideAssign: '/=';
BitwiseANDAssign: '&=';
BitwiseORAssign: '|=';
BitwiseXORAssign: '^=';
RemainderAssign: '%=';
LeftShiftAssign: '<<=';
SignedRightShiftAssign: '>>=';
Assignment: '=';
BitwiseComplement: '~';
LessThan: '<';
GreaterThan: '>';
LogicalComplement: '!';
Question: '?';
Colon: ':';
Addition: '+';
Subtraction: '-';
Multiplication: '*';
Division: '/';
BitwiseAND: '&';
BitwiseOR: '|';
BitwiseXOR: '^';
Remainder: '%';
IDENTIFIER: JavaLetter JavaLetterOrDigit*;
fragment JavaLetter:
[a-zA-Z$_];
fragment JavaLetterOrDigit:
[A-Za-z0-9$_];

248
Assignment-1/ExprParser.g4 Normal file
View File

@@ -0,0 +1,248 @@
parser grammar ExprParser;
options {
tokenVocab=ExprLexer;
}
prog: compilationUnit EOF;
identifier: IDENTIFIER;
qualifiedIdentifier: identifier (Dot identifier)*;
literal: IntegerLiteral
| FloatingPointLiteral
| CharacterLiteral
| StringLiteral
| BooleanLiteral
| NullLiteral;
//Section 15.26: Assignment Operators
expression: unaryExpr assignmentOperator expression | conditionalExpr ;
//Highest Prescedence _Expr = expression
//CI cha 6
conditionalExpr: logicalOrExpr Question conditionalExpr Colon conditionalExpr | logicalOrExpr;
logicalOrExpr: logicalAndExpr (ConditionalOR logicalAndExpr)*;
logicalAndExpr: equalityExpr (ConditionalAND equalityExpr)*;
equalityExpr: relationalExpr ((EqualTo | NotEqualTo) relationalExpr)*;
relationalExpr: additiveExpr((LessThan | GreaterThan | LessThanEqualTo | GreaterThanEqualTo) additiveExpr | InstanceOf type)*;
additiveExpr: multiplicativeExpr((Addition | Subtraction) multiplicativeExpr)*;
multiplicativeExpr: unaryExpr((Multiplication | Division | Remainder) unaryExpr)*;
unaryExpr:postfixExpr |(Addition | Subtraction | LogicalComplement | BitwiseComplement | Increment | Decrement) unaryExpr | parExpression type unaryExpr;
postfixExpr: primaryExpr (Increment| Decrement| Dot IDENTIFIER | SquareBracketLeft expression SquareBracketRight | arguments)*;
primaryExpr: parExpression
| IntegerLiteral
| FloatingPointLiteral
| StringLiteral
| CharacterLiteral
| BooleanLiteral
| NullLiteral
| IDENTIFIER
| This
| Super (Dot IDENTIFIER)?
| New type arguments
| primitiveType (SquareBracketLeft SquareBracketRight)* Dot Class
| type Dot Class;
assignmentOperator: Assignment
| AddAssign
| SubtractAssign
| MultiplyAssign
| DivideAssign
| BitwiseANDAssign
| BitwiseORAssign
| BitwiseXORAssign
| RemainderAssign
| LeftShiftAssign
| SignedRightShiftAssign
| UnsignedRightShiftAssign;
type: identifier (Dot identifier)* bracketsOpt | primitiveType;
statementExpression: expression;
constantExpression: expression;
identifierSuffix: SquareBracketLeft SquareBracketRight bracketsOpt Dot Class
|SquareBracketLeft expression SquareBracketRight
|arguments
|Dot (Class | This | Super arguments New innerCreator);
postfixOp: Increment | Decrement;
primitiveType: Byte | Short| Char | Int| Long| Float| Double| Boolean;
//Method arguments
argumentsOpt: (arguments)?;
arguments: ParenthesesLeft (expression (Comma expression)*)? ParenthesesRight;
bracketsOpt: (SquareBracketLeft SquareBracketRight)*;
creator: qualifiedIdentifier ( arrayCreatorRest | classCreatorRest);
innerCreator: identifier classCreatorRest;
arrayCreatorRest: SquareBracketLeft SquareBracketRight bracketsOpt arrayInitializer
| SquareBracketLeft expression SquareBracketRight (SquareBracketLeft expression SquareBracketRight)*;
classCreatorRest: arguments (classBody)?;
arrayInitializer: CurlyBracketLeft (variableInitializer(Comma variableInitializer)*(Comma)?)? CurlyBracketRight;
variableInitializer: arrayInitializer
|expression;
parExpression: ParenthesesLeft expression ParenthesesRight;
block: CurlyBracketLeft blockStatements CurlyBracketRight;
blockStatements: (blockStatement)*;
blockStatement: localVariableDeclarationStatement
|classOrInterfaceDeclaration
|(identifier Colon)? statement;
localVariableDeclarationStatement: (Final)? type variableDeclarators;
statement:completeIf | If parExpression statementIncompleteIf;
statementIncompleteIf: block
| If parExpression completeIf Else statementIncompleteIf
| For ParenthesesLeft forInit? Semicolon (expression)? Semicolon forUpdate? ParenthesesRight statement
| While parExpression statement
| Do statement While parExpression Semicolon
| Try block catches
| Try block Finally block
| Try block catches Finally block
| switchStatement
| Synchronized parExpression block
| Return (expression)? Semicolon
| Throw expression Semicolon
| Break (identifier)? Semicolon
| Continue (identifier)? Semicolon
| statementExpression Semicolon
| Semicolon;
//solve ambiguity over If()else. aka (Dangling else).
//this will do the longest check by looking for an else section, fincding the closest else!
completeIf: If parExpression completeIf Else completeIf | statementIncompleteIf;
catches: catchClause (catchClause)*;
catchClause: Catch ParenthesesLeft formalParameter ParenthesesRight block;
switchStatement: Switch parExpression CurlyBracketLeft CurlyBracketRight
| Switch parExpression CurlyBracketLeft switchBlockStatementGroups? CurlyBracketRight;
switchBlockStatementGroups: (switchBlockStatementGroup)*;
switchBlockStatementGroup: switchLabel blockStatements;
switchLabel: Case constantExpression Colon
| Default Colon;
moreStatementExpressions: (Comma statementExpression)*;
forInit: statementExpression moreStatementExpressions
| (Final)? type variableDeclarators;
forUpdate: statementExpression moreStatementExpressions;
modifiersOpt: (modifier)*;
modifier: Public
| Protected
| Private
| Static
| Abstract
| Final
| Native
| Synchronized
| Transient
| Volatile
| Strictfp;
variableDeclarators: variableDeclarator (Comma variableDeclarator)*;
variableDeclaratorsRest: variableDeclaratorRest (Comma variableDeclarator)*;
constantDeclaratorsRest: constantDeclaratorRest (Comma constantDeclarator)*;
variableDeclarator: identifier variableDeclaratorsRest;
constantDeclarator: identifier constantDeclaratorRest;
variableDeclaratorRest: bracketsOpt (Assignment variableInitializer)?;
constantDeclaratorRest: bracketsOpt Assignment variableInitializer;
variableDeclaratorId: identifier bracketsOpt;
compilationUnit: (Package qualifiedIdentifier Semicolon)? (importDeclaration)*(typeDeclaration)*;
importDeclaration: Import identifier (Dot identifier)* (Dot Multiplication)? Semicolon;
typeDeclaration: classOrInterfaceDeclaration | Semicolon;
classOrInterfaceDeclaration: modifiersOpt (classDeclaration | interfaceDeclaration);
classDeclaration: Class identifier (Extends type)? (Implements typeList)? classBody;
interfaceDeclaration: Interface identifier (Extends typeList)? interfaceBody;
typeList: type (Comma type)*;
classBody: CurlyBracketLeft (classBodyDeclaration)* CurlyBracketRight;
interfaceBody: CurlyBracketLeft (interfaceBodyDeclaration)* CurlyBracketRight;
classBodyDeclaration: Semicolon
| (Static)? block
| modifiersOpt memberDecl;
memberDecl: methodOrFieldDecl
| Void identifier methodDeclaratorRest
| identifier constructorDeclaratorRest
| classOrInterfaceDeclaration;
methodOrFieldDecl: type identifier methodOrFieldRest;
methodOrFieldRest: variableDeclaratorRest
|methodDeclaratorRest;
interfaceBodyDeclaration: Semicolon
| modifiersOpt interfaceMemberDecl;
interfaceMemberDecl: interfaceMethodOrFieldDecl
| Void identifier voidInterfaceMethodDeclaratorRest
| classOrInterfaceDeclaration;
interfaceMethodOrFieldDecl: type identifier interfaceMethodOrFieldRest;
interfaceMethodOrFieldRest: constantDeclaratorRest Semicolon
| interfaceMethodDeclaratorRest;
methodDeclaratorRest: formalParameters bracketsOpt (Throws qualifiedIdentifierList)?(methodBody | Semicolon);
voidMethodDeclaratorRest: formalParameters (Throws qualifiedIdentifierList)? (methodBody | Semicolon);
interfaceMethodDeclaratorRest: formalParameters bracketsOpt (Throws qualifiedIdentifierList)? Semicolon;
voidInterfaceMethodDeclaratorRest: formalParameters (Throws qualifiedIdentifierList)?;
constructorDeclaratorRest: formalParameters (Throws qualifiedIdentifierList)? methodBody;
qualifiedIdentifierList: qualifiedIdentifier (Comma qualifiedIdentifier)*;
formalParameters: ParenthesesLeft (formalParameter (Comma formalParameter)*)? ParenthesesRight;
formalParameter: (Final)? type variableDeclaratorId;
methodBody: block;

View File

@@ -0,0 +1,92 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.runtime.misc.ParseCancellationException;
public class ExprTool {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
// If no files given then read from stdin
Scanner scanner = new Scanner(System.in);
StringBuilder inputBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
inputBuilder.append(scanner.nextLine()).append("\n");
}
scanner.close();
parseAndWalk(inputBuilder.toString(), "<stdin>");
} else {
// for Loop through all given file paths
for (String filePath : args) {
try {
String inputText = new String(Files.readAllBytes(Paths.get(filePath)));
parseAndWalk(inputText, filePath);
} catch (IOException e) {
System.err.println("Error reading file: " + filePath);
}
}
}
}
private static void parseAndWalk(String inputText, String sourceName) {
try {
// Create char stream
CharStream input = CharStreams.fromString(inputText, sourceName);
ExprLexer lexer = new ExprLexer(input);
lexer.removeErrorListeners();
lexer.addErrorListener(new ThrowingErrorListener());
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExprParser parser = new ExprParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new ThrowingErrorListener());
ParseTree tree = parser.compilationUnit();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(new ClassPrinter(sourceName), tree);
} catch (RuntimeException e) {
System.err.println("Parsing File Failed: " + e.getMessage());
}
}
public static class ClassPrinter extends ExprParserBaseListener {
private final String sourceName;
public ClassPrinter(String sourceName) {
this.sourceName = sourceName;
}
@Override
public void enterClassDeclaration(ExprParser.ClassDeclarationContext ctx) {
int line = ctx.getStart().getLine();
int col = ctx.getStart().getCharPositionInLine();
String className = ctx.identifier().getText();
System.out.printf("Class %s, file %s, line %d, column %d%n",
className, sourceName, line, col);
}
}
// Custom error listener
public static class ThrowingErrorListener extends BaseErrorListener {
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line, int charPositionInLine,
String msg,
RecognitionException e) {
String sourceName = recognizer.getInputStream().getSourceName();
if (sourceName == null || sourceName.isEmpty()) {
sourceName = "<unknown>";
}
String formatted = String.format(
" file %s, line %d, column %d, error-msg: %s",
sourceName, line, charPositionInLine, msg
);
throw new ParseCancellationException(formatted);
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,45 @@
package Test
abstract class TaxCalculator {
protected double income
public TaxCalculator(double income {
this.income = income
}
public abstract double calculateTax()
public double afterTaxIncome() {
return income - calculateTax()
}
class FlatTaxCalculator extends TaxCalculator {
private static final double RATE = 0.15
public FlatTaxCalculator(double income) super(income)
public double calculateTax() {
return income * RATE
}
public class TaxApp {
static class BracketTaxCalculator extends TaxCalculator {
public BracketTaxCalculator(double income)
super(income)
public double calculateTax() {
if (income <= 10000) return income * 0.10
else if (income <= 50000) return (10000 * 0.10) + ((income - 10000) * 0.20)
else return (10000 * 0.10) + (40000 * 0.20) + ((income - 50000) * 0.30)
}
}
public static void main(String[] args) {
double income = 60000
TaxCalculator flat = new FlatTaxCalculator(income)
double flatTax = flat.calculateTax()
double flatAfterTax = flat.afterTaxIncome()
TaxCalculator bracket = new BracketTaxCalculator(income)
double bracketTax = bracket.calculateTax()
double bracketAfterTax = bracket.afterTaxIncome()
}
}

View File

@@ -0,0 +1,44 @@
package Test;
abstract class TaxCalculator {
protected double income;
public TaxCalculator(double income) {
this.income = income;
}
public abstract double calculateTax();
public double afterTaxIncome() {
return income - calculateTax();
}
}
class FlatTaxCalculator extends TaxCalculator {
private static final double RATE = 0.15;
public FlatTaxCalculator(double income) {super(income);}
public double calculateTax() {
return income * RATE;
}
}
public class TaxApp {
static class BracketTaxCalculator extends TaxCalculator {
public BracketTaxCalculator(double income) {
super(income);
}
public double calculateTax() {
if (income <= 10000) {return income * 0.10;}
else if (income <= 50000) { return (10000 * 0.10) + ((income - 10000) * 0.20);}
else { return (10000 * 0.10) + (40000 * 0.20) + ((income - 50000) * 0.30);}
}
}
public static void main(String[] args) {
double income = 60000;
TaxCalculator flat = new FlatTaxCalculator(income);
double flatTax = flat.calculateTax();
double flatAfterTax = flat.afterTaxIncome();
TaxCalculator bracket = new BracketTaxCalculator(income);
double bracketTax = bracket.calculateTax();
double bracketAfterTax = bracket.afterTaxIncome();
}
}

Binary file not shown.