Package org.openquark.cal.internal.javamodel

Examples of org.openquark.cal.internal.javamodel.JavaMethod


         *         return "ModuleName";
         *     }
         *
         */
        private void createMethod_getModuleName () {
            JavaMethod javaMethod = new JavaMethod (Modifier.PUBLIC | Modifier.FINAL, JavaTypeName.STRING, "getModuleName");
            javaClassRep.addMethod (javaMethod);

            javaMethod.addStatement (new ReturnStatement (LiteralWrapper.make (dc.getName().getModuleName().toSourceText())));
        }
View Full Code Here


         *         return "unqualifiedName";
         *     }
         *
         */
        private void createMethod_getUnqualifiedName () {
            JavaMethod javaMethod = new JavaMethod (Modifier.PUBLIC | Modifier.FINAL, JavaTypeName.STRING, "getUnqualifiedName");
            javaClassRep.addMethod (javaMethod);

            javaMethod.addStatement (new ReturnStatement (LiteralWrapper.make (dc.getName().getUnqualifiedName())));
        }
View Full Code Here

         *    public final String getQualifiedName () {
         *        return "Module.unqualifiedName";
         *    }
         */
        private final void createMethod_getQualifiedName () {
            JavaMethod jm = new JavaMethod (Modifier.PUBLIC | Modifier.FINAL, JavaTypeName.STRING, "getQualifiedName");
            javaClassRep.addMethod(jm);
            jm.addStatement(new ReturnStatement(LiteralWrapper.make(dc.getName().getQualifiedName())));
        }
View Full Code Here

            //the generated code is:
            //public final boolean isFunctionSingleton() {
            //    return this == $instance;
            //}

            JavaMethod javaMethod = new JavaMethod (Modifier.PUBLIC | Modifier.FINAL, JavaTypeName.BOOLEAN, "isFunctionSingleton");
            javaClassRep.addMethod (javaMethod);

            JavaExpression conditionExpr =
                new OperatorExpression.Binary(
                    JavaOperator.EQUALS_OBJECT,
                    new JavaExpression.JavaField.This(className),
                    new JavaExpression.JavaField.Static(className, "$instance", className));

            JavaStatement returnStatement =
                new JavaStatement.ReturnStatement(conditionExpr);

            javaMethod.addStatement(returnStatement);
        }
View Full Code Here

            //    }
            //}

            //for strict primitive fields, we generate stuff like "return CAL_Int.make(field)" instead.

            JavaMethod method = new JavaMethod (Modifier.PUBLIC | Modifier.FINAL, JavaTypeName.CAL_VALUE, "childN", JavaTypeName.INT, false, "debug_getChild");
            javaClassRep.addMethod (method);

            MethodVariable childNVar = new JavaExpression.MethodVariable("childN");

            {
                //    if (isFunctionSingleton()) {
                //        throw new IndexOutOfBoundsException();
                //    }

                JavaExpression conditionExpr =
                    new MethodInvocation.Instance(null, "isFunctionSingleton", JavaTypeName.BOOLEAN, MethodInvocation.InvocationType.VIRTUAL);

                JavaStatement thenStatement =
                    new JavaStatement.ThrowStatement(
                        new JavaExpression.ClassInstanceCreationExpression(JavaTypeName.INDEX_OUT_OF_BOUNDS_EXCEPTION));

                JavaStatement.IfThenElseStatement ifThenStatement =
                    new JavaStatement.IfThenElseStatement (conditionExpr, thenStatement);

                method.addStatement(ifThenStatement);
            }

            SwitchStatement switchStatement =
                new SwitchStatement(childNVar);

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

                TypeExpr calFieldType = fieldTypes[i];
                String javaFieldName = javaFieldNames[i];

                JavaExpression javaFieldExpr;
                if (fieldStrictness[i] && SCJavaDefn.canTypeBeUnboxed(calFieldType)) {
                    JavaTypeName javaFieldType = SCJavaDefn.typeExprToTypeName(calFieldType);
                    javaFieldExpr = new JavaExpression.JavaField.Instance(null, javaFieldName, javaFieldType);
                    javaFieldExpr = SCJavaDefn.boxExpression(javaFieldType, javaFieldExpr);
                } else {
                    javaFieldExpr = new JavaExpression.JavaField.Instance(null, javaFieldName, JavaTypeNames.RTVALUE);
                }

                switchStatement.addCase(
                    new SwitchStatement.IntCaseGroup(i, new ReturnStatement(javaFieldExpr)));
            }

            switchStatement.addCase(
                new SwitchStatement.DefaultCase(
                    new JavaStatement.ThrowStatement(
                        new JavaExpression.ClassInstanceCreationExpression(JavaTypeName.INDEX_OUT_OF_BOUNDS_EXCEPTION))));

            method.addStatement(switchStatement);
        }
