package de.dhbwstuttgart.parser.SyntaxTreeGenerator;

import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.antlr.Java8Parser;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.operator.AndOp;
import de.dhbwstuttgart.syntaxtree.operator.OrOp;
import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.statement.literal.*;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typecheck.JavaClassName;
import de.dhbwstuttgart.typecheck.JavaClassRegistry;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.TerminalNode;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StatementGenerator {

    private JavaClassRegistry reg;
    private Set<String> localVars = new HashSet<>();
    private GenericsRegistry generics;

    public StatementGenerator(JavaClassRegistry reg, GenericsRegistry generics){
        this.reg = reg;
        this.generics = generics;
    }


    public Method convert(Java8Parser.MethodDeclarationContext methodDeclarationContext, JavaClassName parentClass) {
        Java8Parser.MethodHeaderContext header = methodDeclarationContext.methodHeader();
        String name = header.methodDeclarator().Identifier().getText();
        GenericDeclarationList gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), methodDeclarationContext.methodHeader().getStart());
        if(methodDeclarationContext.methodHeader().typeParameters() != null){
            gtvDeclarations = TypeGenerator.convert(methodDeclarationContext.methodHeader().typeParameters(), parentClass, name,reg, generics);
        }
        RefTypeOrTPHOrWildcardOrGeneric retType;
        if(header.result() != null){
            if(header.result().unannType() != null){
                retType = TypeGenerator.convert(header.result().unannType(), reg, generics);
            }
            else retType = new de.dhbwstuttgart.syntaxtree.type.Void(header.result().getStart());
        }else{
            retType = TypePlaceholder.fresh(header.getStart());
        }
        int modifiers = SyntaxTreeGenerator.convert(methodDeclarationContext.methodModifier());
        ParameterList parameterList = convert(header.methodDeclarator().formalParameterList());
        Block block = null;
        if(methodDeclarationContext.methodBody().block() == null){
            if(! Modifier.isAbstract(modifiers)){
                //TODO: Error! Abstrakte Methode ohne abstrakt Keyword
            }
        }else{
            block = this.convert(methodDeclarationContext.methodBody().block());
        }
        return new Method(name, retType, modifiers, parameterList,block, gtvDeclarations, methodDeclarationContext.getStart());
    }

    private ParameterList convert(Java8Parser.FormalParameterListContext formalParameterListContext) {
        List<FormalParameter> ret = new ArrayList<>();
        List<Java8Parser.FormalParameterContext> fps = new ArrayList<>();
        if(formalParameterListContext == null || formalParameterListContext.lastFormalParameter() == null)
            return new ParameterList(ret, new NullToken()); //Dann ist die Parameterliste leer

        if(formalParameterListContext.lastFormalParameter().formalParameter() == null)throw new NotImplementedException();

        if(formalParameterListContext != null && formalParameterListContext.formalParameters() != null
                && formalParameterListContext.formalParameters().formalParameter() != null){
            fps = new ArrayList<>(formalParameterListContext.formalParameters().formalParameter());
        }
        fps.add(formalParameterListContext.lastFormalParameter().formalParameter());

        for(Java8Parser.FormalParameterContext fp : fps){
            String paramName = SyntaxTreeGenerator.convert(fp.variableDeclaratorId());
            RefTypeOrTPHOrWildcardOrGeneric type;
            if(fp.unannType() != null){
                type = TypeGenerator.convert(fp.unannType(), reg, generics);
            }else{
                type = TypePlaceholder.fresh(fp.getStart());
            }
            ret.add(new FormalParameter(paramName, type, fp.getStart()));
            localVars.add(paramName);
        }
        return new ParameterList(ret, ret.get(0).getOffset());
    }

  /*
  * StatementGeneration:
   */

    private Statement convert(Java8Parser.StatementContext stmt) {
        if (stmt.statementWithoutTrailingSubstatement() != null) {
            return convert(stmt.statementWithoutTrailingSubstatement());
        } else if (stmt.whileStatement() != null) {
            return convert(stmt.whileStatement());
        } else if (stmt.forStatement() != null) {
            return convert(stmt.forStatement());
        } else if (stmt.ifThenElseStatement() != null) {
            return convert(stmt.ifThenElseStatement());
        } else if (stmt.ifThenStatement() != null) {
            return convert(stmt.ifThenStatement());
        } else if (stmt.labeledStatement() != null) {
            return convert(stmt.labeledStatement() );
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.StatementNoShortIfContext stmt){
        if(stmt.statementWithoutTrailingSubstatement() != null){
            return convert(stmt.statementWithoutTrailingSubstatement());
        }else if(stmt.labeledStatementNoShortIf() != null){
            return convert(stmt.labeledStatementNoShortIf());
        }else if(stmt.ifThenElseStatementNoShortIf() != null){
            return convert(stmt.ifThenElseStatementNoShortIf());
        }else if(stmt.whileStatementNoShortIf() != null){
            return convert(stmt.whileStatementNoShortIf());
        }else if(stmt.forStatementNoShortIf() != null){
            return convert(stmt.forStatementNoShortIf());
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.StatementWithoutTrailingSubstatementContext stmt) {
        if(stmt.block() != null){
            return convert(stmt.block());
        }else if(stmt.emptyStatement() != null){
            return new EmptyStmt(stmt.getStart());
        }else if(stmt.expressionStatement() != null){
            return convert(stmt.expressionStatement());
        }else if(stmt.assertStatement() != null){
            return convert(stmt.assertStatement());
        }else if(stmt.switchStatement() != null){
            return convert(stmt.switchStatement());
        }else if(stmt.doStatement() != null){
            return convert(stmt.doStatement());
        }else if(stmt.breakStatement() != null){
            return convert(stmt.breakStatement());
        }else if(stmt.continueStatement() != null){
            return convert(stmt.continueStatement());
        }else if(stmt.returnStatement() != null){
            return convert(stmt.returnStatement());
        }else if(stmt.synchronizedStatement() != null){
            return convert(stmt.synchronizedStatement());
        }else if(stmt.throwStatement() != null){
            return convert(stmt.throwStatement());
        }else if(stmt.tryStatement() != null){
            return convert(stmt.tryStatement());
        }else throw new NotImplementedException();
    }

    public Block convert(Java8Parser.BlockContext block) {
        List<Statement> statements = new ArrayList<>();
        if(block.blockStatements() != null)
            for(Java8Parser.BlockStatementContext statementContext : block.blockStatements().blockStatement()){
                Statement stmt = convert(statementContext);
                statements.add(stmt);
            }
        statements = SyntacticSugar.addTrailingReturn(statements);
        return new Block(statements, block.getStart());
    }

    private de.dhbwstuttgart.syntaxtree.statement.Statement convert(Java8Parser.BlockStatementContext statementContext) {
        List<de.dhbwstuttgart.syntaxtree.statement.Statement> ret = new ArrayList<>();
        if(statementContext.localVariableDeclarationStatement() != null){
            return convert(statementContext.localVariableDeclarationStatement());
        }else if(statementContext.classDeclaration() != null){
            throw new NotImplementedException();
        }else{
            Java8Parser.StatementContext stmt = statementContext.statement();
            return convert(stmt);
        }
    }

    private Statement convert(Java8Parser.LocalVariableDeclarationStatementContext stmt) {
        Java8Parser.LocalVariableDeclarationContext declaration = stmt.localVariableDeclaration();
        return convert(declaration);
    }

    private Statement convert(Java8Parser.LabeledStatementContext labeledStatementContext) {
        throw new NotImplementedException();
        //return convert(labeledStatementContext.statement());
    }

    private Statement convert(Java8Parser.LabeledStatementNoShortIfContext stmt){
        throw new NotImplementedException();
        //return convert(stmt.statementNoShortIf());
    }

    private Statement convert(Java8Parser.ExpressionStatementContext stmt){
        return convert(stmt.statementExpression());
    }

    private Statement convert(Java8Parser.StatementExpressionContext stmt) {
        if(stmt.assignment() != null){
            return convert(stmt.assignment());
        }else if(stmt.preIncrementExpression() != null){
            return convert(stmt.preIncrementExpression());
        }else if(stmt.preDecrementExpression() != null){
            return convert(stmt.preDecrementExpression());
        }else if(stmt.postIncrementExpression() != null){
            return convert(stmt.postIncrementExpression());
        }else if(stmt.postDecrementExpression() != null){
            return convert(stmt.postDecrementExpression());
        }else if(stmt.methodInvocation() != null){
            return convert(stmt.methodInvocation());
        }else if(stmt.classInstanceCreationExpression() != null){
            return convert(stmt.classInstanceCreationExpression());
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.MethodInvocationContext methodInvocationContext) {
        String name;
        if(methodInvocationContext.methodName()!=null){
            name = methodInvocationContext.methodName().Identifier().getText();
        }else{// if(methodInvocationContext.Identifier() != null){
            name = methodInvocationContext.Identifier().getText();
        }
        Expression receiver;
        if(methodInvocationContext.typeName() != null){
            receiver = generateLocalOrFieldVarOrClassName(methodInvocationContext.typeName().getText(), methodInvocationContext.typeName().getStart());
        }else if(methodInvocationContext.expressionName()!=null){
            receiver = convert(methodInvocationContext.expressionName());
        }else if(methodInvocationContext.primary() != null){
            receiver = convert(methodInvocationContext.primary());
        }else if(methodInvocationContext.toString().startsWith("super")){
            receiver = new Super(methodInvocationContext.getStart());
        }else if(methodInvocationContext.methodName() != null){
            receiver = new This(methodInvocationContext.getStart());
        }else throw new NotImplementedException();

        ArgumentList argumentList = convert(methodInvocationContext.argumentList());
        MethodCall ret = new MethodCall(new Receiver(receiver), name, argumentList, methodInvocationContext.getStart());
        return ret;
    }

    private ArgumentList convert(Java8Parser.ArgumentListContext argumentListContext) {
        if(argumentListContext == null)return new ArgumentList(new ArrayList<>(), new NullToken());
        List<Expression> args = new ArrayList<>();

        Token offset = new NullToken();
        for(Java8Parser.ExpressionContext expr : argumentListContext.expression()){
            args.add(convert(expr));
        }
        if(args.size()>0)offset = args.get(0).getOffset();

        return new ArgumentList(args, offset);
    }

    /**
     * Der Parser kann nicht zwischen einer lokalen Variable, einem Feldzugriff und
     * einer Klassenangabe unterscheiden.
     * @param expression
     * @param offset
     * @return
     */
    private Expression generateLocalOrFieldVarOrClassName(String expression, Token offset){
        String[] parts = expression.split("\\.");
        if(parts.length < 2){
            //Check for localVar:
            if(localVars.contains(expression)){
                return new LocalVar(expression, offset);
            }else {
                throw new NotImplementedException();
            }
        }
        return generateFieldVarOrClassname(expression, offset);
    }

    private Expression generateFieldVarOrClassname(String expression, Token offset){
        String[] parts = expression.split("\\.");
        String whole = "";
        Expression receiver = null;
        for(String part : parts){
            whole+=part;
            //Check for Classname:
            if(reg.contains(whole)){
                receiver = new StaticClassName(reg.getName(whole), offset);
            }
            whole+=".";
        }

        if(parts.length < 2){
            receiver = new This(offset);
        }else if(receiver == null){ //Handelt es sich um keinen Statischen Klassennamen:
            String part = expression.substring(0,expression.length() - (1 + parts[parts.length-1].length()));
            receiver = generateLocalOrFieldVarOrClassName(part, offset);
        }
        return new FieldVar(receiver, parts[parts.length-1], TypePlaceholder.fresh(offset) ,offset);
    }

    private Expression convert(Java8Parser.ExpressionNameContext expressionNameContext) {
        return generateLocalOrFieldVarOrClassName(expressionNameContext.getText(), expressionNameContext.getStart());
    }


    private Statement convert(Java8Parser.ClassInstanceCreationExpressionContext stmt) {
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) {
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.PreDecrementExpressionContext stmt) {
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.PostIncrementExpressionContext stmt) {
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.PostDecrementExpressionContext stmt) {
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.AssignmentContext stmt) {
        LocalVar leftHandSide = convert(stmt.leftHandSide());
        return new Assign(leftHandSide, convert(stmt.expression()), stmt.getStart());
    }

    private LocalVar convert(Java8Parser.LeftHandSideContext leftHandSide) {
        return new LocalVar(leftHandSide.toString(), leftHandSide.getStart());
    }

    private Statement convert(Java8Parser.IfThenStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.IfThenElseStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.IfThenElseStatementNoShortIfContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.AssertStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.SwitchStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.SwitchBlockContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.SwitchBlockStatementGroupContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.WhileStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.WhileStatementNoShortIfContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.DoStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ForStatementContext stmt){
        if(stmt.basicForStatement() != null){
            return convert(stmt.basicForStatement());
        }else if(stmt.enhancedForStatement() != null){
            return convert(stmt.enhancedForStatement());
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ForStatementNoShortIfContext stmt){
        if(stmt.basicForStatementNoShortIf() != null){
            return convert(stmt.basicForStatementNoShortIf());
        }else if(stmt.enhancedForStatementNoShortIf() != null){
            return convert(stmt.enhancedForStatementNoShortIf());
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.BasicForStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.BasicForStatementNoShortIfContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ForInitContext stmt){
        if(stmt.statementExpressionList() != null){
            return convert(stmt.statementExpressionList());
        }else if(stmt.localVariableDeclaration() != null){
            return convert(stmt.localVariableDeclaration());
        }else throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.LocalVariableDeclarationContext declaration) {
        List<LocalVarDecl> declarations = new ArrayList<>();
        if(declaration.variableModifier() != null && declaration.variableModifier().size() > 0){
            //TODO
        }
        RefTypeOrTPHOrWildcardOrGeneric type;
        if(declaration.unannType()==null){
            type = TypePlaceholder.fresh(declaration.getStart());
        }else{
            type = TypeGenerator.convert(declaration.unannType(), reg, generics);
        }
        for(Java8Parser.VariableDeclaratorContext varDecl : declaration.variableDeclaratorList().variableDeclarator()){
            TerminalNode name = varDecl.variableDeclaratorId().Identifier();
            declarations.add(new LocalVarDecl(name.getText(), type, name.getSymbol()));
            this.localVars.add(name.getText());
        }
        if(declarations.size()==1)return declarations.get(0);
        return new LocalVarBunchDeclaration(declarations, declaration.getStart());
    }

    private Statement convert(Java8Parser.ForUpdateContext stmt){
        return convert(stmt.statementExpressionList());
    }

    private Statement convert(Java8Parser.StatementExpressionListContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.EnhancedForStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.EnhancedForStatementNoShortIfContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.BreakStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ContinueStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ReturnStatementContext stmt){
        return new Return(convert(stmt.expression()),stmt.getStart());
        //throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.ThrowStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.SynchronizedStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.TryStatementContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.CatchesContext stmt){
        //TODO
        throw new NotImplementedException();
    }

    private Statement convert(Java8Parser.CatchClauseContext stmt){
        //TODO
        throw new NotImplementedException();
    }

/*
***************+ Expression Conversions:
 */

    private Expression convert(Java8Parser.ExpressionContext expression) {
        if(expression.lambdaExpression()!=null){
            return convert(expression.lambdaExpression());
        }else{
            return convert(expression.assignmentExpression());
        }
    }

    private Expression convert(Java8Parser.AssignmentExpressionContext expression) {
        if(expression.conditionalExpression() != null){
            return convert(expression.conditionalExpression());
        }else{
            return convert(expression.assignment());
        }
    }

    private Expression convert(Java8Parser.ConditionalExpressionContext expression) {
        if(expression.conditionalOrExpression() != null){
            return convert(expression.conditionalOrExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.ConditionalOrExpressionContext expression) {
        if(expression.conditionalOrExpression() == null){
            return convert(expression.conditionalAndExpression());
        }else{
            return new Binary(convert(expression.conditionalOrExpression()),
                    convert(expression.conditionalAndExpression()), new OrOp(null));
        }
    }

    private Expression convert(Java8Parser.ConditionalAndExpressionContext expression) {
        if(expression.conditionalAndExpression() == null){
            return convert(expression.inclusiveOrExpression());
        }else{
            return new Binary(convert(expression.conditionalAndExpression()),
                    convert(expression.inclusiveOrExpression()), new AndOp(null));
        }
    }

    private Expression convert(Java8Parser.InclusiveOrExpressionContext expression) {
        if(expression.inclusiveOrExpression() == null){
            return convert(expression.exclusiveOrExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.ExclusiveOrExpressionContext expression) {
        if(expression.exclusiveOrExpression() == null){
            return convert(expression.andExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.AndExpressionContext expression) {
        if(expression.andExpression() == null){
            return convert(expression.equalityExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.EqualityExpressionContext expression) {
        if(expression.equalityExpression() == null){
            return convert(expression.relationalExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.RelationalExpressionContext expression) {
        if(expression.relationalExpression() == null){
            return convert(expression.shiftExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.ShiftExpressionContext expression) {
        if(expression.shiftExpression() == null){
            return convert(expression.additiveExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.AdditiveExpressionContext expression) {
        if(expression.additiveExpression() == null){
            return convert(expression.multiplicativeExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.MultiplicativeExpressionContext expression) {
        if(expression.multiplicativeExpression() == null){
            return convert(expression.unaryExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.UnaryExpressionContext expression) {
        if(expression.preIncrementExpression() != null){
            return convert(expression.preIncrementExpression());
        }else if(expression.preDecrementExpression() != null){
            return convert(expression.preDecrementExpression());
        }else if(expression.unaryExpressionNotPlusMinus() != null){
            return convert(expression.unaryExpressionNotPlusMinus());
        }else if(expression.getText().startsWith("+")){
            return new UnaryPlus(convert(expression.unaryExpression()));
        }else if(expression.getText().startsWith("-")){
            return new UnaryMinus(convert(expression.unaryExpression()));
        }else{
            //Diese Exceptions sollte nie geworfen werden.
            //Der Code wurde nur noch nicht getestet. Sollte zur Sicherheit drin bleiben.
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.UnaryExpressionNotPlusMinusContext expression) {
        if(expression.postfixExpression() != null){
            return convert(expression.postfixExpression());
        }else if(expression.castExpression() != null){
            return convert(expression.castExpression());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.CastExpressionContext expressionContext) {
        Expression expr = null;
        if(expressionContext.unaryExpression() != null){
            throw new NotImplementedException();
        }else if(expressionContext.unaryExpressionNotPlusMinus() != null){
            expr = convert(expressionContext.unaryExpressionNotPlusMinus());
        }else if(expressionContext.lambdaExpression() != null){
            expr = convert(expressionContext.lambdaExpression());
        }
        return new CastExpr(TypeGenerator.convert(expressionContext.referenceType(), reg, generics),expr, expressionContext.getStart());
    }

    private Expression convert(Java8Parser.PostfixExpressionContext expression) {
        Expression expr;
        if(expression.primary() != null){
            expr = convert(expression.primary());
        }else{
            expr = convert(expression.expressionName());
        }
        if(expression.postDecrementExpression_lf_postfixExpression() == null &&
                expression.postIncrementExpression_lf_postfixExpression() == null){
            return expr;
        }

        for(Java8Parser.PostIncrementExpression_lf_postfixExpressionContext inc : expression.postIncrementExpression_lf_postfixExpression()){
            expr = new PostIncExpr(expr);
        }
        for(Java8Parser.PostDecrementExpression_lf_postfixExpressionContext dec : expression.postDecrementExpression_lf_postfixExpression()){
            expr = new PostDecExpr(expr);
        }

        return expr;
    }

    private Expression convert(Java8Parser.PrimaryContext primary) {
        Expression expr;
        if(primary.primaryNoNewArray_lfno_primary()!=null){
            expr = convert(primary.primaryNoNewArray_lfno_primary());
        }else{
            expr = convert(primary.arrayCreationExpression());
        }

        if(primary.primaryNoNewArray_lf_primary() != null && primary.primaryNoNewArray_lf_primary().size()>0){
            for(Java8Parser.PrimaryNoNewArray_lf_primaryContext e : primary.primaryNoNewArray_lf_primary()){
                expr = convert(expr, e);
            }
        }
        return expr;
    }

    private Expression convert(Expression expr, Java8Parser.PrimaryNoNewArray_lf_primaryContext e) {
        if(e.classInstanceCreationExpression_lf_primary() != null){
            throw new NotImplementedException();
        }else if(e.fieldAccess_lf_primary() != null){
            throw new NotImplementedException();
        }else if(e.arrayAccess_lf_primary() != null){
            throw new NotImplementedException();
        }else if(e.methodReference_lf_primary() != null){
            throw new NotImplementedException();
        }else {
            Java8Parser.MethodInvocation_lf_primaryContext ctxt = e.methodInvocation_lf_primary();
            String methodName = ctxt.Identifier().toString();
            return new MethodCall(new Receiver(expr), methodName, convert(ctxt.argumentList()), e.getStart());
        }
    }

    private Expression convert(Java8Parser.ArrayCreationExpressionContext expression) {
        throw new NotImplementedException();
    }

    private Expression convert(Java8Parser.PrimaryNoNewArray_lfno_primaryContext expression) {
        if(expression.literal() != null){
            return convert(expression.literal());
        }else if(expression.expression()!=null){
            return convert(expression.expression());
        }else if(expression.methodInvocation_lfno_primary() != null){
            return convert(expression.methodInvocation_lfno_primary());
        }else if(expression.classInstanceCreationExpression_lfno_primary() != null) {
            return convert(expression.classInstanceCreationExpression_lfno_primary());
        }else{
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.ClassInstanceCreationExpression_lfno_primaryContext newExpression) {
        if(newExpression.expressionName()!= null)throw new NotImplementedException();

        TerminalNode identifier = newExpression.Identifier(0);
        RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),identifier.getSymbol(),reg,generics);

        ArgumentList args = convert(newExpression.argumentList());
        return new NewClass(newClass, args, newExpression.getStart());
    }

    private Expression convert(Java8Parser.LiteralContext literal) {
        if(literal.IntegerLiteral() != null || literal.FloatingPointLiteral()!= null){
            Number value = Double.parseDouble(literal.IntegerLiteral().getText());
            return new NumberLiteral(TypePlaceholder.fresh(literal.getStart()),
                    value, literal.getStart());
        }else if(literal.BooleanLiteral() != null){
            RefType type = new RefType(reg.getName("java.lang.Boolean"),literal.getStart());
            return new BoolLiteral(type,
                    Boolean.parseBoolean(literal.BooleanLiteral().getText()),
                    literal.getStart());
        }else if(literal.CharacterLiteral() != null){
            RefType type = new RefType(reg.getName("java.lang.Character"),literal.getStart());
            return new CharLiteral(type,
                    literal.CharacterLiteral().getText().charAt(0),
                    literal.getStart());
        }else if(literal.StringLiteral()!=null){
            RefType type = new RefType(reg.getName("java.lang.String"),literal.getStart());
            return new StringLiteral(type,
                    literal.StringLiteral().getText(),
                    literal.getStart());
        }else  if(literal.NullLiteral() != null){
            return new Null(TypePlaceholder.fresh(literal.getStart()),
                    literal.getStart());
        }else {
            throw new NotImplementedException();
        }
    }

    private Expression convert(Java8Parser.MethodInvocation_lfno_primaryContext methodInvocationContext) {
        String name;
        if(methodInvocationContext.methodName()!=null){
            name = methodInvocationContext.methodName().Identifier().getText();
        }else{// if(methodInvocationContext.Identifier() != null){
            name = methodInvocationContext.Identifier().getText();
        }
        Expression receiver;
        if(methodInvocationContext.typeName() != null){
            receiver = generateLocalOrFieldVarOrClassName(methodInvocationContext.typeName().getText(), methodInvocationContext.typeName().getStart());
        }else if(methodInvocationContext.expressionName()!=null){
            receiver = convert(methodInvocationContext.expressionName());
        }else if(methodInvocationContext.toString().startsWith("super")) {
            receiver = new Super(methodInvocationContext.getStart());
        }else if(methodInvocationContext.methodName() != null){
            receiver = new This(methodInvocationContext.methodName().getStart());
        }else {
            throw new NotImplementedException();
        }

        ArgumentList argumentList = convert(methodInvocationContext.argumentList());
        MethodCall ret = new MethodCall(new Receiver(receiver), name, argumentList, methodInvocationContext.getStart());
        return ret;
    }

    private static Expression convert(Java8Parser.LambdaExpressionContext expression) {
        throw new NotImplementedException();
    }

}
