Package org.openquark.cal.internal.machine

Examples of org.openquark.cal.internal.machine.CodeGenerationException


        //System.out.println ("writing source file: " + file.getName());
        try {
            resourceRepository.setContents(targetFile, new ByteArrayInputStream(TextEncodingUtilities.getUTF8Bytes(source)));
       
        } catch (FileNotFoundException e) {
            throw new CodeGenerationException ("Unable to find file: " + targetFile.toString());
       
        } catch (IOException e) {
            throw new CodeGenerationException ("Error writing to file: " + targetFile.toString());
        }
    }
View Full Code Here


        if (label == null || module == null || body == null) {
            throw new IllegalArgumentException ("Unable to create SCJavaDefn due to null argument.");
        }

        if (LECCMachineConfiguration.isLeccRuntimeStatic() && label.isCodeGenerated()) {
            throw new CodeGenerationException ("Code already generated for: " + label.getQualifiedName());
        }

        //this.scar = scar;
        this.body = body;
        this.module = module;
View Full Code Here

                ecp = genS_C(methodBody, variableContext);
            } else
            if (scheme == Scheme.UNBOX_INTERNAL_SCHEME) {
                ecp = generateUnboxedArgument(typeExprToTypeName(resultType), methodBody, variableContext);
            } else {
                throw new CodeGenerationException("Invalid compilation scheme for let variable definition.");
            }

            // Emit let variables
            bodyCode.addStatement(variableContext.popJavaScope());
View Full Code Here

        // With changes to the compiler to lift inner case statements to their own function we
        // should never encounter a case at this level.
        // e is a case/switch?
        if (e.asSwitch() != null) {
            throw new CodeGenerationException  ("Encountered a case statement at an inner level.  schemeC.");
        }

        // Similarly, we should never encounter a data constructor field selection.
        if (e.asDataConsSelection() != null) {
            return generateDCFieldSelection(e.asDataConsSelection(), Scheme.C_SCHEME, variableContext);
            //throw new CodeGenerationException  ("Encountered a data constructor field selection at an inner level.  schemeC.");
        }

        // e is a let var.
        if (e.asLetNonRec() != null) {
            return generateLetNonRec(e.asLetNonRec(), Scheme.C_SCHEME, null, variableContext);
        }

        if (e.asLetRec() != null) {
            return generateLetRec(e.asLetRec(), Scheme.C_SCHEME, variableContext);
        }

        // e is an application?
        Expression.Appl appl = e.asAppl();
        if (appl != null) {
            ExpressionContextPair ecp = buildApplicationChain (appl, Scheme.C_SCHEME, variableContext);
            if (ecp == null) {
                // This is a general application
                ExpressionContextPair target = genS_C(appl.getE1(), variableContext);
                ExpressionContextPair arg = genS_C(appl.getE2(), variableContext);

                // Add the contexts for the target and the arg.
                Block newContextBlock = target.getContextBlock();
                newContextBlock.addStatement(arg.getContextBlock());

                ecp = new ExpressionContextPair(createInvocation(target.getJavaExpression(), APPLY, arg.getJavaExpression()), newContextBlock);
            }

            return ecp;
        }

        //e is a record update
        Expression.RecordUpdate recordUpdate = e.asRecordUpdate();
        if (recordUpdate != null) {
            return generateLazyRecordUpdate(recordUpdate, variableContext);
        }

        // e is a record extension
        Expression.RecordExtension recordExtension = e.asRecordExtension();
        if (recordExtension != null) {
            return generateLazyRecordExtension(recordExtension, variableContext);
        }

        // e is a record selection
        Expression.RecordSelection recordSelection = e.asRecordSelection();
        if (recordSelection != null) {
            return generateLazyRecordSelection(recordSelection, variableContext);
        }

        // e is an error info
        Expression.ErrorInfo errorInfo = e.asErrorInfo();
        if (errorInfo != null){
            return new ExpressionContextPair(createMakeKernelOpaqueInvocation(getErrorInfo(errorInfo)));
        }

        // e is a record case
        Expression.RecordCase recordCase = e.asRecordCase();
        if (recordCase != null) {
            throw new CodeGenerationException ("Encountered a record-case statement at an inner level.  schemeC.");
        }

        throw new CodeGenerationException ("Unhandled expression of type " + e.getClass().getName() + " encountered in C scheme.");
    }