View Full Code Here


            int modifiers = Modifier.PUBLIC | Modifier.FINAL;

            // Add the method to the class.
            JavaMethod javaMethod = new JavaMethod(modifiers, JavaTypeNames.RTVALUE, new String[]{"deepSeq", "rhs"}, new JavaTypeName[]{JavaTypeNames.RTSUPERCOMBINATOR, JavaTypeNames.RTVALUE}, null, "buildDeepSeq");
            javaClassRep.addMethod(javaMethod);

            // Add the throws declaration
            javaMethod.addThrows(JavaTypeName.CAL_EXECUTOR_EXCEPTION);

            // Add the method body.
            // Evaluate each child.
            JavaExpression rhs = METHODVAR_RHS;

            for (int i = dc.getArity() - 1; i >= 0; --i) {
                if (fieldStrictness[i] && !SCJavaDefn.typeExprToTypeName(fieldTypes[i]).equals(JavaTypeNames.RTVALUE)) {
                    // Strict primitive/foreign types don't need to have anything done.
                    continue;
                }

                // We want to build up an expression like:
                // deepSeq(field1 (deepSeq field2 (deepSeq field3 rhs)))
                // However, for non-strict fields we want to access them via the get_field accessor
                // to ensure the compacting of any indirection chains.
                JavaExpression deepSeqArgs[] = new JavaExpression [2];
                if (fieldStrictness[i]) {
                    deepSeqArgs[0] = new JavaField.Instance(null, javaFieldNames[i], JavaTypeNames.RTVALUE);
                } else {
                    deepSeqArgs[0] = new MethodInvocation.Instance(null, "get"+javaFieldNames[i], JavaTypeNames.RTVALUE, MethodInvocation.InvocationType.VIRTUAL);
                }
                deepSeqArgs[1] = rhs;
                rhs = SCJavaDefn.createApplyInvocation(METHODVAR_DEEPSEQ, deepSeqArgs);
            }

            javaMethod.addStatement(new ReturnStatement(rhs));

        }
