Package org.drools.compiler.compiler

Examples of org.drools.compiler.compiler.TypeDeclarationError



    private AnnotationDescr getSingleAnnotation(AbstractClassTypeDeclarationDescr typeDescr, String name) {
        AnnotationDescr annotationDescr = typeDescr.getAnnotation(name);
        if (annotationDescr != null && annotationDescr.isDuplicated()) {
            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                               "Duplicated annotation '" + name +
                                                               "' for type declaration of '" +
                                                               typeDescr.getTypeName() + "'"));
            return null;
        }
View Full Code Here


            cache.put(name, tdescr);

            if (taxonomy.get(name) == null) {
                taxonomy.put(name, new ArrayList<QualifiedName>());
            } else {
                kbuilder.addBuilderResult(new TypeDeclarationError(tdescr,
                                                                   "Found duplicate declaration for type " + tdescr.getType()));
            }

            Collection<QualifiedName> supers = taxonomy.get(name);

            boolean circular = false;
            for (QualifiedName sup : tdescr.getSuperTypes()) {
                if (!Object.class.getName().equals(name.getFullName())) {
                    if (!hasCircularDependency(tdescr.getType(), sup, taxonomy)) {
                        supers.add(sup);
                    } else {
                        circular = true;
                        kbuilder.addBuilderResult(new TypeDeclarationError(tdescr,
                                                                           "Found circular dependency for type " + tdescr.getTypeName()));
                        break;
                    }
                }
            }
View Full Code Here

                            AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation,
                                                                                                   field.getAnnotations().get(annotationName).getValueMap(),
                                                                                                   pkgRegistry.getTypeResolver());
                            fieldDef.addAnnotation(annotationDefinition);
                        } catch (NoSuchMethodException nsme) {
                            kbuilder.addBuilderResult(new TypeDeclarationError(field,
                                                                              "Annotated field " + field.getFieldName() +
                                                                              "  - undefined property in @annotation " +
                                                                              annotationName + ": " + nsme.getMessage() + ";"));
                        }
                    }
                    if (annotation == null || annotation == Key.class || annotation == Position.class) {
                        fieldDef.addMetaData(annotationName, field.getAnnotation(annotationName).getSingleValue());
                    }
                }

                queue.add(fieldDef);
            } catch (ClassNotFoundException cnfe) {
                kbuilder.addBuilderResult(new TypeDeclarationError(field, cnfe.getMessage()));
            }

        }

        return queue;