View Full Code Here

        // With the changes to the compiler to lift inner cases into their own function
        // we should never encounte a case at this level.
        // Expression is a case/switch?
        if (e.asSwitch() != null) {
            throw new CodeGenerationException ("Encountered a case statement that wasn't at top level in schemeE.");
        }

        // Similarly, we should never encounter a data constructor field selection.
        if (e.asDataConsSelection() != null) {
            return generateDCFieldSelection(e.asDataConsSelection(), Scheme.E_SCHEME, variableContext);
            //throw new CodeGenerationException  ("Encountered a data constructor field selection at an inner level.  schemeE.");
        }

        // R is a let var.
        if (e.asLetNonRec() != null) {
            return generateLetNonRec (e.asLetNonRec(), Scheme.E_SCHEME, null, variableContext);
        }
        if (e.asLetRec() != null) {
            return generateLetRec (e.asLetRec(), Scheme.E_SCHEME, variableContext);
        }

        // R is an application?
        Expression.Appl appl = e.asAppl();
        if (appl != null) {
            ExpressionContextPair ecp = buildApplicationChain (appl, Scheme.E_SCHEME, variableContext);
            if (ecp == null) {

                // This is a general application
                ExpressionContextPair target = genS_C(appl.getE1(), variableContext);
                ExpressionContextPair arg = genS_C(appl.getE2(), variableContext);

                Block newContextBlock = target.getContextBlock();
                newContextBlock.addStatement(arg.getContextBlock());

                MethodInvocation applyMI = createInvocation(target.getJavaExpression(), APPLY, arg.getJavaExpression());
                MethodInvocation evaluateMI = createInvocation(applyMI, EVALUATE, EXECUTION_CONTEXT_VAR);//, ExecutionContextClassName));

                ecp = new ExpressionContextPair(evaluateMI, newContextBlock);
            }

            return ecp;
        }

        //e is a record update
        Expression.RecordUpdate recordUpdate = e.asRecordUpdate();
        if (recordUpdate != null) {
            return generateStrictRecordUpdate(recordUpdate, variableContext);
        }

        // e is a record extension
        Expression.RecordExtension recordExtension = e.asRecordExtension();
        if (recordExtension != null) {
            return generateStrictRecordExtension(recordExtension, variableContext);
        }

        // e is a record selection
        Expression.RecordSelection recordSelection = e.asRecordSelection();
        if (recordSelection != null) {
            return generateStrictRecordSelection(recordSelection, true, variableContext);
        }

        // e is an error info
        Expression.ErrorInfo errorInfo = e.asErrorInfo();
        if (errorInfo != null){
            return new ExpressionContextPair(createMakeKernelOpaqueInvocation(getErrorInfo(errorInfo)));
        }

        // e is a record case
        Expression.RecordCase recordCase = e.asRecordCase();
        if (recordCase != null) {
            throw new CodeGenerationException ("Encountered a record-case statement at an inner level.  schemeE.");
        }

        return new ExpressionContextPair(LiteralWrapper.make("Can't handle this expression."));
    }