View Full Code Here

                   
                    final Pair<List<ClassTypeInfo>, ClassTypeInfo> argTypesAndReturnType = getArgTypesAndReturnTypeForLibraryMethod(functionalAgentType);
                    final List<ClassTypeInfo> argTypes = argTypesAndReturnType.fst();
                    final ClassTypeInfo returnType = argTypesAndReturnType.snd();
                   
                    final JavaMethod unboxedArgsVariant =
                        makeLibraryMethod(module, functionalAgent, functionalAgentType, argTypes, returnType, scopedEntityNamingPolicy, crossRefGen, methodNameMapping);
                   
                    classRep.addMethod(unboxedArgsVariant);
                   
                    if (hasNonCalValueArgument(argTypes)) {
                        // The first method has at least one unboxed/foreign argument, so we create a second version
                        // that takes all arguments as CalValues
                       
                        final int nArgs = argTypes.size();
                        final List<ClassTypeInfo> calValueArgTypes = new ArrayList<ClassTypeInfo>();
                        for (int i = 0; i < nArgs; i++) {
                            calValueArgTypes.add(ClassTypeInfo.makeNonForeign());
                        }
                       
                        final JavaMethod calValueArgsVariant =
                            makeLibraryMethod(module, functionalAgent, functionalAgentType, calValueArgTypes, returnType, scopedEntityNamingPolicy, crossRefGen, methodNameMapping);
                       
                        classRep.addMethod(calValueArgsVariant);
                    }
                } else {
                    // Report that the functional agent was skipped because its type contains type class constraints
                    if (functionalAgent instanceof ClassMethod) {
                        monitor.skippingClassMethod(functionalAgent.getName());
                    } else {
                        // an overloaded functional agent is really either a class method or a function, and never a data cons
                        monitor.skippingFunctionWithTypeClassConstraints(functionalAgent.getName());
                    }
                }
            }
        }
       
        // Add the Javadoc
        classRep.setJavaDoc(
            new JavaDocComment(CALDocToJavaDocUtilities.getJavadocFromCALDocComment(
                moduleTypeInfo.getCALDocComment(), true, null, null, null,
                scopedEntityNamingPolicy, crossRefGen, true, true, false, true)));

        ////
        /// Add the static check
        //
       
        // Code fragment:
        //
        // private static boolean __checkConfig()
        //
        final JavaMethod checkConfigMethod = new JavaMethod(Modifier.PRIVATE|Modifier.STATIC, JavaTypeName.BOOLEAN, "__checkConfig");
       
        ////
        /// The classes in the standalone JAR are generated with the machine configuration at "build time".
        /// We capture this configuration into a StandaloneJarGeneratedCodeInfo, to be checked at runtime
        /// against the machine configuration then.
        //
       
        final JavaStatement.LocalVariableDeclaration generatedCodeInfoDecl = makeGeneratedCodeInfoDecl();
        final JavaExpression.LocalVariable generatedCodeInfoLocalVar = generatedCodeInfoDecl.getLocalVariable();
        checkConfigMethod.addStatement(generatedCodeInfoDecl);

        //
        // Code fragment:
        //
        // if (!generatedCodeInfo.isCompatibleWithCurrentConfiguration()) {
        //     throw new IllegalStateException(generatedCodeInfo.getConfigurationHints());
        // } else {
        //     return true;
        // }
        //
        final JavaStatement.Block configCheckFailureBody = new JavaStatement.Block();
       
        configCheckFailureBody.addStatement(
            new JavaStatement.ThrowStatement(
                new JavaExpression.ClassInstanceCreationExpression(
                    JavaTypeName.make(IllegalStateException.class),
                    new JavaExpression.MethodInvocation.Instance(
                        generatedCodeInfoLocalVar,
                        "getConfigurationHints",
                        JavaTypeName.STRING,
                        JavaExpression.MethodInvocation.InvocationType.VIRTUAL),
                    JavaTypeName.STRING)));
       
        final JavaStatement configCheckSuccessBody = new JavaStatement.ReturnStatement(JavaExpression.LiteralWrapper.TRUE);
       
        final JavaStatement configCheck =
            new JavaStatement.IfThenElseStatement(
                new JavaExpression.OperatorExpression.Unary(
                    JavaOperator.LOGICAL_NEGATE,
                    new JavaExpression.MethodInvocation.Instance(
                        generatedCodeInfoLocalVar,
                        "isCompatibleWithCurrentConfiguration",
                        JavaTypeName.BOOLEAN,
                        JavaExpression.MethodInvocation.InvocationType.VIRTUAL)),
                configCheckFailureBody,
                configCheckSuccessBody);
       
        checkConfigMethod.addStatement(configCheck);
       
        classRep.addMethod(checkConfigMethod);

        // Code fragment:
        //
        // private static final boolean isCompatibleWithCurrentConfiguration = __checkConfig();
        //
        final JavaFieldDeclaration isCompatibleWithCurrentConfigurationField = new JavaFieldDeclaration(
            Modifier.PRIVATE|Modifier.STATIC|Modifier.FINAL,
            JavaTypeName.BOOLEAN,
            "isCompatibleWithCurrentConfiguration",
            new JavaExpression.MethodInvocation.Static(
                libClassName, checkConfigMethod.getMethodName(), new JavaExpression[0], new JavaTypeName[0], JavaTypeName.BOOLEAN));
       
        classRep.addFieldDeclaration(isCompatibleWithCurrentConfigurationField);
       
        // We are finished with building the class.
        return classRep;
View Full Code Here

            methodReturnTypeName = JavaTypeName.VOID;
        } else {
            methodReturnTypeName = returnType.getExposedTypeName();
        }
       
        final JavaMethod method = new JavaMethod(
            modifier,
            methodReturnTypeName,
            methodArgNames.toArray(new String[nMethodArgs]),
            methodArgTypeNames.toArray(new JavaTypeName[nMethodArgs]),
            finalFlags,
            methodName);
       
        if (isUnitResultType) {
            // Code fragment:
            //
            // {functional agent's instance}
            //     .apply({marshalled arg #1}, ... {marshalled arg #4})
            //       ...
            //     .apply(... {marshalled arg #n})
            //     .evaluate(executionContext);
            method.addStatement(new JavaStatement.ExpressionStatement(resultExpr));
           
        } else if (isLiteralResult) {
            // Code fragment:
            //
            // return {functional agent's literal value};
            method.addStatement(new JavaStatement.ReturnStatement(resultExpr));
           
        } else {
            // Code fragment:
            //
            // return {functional agent's instance}
            //     .apply({marshalled arg #1}, ... {marshalled arg #4})
            //       ...
            //     .apply(... {marshalled arg #n})
            //     .evaluate(executionContext).{unmarshalling method}();
            //
            // OR (if unmarshalling involves casting)
            //
            // return ({result type})(java.lang.Object){functional agent's instance}
            //     .apply({marshalled arg #1}, ... {marshalled arg #4})
            //       ...
            //     .apply(... {marshalled arg #n})
            //     .evaluate(executionContext).getOpaqueValue();
            method.addStatement(new JavaStatement.ReturnStatement(makeRTValueUnmarshallingExpr(returnType, resultExpr)));
        }
       
        // Add the throws declaration
        method.addThrows(JavaTypeName.CAL_EXECUTOR_EXCEPTION);
       
        // Add the Javadoc
        method.setJavaDocComment(
            new JavaDocComment(CALDocToJavaDocUtilities.getJavadocFromCALDocComment(
                functionalAgent.getCALDocComment(), false, functionalAgent, functionalAgentType,
                functionalAgentArgNames.toArray(new String[nFunctionalAgentArgs]),
                scopedEntityNamingPolicy, crossRefGen, isUnitResultType, true, false, true)));
       