View Full Code Here

        String fullName = typeDescr.getType().getFullName();

        if (type.getKind().equals(TypeDeclaration.Kind.CLASS)) {
            TypeDeclarationDescr tdescr = (TypeDeclarationDescr) typeDescr;
            if (tdescr.getSuperTypes().size() > 1) {
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Declared class " + fullName + "  - has more than one supertype;"));
                return;
            } else if (tdescr.getSuperTypes().isEmpty()) {
                tdescr.addSuperType("java.lang.Object");
            }
        }

        AnnotationDescr traitableAnn = typeDescr.getAnnotation(Traitable.class.getSimpleName());
        boolean traitable = traitableAnn != null;

        String[] fullSuperTypes = new String[typeDescr.getSuperTypes().size() + 1];
        int j = 0;
        for (QualifiedName qname : typeDescr.getSuperTypes()) {
            fullSuperTypes[j++] = qname.getFullName();
        }
        fullSuperTypes[j] = Thing.class.getName();

        List<String> interfaceList = new ArrayList<String>();
        interfaceList.add(traitable ? Externalizable.class.getName() : Serializable.class.getName());
        if (traitable) {
            interfaceList.add(TraitableBean.class.getName());
        }
        String[] interfaces = interfaceList.toArray(new String[interfaceList.size()]);

        // prepares a class definition
        ClassDefinition def;
        switch (type.getKind()) {
            case TRAIT:
                def = new ClassDefinition(fullName,
                                          "java.lang.Object",
                                          fullSuperTypes);
                break;
            case ENUM:
                def = new EnumClassDefinition(fullName,
                                              fullSuperTypes[0],
                                              null);
                break;
            case CLASS:
            default:
                def = new ClassDefinition(fullName,
                                          fullSuperTypes[0],
                                          interfaces);
                def.setTraitable(traitable, traitableAnn != null &&
                                            traitableAnn.getValue("logical") != null &&
                                            Boolean.valueOf(traitableAnn.getValue("logical")));
        }

        for (String annotationName : typeDescr.getAnnotationNames()) {
            Class annotation = resolveAnnotation(annotationName,
                                                 pkgRegistry.getTypeResolver());
            if (annotation != null && annotation.isAnnotation()) {
                try {
                    AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation,
                                                                                           typeDescr.getAnnotations().get(annotationName).getValueMap(),
                                                                                           pkgRegistry.getTypeResolver());
                    def.addAnnotation(annotationDefinition);
                } catch (NoSuchMethodException nsme) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                      "Annotated type " + fullName +
                                                                      "  - undefined property in @annotation " +
                                                                      annotationName + ": " +
                                                                      nsme.getMessage() + ";"));
                }
            }
            if (annotation == null || annotation == Role.class) {
                def.addMetaData(annotationName, typeDescr.getAnnotation(annotationName).getSingleValue());
            }
        }

        // add enum literals, if appropriate
        if (type.getKind() == TypeDeclaration.Kind.ENUM) {
            for (EnumLiteralDescr lit : ((EnumDeclarationDescr) typeDescr).getLiterals()) {
                ((EnumClassDefinition) def).addLiteral(
                        new EnumLiteralDefinition(lit.getName(), lit.getConstructorArgs())
                                                      );
            }
        }

        // fields definitions are created. will be used by subclasses, if any.
        // Fields are SORTED in the process
        if (!typeDescr.getFields().isEmpty()) {
            PriorityQueue<FieldDefinition> fieldDefs = sortFields(typeDescr.getFields(),
                                                                  pkgRegistry);
            int n = fieldDefs.size();
            for (int k = 0; k < n; k++) {
                FieldDefinition fld = fieldDefs.poll();
                if (unresolvedTypeDefinitions != null) {
                    for (TypeDefinition typeDef : unresolvedTypeDefinitions) {
                        if (fld.getTypeName().equals(typeDef.getTypeClassName())) {
                            fld.setRecursive(true);
                            break;
                        }
                    }
                }
                fld.setIndex(k);
                def.addField(fld);
            }
        }

        // check whether it is necessary to build the class or not
        Class<?> existingDeclarationClass = getExistingDeclarationClass(typeDescr);
        type.setNovel(existingDeclarationClass == null);

        // attach the class definition, it will be completed later
        type.setTypeClassDef(def);

        //if is not new, search the already existing declaration and
        //compare them o see if they are at least compatibles
        if (!type.isNovel()) {
            TypeDeclaration previousTypeDeclaration = kbuilder.getPackageRegistry(typeDescr.getNamespace()).getPackage().getTypeDeclaration(typeDescr.getTypeName());

            try {

                if (!type.getTypeClassDef().getFields().isEmpty()) {
                    //since the declaration defines one or more fields, it is a DEFINITION
                    type.setNature(TypeDeclaration.Nature.DEFINITION);
                } else {
                    //The declaration doesn't define any field, it is a DECLARATION
                    type.setNature(TypeDeclaration.Nature.DECLARATION);
                }

                //if there is no previous declaration, then the original declaration was a POJO
                //to the behavior previous these changes
                if (previousTypeDeclaration == null) {
                    // new declarations of a POJO can't declare new fields,
                    // except if the POJO was previously generated/compiled and saved into the kjar
                    if (!kbuilder.getBuilderConfiguration().isPreCompiled() &&
                        !GeneratedFact.class.isAssignableFrom(existingDeclarationClass) && !type.getTypeClassDef().getFields().isEmpty()) {
                        try {
                            Class existingClass = pkgRegistry.getPackage().getTypeResolver().resolveType( typeDescr.getType().getFullName() );
                            ClassFieldInspector cfi = new ClassFieldInspector( existingClass );

                            int fieldCount = 0;
                            for ( String existingFieldName : cfi.getFieldTypesField().keySet() ) {
                                if ( ! cfi.isNonGetter( existingFieldName ) && ! "class".equals( existingFieldName ) && cfi.getSetterMethods().containsKey( existingFieldName ) ) {
                                    if ( ! typeDescr.getFields().containsKey( existingFieldName ) ) {
                                        type.setValid(false);
                                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "New declaration of "+typeDescr.getType().getFullName() +
                                                                                                    " does not include field " + existingFieldName ) );
                                    } else {
                                        String fldType = cfi.getFieldTypes().get( existingFieldName ).getName();
                                        TypeFieldDescr declaredField = typeDescr.getFields().get( existingFieldName );
                                        if ( ! fldType.equals( type.getTypeClassDef().getField( existingFieldName ).getTypeName() ) ) {
                                            type.setValid(false);
                                            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "New declaration of "+typeDescr.getType().getFullName() +
                                                                                                         " redeclared field " + existingFieldName + " : \n" +
                                                                                                         "existing : " + fldType + " vs declared : " + declaredField.getPattern().getObjectType() ) );
                                        } else {
                                            fieldCount++;
                                        }

                                    }
                                }
                            }

                            if ( fieldCount != typeDescr.getFields().size() ) {
                                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "New declaration of "+typeDescr.getType().getFullName()
                                                                                             +" can't declaredeclares a different set of fields \n" +
                                                                                             "existing : " + cfi.getFieldTypesField() + "\n" +
                                                                                             "declared : " + typeDescr.getFields() ));

                            }
                        } catch ( IOException e ) {
                            e.printStackTrace();
                            type.setValid(false);
                            kbuilder.addBuilderResult( new TypeDeclarationError( typeDescr, "Unable to redeclare " + typeDescr.getType().getFullName() + " : " + e.getMessage() ) );
                        } catch ( ClassNotFoundException e ) {
                            type.setValid(false);
                            kbuilder.addBuilderResult( new TypeDeclarationError( typeDescr, "Unable to redeclare " + typeDescr.getType().getFullName() + " : " + e.getMessage() ) );
                        }
                    }
                } else {

                    int typeComparisonResult = this.compareTypeDeclarations(previousTypeDeclaration, type);

                    if (typeComparisonResult < 0) {
                        //oldDeclaration is "less" than newDeclaration -> error
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName()
                                                                             + " declares more fields than the already existing version"));
                        type.setValid(false);
                    } else if (typeComparisonResult > 0 && !type.getTypeClassDef().getFields().isEmpty()) {
                        //oldDeclaration is "grater" than newDeclaration -> error
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName()
                                                                                     + " declares less fields than the already existing version"));
                        type.setValid(false);
                    }

                    //if they are "equal" -> no problem

                    // in the case of a declaration, we need to copy all the
                    // fields present in the previous declaration
                    if (type.getNature() == TypeDeclaration.Nature.DECLARATION) {
                        mergeTypeDeclarations(previousTypeDeclaration, type);
                    }
                }

            } catch (IncompatibleClassChangeError error) {
                //if the types are incompatible -> error
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, error.getMessage()));
            }

        } else {
            //if the declaration is novel, then it is a DEFINITION
            type.setNature(TypeDeclaration.Nature.DEFINITION);
View Full Code Here

                                             tempDef);
                        try {
                            Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(tempDescr.getType().getFullName());
                            tempDeclr.setTypeClass(clazz);
                        } catch (ClassNotFoundException cnfe) {
                            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                               "Internal Trait extension Class '" + target +
                                                                               "' could not be generated correctly'"));
                        } finally {
                            pkgRegistry.getPackage().addTypeDeclaration(tempDeclr);
                        }

                    } else {
                        updateTraitDefinition(type,
                                              resolvedType);
                        pkgRegistry.getTraitRegistry().addTrait(def);
                    }
                } catch (ClassNotFoundException cnfe) {
                    // we already know the class exists
                }
            } else {
                if (def.getClassName().endsWith(TraitFactory.SUFFIX)) {
                    pkgRegistry.getTraitRegistry().addTrait(def.getClassName().replace(TraitFactory.SUFFIX,
                                                                                       ""),
                                                            def);
                } else {
                    pkgRegistry.getTraitRegistry().addTrait(def);
                }
            }

        }

        if (type.isNovel()) {
            String fullName = typeDescr.getType().getFullName();
            JavaDialectRuntimeData dialect = (JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData("java");
            switch (type.getKind()) {
                case TRAIT:
                    try {
                        buildClass(def, fullName, dialect, kbuilder.getBuilderConfiguration().getClassBuilderFactory().getTraitBuilder());
                    } catch (Exception e) {
                        e.printStackTrace();
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                           "Unable to compile declared trait " + fullName +
                                                                           ": " + e.getMessage() + ";"));
                    }
                    break;
                case ENUM:
                    try {
                        buildClass(def, fullName, dialect, kbuilder.getBuilderConfiguration().getClassBuilderFactory().getEnumClassBuilder());
                    } catch (Exception e) {
                        e.printStackTrace();
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                           "Unable to compile declared enum " + fullName +
                                                                           ": " + e.getMessage() + ";"));
                    }
                    break;
                case CLASS:
                default:
                    try {
                        buildClass(def, fullName, dialect, kbuilder.getBuilderConfiguration().getClassBuilderFactory().getBeanClassBuilder());
                    } catch (Exception e) {
                        e.printStackTrace();
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                           "Unable to create a class for declared type " + fullName +
                                                                           ": " + e.getMessage() + ";"));
                    }
                    break;
            }