View Full Code Here

    private JavaStatement genS_R(Expression e, VariableContext variableContext) throws CodeGenerationException {

        // e is a pack constructor?
        if (e.asPackCons() != null) {
            //This is an error!  We should never be at this point with a data constructor expression.
            throw new CodeGenerationException ("PackCons expression encountered in R scheme: " + e.asPackCons().getDataConstructor().getName());
        }

        // R is a literal?
        Expression.Literal lit = e.asLiteral();
        if (lit != null) {
            return generateReturn (getKernelLiteral(lit.getLiteral()).getBoxedReference(), variableContext);
        }

        // Is e a call to a let variable definition function?
        ExpressionContextPair letVarECP = buildLetVarDefCall(e, Scheme.C_SCHEME, variableContext);
        if (letVarECP != null) {
            return generateReturn(letVarECP, variableContext);
        }

        // Is e a primitive operation (arithmetic, comparative etc.)?
        {
            BasicOpTuple bop = BasicOpTuple.isBasicOp(e);
            if (!LECCMachineConfiguration.generateDirectPrimOpCalls()) {

                // When we are generating call chains we want to force all primitive operations
                // to be done as a function call to the generated function.

                //When we have function tracing enabled, we want to force all primitive operations to be
                //done as function calls. This will have the effect of ensuring that they get traced when called.

                if (bop != null && !bop.getName().equals(getQualifiedName())) {
                    bop = null;
                }
            }

            if (bop != null) {
                ExpressionContextPair ecPair = generatePrimitiveOp(e, true, Scheme.R_SCHEME, variableContext);
                return generateReturn (ecPair, variableContext);
            }
        }

        // We can potentially optimize an application of not to use the Java ! operator.
        // Because we are directly evaluating and circumventing laziness it is only safe
        // to do this if there is no chance of a directly/indirectly recursive call.
        if (isNot(e) && !ExpressionAnalyzer.dependsOnStronglyConnectedComponent(e, connectedComponents, getModuleName())) {
            ExpressionContextPair ecPair = generateNot (e.asAppl(), true, variableContext);
            return generateReturn(ecPair, variableContext);
        }

        // Is e an application of 'and' or 'or'?  Test only - don't get tuple
        if (BasicOpTuple.isAndOr(e) != null) {
            ExpressionContextPair ecPair = generateAndOr(e, true, variableContext);
            return generateReturn(ecPair, variableContext);
        }

        // Is e an application of a saturated constructor?
        ConstructorOpTuple constructorOpTuple = ConstructorOpTuple.isConstructorOp(e, false);
        if (constructorOpTuple != null) {
            if (codeGenerationStats != null) {
                codeGenerationStats.incrementFullySaturatedDCInTopLevelContext(constructorOpTuple.getDataConstructor().getName());
            }
            ExpressionContextPair ecPair = generateDataConstructor(constructorOpTuple, Scheme.R_SCHEME, variableContext);
            return generateReturn(ecPair, variableContext);
        }

        // Is e a tail recursive call?
        if (e.asTailRecursiveCall() != null) {
            // We don't need to call generateReturn() at this point since a this
            // expression will generate a loop continuation, not a 'return'.
            return buildTailRecursiveLoopCall(e.asTailRecursiveCall(), variableContext);
        }

        // R is a variable?
        if (e.asVar() != null) {
            Expression.Var var = e.asVar();
            JavaExpression varExpression = expressionVarToJavaDef(var, Scheme.R_SCHEME, variableContext);

            // If the variable is already evaluated we want to call getValue(), which will follow any
            // indirection chains and return the final value.  However, if we are simply returning
            // a strict unboxed function argument this isn't necessary.
            if (variableContext.isLocalVariable(var.getName()) &&
                variableContext.isVarPreEvaluated(var.getName()) &&
                (!variableContext.isFunctionArgument(var.getName()) || !isArgUnboxable(var.getName()))) {
                // Variable is already evaluated so simply do a 'getValue()' on it.
                varExpression = new MethodInvocation.Instance(varExpression, "getValue", JavaTypeNames.RTVALUE, MethodInvocation.InvocationType.VIRTUAL);
            }

            return generateReturn(varExpression, variableContext);
        }

        // Is e a conditional op (if <cond expr> <then expr> <else expr>)?
        // Since this is the top level compilation scheme we can generate an actual 'if' statement.
        CondTuple conditionExpressions = CondTuple.isCondOp(e);
        if (conditionExpressions != null) {
            if (codeGenerationStats != null) {
                codeGenerationStats.incrementOptimizedIfThenElse();
            }

            // This is a conditional op.  The conditionExpressions tuple holds (kCond, kThen, kElse) expressions
            // Generate the code for kThen and kElse, as arguments to a new I_Cond instruction

            Expression condExpression = conditionExpressions.getConditionExpression();
            ExpressionContextPair pair = generateUnboxedArgument(JavaTypeName.BOOLEAN, condExpression, variableContext);

            // Then
            variableContext.pushJavaScope();
            JavaStatement thenPart = genS_R (conditionExpressions.getThenExpression(), variableContext);

            Block thenBlock = variableContext.popJavaScope();
            thenBlock.addStatement(thenPart);

            // Else
            variableContext.pushJavaScope();
            JavaStatement elsePart = genS_R (conditionExpressions.getElseExpression(), variableContext);

            Block elseBlock = variableContext.popJavaScope();
            elseBlock.addStatement(elsePart);

            JavaExpression conditionExpression = pair.getJavaExpression();

            JavaStatement ite = new IfThenElseStatement(conditionExpression, thenBlock, elseBlock);

            Block contextBlock = pair.getContextBlock();
            contextBlock.addStatement(ite);

            // We don't need to call generateReturn() at this point.  Any return statements
            // will have been generated in the sub-parts of the if-then-else.
            return contextBlock;
        }


        // Expression is a case/switch?
        Expression.Switch eswitch = e.asSwitch();
        if (eswitch != null) {
            // We don't need to call generateReturn() at this point.  Any return statements
            // will have been generated in the sub-parts of the switch.
            return generateSwitch (eswitch, variableContext);
        }

        // Expression is a data constructor field selection?
        Expression.DataConsSelection eDCSelection = e.asDataConsSelection();
        if (eDCSelection != null) {
             return generateReturn(generateDCFieldSelection(eDCSelection, Scheme.R_SCHEME, variableContext), variableContext);
        }

        // e is a let var.
        if (e.asLetNonRec() != null) {
            return generateReturn (generateLetNonRec(e.asLetNonRec(), Scheme.R_SCHEME, null, variableContext), variableContext);
        }

        if (e.asLetRec() != null) {
            return generateReturn(generateLetRec(e.asLetRec(), Scheme.R_SCHEME, variableContext), variableContext);
        }

        // e is an application?
        Expression.Appl appl = e.asAppl();
        if (appl != null) {
            JavaStatement topLevelSeq = buildTopLevelSeq (appl, false, variableContext);
            if (topLevelSeq != null) {
                return topLevelSeq;
            }
            ExpressionContextPair ecp = buildApplicationChain (appl, Scheme.R_SCHEME, variableContext);
            if (ecp != null) {
                return generateReturn(ecp, variableContext);
            } else {

                // This is a general application
                ExpressionContextPair target;
                if (appl.getE1().asDataConsSelection() != null) {
                    target = generateDCFieldSelection(appl.getE1().asDataConsSelection(), Scheme.E_SCHEME, variableContext);
                } else {
                    target = genS_C(appl.getE1(), variableContext);
                }
                ExpressionContextPair arg = genS_C(appl.getE2(), variableContext);

                JavaStatement.Block returnBlock = target.getContextBlock();
                returnBlock.addStatement(arg.getContextBlock());

                MethodInvocation mi = createInvocation(target.getJavaExpression(), APPLY, arg.getJavaExpression());
                return generateReturn (new ExpressionContextPair(mi, returnBlock), variableContext);
            }
        }

        //e is a record update
        Expression.RecordUpdate recordUpdate = e.asRecordUpdate();
        if (recordUpdate != null) {
            ExpressionContextPair ecPair = generateStrictRecordUpdate(recordUpdate, variableContext);
            return generateReturn(ecPair, variableContext);
        }

        // e is a record extension
        Expression.RecordExtension recordExtension = e.asRecordExtension();
        if (recordExtension != null) {

            ExpressionContextPair ecPair = generateStrictRecordExtension(recordExtension, variableContext);
            return generateReturn(ecPair, variableContext);
        }

        // e is a record selection
        Expression.RecordSelection recordSelection = e.asRecordSelection();
        if (recordSelection != null) {
            return generateReturn(generateStrictRecordSelection(recordSelection, true, variableContext), variableContext);
        }

        // e is a record case
        Expression.RecordCase recordCase = e.asRecordCase();
        if (recordCase != null) {
            return generateRecordCase (recordCase, variableContext);
        }

        // e is a cast
        Expression.Cast cast = e.asCast();
        if (cast != null) {
            Expression.Var varToCast = cast.getVarToCast();
            if (!variableContext.isFunctionArgument(varToCast.getName())) {
                throw new CodeGenerationException("Expression.Cast is applied to a non-argument variable.");
            }
            if (!isArgStrict(varToCast.getName()) || !isArgUnboxable(varToCast.getName())) {
                throw new CodeGenerationException("Expression.Cast is applied to a non-strict or non-primitive argument.");
            }

            JavaTypeName castType = JavaTypeName.make (getCastType(cast));

            JavaExpression returnVal = boxExpression(castType, new JavaExpression.CastExpression(castType, variableContext.getUnboxedReference(varToCast.getName())));
            return generateReturn(returnVal, variableContext);

        }

        throw new CodeGenerationException("Unrecognized expression: " + e);
    }