View Full Code Here

       
        // Code fragment:
        //
        // public static void main(final String[] args) throws CALExecutorException
        //
        final JavaMethod mainMethod = new JavaMethod(Modifier.PUBLIC|Modifier.STATIC, JavaTypeName.VOID, ARGS_PARAMETER_NAME, JavaTypeName.STRING_ARRAY, true, "main");
       
        mainMethod.addThrows(JavaTypeName.CAL_EXECUTOR_EXCEPTION);
       
        ////
        /// The classes in the standalone JAR are generated with the machine configuration at "build time".
        /// We capture this configuration into a StandaloneJarGeneratedCodeInfo, to be checked at runtime
        /// against the machine configuration then.
        //
       
        final JavaStatement.LocalVariableDeclaration generatedCodeInfoDecl = makeGeneratedCodeInfoDecl();
        final JavaExpression.LocalVariable generatedCodeInfoLocalVar = generatedCodeInfoDecl.getLocalVariable();
        mainMethod.addStatement(generatedCodeInfoDecl);

        //
        // Code fragment:
        //
        // if (!generatedCodeInfo.isCompatibleWithCurrentConfiguration()) {
        //     System.err.println(generatedCodeInfo.getConfigurationHints());
        //     return;
        // }
        //
        final JavaStatement.Block configCheckFailureBody = new JavaStatement.Block();
       
        configCheckFailureBody.addStatement(
            new JavaStatement.ExpressionStatement(
                new JavaExpression.MethodInvocation.Instance(
                    new JavaExpression.JavaField.Static(JavaTypeName.SYSTEM, "err", JavaTypeName.PRINT_STREAM),
                    "println",
                    new JavaExpression.MethodInvocation.Instance(
                        generatedCodeInfoLocalVar,
                        "getConfigurationHints",
                        JavaTypeName.STRING,
                        JavaExpression.MethodInvocation.InvocationType.VIRTUAL),
                    JavaTypeName.STRING,
                    JavaTypeName.VOID,
                    JavaExpression.MethodInvocation.InvocationType.VIRTUAL)));
       
        configCheckFailureBody.addStatement(new JavaStatement.ReturnStatement());
       
        final JavaStatement configCheck =
            new JavaStatement.IfThenElseStatement(
                new JavaExpression.OperatorExpression.Unary(
                    JavaOperator.LOGICAL_NEGATE,
                    new JavaExpression.MethodInvocation.Instance(
                        generatedCodeInfoLocalVar,
                        "isCompatibleWithCurrentConfiguration",
                        JavaTypeName.BOOLEAN,
                        JavaExpression.MethodInvocation.InvocationType.VIRTUAL)),
                configCheckFailureBody);
       
        mainMethod.addStatement(configCheck);
       
        ////
        /// Generate code to obtain the class loader which loaded this main class.
        ///
        /// It is necessary to obtain this class loader and pass it into the execution context and the resource access
        /// because the class loader which loaded the CAL Platform classes may be an *ancestor* of the one which loaded
        /// the standalone JAR (e.g. the bootstrap class loader), and thus may not have access to the foreign classes
        /// and localized resources necessary for the standalone JAR to run.
        //
       
        // Code fragment:
        //
        // ClassLoader classloader = {MainClassName}.class.getClassLoader();
        //
        final JavaTypeName javaTypeName_ClassLoader = JavaTypeName.make(ClassLoader.class);
       
        final JavaExpression classloaderInit =
            new JavaExpression.MethodInvocation.Instance(
                new JavaExpression.ClassLiteral(mainClassName),
                "getClassLoader",
                javaTypeName_ClassLoader,
                JavaExpression.MethodInvocation.InvocationType.VIRTUAL);
       
        final JavaExpression.LocalVariable classloaderLocalVar = new JavaExpression.LocalVariable("classloader", javaTypeName_ClassLoader);
       
        final JavaStatement classloaderDecl = new JavaStatement.LocalVariableDeclaration(classloaderLocalVar, classloaderInit);
       
        mainMethod.addStatement(classloaderDecl);
       
        ////
        /// Generate code to set up the execution context to have access to a standalone-JAR-specific
        /// ResourceAccess implementation.
        //

        // Code fragment:
        //       
        // RTExecutionContext executionContext = new RTExecutionContext(
        //     new ExecutionContextProperties.Builder().toProperties(),
        //     new StandaloneRuntimeEnvironment(
        //         classloader,
        //         new StandaloneJarResourceAccess(classloader)));       
        //
        final JavaTypeName javaTypeName_ExecutionContextProperties = JavaTypeName.make(ExecutionContextProperties.class);
        final JavaTypeName javaTypeName_ResourceAccess = JavaTypeName.make(ResourceAccess.class);
       
        final JavaExpression newRuntimeEnvironment =
            new JavaExpression.ClassInstanceCreationExpression(
                JavaTypeNames.STANDALONE_RUNTIME_ENVIRONMENT,
                new JavaExpression[] {
                    classloaderLocalVar,
                    new JavaExpression.ClassInstanceCreationExpression(
                        JavaTypeName.make(StandaloneJarResourceAccess.class),
                        classloaderLocalVar,
                        javaTypeName_ClassLoader)},
                new JavaTypeName[] {
                    javaTypeName_ClassLoader,
                    javaTypeName_ResourceAccess}                                  
                );
       
        final JavaExpression executionContextInit =
            new JavaExpression.ClassInstanceCreationExpression(
                JavaTypeNames.RTEXECUTION_CONTEXT,
                new JavaExpression[] {
                    new JavaExpression.MethodInvocation.Instance(
                        new JavaExpression.ClassInstanceCreationExpression(JavaTypeName.make(ExecutionContextProperties.Builder.class)),
                        "toProperties",
                        javaTypeName_ExecutionContextProperties,
                        JavaExpression.MethodInvocation.InvocationType.VIRTUAL),
                    newRuntimeEnvironment                  
                },
                new JavaTypeName[] {
                    javaTypeName_ExecutionContextProperties,
                    JavaTypeNames.RUNTIME_ENIVONMENT
                });
       
        final JavaExpression.LocalVariable executionContextLocalVar = new JavaExpression.LocalVariable(EXECUTION_CONTEXT_USER_FRIENDLY_NAME, JavaTypeNames.RTEXECUTION_CONTEXT);
        final JavaStatement executionContextDecl = new JavaStatement.LocalVariableDeclaration(executionContextLocalVar, executionContextInit, true);
       
        mainMethod.addStatement(executionContextDecl);
       
        ////
        /// Generate code to run the entry point.
        //
       
        // Code fragment:
        //
        // {EntryPointClass's instance}
        //     .apply(Input_String_List.$instance.apply(new RTData.CAL_Opaque(args))
        //     .evaluate(executionContext);
        //
        final MachineFunction entryPointMachineFunction = module.getFunction(entryPointName);
       
        final MachineFunction inputStringListMachineFunction = module.getFunction(CAL_Prelude_internal.Functions.inputStringList);
       
        final JavaExpression runExpr =
            makeEvaluateInvocationExpr(
                makeApplyInvocationExpr(
                    getInstanceOfGeneratedClassJavaExpression(entryPointMachineFunction, module, executionContextLocalVar),
                    makeApplyInvocationExpr(
                        getInstanceOfGeneratedClassJavaExpression(inputStringListMachineFunction, module, executionContextLocalVar),
                        new JavaExpression.ClassInstanceCreationExpression(
                            JavaTypeNames.RTDATA_OPAQUE, new JavaExpression.MethodVariable(ARGS_PARAMETER_NAME), JavaTypeName.OBJECT))), executionContextLocalVar);
       
        mainMethod.addStatement(new JavaStatement.ExpressionStatement(runExpr));
       
        classRep.addMethod(mainMethod);
       
        // We are finished with building the class.
        return classRep;
View Full Code Here

TOP

Related Classes of org.openquark.cal.internal.javamodel.JavaMethod

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.