View Full Code Here

        for (Field fld : fields) {
            Position pos = fld.getAnnotation(Position.class);
            if (pos != null) {
                if (pos.value() < 0 || pos.value() >= fields.size()) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDeclaration,
                                                                       "Out of range position " + pos.value() + " for field '" + fld.getName() + "' on class " + cls.getName()));
                    continue;
                }
                if (orderedFields[pos.value()] != null) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDeclaration,
                                                                       "Duplicated position " + pos.value() + " for field '" + fld.getName() + "' on class " + cls.getName()));
                    continue;
                }
                FieldDefinition fldDef = clsDef.getField(fld.getName());
                if (fldDef == null) {
View Full Code Here

                    declaredSuperType = typeName2ClassName(declaredSuperType);

                    // sets supertype name and supertype package
                    separator = declaredSuperType.lastIndexOf(".");
                    if (separator < 0) {
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                           "Cannot resolve supertype '" + declaredSuperType + "'"));
                        qname.setName(null);
                        qname.setNamespace(null);
                    } else {
                        qname.setName(declaredSuperType.substring(separator + 1));
View Full Code Here

                        // will fail later
                    }
                }

                if (!type1.equals(type2)) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                       "Cannot redeclare field '" + fieldName + " from " + type1 + " to " + type2));
                    typeDescr.setType(null,
                                      null);
                    return false;
                } else {
View Full Code Here

        if (type.getTypeClassDef() != null) {
            try {
                buildFieldAccessors(type, pkgRegistry);
            } catch (Throwable e) {
                if (!firstAttempt) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                       "Error creating field accessors for TypeDeclaration '" + type.getTypeName() +
                                                                       "' for type '" +
                                                                       type.getTypeName() +
                                                                       " : " + e.getMessage() +
                                                                       "'"));
                }
                return false;
            }
        }

        AnnotationDescr annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_TIMESTAMP);
        String timestamp = (annotationDescr != null) ? annotationDescr.getSingleValue() : null;
        if (timestamp != null) {
            type.setTimestampAttribute(timestamp);
            InternalKnowledgePackage pkg = pkgRegistry.getPackage();

            MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect("mvel");
            PackageBuildContext context = new PackageBuildContext();
            context.init(kbuilder, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null);
            if (!type.isTypesafe()) {
                context.setTypesafe(false);
            }

            MVELAnalysisResult results = (MVELAnalysisResult)
                    context.getDialect().analyzeExpression(context,
                                                           typeDescr,
                                                           timestamp,
                                                           new BoundIdentifiers(Collections.EMPTY_MAP,
                                                                                Collections.EMPTY_MAP,
                                                                                Collections.EMPTY_MAP,
                                                                                type.getTypeClass()));

            if (results != null) {
                InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader(ClassUtils.getPackage(type.getTypeClass()),
                                                                                             type.getTypeClass().getName(),
                                                                                             timestamp,
                                                                                             type.isTypesafe(),
                                                                                             results.getReturnType());

                MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData("mvel");
                data.addCompileable((MVELCompileable) reader);
                ((MVELCompileable) reader).compile(data);
                type.setTimestampExtractor(reader);
            } else {
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                   "Error creating field accessors for timestamp field '" + timestamp +
                                                                   "' for type '" +
                                                                   type.getTypeName() +
                                                                   "'"));
            }
        }

        annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_DURATION);
        String duration = (annotationDescr != null) ? annotationDescr.getSingleValue() : null;
        if (duration != null) {
            type.setDurationAttribute(duration);
            InternalKnowledgePackage pkg = pkgRegistry.getPackage();

            MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect("mvel");
            PackageBuildContext context = new PackageBuildContext();
            context.init(kbuilder, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null);
            if (!type.isTypesafe()) {
                context.setTypesafe(false);
            }

            MVELAnalysisResult results = (MVELAnalysisResult)
                    context.getDialect().analyzeExpression(context,
                                                           typeDescr,
                                                           duration,
                                                           new BoundIdentifiers(Collections.EMPTY_MAP,
                                                                                Collections.EMPTY_MAP,
                                                                                Collections.EMPTY_MAP,
                                                                                type.getTypeClass()));

            if (results != null) {
                InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader(ClassUtils.getPackage(type.getTypeClass()),
                                                                                             type.getTypeClass().getName(),
                                                                                             duration,
                                                                                             type.isTypesafe(),
                                                                                             results.getReturnType());

                MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData("mvel");
                data.addCompileable((MVELCompileable) reader);
                ((MVELCompileable) reader).compile(data);
                type.setDurationExtractor(reader);
            } else {
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                                   "Error processing @duration for TypeDeclaration '" + type.getFullName() +
                                                                   "': cannot access the field '" + duration + "'"));
            }
        }
View Full Code Here

                                 unresolvedTypes);

            Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(typeDescr.getType().getFullName());
            type.setTypeClass(clazz);
        } catch (final ClassNotFoundException e) {
            kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr,
                                                               "Class '" + className +
                                                               "' not found for type declaration of '" +
                                                               type.getTypeName() + "'"));
            return;
        }
View Full Code Here

TOP

Related Classes of org.drools.compiler.compiler.TypeDeclarationError

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.