Package org.openquark.cal.internal.javamodel

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


                final String mainClassRelativePath = mainClassName.getName().replace('.', '/') + ".class";
                final ZipEntry mainClassEntry = new ZipEntry(mainClassRelativePath);

                final byte[] mainClassBytecode;
                try {
                    final JavaClassRep mainClassRep = makeMainClass(mainClassName, entryPointName, workspaceManager);
                    mainClassBytecode = AsmJavaBytecodeGenerator.encodeClass(mainClassRep);
                   
                    // Write out the source for the class
                    final String javaFileRelativePath = mainClassName.getName().replace('.', '/') + ".java";
                    final ZipEntry javaFileEntry = new ZipEntry(javaFileRelativePath);
                    sourceGen.generateSource(javaFileEntry, mainClassRep);
                   
                    writeClassAndOtherRequiredClassesAndGatherResources(workspaceManager, jos, classesAlreadyAdded, sourcesAlreadyAdded, allRequredModules, rootModule, mainClassEntry, mainClassBytecode, sourceGen);
                   
                } catch (final JavaGenerationException e) {
                    // We should not have problems generating the main class - if there are any then it is an internal problem
                    throw new InternalProblemException(e);
                }
            }

            ////
            /// Then generate the library classes (and their associated classes and resources)
            //
            for (final LibraryClassSpec spec : libClassSpecs) {
               
                final JavaTypeName libClassName = spec.getClassName();
                final ModuleName libModuleName = spec.getModuleName();

                // Check the library class's configuration, and throw InvalidConfigurationException if there are problems
                checkLibraryClassConfiguration(libModuleName, workspaceManager);
               
                ////
                /// Write out the library class and the generated classes required by the class.
                //
                final String libClassRelativePath = libClassName.getName().replace('.', '/') + ".class";
                final ZipEntry libClassEntry = new ZipEntry(libClassRelativePath);

                final byte[] libClassBytecode;
                try {
                    final JavaClassRep libClassRep = makeLibraryClass(spec.getScope(), libClassName, libModuleName, workspaceManager, monitor);
                    libClassBytecode = AsmJavaBytecodeGenerator.encodeClass(libClassRep);
                   
                    // Write out the source for the class
                    final String javaFileRelativePath = libClassName.getName().replace('.', '/') + ".java";
                    final ZipEntry javaFileEntry = new ZipEntry(javaFileRelativePath);
View Full Code Here


                // Add the class to the JAR
                addClassToJar(jos, className, bytecode);
               
                // Add the source to the JAR (if we are generating a source zip)
                if (!(sourceGen instanceof SourceGenerator.Null)) {
                    final JavaClassRep classRep = classLoader.getClassRepWithInnerClasses(className);
                    final String sourceName = classRep.getClassName().getName();

                    if (!sourcesAlreadyAdded.contains(sourceName)) {
                        final String javaFileRelativePath = sourceName.replace('.', '/') + ".java";
                        final ZipEntry javaFileEntry = new ZipEntry(javaFileRelativePath);
                        sourceGen.generateSource(javaFileEntry, classRep);
View Full Code Here

     */
    private static JavaClassRep makeMainClass(final JavaTypeName mainClassName, final QualifiedName entryPointName, final ProgramModelManager programModelManager) {
       
        final LECCModule module = (LECCModule)programModelManager.getModule(entryPointName.getModuleName());
       
        final JavaClassRep classRep = new JavaClassRep(mainClassName, JavaTypeName.OBJECT, Modifier.PUBLIC|Modifier.FINAL, new JavaTypeName[0]);
       
        // Code fragment:
        //
        // private {MainClassConstructorName} {}
        //
       
        classRep.addConstructor(makePrivateConstructor(mainClassName));
       
        // 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

        final ModuleTypeInfo moduleTypeInfo = programModelManager.getModuleTypeInfo(moduleName);
        final LECCModule module = (LECCModule)programModelManager.getModule(moduleName);
        final ScopedEntityNamingPolicy.UnqualifiedInCurrentModuleOrInPreludeIfUnambiguous scopedEntityNamingPolicy =
            new ScopedEntityNamingPolicy.UnqualifiedInCurrentModuleOrInPreludeIfUnambiguous(moduleTypeInfo);
       
        final JavaClassRep classRep = new JavaClassRep(libClassName, JavaTypeName.OBJECT, libClassScope.getModifier()|Modifier.FINAL, new JavaTypeName[0]);
       
        // Code fragment:
        //
        // private {LibClassConstructorName} {}
        //
       
        classRep.addConstructor(makePrivateConstructor(libClassName));

        // We sort the functional agents, because the order returned by the ModuleTypeInfo is neither source order nor alphabetical order
        // Case-sensitive ordering would order data constructors ahead of functions
        final FunctionalAgent[] functionalAgents = moduleTypeInfo.getFunctionalAgents();
        Arrays.sort(functionalAgents, new Comparator<FunctionalAgent>() {
            public int compare(final FunctionalAgent a, final FunctionalAgent b) {
                return a.getName().compareTo(b.getName());
            }});
       
        final Map<String, String> methodNameMapping = sanitizeMethodNamesForJava(functionalAgents);
        final JavadocCrossReferenceGenerator crossRefGen = new JavadocLinkGenerator(methodNameMapping, scopedEntityNamingPolicy);
       
        // Add each functional agent as a method if it has a visible scope and it is not an overloaded function
        for (final FunctionalAgent functionalAgent : functionalAgents) {
            if (isScopeVisibleAsJavaLibraryAPI(functionalAgent.getScope())) {
                // Check that the functional agent has a type that can be handled.
                final TypeExpr functionalAgentType = functionalAgent.getTypeExpr();
               
                if (!hasTypeClassConstraints(functionalAgentType)) {
                   
                    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

        boolean sourceExists = resourceRepository.exists(sourceFile);
        boolean fileChange = false;
        if (forceWrite || !sourceExists) {
           
            // Get the sc definition, generate source.
            JavaClassRep classRep = JavaDefinitionBuilder.getSCDefinition(functionGroupInfo, module, getCodeGenerationStats());
            if (classRep.getJavaDoc() == null) {
                classRep.setJavaDoc(new JavaDocComment(getClassJavadocComment()));
            }
           
            try {
                String source =
                    JavaSourceGenerator.generateSourceCode(classRep);
View Full Code Here

          
        boolean sourceExists = resourceRepository.exists(sourceFile);
        boolean fileChange = false;
        if (forceWrite || !sourceExists) {
            // Get the sc definition, generate source.
            JavaClassRep classRep = JavaDefinitionBuilder.getDataTypeDefinition(typeCons, module, getCodeGenerationStats());
            if (classRep.getJavaDoc() == null) {
                classRep.setJavaDoc(new JavaDocComment(getClassJavadocComment()));
            }

            try {
                String source =
                    JavaSourceGenerator.generateSourceCode(classRep);
View Full Code Here

TOP

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

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.