View Full Code Here

                recordUpdateBlock);
        }


        //the empty record update is not allowed (should be caught by static checks).
        throw new CodeGenerationException("The empty record update is not allowed.");
    }
View Full Code Here

     * @throws CodeGenerationException
     */
    private KernelLiteral getKernelLiteral(Object object) throws CodeGenerationException {
        KernelLiteral kl = sharedValues.getKernelLiteral(object);
        if (kl == null) {
            throw new CodeGenerationException ("Reference to unknown literal value: " + object.toString());
        }

        return kl;

    }
View Full Code Here

        }

        if (LECCMachineConfiguration.TREAT_ENUMS_AS_INTS) {
            if (isEnumDataType(dc)) {
                // We should never see a DataConstructor instance for an enumeration type.
                throw new CodeGenerationException("Encountered enumeration data constructor: " + dc.getName().getQualifiedName());
            }
        }

        int arity = dc.getArity();

        JavaTypeName dcTypeName = CALToJavaNames.createTypeNameFromDC(dc, module);
        Block argContext = new Block();

        boolean[] fieldStrictness = new boolean [dc.getArity()];
        boolean dcHasStrictFields = false;
        if (LECCMachineConfiguration.IGNORE_STRICTNESS_ANNOTATIONS) {
            Arrays.fill(fieldStrictness, false);
        } else {
            for (int i = 0; i < dc.getArity(); ++i) {
                fieldStrictness[i] = dc.isArgStrict(i);
                if (fieldStrictness[i]) {
                    dcHasStrictFields = true;
                }
            }
        }

        // If there are no strict arguments we can simply create an instance of the DC class.
        // The simplest way to do this is to treat this DC application as if it were in a strict context.
        if (!dcHasStrictFields) {
            scheme = Scheme.E_SCHEME;
        } else {
            // If all strict arguments are already evaluated, or we consider them safe to evaluate (i.e. cheap and
            // with no side effects) we can treat this as strict.
            boolean allOK = true;
            for (int i = 0; i < dc.getArity(); ++i) {
                if (dc.getArgStrictness()[i] && !canIgnoreLaziness(constructorOpExpressions.getArgument(i), variableContext)) {
                    allOK = false;
                    break;
                }
            }

            if (allOK) {
                scheme = Scheme.E_SCHEME;
            }
        }

        if (arity < 0) {
            throw new CodeGenerationException("Invalid constructor operator arity: " + arity);
        } else
        if (arity == 0) {
            JavaExpression dcInstance;
            JavaTypeName typeName = CALToJavaNames.createTypeNameFromDC(dc, module);
            if (LECCMachineConfiguration.generateStatistics()) {
View Full Code Here

                       kind == ForeignFunctionInfo.JavaKind.NARROWING_REFERENCE_CAST) {

                returnExpression = new JavaExpression.CastExpression(JavaTypeName.make(resultType), argExpr);

            } else {
                throw new CodeGenerationException("Unrecognized foreign function cast kind: " + kind);
            }

            if (boxResult) {
                ExpressionContextPair pair = returnTypeToCal(resultType, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind.isInstanceOf()) {

            final Class<?> argType = SCJavaDefn.getJavaArgumentType(foreignFunctionInfo, 0);
            final ForeignFunctionInfo.InstanceOf instanceOfInfo = (ForeignFunctionInfo.InstanceOf)foreignFunctionInfo;
            final Class<?> instanceOfType = SCJavaDefn.getInstanceOfType(instanceOfInfo);

            final ExpressionContextPair argExprPair = generateUnboxedForeignFunctionArgument(JavaTypeName.make(argType), basicOpExpressions.getArgument(0), variableContext);
            final JavaExpression argExpr = argExprPair.getJavaExpression();
            returnContext.addStatement(argExprPair.getContextBlock());

            returnExpression = new JavaExpression.InstanceOf(argExpr, JavaTypeName.make(instanceOfType));

            if (boxResult) {
                ExpressionContextPair pair = returnTypeToCal(boolean.class, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind.isClassLiteral()) {

            final ForeignFunctionInfo.ClassLiteral classLiteralInfo = (ForeignFunctionInfo.ClassLiteral)foreignFunctionInfo;
            final Class<?> referentType = SCJavaDefn.getReferentType(classLiteralInfo);

            returnExpression = new JavaExpression.ClassLiteral(JavaTypeName.make(referentType));

            if (boxResult) {
                ExpressionContextPair pair = returnTypeToCal(Class.class, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind.isNullLiteral()) {

            returnExpression = JavaExpression.LiteralWrapper.NULL;
            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(SCJavaDefn.getJavaReturnType(foreignFunctionInfo), returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind.isNullCheck()) {

            final ForeignFunctionInfo.NullCheck nullCheckInfo = (ForeignFunctionInfo.NullCheck)foreignFunctionInfo;

            final Class<?> argType = SCJavaDefn.getJavaArgumentType(foreignFunctionInfo, 0);

            final ExpressionContextPair argExprPair = generateUnboxedForeignFunctionArgument(JavaTypeName.make(argType), basicOpExpressions.getArgument(0), variableContext);
            final JavaExpression argExpr = argExprPair.getJavaExpression();
            returnContext.addStatement(argExprPair.getContextBlock());

            final JavaOperator javaOp = nullCheckInfo.checkIsNull() ? JavaOperator.EQUALS_OBJECT : JavaOperator.NOT_EQUALS_OBJECT;

            returnExpression = new JavaExpression.OperatorExpression.Binary(javaOp, argExpr, LiteralWrapper.NULL);

            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(boolean.class, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind == ForeignFunctionInfo.JavaKind.NEW_ARRAY) {

            //e.g. newString3Array :: Int -> Int -> JString3Array; (for new String[d1][d2][])

            //note, this may be less than the dimension of the array e.g. for new String[10][7][] this is 2.
            final int nJavaArgs = SCJavaDefn.getNArguments(foreignFunctionInfo);
            final Class<?> newArrayType = SCJavaDefn.getJavaReturnType(foreignFunctionInfo);

            final JavaExpression[] args = new JavaExpression[nJavaArgs];
            final JavaTypeName[] argTypeNames = new JavaTypeName[nJavaArgs];
            for (int i = 0; i < nJavaArgs; i++) {
                final ExpressionContextPair pair = generateUnboxedForeignFunctionArgument(JavaTypeName.INT, basicOpExpressions.getArgument(i), variableContext);
                args[i] = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
                argTypeNames[i] = JavaTypeName.INT;
            }

            returnExpression = new ClassInstanceCreationExpression(JavaTypeName.make(newArrayType), args, argTypeNames);

            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(newArrayType, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind == ForeignFunctionInfo.JavaKind.LENGTH_ARRAY) {

            final Class<?> argType = SCJavaDefn.getJavaArgumentType(foreignFunctionInfo, 0);

            final ExpressionContextPair argExprPair = generateUnboxedForeignFunctionArgument(JavaTypeName.make(argType), basicOpExpressions.getArgument(0), variableContext);
            final JavaExpression argExpr = argExprPair.getJavaExpression();
            returnContext.addStatement(argExprPair.getContextBlock());

            returnExpression = new JavaExpression.ArrayLength(argExpr);

            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(int.class, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);


        } else if (kind == ForeignFunctionInfo.JavaKind.SUBSCRIPT_ARRAY) {

            //e.g. subscriptString3Array :: String3Array -> Int -> Int -> StringArray;
            //for subscripting using 2 indices a 3-dimensional String array to get a 1-dimensional String array

            //note, this may be less than the dimension of the array e.g. for new String[10][7][] this is 2.
            final int nJavaArgs = SCJavaDefn.getNArguments(foreignFunctionInfo);
            final Class<?> subscriptedArrayType = SCJavaDefn.getJavaReturnType(foreignFunctionInfo);

            for (int i = 0; i < nJavaArgs; i++) {

                final JavaTypeName argTypeName = JavaTypeName.make(SCJavaDefn.getJavaArgumentType(foreignFunctionInfo, i));
                final ExpressionContextPair pair =
                    generateUnboxedForeignFunctionArgument(argTypeName, basicOpExpressions.getArgument(i), variableContext);
                returnContext.addStatement(pair.getContextBlock());

                if (i == 0) {
                    //the initial array expression
                    returnExpression = pair.getJavaExpression();
                } else {
                    //subscript by the next index
                    returnExpression = new JavaExpression.ArrayAccess(returnExpression, pair.getJavaExpression());
                }
            }

            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(subscriptedArrayType, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);

        } else if (kind == ForeignFunctionInfo.JavaKind.UPDATE_ARRAY) {

            //e.g. updateString3Array :: String3Array -> Int -> Int -> StringArray -> StringArray;
            //for updating using 2 indices a 3-dimensional String array with a 1-dimensional String array

            //note, this may be less than the dimension of the array to update
            final int nJavaArgs = SCJavaDefn.getNArguments(foreignFunctionInfo);
            final Class<?> updatedElementType = SCJavaDefn.getJavaReturnType(foreignFunctionInfo);

            for (int i = 0; i < nJavaArgs; i++) {

                final JavaTypeName argTypeName = JavaTypeName.make(SCJavaDefn.getJavaArgumentType(foreignFunctionInfo, i));
                final ExpressionContextPair pair =
                    generateUnboxedForeignFunctionArgument(argTypeName, basicOpExpressions.getArgument(i), variableContext);
                returnContext.addStatement(pair.getContextBlock());

                if (i == 0) {

                    //the initial array expression
                    returnExpression = pair.getJavaExpression();

                } else if (i < nJavaArgs - 1) {

                    //subscript by the next index
                    returnExpression = new JavaExpression.ArrayAccess(returnExpression, pair.getJavaExpression());

                } else if (i == nJavaArgs - 1) {

                    returnExpression = new JavaExpression.Assignment((JavaExpression.Nameable)returnExpression, pair.getJavaExpression());

                }
            }


            if (boxResult) {
                final ExpressionContextPair pair = returnTypeToCal(updatedElementType, returnExpression);
                returnExpression = pair.getJavaExpression();
                returnContext.addStatement(pair.getContextBlock());
            }

            return new ExpressionContextPair(returnExpression, returnContext);
        }

        throw new CodeGenerationException("Unrecognized foreign function kind: " + kind);
    }
View Full Code Here

TOP

Related Classes of org.openquark.cal.internal.machine.CodeGenerationException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.