Package com.sun.msv.grammar.util

Examples of com.sun.msv.grammar.util.ExpressionWalker


        --------------
       
        create a "(element name,attribute name)->Id datatype name" map.
        Also detects invalid use of datatypes.
        */
        reader.getGrammar().visit( new ExpressionWalker(){
           
            /** current element name. Only available when in a simple-name element */
            private StringPair elementName=null;
            /** current element. */
            private ElementExp curElm=null;
           
            private IDAttMap curAtts = null;
           
            public void onElement( ElementExp exp ) {
                if(!elements.add(exp))
                    return;    // this element has already processed.
               
                StringPair _en = elementName;
                IDAttMap _curAtts = curAtts;
                ElementExp _curElm = curElm;
               
                NameClass nc = exp.getNameClass();
                if(nc instanceof SimpleNameClass) {
                    elementName = new StringPair((SimpleNameClass)nc);
                    curAtts = (IDAttMap)name2value.get(elementName);    // maybe null.
                } else
                    elementName = null;
                curElm = exp;
               
//                System.out.println("tested:" +
//                    com.sun.msv.grammar.util.ExpressionPrinter.printContentModel(
//                    exp.contentModel.visit(remover)));
                // visit the content model, but remove reference exps first.
                exp.contentModel.visit(remover).visit(this);
               
                if( elementName!=null && curAtts!=null )
                    name2value.put(elementName,curAtts);
               
                elementName = _en;
                curAtts = _curAtts;
                curElm = _curElm;
            }
           
            public void onAttribute( AttributeExp exp ) {
               
                if(!(exp.exp instanceof DataOrValueExp)) {
                    // otherwise visit the content model normally
                    // so that we can find any invalid use of ID/IDREF types.
                    exp.exp.visit(this);
                    return;
                }
               
                DataOrValueExp texp = (DataOrValueExp)exp.exp;
                           
                if(texp.getType().getIdType()==Datatype.ID_TYPE_NULL) {
                    // if this type is not ID/IDREF type, then it's OK
                    return;
                }
               
                if(!(exp.nameClass instanceof SimpleNameClass)) {
                    reportCompError(
                        new Locator[]{reader.getDeclaredLocationOf(exp)},
                        CERR_ID_TYPE_WITH_NON_SIMPLE_ATTNAME,
                        new Object[]{
                            texp.getName().localName,
                            getSemanticsStr(texp.getType().getIdType())} );
                    return;
                }
                   
                StringPair attName = new StringPair((SimpleNameClass)exp.nameClass);
               
                if( elementName==null ) {
                    reportCompError(
                        new Locator[]{
                            reader.getDeclaredLocationOf(exp),
                            reader.getDeclaredLocationOf(curElm)},
                        CERR_ID_TYPE_WITH_NON_SIMPLE_ELEMENTNAME,
                        new Object[]{
                            texp.getName().localName,
                            getSemanticsStr(texp.getType().getIdType())} );
                    return;
                }
                   
                // the enclosing attribute name is simple, and
                // the enclosing element name is simple, too.
                // this is the only place we can have ID/IDREF types.
                                   
                // store that this attribute is used for ID/IDREF.
                if(curAtts==null)
                    curAtts = new IDAttMap(curElm);
                curAtts.idatts.put(attName,texp.getName());
                           
            }
           
            public void onData( DataExp exp )    { checkIdType(exp); }
            public void onValue( ValueExp exp ) { checkIdType(exp); }
            private void checkIdType( DataOrValueExp exp ) {
                if(exp.getType().getIdType()!=Datatype.ID_TYPE_NULL) {
                    // ID/IDREF type in all other locations are subject to
                    // a compatibility error.
                    reportCompError(
                        new Locator[]{reader.getDeclaredLocationOf(exp)},
                        CERR_MALPLACED_ID_TYPE,
                        new Object[]{
                            exp.getName().localName,
                            getSemanticsStr(exp.getType().getIdType())});
                }
            }
        });
       
       
        if(!grammar.isIDcompatible)
            // if an compatibility error has been found, abort further check.
            return;
       
        /*
        2nd pass
        ========
       
        make sure that no other attributes are competing with id attributes.
        */
        Iterator itr = elements.iterator();
        final Vector vec = new Vector();    // IDAttMaps of the competing elements
        while( itr.hasNext() ) {
            final ElementExp eexp = (ElementExp)itr.next();
           
            // list up all competing elements.
            vec.clear();
            Iterator jtr = name2value.entrySet().iterator();
            while(jtr.hasNext()) {
                Map.Entry e = (Map.Entry)jtr.next();
                if( eexp.getNameClass().accepts((StringPair)e.getKey()) )
                    vec.add( e.getValue()/*IDAttMap*/ );
            }
           
            if(vec.size()==0)
                continue;    // this element does not comete with anything.
                            // no need to check
           
            // make sure that no attributes are actually competing.
            eexp.contentModel.visit(remover).visit( new ExpressionWalker() {
                public void onElement( ElementExp exp ) {
                    return;    // do not recurse child elements.
                }
                public void onAttribute( AttributeExp exp ) {
                    if(exp.exp instanceof DataOrValueExp) {
View Full Code Here


       
        // tests if defaulted attributes are optional and doesn't have
        // oneOrMoreAncestor.
        // also (element name,attribute name)->default value
        // map is created here.
        grammar.visit( new ExpressionWalker() {
            // in the first pass, the elements variable
            // is used to record visited ElementExps.
           
            // condition that has to be met for default attributes to be valid.
            private boolean inOneOrMore = false;
View Full Code Here

            return;
       
        final Set explicitAtts = new HashSet();
       
        // visit the derived type and enumerate explicitly declared attributes in it.
        cexp.body.visit( new ExpressionWalker() {
            // stop if we hit an ElementExp.
            public void onElement( ElementExp exp ) {}
            public void onAttribute( AttributeExp exp ) {
                if(!(exp.nameClass instanceof SimpleNameClass))
                    // attribute uses must have a simple name.
                    throw new Error(exp.nameClass.toString());
               
                explicitAtts.add( ((SimpleNameClass)exp.nameClass).toStringPair() );
            }
        });
       
       
        // visit the base type and enumerate all attributes in it.
        cexp.complexBaseType.body.visit( new ExpressionWalker() {
           
            private boolean isOptional = false;
           
            public void onChoice( ChoiceExp exp ) {
                boolean b = isOptional;
View Full Code Here

        // collect all reachable ElementExps and ReferenceExps.
        final Set nodes = new HashSet();
        // ElementExps and ReferenceExps who are referenced more than once.
        final Set heads = new HashSet();
       
        g.getTopLevel().visit( new ExpressionWalker(){
            // ExpressionWalker class traverses expressions in depth-first order.
            // So this invokation traverses the all reachable expressions from
            // the top level expression.
           
            // Whenever visiting elements and RefExps, they are memorized
View Full Code Here

     */
    public XMLSchemaTypeExp getTypeDefinition() {
        final RuntimeException eureka = new RuntimeException();
        final XMLSchemaTypeExp[] result = new XMLSchemaTypeExp[1];
        try {
            getContentModel().visit( new ExpressionWalker(){
                public void onElement( ElementExp exp ) {}
                public void onRef( ReferenceExp exp ) {
                    if(exp instanceof XMLSchemaTypeExp) {
                        result[0] = (XMLSchemaTypeExp)exp;
                        throw eureka;
View Full Code Here

            ComplexTypeExp cexp = baseSchema.complexTypes.get(baseTypeName[1]);
            if(cexp!=null) {
                // we've found the complex type as the base type
                // look for XSDatatypeExp inside
                final XSDatatypeExp[] dexp = new XSDatatypeExp[1];
                cexp.body.visit(new ExpressionWalker() {
                    public void onAttribute( AttributeExp exp ) {
                        // don't visit inside attributes
                    }
                    public void onRef( ReferenceExp exp ) {
                        if(exp instanceof XSDatatypeExp) {
View Full Code Here

              pool.createData(StringType.theInstance) )),
          exp.exp );
     
      try {
        // see if "exp" contains FieldItem.
        exp.exp.visit( new ExpressionWalker(){
          public void onOther( OtherExp exp ) {
            if(exp instanceof FieldItemthrow eureka;
            if(exp instanceof JavaItem)    return;
            super.onOther(exp);
          }
View Full Code Here

        annotatedRefs.put(exp,r);
     
//  debug: assertion check
// since it is now properly annotated,
// every ClassItem, PrimitiveItem or InterfaceItem must be wrapped by FieldItem.
      r.visit( new ExpressionWalker(){
        public void onOther( OtherExp exp ) {
          if( exp instanceof FieldItem )
            return;
          if( exp instanceof IgnoreItem )
            return;
View Full Code Here

      final Map classes = new java.util.HashMap()// ClassItems
      final Map fields = new java.util.HashMap();    // FieldItems
      final Map primitives = new java.util.HashMap()// PrimitiveItems
      final Map ignores = new java.util.HashMap()// IgnoreItems
     
      grammar.getTopLevel().visit( new ExpressionWalker(){
        public void onElement( ElementExp exp ) {
          if(!elements.containsKey(exp)) {
            elements.put(exp,computeName(exp.getNameClass(),elements));
            super.onElement(exp);
          }
        }
        public void onAttribute( AttributeExp exp ) {
          if(!attributes.containsKey(exp)) {
            attributes.put(exp,computeName(exp.nameClass,attributes));
            super.onAttribute(exp);
          }
        }
        public void onData( DataExp exp ) {
          if(!datatypes.containsKey(exp)) {
            datatypes.put(exp,computeName(exp.dt,datatypes));
            super.onData(exp);
          }
        }
        public void onValue( ValueExp exp ) {
          if(!datatypes.containsKey(exp)) {
            datatypes.put(exp,computeName(exp.dt,datatypes));
            super.onValue(exp);
          }
        }
        public void onOther( OtherExp exp ) {
          if(exp instanceof ClassItem) {
            if(!classes.containsKey(exp)) {
              classes.put(exp,computeName((ClassItem)exp,classes));
              super.onOther(exp);
            }
            return;
          }
          if(exp instanceof PrimitiveItem) {
            if(!primitives.containsKey(exp)) {
              primitives.put(exp,computeName((PrimitiveItem)exp,primitives));
              super.onOther(exp);
            }
            return;
          }
          if(exp instanceof FieldItem) {
            if(!fields.containsKey(exp)) {
              fields.put(exp,computeName((FieldItem)exp,fields));
              super.onOther(exp);
            }
            return;
          }
          if(exp instanceof IgnoreItem) {
            if(!ignores.containsKey(exp)) {
              ignores.put(exp,computeName((IgnoreItem)exp,ignores));
              super.onOther(exp);
            }
            return;
          }
         
          super.onOther(exp);
        }
      });
     
    // assign names to intermediate non-terminals.
    //====================================================================
     
     
      copyAll( elements, "E", allNames );
      copyAll( attributes, "A", allNames );
      copyAll( datatypes, "D", allNames );
      copyAll( classes, "C", allNames );
      copyAll( fields, "N", allNames );
      copyAll( primitives, "P", allNames );
      copyAll( ignores, "Ignore", allNames );
     
     
      final ElementExp[] elms = (ElementExp[])elements.keySet().toArray(new ElementExp[0]);
      final AttributeExp[] atts = (AttributeExp[])attributes.keySet().toArray(new AttributeExp[0]);
      final DataOrValueExp[] dts = (DataOrValueExp[])datatypes.keySet().toArray(new DataOrValueExp[0]);
      final ClassItem[] cis = (ClassItem[])classes.keySet().toArray(new ClassItem[0]);
      final FieldItem[] fis = (FieldItem[])fields.keySet().toArray(new FieldItem[0]);
      final PrimitiveItem[] pis = (PrimitiveItem[])primitives.keySet().toArray(new PrimitiveItem[0]);
      final IgnoreItem[] iis = (IgnoreItem[])ignores.keySet().toArray(new IgnoreItem[0]);
     
      for( int i=0; i<dts.length; i++ ) {
        // TODO: serious implementation
        out.start( "dataSymbol", new String[]{
          "id",(String)allNames.get(dts[i])});
       
        out.element("library", dts[i].getName().namespaceURI );
        out.element("name", dts[i].getName().localName );
       
        out.end("dataSymbol");
       
//          "type", ((XSDatatype)dts[i].dt).getConcreteType().getName()
//          } );
      }
     
      for( int i=0; i<cis.length; i++ ) {
        out.element( "classSymbol", new String[]{
          "id",(String)allNames.get(cis[i]),
          "type",(String)cis[i].getTypeName()
        } );
      }
     
      for( int i=0; i<pis.length; i++ )
        out.element( "primitiveSymbol", new String[]{"id",(String)allNames.get(pis[i])} );
     
      for( int i=0; i<fis.length; i++ )
        out.element( "namedSymbol", new String[]{"id",(String)allNames.get(fis[i])} );
     
      for( int i=0; i<iis.length; i++ )
        out.element( "ignoreSymbol", new String[]{"id",(String)allNames.get(iis[i])} );
     
      {// generate intermediate symbols.
        int cnt=1;
        for( Iterator itr = rules.iterateKeys(); itr.hasNext(); ) {
          Expression symbol = (Expression)itr.next();
          if(!allNames.containsKey(symbol)) {
            out.element( "intermediateSymbol", new String[]{"id","T"+cnt});
            allNames.put( symbol, "T"+cnt );
            cnt++;
          }
        }
      }
     
      {// write all rules
        int rcounter = 0;
        Iterator itr = rules.iterateKeys();
        while(itr.hasNext()) {
          Expression nonTerminal = (Expression)itr.next();
          Rule[] rs = rules.getAll(nonTerminal);
         
          for( int j=0; j<rs.length; j++ ) {
            if(allNames.get(rs[j])==null) {
              // name this rule.
              allNames.put( rs[j], Integer.toString(rcounter++) );
              // write this rule
              rs[j].write(out,this);
            }
          }
        }
      }
     
      {// write non-term -> rule relationship
        out.start("rulesList");
        Iterator itr = rules.iterateKeys();
        while(itr.hasNext()) {
          Expression symbol = (Expression)itr.next();
          out.start("nonTerminal",
            new String[]{"id",getId(symbol)});
          Rule[] rs = rules.getAll(symbol);
          for( int i=0; i<rs.length; i++ )
            out.element("rule",new String[]{"no",getId(rs[i])});
         
          out.end("nonTerminal");
        }
        out.end("rulesList");
      }
 
    // generate a source code that constructs the grammar.
    //==============================================================
     
      ExpressionSerializer eser = new ExpressionSerializer(this,out);
     
      /*
      visit all elements and attributes to compute the dependency between expressions.
      */
      for( int i=0; i<atts.length; i++ ) {
        atts[i].exp.visit(eser.sequencer);
        eser.assignId( atts[i] );
        // attributes are serialized just like other particles.
      }
      for( int i=0; i<elms.length; i++ )
        elms[i].contentModel.visit(eser.sequencer);
     
      // ... and don't forget to visit top level expression.
      grammar.getTopLevel().visit(eser.sequencer);
     
      // then obtain the serialization order by creating a map from id to expr.
      java.util.TreeMap id2expr = new java.util.TreeMap();
      for( Iterator itr=eser.sharedExps.iterator(); itr.hasNext(); ) {
        Expression exp = (Expression)itr.next();
        id2expr.put( eser.expr2id.get(exp), exp );
      }
     
      // then serialize shared expressions
      for( Iterator itr=id2expr.keySet().iterator(); itr.hasNext(); ) {
        Integer n = (Integer)itr.next();
       
        Expression exp = (Expression)id2expr.get(n);
       
        if( exp instanceof AttributeExp ) {
          AttributeExp aexp = (AttributeExp)exp;
          out.start( "attributeSymbol", new String[]{"id",(String)allNames.get(aexp)} );
       
          ExpressionSerializer.serializeNameClass(aexp.getNameClass(),out);
          out.start("content");
          aexp.visit(eser.serializer);
          out.end("content");
         
          LLTableCalculator.calc( aexp, rules, grammar.getPool(),this ).write(out,this);
         
          out.end("attributeSymbol");
        } else {
          // other normal particles.
          out.start("particle",new String[]{"id","o"+n});
          exp.visit(eser.serializer);
          out.end("particle");
        }
      }
     
      // elements are serialized at last.
      for( int i=0; i<elms.length; i++ ) {
        out.start("elementSymbol", new String[]{"id",(String)allNames.get(elms[i])} );
     
        ExpressionSerializer.serializeNameClass(elms[i].getNameClass(),out);
        out.start("content");
        elms[i].visit(eser.serializer);
        out.end("content");
       
        LLTableCalculator.calc( elms[i], rules, grammar.getPool(),this ).write(out,this);
       
        out.end("elementSymbol");
      }
     
      if( elements.containsKey(grammar.getTopLevel()) ) {
        // if the top-level expression is element symbol,
        // then we don't need the root grammar.
        out.start("topLevel");
        out.start("content");
        eser.serialize(grammar.getTopLevel());
        out.end("content");
        out.end("topLevel");
      } else {
        // serialize top-level expression
        out.start("topLevel",new String[]{"id",getId(grammar.getTopLevel())});
        out.start("content");
        grammar.getTopLevel().visit(eser.serializer);
        out.end("content");
          LLTableCalculator.calc( grammar.getTopLevel(), rules, grammar.getPool(),this ).write(out,this);
        out.end("topLevel");
      }
     
     
      {// compute the base type of possible top-level classes
        final Set rootClasses = new java.util.HashSet();
        grammar.getTopLevel().visit( new ExpressionWalker(){
          private Set visitedExps = new java.util.HashSet();
          public void onOther( OtherExp exp ) {
            if( exp instanceof TypeItem )
              rootClasses.add(exp);
            // we don't need to parse inside a JavaItem.
View Full Code Here

            ComplexTypeExp cexp = baseSchema.complexTypes.get(baseTypeName[1]);
            if(cexp!=null) {
                // we've found the complex type as the base type
                // look for XSDatatypeExp inside
                final XSDatatypeExp[] dexp = new XSDatatypeExp[1];
                cexp.body.visit(new ExpressionWalker() {
                    public void onAttribute( AttributeExp exp ) {
                        // don't visit inside attributes
                    }
                    public void onRef( ReferenceExp exp ) {
                        if(exp instanceof XSDatatypeExp) {
View Full Code Here

TOP

Related Classes of com.sun.msv.grammar.util.ExpressionWalker

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.