You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@xalan.apache.org by mu...@apache.org on 2024/08/02 11:44:24 UTC

(xalan-java) branch xalan-j_xslt3.0 updated: committing implementation of jira issue XALANJ-2766 with few conformance tests, and code refactoring as well

This is an automated email from the ASF dual-hosted git repository.

mukulg pushed a commit to branch xalan-j_xslt3.0
in repository https://gitbox.apache.org/repos/asf/xalan-java.git


The following commit(s) were added to refs/heads/xalan-j_xslt3.0 by this push:
     new 7f2acf9e3 committing implementation of jira issue XALANJ-2766 with few conformance tests, and code refactoring as well
7f2acf9e3 is described below

commit 7f2acf9e3e5343aa3db22d9c8f5eb66c7693f6b7
Author: Mukul Gandhi <ga...@gmail.com>
AuthorDate: Fri Aug 2 17:14:11 2024 +0530

    committing implementation of jira issue XALANJ-2766 with few conformance tests, and code refactoring as well
---
 .../apache/xalan/processor/StylesheetHandler.java  |  20 +-
 .../apache/xalan/templates/ElemApplyTemplates.java |   2 +-
 src/org/apache/xalan/templates/ElemCopyOf.java     |   2 +
 src/org/apache/xalan/templates/ElemFunction.java   |  75 +++-
 .../xalan/templates/ElemIterateNextIteration.java  |   2 +-
 src/org/apache/xalan/templates/ElemParam.java      |   2 +-
 src/org/apache/xalan/templates/ElemTemplate.java   |   2 +-
 .../xalan/templates/ElemTemplateElement.java       |  10 +
 src/org/apache/xalan/templates/ElemVariable.java   |  24 +-
 src/org/apache/xalan/templates/ElemWithParam.java  |   2 +-
 .../xslt/util/XslTransformSharedDatastore.java     |  22 +-
 src/org/apache/xpath/compiler/Compiler.java        |  32 +-
 src/org/apache/xpath/compiler/OpCodes.java         |   4 +-
 src/org/apache/xpath/compiler/XPathParser.java     | 432 ++++++++++++++++-----
 .../apache/xpath/composite/SequenceTypeData.java   |  55 +--
 .../xpath/composite/SequenceTypeKindTest.java      |  26 +-
 .../xpath/composite/SequenceTypeSupport.java       | 296 +++++++++-----
 .../xpath/composite/XPathSequenceTypeExpr.java     |  66 ++--
 src/org/apache/xpath/functions/FuncBoolean.java    |   6 +-
 src/org/apache/xpath/functions/FuncDeepEqual.java  |  21 +-
 src/org/apache/xpath/functions/FuncNot.java        |   4 +-
 .../xpath/functions/XPathDynamicFunctionCall.java  |   4 +-
 ...SLConstructorStylesheetOrExtensionFunction.java |   6 +
 .../apache/xpath/functions/XSLFunctionService.java |  42 +-
 src/org/apache/xpath/objects/XObject.java          |  16 +-
 src/org/apache/xpath/operations/CastAs.java        |  11 +-
 src/org/apache/xpath/operations/InstanceOf.java    | 144 +++----
 src/org/apache/xpath/operations/Operation.java     |   2 +
 .../xpath/operations/{CastAs.java => TreatAs.java} |   9 +-
 .../apache/xalan/xslt3/XSLImportSchemaTests.java   |  20 +
 tests/xsl_import_schema/address.xsd                |  26 ++
 tests/xsl_import_schema/gold/test8.out             |  20 +
 tests/xsl_import_schema/test2.xml                  |  28 ++
 tests/xsl_import_schema/test8.xsl                  |  58 +++
 tests/xsl_import_schema/test9.xsl                  |  82 ++++
 35 files changed, 1169 insertions(+), 404 deletions(-)

diff --git a/src/org/apache/xalan/processor/StylesheetHandler.java b/src/org/apache/xalan/processor/StylesheetHandler.java
index 20491bf96..a563c2335 100644
--- a/src/org/apache/xalan/processor/StylesheetHandler.java
+++ b/src/org/apache/xalan/processor/StylesheetHandler.java
@@ -38,6 +38,7 @@ import org.apache.xalan.templates.ElemForEach;
 import org.apache.xalan.templates.ElemTemplateElement;
 import org.apache.xalan.templates.Stylesheet;
 import org.apache.xalan.templates.StylesheetRoot;
+import org.apache.xalan.xslt.util.XslTransformSharedDatastore;
 import org.apache.xml.utils.BoolStack;
 import org.apache.xml.utils.NamespaceSupport2;
 import org.apache.xml.utils.NodeConsumer;
@@ -114,9 +115,8 @@ public class StylesheetHandler extends DefaultHandler
             TransformerFactoryImpl.FEATURE_INCREMENTAL)).booleanValue();
     m_source_location = ((Boolean) processor.getAttribute(
             TransformerFactoryImpl.FEATURE_SOURCE_LOCATION)).booleanValue();
-    // m_schema = new XSLTSchema();
+    // m_schema = new XSLTSchema();    
     init(processor);
-    
   }
 
   /**
@@ -1196,12 +1196,16 @@ public class StylesheetHandler extends DefaultHandler
    */
   public StylesheetRoot getStylesheetRoot()
   {
-    if (m_stylesheetRoot != null){
-        m_stylesheetRoot.setOptimizer(m_optimize);
-        m_stylesheetRoot.setIncremental(m_incremental);
-        m_stylesheetRoot.setSource_location(m_source_location);  		
-    }
-    return m_stylesheetRoot;
+	  if (m_stylesheetRoot != null){
+		  m_stylesheetRoot.setOptimizer(m_optimize);
+		  m_stylesheetRoot.setIncremental(m_incremental);
+		  m_stylesheetRoot.setSource_location(m_source_location);  		
+	  }
+
+	  XslTransformSharedDatastore.stylesheetRoot = m_stylesheetRoot;
+	  XslTransformSharedDatastore.xslSystemId = getSystemId();
+
+	  return m_stylesheetRoot;
   }
 
   /** The root stylesheet of the stylesheets tree. */
diff --git a/src/org/apache/xalan/templates/ElemApplyTemplates.java b/src/org/apache/xalan/templates/ElemApplyTemplates.java
index e289ca009..c8b476f3e 100644
--- a/src/org/apache/xalan/templates/ElemApplyTemplates.java
+++ b/src/org/apache/xalan/templates/ElemApplyTemplates.java
@@ -440,7 +440,7 @@ public class ElemApplyTemplates extends ElemCallTemplate
                NodeList nodeList = (new XRTreeFrag(dtmNodeHandle, xctxt, template)).convertToNodeset();             
                XObject templateEvalResultForAsAttr = new XNodeSetForDOM(nodeList, xctxt);
                
-               templateEvalResultForAsAttr = SequenceTypeSupport.convertXdmValueToAnotherType(templateEvalResultForAsAttr, templateAsAttrVal, 
+               templateEvalResultForAsAttr = SequenceTypeSupport.castXdmValueToAnotherType(templateEvalResultForAsAttr, templateAsAttrVal, 
                                                                                                                                           null, xctxt);
                if (templateEvalResultForAsAttr != null) {
                    SerializationHandler handler = transformer.getSerializationHandler();        
diff --git a/src/org/apache/xalan/templates/ElemCopyOf.java b/src/org/apache/xalan/templates/ElemCopyOf.java
index 5a5522672..576cdce74 100644
--- a/src/org/apache/xalan/templates/ElemCopyOf.java
+++ b/src/org/apache/xalan/templates/ElemCopyOf.java
@@ -181,6 +181,8 @@ public class ElemCopyOf extends ElemTemplateElement
     {
       XPathContext xctxt = transformer.getXPathContext();
       
+      setXPathContext(xctxt);
+      
       SourceLocator srcLocator = xctxt.getSAXLocator();
               
       int sourceNode = xctxt.getCurrentNode();
diff --git a/src/org/apache/xalan/templates/ElemFunction.java b/src/org/apache/xalan/templates/ElemFunction.java
index a740a8f82..cfb21f3eb 100644
--- a/src/org/apache/xalan/templates/ElemFunction.java
+++ b/src/org/apache/xalan/templates/ElemFunction.java
@@ -28,6 +28,7 @@ import javax.xml.transform.TransformerException;
 import org.apache.xalan.transformer.TransformerImpl;
 import org.apache.xalan.xslt.util.XslTransformEvaluationHelper;
 import org.apache.xalan.xslt.util.XslTransformSharedDatastore;
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xml.dtm.ref.DTMNodeList;
 import org.apache.xml.utils.PrefixResolver;
 import org.apache.xml.utils.QName;
@@ -224,13 +225,37 @@ public class ElemFunction extends ElemTemplate
           for (ElemTemplateElement elem = getFirstChildElem(); elem != null; 
                                                                   elem = elem.getNextSiblingElem()) {
               if (elem.getXSLToken() == Constants.ELEMNAME_PARAMVARIABLE) {
-                 XObject argValue = argSequence.item(paramIdx);
-                 XObject argConvertedVal = argValue;
-                 String paramAsAttrStrVal = ((ElemParam)elem).getAs();              
+                 XObject argValue = argSequence.item(paramIdx);                 
+                 XObject argConvertedVal = null;
+                 String paramAsAttrStrVal = ((ElemParam)elem).getAs();
+                 
                  if (paramAsAttrStrVal != null) {
                     try {
-                       argConvertedVal = SequenceTypeSupport.convertXDMValueToAnotherType(argValue, paramAsAttrStrVal, null, 
+                       XNodeSet nodeSet = SequenceTypeSupport.getNodeReference(argValue);
+                       if (nodeSet != null) {
+                    	  XSTypeDefinition typeDef = nodeSet.getXsTypeDefinition();                    	  
+                    	  if (typeDef != null) {
+                    		  XPath seqTypeXPath = new XPath(paramAsAttrStrVal, srcLocator, xctxt.getNamespaceContext(), 
+                                                                                                             XPath.SELECT, null, true);            
+                              XObject seqTypeExpressionEvalResult = seqTypeXPath.execute(xctxt, xctxt.getContextNode(), xctxt.getNamespaceContext());
+                              SequenceTypeData seqExpectedTypeData = (SequenceTypeData)seqTypeExpressionEvalResult;
+                              XSTypeDefinition typeDef2 = seqExpectedTypeData.getXsTypeDefinition();
+                              if (typeDef2 != null && isTypeXsDefinitionEqual(typeDef, typeDef2)) {                            	  
+                            	  argConvertedVal = nodeSet;                      			
+                              }
+                              else {
+                            	  throw new TransformerException("XPTY0004 : Function call argument at position " + (paramIdx + 1) + " for "
+                                                                                                  + "function {" + funcNameSpaceUri + "}" + funcLocalName + "(), doesn't "
+                                                                                                  + "match the declared parameter type " + paramAsAttrStrVal + ".", srcLocator);
+                              }
+                    	  }
+                       }
+                       
+                       if (argConvertedVal == null) {
+                          argConvertedVal = SequenceTypeSupport.castXDMValueToAnotherType(argValue, paramAsAttrStrVal, null, 
                     		                                                                                        xctxt, elem.getPrefixTable());
+                       }
+                       
                        if (argConvertedVal == null) {
                           throw new TransformerException("XPTY0004 : Function call argument at position " + (paramIdx + 1) + " for "
                                                                             + "function {" + funcNameSpaceUri + "}" + funcLocalName + "(), doesn't "
@@ -249,6 +274,9 @@ public class ElemFunction extends ElemTemplate
                        }
                     }
                  }
+                 else {
+                	argConvertedVal = argValue;  
+                 }
                  
                  if (argConvertedVal instanceof ResultSequence) {                
                     XNodeSet nodeSet = XslTransformEvaluationHelper.getXNodeSetFromResultSequence((ResultSequence)argConvertedVal, 
@@ -257,7 +285,7 @@ public class ElemFunction extends ElemTemplate
                        argConvertedVal = nodeSet;  
                     }
                  }
-                  
+                 
                  varStack.setLocalVariable(paramIdx, argConvertedVal, argsFrame);
                  paramIdx++;
               }
@@ -298,7 +326,7 @@ public class ElemFunction extends ElemTemplate
              funcResultConvertedVal = preprocessXslFunctionOrAVariableResult(result, funcAsAttrStrVal, xctxt, null);
             
              if (funcResultConvertedVal == null) {
-                funcResultConvertedVal = SequenceTypeSupport.convertXdmValueToAnotherType(result, funcAsAttrStrVal, null, xctxt);
+                funcResultConvertedVal = SequenceTypeSupport.castXdmValueToAnotherType(result, funcAsAttrStrVal, null, xctxt);
                 
                 if (funcResultConvertedVal == null) {
                    throw new TransformerException("XPTY0004 : The function call result for function {" + funcNameSpaceUri + "}" + funcLocalName + 
@@ -321,8 +349,8 @@ public class ElemFunction extends ElemTemplate
       
       return funcResultConvertedVal;
   }
-  
-  /**
+
+/**
    * This function is called after everything else has been
    * recomposed, and allows a xsl:function to set remaining
    * values that may be based on some other property that
@@ -397,14 +425,14 @@ public class ElemFunction extends ElemTemplate
                    String[] strParts = strVal.split(ElemSequence.STRING_VAL_SERIALIZATION_SUFFIX);
                    for (int idx = 0; idx < strParts.length; idx++) {
                       String seqItemStrVal = strParts[idx];
-                      XObject xObject = getXSTypedAtomicValue(seqItemStrVal, seqExpectedTypeData.getSequenceType());
+                      XObject xObject = getXSTypedAtomicValue(seqItemStrVal, seqExpectedTypeData.getBuiltInSequenceType());
                       if (xObject != null) {
                          resultSequence.add(xObject);
                       }
                    }
                 }
                 else {
-                   XObject xObject = getXSTypedAtomicValue(strVal, seqExpectedTypeData.getSequenceType());
+                   XObject xObject = getXSTypedAtomicValue(strVal, seqExpectedTypeData.getBuiltInSequenceType());
                    if (xObject != null) {
                       resultSequence.add(xObject);
                    }
@@ -416,7 +444,7 @@ public class ElemFunction extends ElemTemplate
      if (seqExpectedTypeData.getSequenceTypeKindTest() == null) {
          if ((seqExpectedTypeData.getItemTypeOccurrenceIndicator() == 0) || 
                                                                (seqExpectedTypeData.getItemTypeOccurrenceIndicator() == 
-                                                                                                               SequenceTypeSupport.OccurenceIndicator.ZERO_OR_ONE)) {
+                                                                                                               SequenceTypeSupport.OccurrenceIndicator.ZERO_OR_ONE)) {
              if ((resultSequence != null) && (resultSequence.size() > 1)) {
                 String errMesg = null;
                 if (m_name != null) {
@@ -565,5 +593,30 @@ public class ElemFunction extends ElemTemplate
      
       return result;
   }
+  
+  /**
+   * Check whether two XSTypeDefinition objects, represent the same schema type. 
+   */
+  private boolean isTypeXsDefinitionEqual(XSTypeDefinition typeDef1, XSTypeDefinition typeDef2) {	  
+	  boolean result = false;
+
+	  String typeName1 = typeDef1.getName();
+	  String typeNamespace1 = typeDef1.getNamespace();
+
+	  String typeName2 = typeDef2.getName();
+	  String typeNamespace2 = typeDef2.getNamespace();
+	  
+	  if ((typeNamespace1 == null) && (typeNamespace2 == null)) {
+		 result = typeName1.equals(typeName2);   
+	  }
+	  else if (((typeNamespace1 == null) && (typeNamespace2 != null)) || ((typeNamespace1 != null) && (typeNamespace2 == null))) {
+		 result = false; 
+	  }
+	  else if (typeNamespace1.equals(typeNamespace2) && typeName1.equals(typeName2)) {
+		 result = true; 
+	  }
+
+	  return result;
+  }
 
 }
diff --git a/src/org/apache/xalan/templates/ElemIterateNextIteration.java b/src/org/apache/xalan/templates/ElemIterateNextIteration.java
index d08efc5e7..3662829b9 100644
--- a/src/org/apache/xalan/templates/ElemIterateNextIteration.java
+++ b/src/org/apache/xalan/templates/ElemIterateNextIteration.java
@@ -254,7 +254,7 @@ public class ElemIterateNextIteration extends ElemTemplateElement implements Exp
                 String withParamAsAttr = elemWithParam.getAs();
                 if (withParamAsAttr != null) {
                    try {
-                      withParamVal = SequenceTypeSupport.convertXdmValueToAnotherType(withParamVal, withParamAsAttr, null, 
+                      withParamVal = SequenceTypeSupport.castXdmValueToAnotherType(withParamVal, withParamAsAttr, null, 
                                                                                                                  transformer.getXPathContext());
                    }
                    catch (TransformerException ex) {
diff --git a/src/org/apache/xalan/templates/ElemParam.java b/src/org/apache/xalan/templates/ElemParam.java
index 75a26bbed..fe118748d 100644
--- a/src/org/apache/xalan/templates/ElemParam.java
+++ b/src/org/apache/xalan/templates/ElemParam.java
@@ -186,7 +186,7 @@ public class ElemParam extends ElemVariable
     	if (asAttrVal != null) {
     		try {
     			XObject var = transformer.getXPathContext().getVarStack().getLocalVariable(xctx, m_index);
-    			var = SequenceTypeSupport.convertXdmValueToAnotherType(var, asAttrVal, null, transformer.getXPathContext());
+    			var = SequenceTypeSupport.castXdmValueToAnotherType(var, asAttrVal, null, transformer.getXPathContext());
     			if (var == null) {
     				throw new TransformerException("XTTE0590 : The required item type of the value of parameter " + 
     						                                     m_qname.toString() + " is " + asAttrVal + ". The supplied value "
diff --git a/src/org/apache/xalan/templates/ElemTemplate.java b/src/org/apache/xalan/templates/ElemTemplate.java
index 21384664c..f84d29f9c 100644
--- a/src/org/apache/xalan/templates/ElemTemplate.java
+++ b/src/org/apache/xalan/templates/ElemTemplate.java
@@ -430,7 +430,7 @@ public class ElemTemplate extends ElemTemplateElement
                }
            }
            else {
-        	   templateEvalResultForAsAttr = SequenceTypeSupport.convertXdmValueToAnotherType(templateEvalResultForAsAttr, m_asAttr, 
+        	   templateEvalResultForAsAttr = SequenceTypeSupport.castXdmValueToAnotherType(templateEvalResultForAsAttr, m_asAttr, 
         			                                                                                                             null, xctxt);
         	   if (templateEvalResultForAsAttr == null) {
         		   String errTemplateStr = (m_name != null) ? m_name.toString() : m_matchPattern.getPatternString();
diff --git a/src/org/apache/xalan/templates/ElemTemplateElement.java b/src/org/apache/xalan/templates/ElemTemplateElement.java
index c45902d95..5828bbf14 100644
--- a/src/org/apache/xalan/templates/ElemTemplateElement.java
+++ b/src/org/apache/xalan/templates/ElemTemplateElement.java
@@ -91,6 +91,8 @@ public class ElemTemplateElement extends UnImplNode
     * This field supports implementation of, XSLT tunnel parameters.
     */
    private List<XObject> m_tunnelParamObjList = new ArrayList<XObject>();
+   
+   private XPathContext m_xpathContext;
 
   /**
    * Construct a template element instance.
@@ -1813,4 +1815,12 @@ public class ElemTemplateElement extends UnImplNode
 	 return m_tunnelParamObjList; 
   }
 
+  public XPathContext getXPathContext() {
+	 return m_xpathContext;
+  }
+
+  public void setXPathContext(XPathContext xpathContext) {
+	 this.m_xpathContext = xpathContext;
+  }
+
 }
diff --git a/src/org/apache/xalan/templates/ElemVariable.java b/src/org/apache/xalan/templates/ElemVariable.java
index 56a28c313..6d057102c 100644
--- a/src/org/apache/xalan/templates/ElemVariable.java
+++ b/src/org/apache/xalan/templates/ElemVariable.java
@@ -373,7 +373,7 @@ public class ElemVariable extends ElemTemplateElement
             	
             	String evalResultStrValue = (evalResult instanceof XSString) ? ((XSString)evalResult).stringValue() : null;            	
             	if (m_asAttr != null && !(XSLFunctionService.XS_VALID_TRUE).equals(evalResultStrValue)) {           	     
-                   evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
+                   evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
                    if (evalResult == null) {
                 	  String xpathPatternStr = m_selectPattern.getPatternString();
                 	  throw new TransformerException("XTTE0570 : The supplied value " + xpathPatternStr + ", doesn't "
@@ -409,7 +409,7 @@ public class ElemVariable extends ElemTemplateElement
             if ((evalResult instanceof ResultSequence) || (evalResult instanceof XPathArray) || 
                                                 (evalResult instanceof XSAnyType)) {
                 if (m_asAttr != null) {
-                   evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
+                   evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
                    if (evalResult == null) {
                  	  throw new javax.xml.transform.TransformerException("XTTE0570 : variable's computed value is not of "
                  	  		                                                        + "an expected type " + m_asAttr +".", srcLocator); 
@@ -423,7 +423,7 @@ public class ElemVariable extends ElemTemplateElement
             XObject evalResult = selectExpression.execute(xctxt);
             
             if (m_asAttr != null) {
-               evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
+               evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
                if (evalResult == null) {
              	  throw new javax.xml.transform.TransformerException("XTTE0570 : variable's computed value is not of "
              	  		                                                         + "an expected type " + m_asAttr +".", srcLocator); 
@@ -436,7 +436,7 @@ public class ElemVariable extends ElemTemplateElement
             XObject evalResult = selectExpression.execute(xctxt);
             
             if (m_asAttr != null) {
-               evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
+               evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
                if (evalResult == null) {
               	  throw new javax.xml.transform.TransformerException("XTTE0570 : variable's computed value is not of "
               	  		                                                         + "an expected type " + m_asAttr +".", srcLocator); 
@@ -459,7 +459,7 @@ public class ElemVariable extends ElemTemplateElement
             }
             
             if (m_asAttr != null) {
-               evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
+               evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, m_asAttr, null, xctxt);
                if (evalResult == null) {
             	  throw new javax.xml.transform.TransformerException("XTTE0570 : variable's computed value is not of "
             	  		                                                         + "an expected type " + m_asAttr +".", srcLocator); 
@@ -472,7 +472,7 @@ public class ElemVariable extends ElemTemplateElement
             XObject xpath3ContextItem = xctxt.getXPath3ContextItem();
             if (xpath3ContextItem != null) {               
               if (m_asAttr != null) {
-                 xpath3ContextItem = SequenceTypeSupport.convertXdmValueToAnotherType(xpath3ContextItem, m_asAttr, 
+                 xpath3ContextItem = SequenceTypeSupport.castXdmValueToAnotherType(xpath3ContextItem, m_asAttr, 
                                                                                                                null, xctxt);  
               }
                 
@@ -496,7 +496,7 @@ public class ElemVariable extends ElemTemplateElement
                var = new XNodeSet(dtmIter);
                
                if (m_asAttr != null) {
-                  var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt);  
+                  var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt);  
                }
                  
                return var; 
@@ -589,7 +589,7 @@ public class ElemVariable extends ElemTemplateElement
                var = resultSeq;
                
                if (m_asAttr != null) {
-                  var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt);  
+                  var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt);  
                }
                   
                return var;
@@ -669,12 +669,12 @@ public class ElemVariable extends ElemTemplateElement
              var = variableConvertedVal;    
           }
           else {
-             var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt); 
+             var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt); 
           }
        }
        else if (var instanceof XPathMap) {
     	  try {
-    	     var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt);
+    	     var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt);
     	  }
     	  catch (TransformerException ex) {
     		 String errMesg = ex.getMessage();
@@ -691,7 +691,7 @@ public class ElemVariable extends ElemTemplateElement
        }
        else if (var instanceof XPathArray) {
     	  try {
-      	     var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt);
+      	     var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt);
       	  }
       	  catch (TransformerException ex) {
       		 String errMesg = ex.getMessage();
@@ -708,7 +708,7 @@ public class ElemVariable extends ElemTemplateElement
        }
        else {
     	  try {
-             var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, xctxt);
+             var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, xctxt);
     	  }
     	  catch (TransformerException ex) {
     		 throw ex; 
diff --git a/src/org/apache/xalan/templates/ElemWithParam.java b/src/org/apache/xalan/templates/ElemWithParam.java
index 3ab02f7be..2b0d2be00 100644
--- a/src/org/apache/xalan/templates/ElemWithParam.java
+++ b/src/org/apache/xalan/templates/ElemWithParam.java
@@ -299,7 +299,7 @@ public class ElemWithParam extends ElemTemplateElement
     }
     
     if (m_asAttr != null) {
-       var = SequenceTypeSupport.convertXdmValueToAnotherType(var, m_asAttr, null, 
+       var = SequenceTypeSupport.castXdmValueToAnotherType(var, m_asAttr, null, 
                                                                           transformer.getXPathContext());
        if (var == null) {
           throw new TransformerException("XTTE0590 : The required item type of the value of argument used for xsl:with-param " + 
diff --git a/src/org/apache/xalan/xslt/util/XslTransformSharedDatastore.java b/src/org/apache/xalan/xslt/util/XslTransformSharedDatastore.java
index 09acc1ec6..b65dc7abe 100644
--- a/src/org/apache/xalan/xslt/util/XslTransformSharedDatastore.java
+++ b/src/org/apache/xalan/xslt/util/XslTransformSharedDatastore.java
@@ -16,10 +16,13 @@
  */
 package org.apache.xalan.xslt.util;
 
+import org.apache.xalan.templates.StylesheetRoot;
 import org.apache.xpath.objects.XPathInlineFunction;
 
 /**
- * This class, has few Xalan-J, XSL stylesheet transformation wide variables.
+ * This class, has few XSL stylesheet transformation-wide 
+ * variables that're used during evaluation of specific XSLT 
+ * instructions and XPath expressions.
  * 
  * @author Mukul Gandhi <mu...@apache.org>
  * 
@@ -27,11 +30,22 @@ import org.apache.xpath.objects.XPathInlineFunction;
  */
 public class XslTransformSharedDatastore {
     
-    // XSL stylesheet document's uri, used for error handling
+	/**    
+     * This class field represents, an XSL stylesheet 
+     * document's uri, if available.
+     */
     public static String xslSystemId;
     
-    // Used to return function items, from XSL stylesheet 
-    // xsl:function calls.
+    /**
+     * This class field represents, function items that're 
+     * returned from XSL stylesheet xsl:function calls.
+     */
     public static XPathInlineFunction xpathInlineFunction;
+    
+    /**
+     * This class field represents, compiled representation 
+     * of an XSL stylesheet.
+     */
+    public static StylesheetRoot stylesheetRoot;
 
 }
diff --git a/src/org/apache/xpath/compiler/Compiler.java b/src/org/apache/xpath/compiler/Compiler.java
index e51f20949..32efe2780 100644
--- a/src/org/apache/xpath/compiler/Compiler.java
+++ b/src/org/apache/xpath/compiler/Compiler.java
@@ -72,6 +72,7 @@ import org.apache.xpath.operations.Plus;
 import org.apache.xpath.operations.Range;
 import org.apache.xpath.operations.SimpleMapOperator;
 import org.apache.xpath.operations.StrConcat;
+import org.apache.xpath.operations.TreatAs;
 import org.apache.xpath.operations.UnaryOperation;
 import org.apache.xpath.operations.Variable;
 import org.apache.xpath.operations.VcEquals;
@@ -113,18 +114,17 @@ public class Compiler extends OpMap
    *
    * @param errorHandler Error listener where messages will be sent, or null 
    *                     if messages should be sent to System err.
-   * @param locator The location object where the expression lives, which 
-   *                may be null, but which, if not null, must be valid over 
-   *                the long haul, in other words, it will not be cloned.
-   * @param fTable  The FunctionTable object where the xpath build-in 
-   *                functions are stored.
+   * @param locator      The location object where the expression lives, which 
+   *                     may be null, but which, if not null, must be valid over 
+   *                     the long haul, in other words, it will not be cloned.
+   * @param funcTable    The FunctionTable object where the xpath build-in 
+   *                     functions are stored.
    */
-  public Compiler(ErrorListener errorHandler, SourceLocator locator, 
-            FunctionTable fTable)
+  public Compiler(ErrorListener errorHandler, SourceLocator locator, FunctionTable funcTable)
   {
     m_errorHandler = errorHandler;
     m_locator = locator;
-    m_functionTable = fTable;
+    m_functionTable = funcTable;
   }
 
   /**
@@ -205,7 +205,9 @@ public class Compiler extends OpMap
     case OpCodes.OP_CAST_AS :
       expr = castAsExpr(opPos); break;
     case OpCodes.OP_CASTABLE_AS :
-        expr = castableAsExpr(opPos); break;
+      expr = castableAsExpr(opPos); break;
+    case OpCodes.OP_TREAT_AS :
+      expr = treatAsExpr(opPos); break;
     case OpCodes.OP_LTE :
       expr = lte(opPos); break;
     case OpCodes.OP_LT :
@@ -603,6 +605,18 @@ public class Compiler extends OpMap
   {
 	return compileOperation(new CastableAs(), opPos); 
   }
+  
+  /**
+   * Compile a 'treat as' operation.
+   * 
+   * @param    opPos The current position in the m_opMap array.
+   * @return   an XPath compiled representation of 'treat as' expression 
+   * @throws TransformerException
+   */
+  protected Expression treatAsExpr(int opPos) throws TransformerException
+  {
+	return compileOperation(new TreatAs(), opPos); 
+  }
 
   /**
    * Compile a '>=' operation.
diff --git a/src/org/apache/xpath/compiler/OpCodes.java b/src/org/apache/xpath/compiler/OpCodes.java
index 393447465..f4b18475c 100644
--- a/src/org/apache/xpath/compiler/OpCodes.java
+++ b/src/org/apache/xpath/compiler/OpCodes.java
@@ -740,8 +740,10 @@ public class OpCodes
   public static final int OP_ARROW = 79;
   
   public static final int OP_NAMED_FUNCTION_REFERENCE = 80;
+  
+  public static final int OP_TREAT_AS = 81;
 
   /** The next free ID. Please keep this up to date. */
-  private static final int NEXT_FREE_ID = 81;
+  private static final int NEXT_FREE_ID = 82;
   
 }
diff --git a/src/org/apache/xpath/compiler/XPathParser.java b/src/org/apache/xpath/compiler/XPathParser.java
index a52936d6d..2cf635377 100644
--- a/src/org/apache/xpath/compiler/XPathParser.java
+++ b/src/org/apache/xpath/compiler/XPathParser.java
@@ -20,7 +20,12 @@
  */
 package org.apache.xpath.compiler;
 
+import java.io.StringReader;
 import java.math.BigDecimal;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -34,16 +39,18 @@ import javax.xml.transform.ErrorListener;
 import javax.xml.transform.TransformerException;
 
 import org.apache.xalan.res.XSLMessages;
+import org.apache.xalan.templates.Constants;
+import org.apache.xalan.templates.StylesheetRoot;
+import org.apache.xalan.xslt.util.XslTransformSharedDatastore;
+import org.apache.xerces.dom.DOMInputImpl;
+import org.apache.xerces.impl.xs.XSLoaderImpl;
+import org.apache.xerces.xs.XSModel;
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xml.utils.PrefixResolver;
+import org.apache.xml.utils.QName;
 import org.apache.xpath.XPathProcessorException;
-import org.apache.xpath.composite.XPathForExpr;
 import org.apache.xpath.composite.ForQuantifiedExprVarBinding;
-import org.apache.xpath.composite.XPathIfExpr;
-import org.apache.xpath.composite.XPathLetExpr;
 import org.apache.xpath.composite.LetExprVarBinding;
-import org.apache.xpath.composite.XPathMapConstructor;
-import org.apache.xpath.composite.XPathNamedFunctionReference;
-import org.apache.xpath.composite.XPathQuantifiedExpr;
 import org.apache.xpath.composite.SequenceTypeArrayTest;
 import org.apache.xpath.composite.SequenceTypeData;
 import org.apache.xpath.composite.SequenceTypeFunctionTest;
@@ -51,15 +58,31 @@ import org.apache.xpath.composite.SequenceTypeKindTest;
 import org.apache.xpath.composite.SequenceTypeMapTest;
 import org.apache.xpath.composite.SequenceTypeSupport;
 import org.apache.xpath.composite.XPathArrayConstructor;
+import org.apache.xpath.composite.XPathForExpr;
+import org.apache.xpath.composite.XPathIfExpr;
+import org.apache.xpath.composite.XPathLetExpr;
+import org.apache.xpath.composite.XPathMapConstructor;
+import org.apache.xpath.composite.XPathNamedFunctionReference;
+import org.apache.xpath.composite.XPathQuantifiedExpr;
 import org.apache.xpath.composite.XPathSequenceConstructor;
 import org.apache.xpath.composite.XPathSequenceTypeExpr;
 import org.apache.xpath.domapi.XPathStylesheetDOM3Exception;
 import org.apache.xpath.functions.XPathDynamicFunctionCall;
-import org.apache.xpath.objects.XPathInlineFunction;
+import org.apache.xpath.functions.XSLFunctionService;
 import org.apache.xpath.objects.InlineFunctionParameter;
 import org.apache.xpath.objects.XNumber;
+import org.apache.xpath.objects.XPathInlineFunction;
 import org.apache.xpath.objects.XString;
 import org.apache.xpath.res.XPATHErrorResources;
+import org.w3c.dom.DOMConfiguration;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.bootstrap.DOMImplementationRegistry;
+import org.w3c.dom.ls.DOMImplementationLS;
+import org.w3c.dom.ls.LSSerializer;
 
 import xml.xpath31.processor.types.XSDecimal;
 import xml.xpath31.processor.types.XSDouble;
@@ -133,7 +156,8 @@ public class XPathParser
    * When an XPath expression is () (i.e, representing an xdm empty sequence),
    * we translate that within this XPath parser implementation, to an XPath
    * range "to" expression using this class field (this equivalently produces
-   * an xdm empty sequence).
+   * an xdm empty sequence). There may be other direct ways of implementing this.
+   * Pls review.
    */
   public static final String XPATH_EXPR_STR_EMPTY_SEQUENCE = "1 to 0";
   
@@ -229,6 +253,8 @@ public class XPathParser
   
   private String m_arrowOpRemainingXPathExprStr = null;
   
+  private boolean isFunctionArgumentParse;
+  
   /**
    * The parser constructor.
    */
@@ -385,7 +411,7 @@ public class XPathParser
   javax.xml.transform.SourceLocator m_sourceLocator;
   
   /** The table contains build-in functions and customized functions */
-  private FunctionTable m_functionTable;
+  private FunctionTable m_functionTable;  
 
   /**
    * Allow an application to register an error event handler, where syntax 
@@ -761,7 +787,6 @@ public class XPathParser
    * not. We simultaneously accumulate function call argument details within a list 
    * 'argDetailsStrPartsList' (that has been passed as an argument to this method) 
    * whose contents are accessible to the caller of this method.
- * @throws TransformerException 
    */
   private boolean isXPathDynamicFuncCallParseAhead(List<String> argDetailsStrPartsList, 
 		                                           String delim) throws TransformerException {
@@ -916,26 +941,26 @@ public class XPathParser
    * XPath parse of sequence type expressions.
    */
   private void setSequenceTypeOccurenceIndicator(XPathSequenceTypeExpr xpathSequenceTypeExpr, 
-                                                                                   boolean isInlineFunction) throws TransformerException {
+                                                 boolean isXPathInlineFunctionParse) throws TransformerException {
       if (tokenIs(SequenceTypeSupport.Q_MARK)) {
          xpathSequenceTypeExpr.setItemTypeOccurrenceIndicator(SequenceTypeSupport.
-                                                                                 OccurenceIndicator.ZERO_OR_ONE);
+                                                                                 OccurrenceIndicator.ZERO_OR_ONE);
          nextToken();
       }
       else if (tokenIs(SequenceTypeSupport.STAR)) {
          xpathSequenceTypeExpr.setItemTypeOccurrenceIndicator(SequenceTypeSupport.
-                                                                                 OccurenceIndicator.ZERO_OR_MANY);
+                                                                                 OccurrenceIndicator.ZERO_OR_MANY);
          nextToken();
       }
       else if (tokenIs(SequenceTypeSupport.PLUS)) {
          xpathSequenceTypeExpr.setItemTypeOccurrenceIndicator(SequenceTypeSupport.
-                                                                                 OccurenceIndicator.ONE_OR_MANY);
+                                                                                 OccurrenceIndicator.ONE_OR_MANY);
          nextToken();
       }
-      else if (!isInlineFunction) {
+      else if ((m_token != null) && !isXPathInlineFunctionParse) {
          throw new javax.xml.transform.TransformerException("XPST0051 A sequence type occurence indicator '" + m_token + "', is not recognized."); 
       }
-   }
+  }
   
   /**
    * Given an XML node's raw name like abc:pqr, this method returns
@@ -976,10 +1001,12 @@ public class XPathParser
        nextToken();
        consumeExpected('(');
        String nodeKindTestStr = "";
+       
        while (!tokenIs(")") && m_token != null) {
            nodeKindTestStr += m_token;
            nextToken();
        }
+       
        if (tokenIs(')')) {
            if (isInlineFunction) {
                nextToken();                
@@ -1018,6 +1045,10 @@ public class XPathParser
            sequenceTypeKindTest.setNodeNsUri(nodeNsParts[1]);
            sequenceTypeKindTest.setDataTypeName(nodeDataTypeParts[0]);
            sequenceTypeKindTest.setDataTypeUri(nodeDataTypeParts[1]);
+           if (nodeDataTypeParts[1] == null) {
+        	  // Check for a possibility, of data type being an user-defined schema type
+        	  parseSequenceTypeExprWithUserDefinedType(xpathSequenceTypeExpr, nodeDataTypeParts[0]);
+           }
        }
        else if (seqTypeSubParts.length > 2) {
            throw new javax.xml.transform.TransformerException("XPST0051 : The sequence type expression is "
@@ -2704,6 +2735,22 @@ public class XPathParser
           
           m_xpathSequenceTypeExpr = SequenceTypeExpr(false);
           
+          m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH, 
+                                                  m_ops.getOp(addPos + op1 + 1) + op1);
+          addPos += 2;
+      }
+      else if (tokenIs("treat") && lookahead("as", 1)) {
+          // XPath parse of "treat as" expression    	  
+          
+          consumeExpected("treat");
+          consumeExpected("as");
+          
+          insertOp(addPos, 2, OpCodes.OP_TREAT_AS);
+          
+          int op1 = m_ops.getOp(OpMap.MAPINDEX_LENGTH) - addPos;          
+          
+          m_xpathSequenceTypeExpr = SequenceTypeExpr(false);
+          
           m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH, 
                                                   m_ops.getOp(addPos + op1 + 1) + op1);
           addPos += 2;
@@ -3297,7 +3344,7 @@ public class XPathParser
                      nextToken();                     
                      SequenceTypeData paramType = new SequenceTypeData();
                      XPathSequenceTypeExpr seqTypeExpr = SequenceTypeExpr(true);
-                     paramType.setSequenceType(seqTypeExpr.getSequenceType());
+                     paramType.setBuiltInSequenceType(seqTypeExpr.getBuiltInSequenceType());
                      paramType.setItemTypeOccurrenceIndicator(seqTypeExpr.getItemTypeOccurrenceIndicator());
                      paramType.setSequenceTypeKindTest(seqTypeExpr.getSequenceTypeKindTest());
                      paramType.setSequenceTypeFunctionTest(seqTypeExpr.getSequenceTypeFunctionTest());
@@ -3333,7 +3380,7 @@ public class XPathParser
          nextToken();
          XPathSequenceTypeExpr seqTypeExpr = SequenceTypeExpr(true);
          SequenceTypeData returnType = new SequenceTypeData();
-         returnType.setSequenceType(seqTypeExpr.getSequenceType());
+         returnType.setBuiltInSequenceType(seqTypeExpr.getBuiltInSequenceType());
          returnType.setItemTypeOccurrenceIndicator(seqTypeExpr.getItemTypeOccurrenceIndicator());
          returnType.setSequenceTypeKindTest(seqTypeExpr.getSequenceTypeKindTest());
          
@@ -3379,7 +3426,9 @@ public class XPathParser
   protected void Argument() throws javax.xml.transform.TransformerException
   {
 	
-    int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
+    isFunctionArgumentParse = true;
+    
+	int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
     
     appendOp(2, OpCodes.OP_ARGUMENT);
     
@@ -3574,6 +3623,7 @@ public class XPathParser
     
     m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
                                            m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
+    isFunctionArgumentParse = false;
     
   }
 
@@ -4791,11 +4841,11 @@ public class XPathParser
    /**
     * XPath parse of sequence type expressions.
     */
-   private XPathSequenceTypeExpr SequenceTypeExpr(boolean isInlineFunction) 
+   private XPathSequenceTypeExpr SequenceTypeExpr(boolean isXPathInlineFunctionParse) 
  		                                                                 throws javax.xml.transform.TransformerException {
        int opPos = 0;
        
-       if (!isInlineFunction) {
+       if (!isXPathInlineFunctionParse) {
           opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);                  
           insertOp(opPos, 2, OpCodes.OP_SEQUENCE_TYPE_EXPR);
        }
@@ -4805,19 +4855,19 @@ public class XPathParser
        SequenceTypeKindTest sequenceTypeKindTest = null;
        
        if (tokenIs("empty-sequence") && lookahead('(', 1) && lookahead(')', 2)) {
-           xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.EMPTY_SEQUENCE);
+           xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.EMPTY_SEQUENCE);
            consumeExpected("empty-sequence");
            consumeExpected('(');
            consumeExpected(')');
        }      
        else if (tokenIs("element")) {
            sequenceTypeKindTest = constructSequenceTypeKindTestForXDMNodes(xpathSequenceTypeExpr, 
-                                                                                         SequenceTypeSupport.ELEMENT_KIND, isInlineFunction);          
+                                                                                         SequenceTypeSupport.ELEMENT_KIND, isXPathInlineFunctionParse);          
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);          
        }
        else if (tokenIs("attribute")) {
            sequenceTypeKindTest = constructSequenceTypeKindTestForXDMNodes(xpathSequenceTypeExpr, 
-                                                                                         SequenceTypeSupport.ATTRIBUTE_KIND, isInlineFunction);          
+                                                                                         SequenceTypeSupport.ATTRIBUTE_KIND, isXPathInlineFunctionParse);          
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);
        }
        else if (tokenIs("text")) {
@@ -4828,7 +4878,7 @@ public class XPathParser
            consumeExpected(')');
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);
            if (m_token != null) {
-              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isInlineFunction); 
+              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isXPathInlineFunctionParse); 
            }          
        }
        else if (tokenIs("namespace-node")) {
@@ -4839,7 +4889,7 @@ public class XPathParser
            consumeExpected(')');
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);
            if (m_token != null) {
-              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isInlineFunction); 
+              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isXPathInlineFunctionParse); 
            }
        }
        else if (tokenIs("node")) { 
@@ -4850,7 +4900,7 @@ public class XPathParser
            consumeExpected(')');
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);
            if (m_token != null) {
-              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isInlineFunction);  
+              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isXPathInlineFunctionParse);  
            }
        }
        else if (tokenIs("item")) {
@@ -4861,7 +4911,7 @@ public class XPathParser
            consumeExpected(')');
            xpathSequenceTypeExpr.setSequenceTypeKindTest(sequenceTypeKindTest);
            if (m_token != null) {
-              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isInlineFunction);  
+              setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isXPathInlineFunctionParse);  
            }
        }
        else if (tokenIs("function")) {
@@ -4874,123 +4924,309 @@ public class XPathParser
            parseXdmArraySequenceType(xpathSequenceTypeExpr);
        }
        else if (tokenIs(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
-           parseXdmBuiltInXmlSchemaSequenceType(isInlineFunction, xpathSequenceTypeExpr);         
+           parseXdmBuiltInXmlSchemaSequenceType(xpathSequenceTypeExpr, isXPathInlineFunctionParse);         
        }
        else {
-           throw new javax.xml.transform.TransformerException("XPST0051 The sequence type '" + m_token + "' is not "
-                                                                                    + "recognized, within the provided sequence type expression."); 
+    	   // Check possibility of user-defined schema type specified within the sequence type expression
+    	   parseSequenceTypeExprWithUserDefinedType(xpathSequenceTypeExpr, null);                                                                                    
        }
        
-       if (!isInlineFunction) {
+       if (!isXPathInlineFunctionParse) {
           m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,
                                                  m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
        }
        
        return xpathSequenceTypeExpr;
    }
+
+   /**
+    * While XPath parse of sequence type expression, check for the possibility of
+    * user-defined schema type specified within the sequence type expression.
+    */
+   private void parseSequenceTypeExprWithUserDefinedType(XPathSequenceTypeExpr xpathSequenceTypeExpr, String typeName) 
+		                                                                                  throws TransformerException {
+
+	   StylesheetRoot stylesheetRoot = XslTransformSharedDatastore.stylesheetRoot;
+	   String xslSystemId = XslTransformSharedDatastore.xslSystemId;
+
+	   String type_namespace = null;
+	   String type_name = null;
+	   
+	   if (typeName == null) {
+		   type_namespace = m_token;
+		   type_name = null;
+		   nextToken();
+		   if (":".equals(m_token)) {
+			   nextToken();
+			   type_name = m_token;    		  
+		   }
+		   else {
+			   type_name = type_namespace;
+			   type_namespace = null;
+		   }
+	   }
+	   else {
+		   type_name = typeName;
+		   type_namespace = null;
+	   }
+
+	   HashMap stylesheetAvailableElems = stylesheetRoot.getAvailableElements();
+
+	   if (stylesheetAvailableElems.containsKey(new QName(Constants.S_XSLNAMESPACEURL, 
+			                                                     Constants.ELEMNAME_IMPORT_SCHEMA_STRING))) {
+		   Node elemTemplateElem = stylesheetRoot.getFirstChildElem();
+
+		   while (elemTemplateElem != null && !(Constants.ELEMNAME_IMPORT_SCHEMA_STRING).equals(elemTemplateElem.getLocalName())) {   
+			   elemTemplateElem = elemTemplateElem.getNextSibling();
+		   }
+
+		   NodeList nodeList = elemTemplateElem.getChildNodes();
+		   Node xsSchemaTopMostNode = nodeList.item(0);		   
+
+		   if (xsSchemaTopMostNode != null) {
+			   // xsl:import-schema instruction's child contents specifies a literal XML Schema document
+			   parseImportSchemaWithChildSchemaContents(xpathSequenceTypeExpr, type_namespace, type_name, xsSchemaTopMostNode); 
+		   }
+		   else {
+			   // An XML Schema document is available, at the uri referenced by xsl:import-schema 
+			   // element's attribute 'schema-location'.			   
+			   parseImportSchemaFromExternalLocation(xpathSequenceTypeExpr, xslSystemId, type_namespace, type_name, elemTemplateElem);
+		   }
+	   }
+   }
+
+   /**
+    * XPath parse of xsl:import-schema instruction, where schema details are available as child contents
+    * of xsl:import-schema element.
+    */
+   private void parseImportSchemaWithChildSchemaContents(XPathSequenceTypeExpr xpathSequenceTypeExpr, String typeNamespace,
+		                                                 String typeName, Node xsSchemaTopMostNode) throws TransformerException {
+	   String xmlSchemaDocumentStr = null;
+	   
+	   XSModel xsModel = null;
+	   XSLoaderImpl xsLoader = new XSLoaderImpl();
+
+	   try {
+		   DOMImplementationLS domImplLS = (DOMImplementationLS)((DOMImplementationRegistry.newInstance()).getDOMImplementation("LS"));
+		   LSSerializer lsSerializer = domImplLS.createLSSerializer();
+		   DOMConfiguration domConfig = lsSerializer.getDomConfig();
+		   domConfig.setParameter(XSLFunctionService.XML_DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
+		   xmlSchemaDocumentStr = lsSerializer.writeToString((Document)xsSchemaTopMostNode);
+		   xmlSchemaDocumentStr = xmlSchemaDocumentStr.replaceFirst(XSLFunctionService.UTF_16, XSLFunctionService.UTF_8);
+		   xmlSchemaDocumentStr = xmlSchemaDocumentStr.replaceFirst("schema", "schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"");
+
+		   DOMInputImpl lsInput = new DOMInputImpl();
+		   lsInput.setCharacterStream(new StringReader(xmlSchemaDocumentStr));
+
+		   xsModel = xsLoader.load(lsInput);    						
+
+		   if (xsModel != null) {
+			   XSTypeDefinition xsTypeDefinition = xsModel.getTypeDefinition(typeName, typeNamespace);
+			   if (xsTypeDefinition != null) {
+				   if (!isFunctionArgumentParse && tokenIs(')')) {
+					   consumeExpected(')');
+				   }
+				   xpathSequenceTypeExpr.setXsSequenceTypeDefinition(xsTypeDefinition);
+
+				   // TO handle occurrence indicator
+			   }
+			   else {
+				   throw new javax.xml.transform.TransformerException("FODC0005 : The child contents of xs:import-schema "
+						                                            + "instruction were successfully built to a valid XML schema, but this "
+						                                            + "schema doesn't contain the type definition with expanded name "
+						                                            + "{" + typeNamespace + "}:" + typeName + ".");							
+			   }	    							    						
+		   }
+		   else {
+			   throw new javax.xml.transform.TransformerException("FODC0005 : A valid XML schema could not be built, from child "
+					                                                                  + "contents of xs:import-schema instruction.");
+		   }
+	   }
+	   catch (Exception ex) {
+		   throw new TransformerException(ex.getMessage());
+	   }
+   }
+   
+   /**
+    * XPath parse of xsl:import-schema instruction, where schema details are available from
+    * xsl:import-schema element's attribute schema-location.
+    */
+   private void parseImportSchemaFromExternalLocation(XPathSequenceTypeExpr xpathSequenceTypeExpr, String xslSystemId,
+		                                              String typeNamespace, String typeName, Node elemTemplateElem) throws TransformerException {
+	   
+	   XSModel xsModel = null;
+	   XSLoaderImpl xsLoader = new XSLoaderImpl();
+
+	   NamedNodeMap importSchemaNodeAttributes = ((Element)elemTemplateElem).getAttributes();        			   
+
+	   if (importSchemaNodeAttributes != null) {
+		   Node attrNode1 = importSchemaNodeAttributes.item(0);
+		   Node attrNode2 = importSchemaNodeAttributes.item(1);	        			   	        			   	        			   
+
+		   try {
+			   URL url = null;							
+			   if (attrNode1 != null) {
+				   URI inpUri = new URI(attrNode1.getNodeValue());
+				   String stylesheetSystemId = xslSystemId;
+
+				   if (!inpUri.isAbsolute() && (stylesheetSystemId != null)) {
+					   URI resolvedUri = (new URI(stylesheetSystemId)).resolve(inpUri);
+					   url = resolvedUri.toURL(); 
+					   if (!"namespace".equals(attrNode1.getNodeName())) {
+						   xsModel = xsLoader.loadURI(url.toString());
+					   }
+				   }
+			   }
+
+			   if (attrNode2 != null && xsModel == null) {
+				   URI inpUri = new URI(attrNode2.getNodeValue());
+				   String stylesheetSystemId = xslSystemId;
+
+				   if (!inpUri.isAbsolute() && (stylesheetSystemId != null)) {
+					   URI resolvedUri = (new URI(stylesheetSystemId)).resolve(inpUri);
+					   url = resolvedUri.toURL();
+					   if ("schema-location".equals(attrNode2.getNodeName())) {
+						   xsModel = xsLoader.loadURI(url.toString());
+					   }
+				   }	        				  
+			   }
+
+			   if (xsModel != null) {
+				   XSTypeDefinition xsTypeDefinition = xsModel.getTypeDefinition(typeName, typeNamespace);
+				   if (xsTypeDefinition != null) {									
+					   if (!isFunctionArgumentParse && tokenIs(')')) {
+						   consumeExpected(')');
+					   }
+					   xpathSequenceTypeExpr.setXsSequenceTypeDefinition(xsTypeDefinition);
+
+					   // TO handle occurrence indicator
+				   }
+				   else {
+					   throw new javax.xml.transform.TransformerException("FODC0005 : A valid XML schema was found at "
+																					   + "uri " + url.toString() + ". But it doesn't contain a schema "
+																					   + "type definition with expanded name {" + typeNamespace + "}:" + 
+																					   typeName + ".");							
+				   }
+			   }
+			   else {
+				   throw new javax.xml.transform.TransformerException("FODC0005 : A valid XML schema could not be built, "
+																					   + "from document available at uri " + url.toString() + " referenced "
+																					   + "from xs:import-schema instruction.");
+			   }
+		   }
+		   catch (URISyntaxException ex) {
+			   throw new javax.xml.transform.TransformerException("FODC0005 : The schema uri specified with xsl:import-schema instruction "
+					   																   + "is not a valid absolute uri, or cannot be resolved to an absolute uri.");   
+		   }
+		   catch (MalformedURLException ex) {
+			   throw new javax.xml.transform.TransformerException("FODC0005 : The schema uri specified with xsl:import-schema instruction "
+					   																   + "is not a valid absolute uri, or cannot be resolved to an absolute uri."); 
+		   }						
+	   }
+   }
    
    /**
     * XPath parse of built-in XML Schema sequence type expressions.
     */
-   private void parseXdmBuiltInXmlSchemaSequenceType(boolean isInlineFunction, XPathSequenceTypeExpr xpathSequenceTypeExpr)
- 		                                                                      throws TransformerException {	  
+   private void parseXdmBuiltInXmlSchemaSequenceType(XPathSequenceTypeExpr xpathSequenceTypeExpr, 
+		                                             boolean isXPathInlineFunctionParse) throws TransformerException {	  
  	  
  	  consumeExpected(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  	  consumeExpected(':');
  	  
  	  switch (m_token) {
  	     case Keywords.FUNC_BOOLEAN_STRING :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.BOOLEAN);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.BOOLEAN);
  	        break;
  	     case Keywords.XS_STRING :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.STRING);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.STRING);
  	        break; 
  	     case Keywords.XS_NORMALIZED_STRING :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_NORMALIZED_STRING);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_NORMALIZED_STRING);
  	         break;
  	     case Keywords.XS_TOKEN :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_TOKEN);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_TOKEN);
  	         break;
  	     case Keywords.XS_DECIMAL :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DECIMAL);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DECIMAL);
  	        break; 
  	     case Keywords.XS_FLOAT :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_FLOAT);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_FLOAT);
  	        break; 
  	     case Keywords.XS_DOUBLE :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DOUBLE);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DOUBLE);
  	        break;
  	     case Keywords.XS_INTEGER :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_INTEGER);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_INTEGER);
  	        break;
  	     case Keywords.XS_NON_POSITIVE_INTEGER :
- 		    xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_NON_POSITIVE_INTEGER);
+ 		    xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_NON_POSITIVE_INTEGER);
  		    break;
  	     case Keywords.XS_NEGATIVE_INTEGER :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_NEGATIVE_INTEGER);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_NEGATIVE_INTEGER);
  			break;
  	     case Keywords.XS_NON_NEGATIVE_INTEGER :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER);
  			break;
  	     case Keywords.XS_POSITIVE_INTEGER :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_POSITIVE_INTEGER);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_POSITIVE_INTEGER);
  			break;
  	     case Keywords.XS_LONG :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_LONG);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_LONG);
  	        break; 
  	     case Keywords.XS_INT :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_INT);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_INT);
  	        break;
  	     case Keywords.XS_SHORT :
- 		    xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_SHORT);
+ 		    xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_SHORT);
  		    break;
  	     case Keywords.XS_BYTE :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_BYTE);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_BYTE);
  			break;
  	     case Keywords.XS_UNSIGNED_LONG :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_LONG);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_LONG);
  			break;
  	     case Keywords.XS_UNSIGNED_INT :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_INT);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_INT);
  			break;
  	     case Keywords.XS_UNSIGNED_SHORT :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_SHORT);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_SHORT);
  			break;
  	     case Keywords.XS_UNSIGNED_BYTE :
- 			xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_BYTE);
+ 			xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_BYTE);
  			break;
  	     case Keywords.XS_DATE :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DATE);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DATE);
  	        break;
  	     case Keywords.XS_DATETIME :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DATETIME);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DATETIME);
  	        break;
  	     case Keywords.XS_DURATION :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DURATION);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DURATION);
  	        break;
  	     case Keywords.XS_YEAR_MONTH_DURATION :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_YEARMONTH_DURATION);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_YEARMONTH_DURATION);
  	        break;
  	     case Keywords.XS_DAY_TIME_DURATION :
- 	        xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_DAYTIME_DURATION);
+ 	        xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_DAYTIME_DURATION);
  	        break;
  	     case Keywords.XS_TIME :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_TIME);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_TIME);
  	         break;
  	     case Keywords.XS_ANY_URI :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_ANY_URI);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_ANY_URI);
  	         break;
  	     case Keywords.XS_QNAME :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_QNAME);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_QNAME);
  	         break;
  	     case Keywords.XS_ANY_ATOMIC_TYPE :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_ANY_ATOMIC_TYPE);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_ANY_ATOMIC_TYPE);
  	         break;
  	     case Keywords.XS_UNTYPED_ATOMIC :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNTYPED_ATOMIC);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNTYPED_ATOMIC);
  	         break;
  	     case Keywords.XS_UNTYPED :
- 	         xpathSequenceTypeExpr.setSequenceType(SequenceTypeSupport.XS_UNTYPED);
+ 	         xpathSequenceTypeExpr.setBuiltInSequenceType(SequenceTypeSupport.XS_UNTYPED);
  	         break;
  	     default :
  	        throw new javax.xml.transform.TransformerException("XPST0051 : An XML Schema type 'xs:" + m_token + "' is not "
@@ -4999,8 +5235,8 @@ public class XPathParser
  	  
  	  nextToken();
  	  
- 	  if ((m_token != null) && (xpathSequenceTypeExpr.getSequenceType() > 0)) {
- 	     setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isInlineFunction);
+ 	  if ((m_token != null) && (xpathSequenceTypeExpr.getBuiltInSequenceType() > 0)) {
+ 	     setSequenceTypeOccurenceIndicator(xpathSequenceTypeExpr, isXPathInlineFunctionParse);
  	  }
    }
    
@@ -5198,97 +5434,97 @@ public class XPathParser
  	  
  	switch (m_token) {
  	    case Keywords.FUNC_BOOLEAN_STRING :
- 	        seqTypeData.setSequenceType(SequenceTypeSupport.BOOLEAN);
+ 	        seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.BOOLEAN);
  	        break;
  	    case Keywords.XS_STRING :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.STRING);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.STRING);
  	        break; 
  	    case Keywords.XS_NORMALIZED_STRING :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_NORMALIZED_STRING);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_NORMALIZED_STRING);
  	        break;
  	    case Keywords.XS_TOKEN :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_TOKEN);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_TOKEN);
  	        break;
  	    case Keywords.XS_DECIMAL :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DECIMAL);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DECIMAL);
  	        break; 
  	    case Keywords.XS_FLOAT :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_FLOAT);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_FLOAT);
  	        break; 
  	    case Keywords.XS_DOUBLE :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DOUBLE);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DOUBLE);
  	        break;
  	    case Keywords.XS_INTEGER :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_INTEGER);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_INTEGER);
  	        break;
  	    case Keywords.XS_NON_POSITIVE_INTEGER :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_NON_POSITIVE_INTEGER);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_NON_POSITIVE_INTEGER);
  	        break;
  	    case Keywords.XS_NEGATIVE_INTEGER :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_NEGATIVE_INTEGER);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_NEGATIVE_INTEGER);
  	        break;
  	    case Keywords.XS_NON_NEGATIVE_INTEGER :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER);
  	        break;
  	    case Keywords.XS_POSITIVE_INTEGER :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_POSITIVE_INTEGER);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_POSITIVE_INTEGER);
  	        break;
  	    case Keywords.XS_LONG :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_LONG);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_LONG);
  	        break; 
  	    case Keywords.XS_INT :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_INT);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_INT);
  	        break;
  	    case Keywords.XS_SHORT :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_SHORT);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_SHORT);
  	        break;
  	    case Keywords.XS_BYTE :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_BYTE);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_BYTE);
  	        break;
  	    case Keywords.XS_UNSIGNED_LONG :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_LONG);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_LONG);
  	        break;
  	    case Keywords.XS_UNSIGNED_INT :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_INT);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_INT);
  	        break;
  	    case Keywords.XS_UNSIGNED_SHORT :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_SHORT);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_SHORT);
  	        break;
  	    case Keywords.XS_UNSIGNED_BYTE :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNSIGNED_BYTE);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNSIGNED_BYTE);
  	        break;
  	    case Keywords.XS_DATE :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DATE);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DATE);
  	        break;
  	    case Keywords.XS_DATETIME :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DATETIME);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DATETIME);
  	        break;
  	    case Keywords.XS_DURATION :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DURATION);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DURATION);
  	        break;
  	    case Keywords.XS_YEAR_MONTH_DURATION :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_YEARMONTH_DURATION);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_YEARMONTH_DURATION);
  	        break;
  	    case Keywords.XS_DAY_TIME_DURATION :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_DAYTIME_DURATION);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_DAYTIME_DURATION);
  	        break;
  	    case Keywords.XS_TIME :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_TIME);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_TIME);
  	        break;
  	    case Keywords.XS_ANY_URI :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_ANY_URI);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_ANY_URI);
  	        break;
  	    case Keywords.XS_QNAME :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_QNAME);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_QNAME);
  	        break;
  	    case Keywords.XS_ANY_ATOMIC_TYPE :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_ANY_ATOMIC_TYPE);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_ANY_ATOMIC_TYPE);
  	        break;
  	    case Keywords.XS_UNTYPED_ATOMIC :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNTYPED_ATOMIC);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNTYPED_ATOMIC);
  	        break;
  	    case Keywords.XS_UNTYPED :
- 	    	seqTypeData.setSequenceType(SequenceTypeSupport.XS_UNTYPED);
+ 	    	seqTypeData.setBuiltInSequenceType(SequenceTypeSupport.XS_UNTYPED);
  	        break;
  	    default :
  	        throw new javax.xml.transform.TransformerException("XPST0051 : An XML Schema type 'xs:" + m_token + "' is not "
diff --git a/src/org/apache/xpath/composite/SequenceTypeData.java b/src/org/apache/xpath/composite/SequenceTypeData.java
index 73e08504b..20fe64ace 100644
--- a/src/org/apache/xpath/composite/SequenceTypeData.java
+++ b/src/org/apache/xpath/composite/SequenceTypeData.java
@@ -16,6 +16,7 @@
  */
 package org.apache.xpath.composite;
 
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xpath.objects.XObject;
 
 /**
@@ -35,32 +36,42 @@ public class SequenceTypeData extends XObject {
     
     private static final long serialVersionUID = -8207360998434418776L;
 
-    private int fSequenceType;
+    private int builtInSequenceType;
     
-    private int fItemTypeOccurrenceIndicator;
+    private XSTypeDefinition xsTypeDefinition;
+    
+    private int itemTypeOccurrenceIndicator;
     
     private SequenceTypeKindTest sequenceTypeKindTest;
     
-    private SequenceTypeFunctionTest fSequenceTypeFunctionTest;
+    private SequenceTypeFunctionTest sequenceTypeFunctionTest;
     
-    private SequenceTypeMapTest fSequenceTypeMapTest;
+    private SequenceTypeMapTest sequenceTypeMapTest;
     
-    private SequenceTypeArrayTest fSequenceTypeArrayTest;
+    private SequenceTypeArrayTest sequenceTypeArrayTest;
 
-    public int getSequenceType() {
-        return fSequenceType;
+    public int getBuiltInSequenceType() {
+        return builtInSequenceType;
     }
 
-    public void setSequenceType(int sequenceType) {
-        this.fSequenceType = sequenceType;
+    public void setBuiltInSequenceType(int sequenceType) {
+        this.builtInSequenceType = sequenceType;
     }
 
-    public int getItemTypeOccurrenceIndicator() {
-        return fItemTypeOccurrenceIndicator;
+    public XSTypeDefinition getXsTypeDefinition() {
+		return xsTypeDefinition;
+	}
+
+	public void setXsTypeDefinition(XSTypeDefinition xsTypeDefinition) {
+		this.xsTypeDefinition = xsTypeDefinition;
+	}
+
+	public int getItemTypeOccurrenceIndicator() {
+        return itemTypeOccurrenceIndicator;
     }
 
     public void setItemTypeOccurrenceIndicator(int itemTypeOccurrenceIndicator) {
-        this.fItemTypeOccurrenceIndicator = itemTypeOccurrenceIndicator;
+        this.itemTypeOccurrenceIndicator = itemTypeOccurrenceIndicator;
     }
 
     public SequenceTypeKindTest getSequenceTypeKindTest() {
@@ -72,27 +83,27 @@ public class SequenceTypeData extends XObject {
     }
 
 	public SequenceTypeFunctionTest getSequenceTypeFunctionTest() {
-		return fSequenceTypeFunctionTest;
+		return sequenceTypeFunctionTest;
 	}
 
 	public void setSequenceTypeFunctionTest(SequenceTypeFunctionTest sequenceTypeFunctionTest) {
-		this.fSequenceTypeFunctionTest = sequenceTypeFunctionTest;
+		this.sequenceTypeFunctionTest = sequenceTypeFunctionTest;
 	}
 	
 	public SequenceTypeMapTest getSequenceTypeMapTest() {
-		return fSequenceTypeMapTest;
+		return sequenceTypeMapTest;
 	}
 
 	public void setSequenceTypeMapTest(SequenceTypeMapTest sequenceTypeMapTest) {
-		this.fSequenceTypeMapTest = sequenceTypeMapTest;
+		this.sequenceTypeMapTest = sequenceTypeMapTest;
 	}
 	
 	public SequenceTypeArrayTest getSequenceTypeArrayTest() {
-		return fSequenceTypeArrayTest;
+		return sequenceTypeArrayTest;
 	}
 
 	public void setSequenceTypeArrayTest(SequenceTypeArrayTest sequenceTypeArrayTest) {
-		this.fSequenceTypeArrayTest = sequenceTypeArrayTest;
+		this.sequenceTypeArrayTest = sequenceTypeArrayTest;
 	}
 	
     /**
@@ -102,15 +113,15 @@ public class SequenceTypeData extends XObject {
 	public boolean equal(SequenceTypeData sequenceTypeData) {
 	    boolean isEqual = true;
 	    
-	    int seqType2 = sequenceTypeData.getSequenceType();
+	    int seqType2 = sequenceTypeData.getBuiltInSequenceType();
 	    int occrInd2 = sequenceTypeData.getItemTypeOccurrenceIndicator();
 	    SequenceTypeKindTest sequenceTypeKindTest2 = sequenceTypeData.getSequenceTypeKindTest();
 	    
-	    if ((this.fSequenceType != 0) && (this.fSequenceType == seqType2) 
-	    		                           && (this.fItemTypeOccurrenceIndicator == occrInd2)) {
+	    if ((this.builtInSequenceType != 0) && (this.builtInSequenceType == seqType2) 
+	    		                           && (this.itemTypeOccurrenceIndicator == occrInd2)) {
 	       isEqual = true;
 	    }
-	    else if (this.fItemTypeOccurrenceIndicator != occrInd2) {
+	    else if (this.itemTypeOccurrenceIndicator != occrInd2) {
 	       isEqual = false;
 	    }
 	    else if (!(this.sequenceTypeKindTest).equal(sequenceTypeKindTest2)) {
diff --git a/src/org/apache/xpath/composite/SequenceTypeKindTest.java b/src/org/apache/xpath/composite/SequenceTypeKindTest.java
index 7e240371a..4219b9e8c 100644
--- a/src/org/apache/xpath/composite/SequenceTypeKindTest.java
+++ b/src/org/apache/xpath/composite/SequenceTypeKindTest.java
@@ -17,9 +17,9 @@
 package org.apache.xpath.composite;
 
 /**
- * An object of this class stores, an XSLT transformation run-time
- * information for an occurrence of a XPath 3.1 sequence type
- * kind test (for e.g, element(), element(elemName), attribute(), 
+ * An object of this class stores, an XPath run-time
+ * information for a sequence type kind test (for e.g, 
+ * element(), element(elemName), attribute(), 
  * element(elemName, typeName)* etc. 
  * 
  * @author Mukul Gandhi <mu...@apache.org>
@@ -28,18 +28,30 @@ package org.apache.xpath.composite;
  */
 public class SequenceTypeKindTest {
     
+	/**
+	 * Xalan-J specific valid values for this variable are
+	 * specified in the class SequenceTypeSupport.
+	 */
     private int kindVal;
     
-    // For XML element and attribute nodes
+    /**
+     * An XML element or attribute node's local-name.
+     */
     private String nodeLocalName;
     
-    // For XML element and attribute nodes
+    /**
+     * An XML element or attribute node's namespace-uri.
+     */
     private String nodeNsUri;
     
-    // Data type's name (for e.g, string, integer etc)
+    /**
+     * Data type's local-name.
+     */
     private String dataTypeLocalName;
     
-    // XML namespace uri of the data type (for e.g, http://www.w3.org/2001/XMLSchema)
+    /**
+     * Data type's namespace-uri.
+     */
     private String dataTypeUri;
 
     public int getKindVal() {
diff --git a/src/org/apache/xpath/composite/SequenceTypeSupport.java b/src/org/apache/xpath/composite/SequenceTypeSupport.java
index 046cb1cea..dba358dcf 100644
--- a/src/org/apache/xpath/composite/SequenceTypeSupport.java
+++ b/src/org/apache/xpath/composite/SequenceTypeSupport.java
@@ -16,17 +16,33 @@
  */
 package org.apache.xpath.composite;
 
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.SourceLocator;
 import javax.xml.transform.TransformerException;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.Validator;
 
 import org.apache.xalan.templates.XMLNSDecl;
 import org.apache.xalan.xslt.util.XslTransformEvaluationHelper;
+import org.apache.xerces.impl.dv.XSSimpleType;
+import org.apache.xerces.impl.xs.SchemaGrammar;
+import org.apache.xerces.impl.xs.XSComplexTypeDecl;
+import org.apache.xerces.impl.xs.XSDDescription;
+import org.apache.xerces.impl.xs.XSElementDecl;
+import org.apache.xerces.jaxp.validation.XMLSchemaFactory;
+import org.apache.xerces.util.XMLGrammarPoolImpl;
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xml.dtm.DTM;
 import org.apache.xml.dtm.DTMIterator;
 import org.apache.xml.dtm.DTMManager;
@@ -54,8 +70,10 @@ import org.apache.xpath.types.XSUnsignedByte;
 import org.apache.xpath.types.XSUnsignedInt;
 import org.apache.xpath.types.XSUnsignedLong;
 import org.apache.xpath.types.XSUnsignedShort;
+import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
 
 import xml.xpath31.processor.types.XSAnyAtomicType;
 import xml.xpath31.processor.types.XSBoolean;
@@ -95,12 +113,16 @@ public class SequenceTypeSupport {
         
     public static int EMPTY_SEQUENCE = 1;
     
-    // Represents both XML Schema data type xs:boolean, and 
-    // XalanJ legacy boolean data type.
+    /**
+     * Represents both, an XML Schema data type xs:boolean and 
+     * Xalan-J legacy boolean data type.
+     */
     public static int BOOLEAN = 2;
     
-    // Represents both XML Schema data type xs:string, and 
-    // XalanJ legacy string data type.
+    /**
+     * Represents both, an XML Schema data type xs:string and 
+     * Xalan-J legacy string data type.
+     */
     public static int STRING = 3;
     
     public static int XS_DATE = 4;
@@ -177,8 +199,14 @@ public class SequenceTypeSupport {
     public static int NODE_KIND = 105;
     
     public static int ITEM_KIND = 106;    
-        
-    public static class OccurenceIndicator {
+    
+    /**
+     * Sequence type occurrence indicator values, for Xalan-J 
+     * implementation.
+     * 
+     * @author Mukul Gandhi <mu...@apache.org>
+     */
+    public static class OccurrenceIndicator {
        // Represents the sequence type occurrence indicator '?'
        public static int ZERO_OR_ONE = 1;
        
@@ -266,7 +294,7 @@ public class SequenceTypeSupport {
     }
     
     /**
-     * This method converts/casts an XPath 3.1 xdm source value represented by an
+     * This method casts an XPath 3.1 xdm source value represented by an
      * XObject object instance, to a value of another xdm data type.
      * 
      * For XPath sequence type expressions that represent KindTest (i.e,
@@ -286,13 +314,13 @@ public class SequenceTypeSupport {
      * 
      * @throws TransformerException
      */
-    public static XObject convertXDMValueToAnotherType(XObject srcValue, String sequenceTypeXPathExprStr, 
-                                                       SequenceTypeData seqExpectedTypeDataInp,  
-                                                       XPathContext xctxt, List prefixTable) throws TransformerException {
+    public static XObject castXDMValueToAnotherType(XObject srcValue, String sequenceTypeXPathExprStr, 
+                                                    SequenceTypeData seqExpectedTypeDataInp,  
+                                                    XPathContext xctxt, List prefixTable) throws TransformerException {
     	XObject result = null;
     	
     	m_PrefixTable = prefixTable;    	
-    	result = convertXdmValueToAnotherType(srcValue, sequenceTypeXPathExprStr, null, xctxt);
+    	result = castXdmValueToAnotherType(srcValue, sequenceTypeXPathExprStr, null, xctxt);
     	
     	return result;
     }
@@ -301,18 +329,18 @@ public class SequenceTypeSupport {
      * This method, supports XPath implementation of "cast as" and 
      * "castable as" expressions.
      */
-    public static XObject castXdmValueToAnotherType(XObject srcValue, SequenceTypeData seqExpectedTypeDataInp) 
+    public static XObject castXdmValueToAnotherType(XObject srcValue, SequenceTypeData expectedSeqTypeData) 
     		                                                                                throws TransformerException {
         XObject result = null;
     	
-        result = convertXdmValueToAnotherType(srcValue, null, seqExpectedTypeDataInp, null);
+        result = castXdmValueToAnotherType(srcValue, null, expectedSeqTypeData, null);
 
         return result;
     }
     
     
     /**
-     * This method converts/casts an XPath 3.1 xdm source value represented by an
+     * This method casts an XPath 3.1 xdm source value represented by an
      * XObject object instance, to a value of another xdm data type.
      * 
      * For XPath sequence type expressions that represent KindTest (i.e,
@@ -323,7 +351,7 @@ public class SequenceTypeSupport {
      * @param srcValue                     an XObject object instance that represents a
      *                                     source xdm value. 
      * @param sequenceTypeXPathExprStr     an XPath sequence type expression string 
-     * @param seqExpectedTypeDataInp       an XPath sequence type compiled expression                                                                  
+     * @param expectedSeqTypeData          an XPath sequence type compiled expression                                                                  
      * @param xctxt                        the current XPath context object
      * 
      * @return                             an XObject object instance produced, as a result of data type 
@@ -332,9 +360,9 @@ public class SequenceTypeSupport {
      *                                
      * @throws TransformerException 
      */
-    public static XObject convertXdmValueToAnotherType(XObject srcValue, String sequenceTypeXPathExprStr, 
-                                                                                       SequenceTypeData seqExpectedTypeDataInp, 
-                                                                                       XPathContext xctxt) throws TransformerException {
+    public static XObject castXdmValueToAnotherType(XObject srcValue, String sequenceTypeXPathExprStr, 
+                                                    SequenceTypeData expectedSeqTypeData, XPathContext xctxt) 
+                                                    		                                          throws TransformerException {
         XObject result = null;
         
         int contextNode = DTM.NULL;        
@@ -350,32 +378,46 @@ public class SequenceTypeSupport {
             XObject seqTypeExpressionEvalResult = null;
             SequenceTypeData seqExpectedTypeData = null;
             
-            if ((xctxt != null) && (sequenceTypeXPathExprStr != null) && (seqExpectedTypeDataInp == null)) {
-               seqTypeXPath = new XPath(sequenceTypeXPathExprStr, srcLocator, 
-                                                                          xctxt.getNamespaceContext(), XPath.SELECT, null, true);            
-               seqTypeExpressionEvalResult = seqTypeXPath.execute(xctxt, contextNode, xctxt.getNamespaceContext());            
-               seqExpectedTypeData = (SequenceTypeData)seqTypeExpressionEvalResult;
+            if ((xctxt != null) && (sequenceTypeXPathExprStr != null) && (expectedSeqTypeData == null)) {
+            	seqTypeXPath = new XPath(sequenceTypeXPathExprStr, srcLocator, xctxt.getNamespaceContext(), 
+            			                                                                          XPath.SELECT, null, true);            
+            	seqTypeExpressionEvalResult = seqTypeXPath.execute(xctxt, contextNode, xctxt.getNamespaceContext());            
+            	seqExpectedTypeData = (SequenceTypeData)seqTypeExpressionEvalResult;
             }
             else {
-               seqExpectedTypeData = seqExpectedTypeDataInp; 
+            	seqExpectedTypeData = expectedSeqTypeData; 
             }
-            
-            int expectedType = seqExpectedTypeData.getSequenceType();            
+
+            int expectedType = seqExpectedTypeData.getBuiltInSequenceType();            
             int itemTypeOccurenceIndicator = seqExpectedTypeData.getItemTypeOccurrenceIndicator();
             SequenceTypeKindTest sequenceTypeKindTest = seqExpectedTypeData.getSequenceTypeKindTest();
+
+            XSTypeDefinition xsTypeDefinition = seqExpectedTypeData.getXsTypeDefinition();
+            
+            XNodeSet nodeSet = getNodeReference(srcValue);
+            
+            if ((nodeSet != null) && (xsTypeDefinition != null)) {
+	            boolean isNodeValid = isXdmNodeValidWithSchemaType(nodeSet, xctxt, xsTypeDefinition);	            
+	            if (isNodeValid) {
+	               result = srcValue;
+	               result.setXsTypeDefinition(xsTypeDefinition);
+	               
+	               return result;
+	            }
+            }
             
             if (srcValue != null) {
             	if (sequenceTypeKindTest != null) {
 	            	if (sequenceTypeKindTest.getKindVal() == ITEM_KIND) {
 	            		if (srcValue instanceof ResultSequence) {
 	            		  ResultSequence rSeq = (ResultSequence)srcValue;
-	               		  if (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_MANY) {
+	               		  if (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_MANY) {
 	               			 result = srcValue;   
 	               		  }
-	               		  else if ((itemTypeOccurenceIndicator == OccurenceIndicator.ONE_OR_MANY) && (rSeq.size() > 0)) {
+	               		  else if ((itemTypeOccurenceIndicator == OccurrenceIndicator.ONE_OR_MANY) && (rSeq.size() > 0)) {
 	               			 result = srcValue; 
 	               		  }
-	               		  else if ((itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE) && (rSeq.size() <= 1)) {
+	               		  else if ((itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE) && (rSeq.size() <= 1)) {
 	               			 result = srcValue; 
 	               		  }
 	               		  
@@ -383,13 +425,13 @@ public class SequenceTypeSupport {
 	               	   }
 	            	   else if (srcValue instanceof XPathArray) {
 	            		  XPathArray xpathArr = (XPathArray)srcValue;
-	            		  if (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_MANY) {
+	            		  if (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_MANY) {
 	            			 result = srcValue;   
 	            		  }
-	            		  else if ((itemTypeOccurenceIndicator == OccurenceIndicator.ONE_OR_MANY) && (xpathArr.size() > 0)) {
+	            		  else if ((itemTypeOccurenceIndicator == OccurrenceIndicator.ONE_OR_MANY) && (xpathArr.size() > 0)) {
 	            			 result = srcValue; 
 	            		  }
-	            		  else if ((itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE) && (xpathArr.size() <= 1)) {
+	            		  else if ((itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE) && (xpathArr.size() <= 1)) {
 	            			 result = srcValue; 
 	            		  }
 	            		  
@@ -397,20 +439,20 @@ public class SequenceTypeSupport {
 	            	   }
 	            	}
             	}
-            	else if (seqExpectedTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE) {
+            	else if (seqExpectedTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE) {
             		if (srcValue instanceof ResultSequence) {
             			ResultSequence rSeq = (ResultSequence)srcValue;
             			if ((rSeq.size() == 1) && ((itemTypeOccurenceIndicator == 0) || 
-            					                   (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE) || 
-            					                   (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_MANY) ||
-            					                   (itemTypeOccurenceIndicator == OccurenceIndicator.ONE_OR_MANY))) {
+            					                   (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE) || 
+            					                   (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_MANY) ||
+            					                   (itemTypeOccurenceIndicator == OccurrenceIndicator.ONE_OR_MANY))) {
             			   if (rSeq.item(0) instanceof XSAnyAtomicType) {
             			      result = rSeq.item(0);            			      
             			      return result;
             			   }
             			}
-            			else if ((rSeq.size() > 0) && ((itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_MANY) || 
-            					                       (itemTypeOccurenceIndicator == OccurenceIndicator.ONE_OR_MANY))) {
+            			else if ((rSeq.size() > 0) && ((itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_MANY) || 
+            					                       (itemTypeOccurenceIndicator == OccurrenceIndicator.ONE_OR_MANY))) {
             			    boolean isSeqAnyAtomicType = true;
             			    for (int idx = 0; idx < rSeq.size(); idx++) {
             			       if (!(rSeq.item(0) instanceof XSAnyAtomicType)) {
@@ -423,8 +465,8 @@ public class SequenceTypeSupport {
             			       return result;
             			    }
             			}
-            			else if ((itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE) || 
-            					 (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_MANY)) {
+            			else if ((itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE) || 
+            					 (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_MANY)) {
             				// an input sequence is empty
             				result = rSeq;
          			        return result;
@@ -591,22 +633,22 @@ public class SequenceTypeSupport {
             else if (srcValue instanceof XSUntyped) {
                String srcStrVal = ((XSUntyped)srcValue).stringValue();
                // Recursive call to this function
-               result = convertXdmValueToAnotherType(new XSString(srcStrVal), sequenceTypeXPathExprStr, 
-                                                                                                    seqExpectedTypeDataInp, xctxt);
+               result = castXdmValueToAnotherType(new XSString(srcStrVal), sequenceTypeXPathExprStr, 
+                                                                                                    expectedSeqTypeData, xctxt);
             }
             else if (srcValue instanceof XSUntypedAtomic) {
                String srcStrVal = ((XSUntypedAtomic)srcValue).stringValue();
                // Recursive call to this function
-               result = convertXdmValueToAnotherType(new XSString(srcStrVal), sequenceTypeXPathExprStr, 
-                                                                                                    seqExpectedTypeDataInp, xctxt);
+               result = castXdmValueToAnotherType(new XSString(srcStrVal), sequenceTypeXPathExprStr, 
+                                                                                                    expectedSeqTypeData, xctxt);
             }
             else if (srcValue instanceof XNodeSetForDOM) {               
-               result = castXNodeSetForDOMInstance(srcValue, sequenceTypeXPathExprStr, seqExpectedTypeDataInp, 
+               result = castXNodeSetForDOMInstance(srcValue, sequenceTypeXPathExprStr, expectedSeqTypeData, 
                                                                               xctxt, srcLocator, itemTypeOccurenceIndicator, 
                                                                                                                        sequenceTypeKindTest);
             }
             else if (srcValue instanceof XNodeSet) {
-               result = castXNodeSetInstance(srcValue, sequenceTypeXPathExprStr, seqExpectedTypeDataInp, 
+               result = castXNodeSetInstance(srcValue, sequenceTypeXPathExprStr, expectedSeqTypeData, 
                                                                               xctxt, srcLocator, itemTypeOccurenceIndicator, 
                                                                                                                        sequenceTypeKindTest);
             }
@@ -614,14 +656,14 @@ public class SequenceTypeSupport {
                ResultSequence srcResultSeq = (ResultSequence)srcValue;
                if (srcResultSeq.size() == 1) {
             	   // Recursive call to this function
-                   result = convertXdmValueToAnotherType(srcResultSeq.item(0), sequenceTypeXPathExprStr, seqExpectedTypeDataInp, xctxt);   
+                   result = castXdmValueToAnotherType(srcResultSeq.item(0), sequenceTypeXPathExprStr, expectedSeqTypeData, xctxt);   
                }
                else if ((srcResultSeq.size() > 1) && (itemTypeOccurenceIndicator == 0)) {
             	   return null;
                }
                else {
-                   result = castResultSequenceInstance(srcValue, sequenceTypeXPathExprStr, seqExpectedTypeDataInp, xctxt, srcLocator, 
-                                                                                                         expectedType, itemTypeOccurenceIndicator);
+                   result = castResultSequenceInstance((ResultSequence)srcValue, sequenceTypeXPathExprStr, expectedSeqTypeData, xctxt, srcLocator, 
+                                                        expectedType, itemTypeOccurenceIndicator);
                }
             }
             else if (srcValue instanceof XPathInlineFunction) {
@@ -702,13 +744,13 @@ public class SequenceTypeSupport {
              			 }
              			 SequenceTypeData keySeqTypeData = sequenceTypeMapTest.getKeySequenceTypeData();
              			 SequenceTypeData valueSeqTypeData = sequenceTypeMapTest.getValueSequenceTypeData();
-             			 XObject mapKeyValTypeCheckResult = SequenceTypeSupport.convertXdmValueToAnotherType(mapKey, null, keySeqTypeData, xctxt);
+             			 XObject mapKeyValTypeCheckResult = SequenceTypeSupport.castXdmValueToAnotherType(mapKey, null, keySeqTypeData, xctxt);
              			 String mapSequenceTypeStr = (sequenceTypeXPathExprStr != null) ? sequenceTypeXPathExprStr : "";
              			 if (mapKeyValTypeCheckResult == null) {             				
              				throw new TransformerException("XPTY0004 : XPath map entry key's [entry's key name: '" + keyStrVal + "'] value doesn't conform to the key's expected "
              						                                            + "type [map's sequenceType is '" + mapSequenceTypeStr + "']."); 
              			 }
-             			 XObject mapEntryValTypeCheckResult = SequenceTypeSupport.convertXdmValueToAnotherType(mapEntry, null, valueSeqTypeData, xctxt);
+             			 XObject mapEntryValTypeCheckResult = SequenceTypeSupport.castXdmValueToAnotherType(mapEntry, null, valueSeqTypeData, xctxt);
              			 if (mapEntryValTypeCheckResult == null) {
              				throw new TransformerException("XPTY0004 : XPath map entry's [entry's key name: '" + keyStrVal + "'] value doesn't conform to the map entry value's expected "
              						                                            + "type [map's sequenceType is '" + mapSequenceTypeStr + "'].");  
@@ -736,7 +778,7 @@ public class SequenceTypeSupport {
              				arrItem = ((ResultSequence)arrItem).item(0);
              			 }
              			 SequenceTypeData arrayItemTypeInfo = sequenceTypeArrayTest.getArrayItemTypeInfo();
-             			 XObject arrayItemTypeCheckResult = SequenceTypeSupport.convertXdmValueToAnotherType(arrItem, null, arrayItemTypeInfo, xctxt);
+             			 XObject arrayItemTypeCheckResult = SequenceTypeSupport.castXdmValueToAnotherType(arrItem, null, arrayItemTypeInfo, xctxt);
              			 String arrayItemSequenceTypeStr = (sequenceTypeXPathExprStr != null) ? sequenceTypeXPathExprStr : "";
              			 if (arrayItemTypeCheckResult == null) {             				
              				throw new TransformerException("XPTY0004 : One or more, of XPath array's item doesn't conform to array item's expected "
@@ -767,20 +809,101 @@ public class SequenceTypeSupport {
     }
     
     /**
-     * Check whether, two XML namespace uris are equal.
+     * Check whether, two XML namespace values are equal.
      */
-    public static boolean isTwoXmlNamespacesEqual(String nsUr1, String nsUri2) {
+    public static boolean isTwoXmlNamespaceValuesEqual(String ns0, String ns1) {
         boolean xmlNamespacesEqual = false;
         
-        if ((nsUr1 == null) && (nsUri2 == null)) {
+        if ((ns0 == null) && (ns1 == null)) {
            xmlNamespacesEqual = true; 
         }
-        else if ((nsUr1 != null) && (nsUri2 != null)) {
-           xmlNamespacesEqual = nsUr1.equals(nsUri2);  
+        else if ((ns0 != null) && (ns1 != null)) {
+           xmlNamespacesEqual = ns0.equals(ns1);  
         }
         
         return xmlNamespacesEqual; 
     }
+
+    /**
+     * Validate an XDM node with an XML Schema type definition.
+     */
+	private static boolean isXdmNodeValidWithSchemaType(XNodeSet xdmNode, XPathContext xctxt,
+														XSTypeDefinition xsTypeDefinition)
+														       throws Exception, ParserConfigurationException, SAXException, 
+															   IOException, TransformerException {
+		
+		boolean isNodeValidWithSchemaType = false;
+		
+		if (xsTypeDefinition instanceof XSSimpleType) {
+		    // TO DO
+		}
+		else {
+			// Validate the node with an XML Schema complexType
+			xdmNode = (XNodeSet)(xdmNode.getFresh());
+			DTMIterator dtmIter = ((XNodeSet)xdmNode).iterRaw();
+			int nodeHandle = dtmIter.nextNode();
+			DTM dtm = xctxt.getDTM(nodeHandle);
+			Node node = dtm.getNode(nodeHandle);
+
+			String xmlDocumentStr = XslTransformEvaluationHelper.serializeXmlDomElementNode(node);
+
+			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+			dbf.setNamespaceAware(true);
+			DocumentBuilder dBuilder = dbf.newDocumentBuilder();
+			Document document = dBuilder.parse(new ByteArrayInputStream(xmlDocumentStr.getBytes()));
+
+			String elemName = (document.getDocumentElement()).getNodeName();
+
+			XSComplexTypeDecl xsComplexTypeDecl = (XSComplexTypeDecl)xsTypeDefinition;
+
+			String xsTargetNamespace = xsComplexTypeDecl.getTargetNamespace();	            		
+
+			SchemaGrammar schemaGrammar = new SchemaGrammar(xsTargetNamespace, new XSDDescription(), null);	            			            		
+
+			XSElementDecl xsElemDecl = new XSElementDecl();
+			xsElemDecl.fName = elemName;
+			xsElemDecl.fTargetNamespace = xsTargetNamespace;
+			xsElemDecl.fType = xsComplexTypeDecl;
+			xsElemDecl.setIsGlobal();
+
+			schemaGrammar.addGlobalElementDecl(xsElemDecl);	            		
+			schemaGrammar.addGlobalTypeDecl(xsComplexTypeDecl);	            		
+			XMLGrammarPoolImpl xmlGrammarPool = new XMLGrammarPoolImpl();
+			xmlGrammarPool.putGrammar(schemaGrammar);
+
+			XMLSchemaFactory xmlSchemaFactory = new XMLSchemaFactory();
+			Schema schema = xmlSchemaFactory.newSchema(xmlGrammarPool);
+			Validator validator = schema.newValidator();
+			validator.validate(new DOMSource(document));
+
+			isNodeValidWithSchemaType = true;
+			
+		}
+		
+		return isNodeValidWithSchemaType;
+	}
+	
+	/**
+	 * Given an XObject object instance check whether it represents
+	 * an XDM node. A non-null object reference returned by this
+	 * method, indicates that an input object reference is a node.
+	 */
+	public static XNodeSet getNodeReference(XObject item) {
+		
+		XNodeSet nodeSet = null;
+		
+		if (item instanceof XNodeSet) {
+		   nodeSet = (XNodeSet)item;			
+		}
+		else if (item instanceof ResultSequence) {
+			ResultSequence rSeq = (ResultSequence)item;
+			if ((rSeq.size() == 1) && (rSeq.item(0) instanceof XNodeSet)) {
+			   nodeSet = (XNodeSet)(rSeq.item(0));
+			}
+		}
+		
+		return nodeSet;
+	}
     
     /**
      * Cast a string value to an expected xdm type.
@@ -1129,7 +1252,7 @@ public class SequenceTypeSupport {
         ResultSequence convertedResultSeq = new ResultSequence();
         
         if ((nodeSetLen > 1) && ((itemTypeOccurenceIndicator == 0) || (itemTypeOccurenceIndicator == 
-                                                                                             OccurenceIndicator.ZERO_OR_ONE))) {
+                                                                                             OccurrenceIndicator.ZERO_OR_ONE))) {
             throw new TransformerException("XTTE0570 : A sequence of size " + nodeSetLen + ", cannot be cast to a type " 
                                                                                                          + sequenceTypeXPathExprStr + ".", srcLocator);  
         }
@@ -1152,7 +1275,7 @@ public class SequenceTypeSupport {
 
                     if (sequenceTypeKindTest.getDataTypeName() != null) {
                         String dataTypeStr = (sequenceTypeNewXPathExprStr != null) ? sequenceTypeNewXPathExprStr : sequenceTypeXPathExprStr; 
-                        throw new TransformerException("XTTE0570 : The required item type of an xdm input node is " + dataTypeStr + ". "
+                        throw new TransformerException("XTTE0570 : The required item type of an xdm node is " + dataTypeStr + ". "
                         		                                                  + "The supplied value " + nodeName + " does'nt match an expected type. "
                         		                                                  + "The supplied node has not been validated with a schema.", srcLocator); 
                     }
@@ -1167,7 +1290,7 @@ public class SequenceTypeSupport {
                             boolean isSeqTypeMatchOk = false;
 
                             if ((sequenceTypeKindTest.getKindVal() == ELEMENT_KIND) && (nodeName.equals(elemNodeKindTestNodeName)) 
-                                                                                             && (isTwoXmlNamespacesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
+                                                                                             && (isTwoXmlNamespaceValuesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
                                 isSeqTypeMatchOk = true;
                             }
                             else if ((sequenceTypeKindTest.getKindVal() == NODE_KIND) || (sequenceTypeKindTest.getKindVal() == ITEM_KIND)) {
@@ -1192,7 +1315,7 @@ public class SequenceTypeSupport {
                             boolean isSeqTypeMatchOk = false;
 
                             if ((sequenceTypeKindTest.getKindVal() == ATTRIBUTE_KIND) && (nodeName.equals(attrNodeKindTestNodeName)) 
-                                                                                               && (isTwoXmlNamespacesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
+                                                                                               && (isTwoXmlNamespaceValuesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
                                 isSeqTypeMatchOk = true;  
                             }
                             else if ((sequenceTypeKindTest.getKindVal() == NODE_KIND) || (sequenceTypeKindTest.getKindVal() == ITEM_KIND)) {
@@ -1223,7 +1346,7 @@ public class SequenceTypeSupport {
                     }
 
                     String nodeStrVal = node.getTextContent();
-                    XObject xObject = convertXdmValueToAnotherType(new XSString(nodeStrVal), sequenceTypeNewXPathExprStr, 
+                    XObject xObject = castXdmValueToAnotherType(new XSString(nodeStrVal), sequenceTypeNewXPathExprStr, 
                                                                                                                       seqExpectedTypeDataInp, xctxt);                       
                     convertedResultSeq.add(xObject); 
                 }
@@ -1269,7 +1392,7 @@ public class SequenceTypeSupport {
         }
         
         if ((nodeSetLen > 1) && ((itemTypeOccurenceIndicator == 0) || (itemTypeOccurenceIndicator == 
-                                                                                             OccurenceIndicator.ZERO_OR_ONE))) {
+                                                                                             OccurrenceIndicator.ZERO_OR_ONE))) {
             throw new TransformerException("XTTE0570 : A sequence of size " + nodeSetLen + ", cannot be cast to a type " 
                                                                                                            + sequenceTypeXPathExprStr + ".", srcLocator);  
         }
@@ -1306,7 +1429,7 @@ public class SequenceTypeSupport {
                   
                   if (sequenceTypeKindTest.getDataTypeName() != null) {
                      String dataTypeStr = (sequenceTypeNewXPathExprStr != null) ? sequenceTypeNewXPathExprStr : sequenceTypeXPathExprStr;
-                     throw new TransformerException("XTTE0570 : The required item type of an xdm input node is " + dataTypeStr + ". "
+                     throw new TransformerException("XTTE0570 : The required item type of an xdm node is " + dataTypeStr + ". "
                                                                           + "The supplied value " + nodeName + " does'nt match an expected type. "
                                                                           + "The supplied node has not been validated with a schema.", srcLocator);
                   }
@@ -1319,7 +1442,7 @@ public class SequenceTypeSupport {
                         }
                         
                         if ((sequenceTypeKindTest.getKindVal() == ELEMENT_KIND) && (nodeName.equals(elemNodeKindTestNodeName)) 
-                                                                                                 && (isTwoXmlNamespacesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
+                                                                                                 && (isTwoXmlNamespaceValuesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
                            convertedResultSeq.add(nodeSetItem);  
                         }
                         else if ((sequenceTypeKindTest.getKindVal() == NODE_KIND) || (sequenceTypeKindTest.getKindVal() == ITEM_KIND)) {
@@ -1345,7 +1468,7 @@ public class SequenceTypeSupport {
                         }
                         
                         if ((sequenceTypeKindTest.getKindVal() == ATTRIBUTE_KIND) && (nodeName.equals(attrNodeKindTestNodeName)) 
-                                                                                                   && (isTwoXmlNamespacesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
+                                                                                                   && (isTwoXmlNamespaceValuesEqual(nodeNsUri, sequenceTypeKindTest.getNodeNsUri()))) {
                             convertedResultSeq.add(nodeSetItem);  
                         }
                         else if ((sequenceTypeKindTest.getKindVal() == NODE_KIND) || (sequenceTypeKindTest.getKindVal() == ITEM_KIND)) {
@@ -1411,7 +1534,7 @@ public class SequenceTypeSupport {
                   if (!((xctxt == null) && ((seqExpectedTypeDataInp != null) && 
                                                                (seqExpectedTypeDataInp.getSequenceTypeKindTest() == null)))) {
                      String nodeStrVal = nodeSetItem.str();
-                     XObject xObject = convertXdmValueToAnotherType(new XSString(nodeStrVal), sequenceTypeNewXPathExprStr, 
+                     XObject xObject = castXdmValueToAnotherType(new XSString(nodeStrVal), sequenceTypeNewXPathExprStr, 
                                                                                                                     seqExpectedTypeDataInp, xctxt);                     
                      if (nodeSetLen == 1) {
                          result = xObject;                             
@@ -1435,22 +1558,19 @@ public class SequenceTypeSupport {
     }
 
 	/**
-     * This method casts a provided XDM evaluated sequence, to another type 
-     * specified by an xdm sequence type expression.
+     * This method casts an xdm input sequence value, to another type 
+     * specified by a sequence type expression.
      */
-    private static XObject castResultSequenceInstance(XObject srcValue,
-                                                                    String sequenceTypeXPathExprStr,
-                                                                    SequenceTypeData seqExpectedTypeDataInp, XPathContext xctxt,
-                                                                    SourceLocator srcLocator, int expectedType,
-                                                                    int itemTypeOccurenceIndicator) throws TransformerException {
+    private static XObject castResultSequenceInstance(ResultSequence srcSeqValue, String sequenceTypeXPathExprStr,
+                                                      SequenceTypeData seqExpectedTypeDataInp, XPathContext xctxt,
+                                                      SourceLocator srcLocator, int expectedType, int itemTypeOccurenceIndicator) 
+                                                    		                                                     throws TransformerException {
         
         XObject result = null;
         
-        ResultSequence srcResultSeq = (ResultSequence)srcValue;
-        
-        int seqLen = srcResultSeq.size();
+        int seqLen = srcSeqValue.size();
         
-        if ((seqLen == 0) && (itemTypeOccurenceIndicator == OccurenceIndicator.ONE_OR_MANY)) {
+        if ((seqLen == 0) && (itemTypeOccurenceIndicator == OccurrenceIndicator.ONE_OR_MANY)) {
            throw new TransformerException("XTTE0570 : An empty sequence is not allowed, as result of evaluation for sequence "
                                                                                                               + "type's occurence indicator +.", srcLocator);  
         }
@@ -1458,7 +1578,7 @@ public class SequenceTypeSupport {
            throw new TransformerException("XTTE0570 : The sequence doesn't conform to an expected type empty-sequence(). "
                                                                                                + "The supplied sequence has size " + seqLen + ".", srcLocator);  
         }
-        else if ((seqLen > 1) && (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE)) {
+        else if ((seqLen > 1) && (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE)) {
             throw new TransformerException("XTTE0570 : A sequence of size " + seqLen + ", cannot be cast to a type " 
                                                                                                                 + sequenceTypeXPathExprStr + ".", srcLocator); 
         }
@@ -1473,9 +1593,9 @@ public class SequenceTypeSupport {
             
             ResultSequence convertedResultSeq = new ResultSequence();
             
-            for (int idx = 0; idx < srcResultSeq.size(); idx++) {
-               XObject seqItem = (XObject)(srcResultSeq.item(idx));                       
-               XObject convertedSeqItem = convertXdmValueToAnotherType(seqItem, sequenceTypeNewXPathExprStr, 
+            for (int idx = 0; idx < srcSeqValue.size(); idx++) {
+               XObject seqItem = (XObject)(srcSeqValue.item(idx));                       
+               XObject convertedSeqItem = castXdmValueToAnotherType(seqItem, sequenceTypeNewXPathExprStr, 
                                                                                                          seqExpectedTypeDataInp, xctxt);
                convertedResultSeq.add(convertedSeqItem);
             }
@@ -1487,16 +1607,16 @@ public class SequenceTypeSupport {
     }
     
     /**
-     * Check whether the, xdm sequence type's xalanj kind value refers to one of 
+     * Check whether the, xdm sequence type's xalan-j kind value refers to one of 
      * the various node kinds.
      */
-    private static boolean isSequenceTypeExprOneOfTheNodeKinds(int kindVal) {
+    private static boolean isSequenceTypeExprOneOfTheNodeKinds(int seqTypekindVal) {
 		boolean isXdmItemOneOfTheNodeKinds = false;
 		
-		isXdmItemOneOfTheNodeKinds = ((kindVal == SequenceTypeSupport.ELEMENT_KIND) || 
-				                     (kindVal == SequenceTypeSupport.ATTRIBUTE_KIND) || 
-				                     (kindVal == SequenceTypeSupport.NAMESPACE_NODE_KIND) || 
-				                     (kindVal == SequenceTypeSupport.NODE_KIND));
+		isXdmItemOneOfTheNodeKinds = ((seqTypekindVal == SequenceTypeSupport.ELEMENT_KIND) || 
+				                      (seqTypekindVal == SequenceTypeSupport.ATTRIBUTE_KIND) || 
+				                      (seqTypekindVal == SequenceTypeSupport.NAMESPACE_NODE_KIND) || 
+				                      (seqTypekindVal == SequenceTypeSupport.NODE_KIND));
 		
 		return isXdmItemOneOfTheNodeKinds; 
 	}
diff --git a/src/org/apache/xpath/composite/XPathSequenceTypeExpr.java b/src/org/apache/xpath/composite/XPathSequenceTypeExpr.java
index 9d0199e3d..e569df44b 100644
--- a/src/org/apache/xpath/composite/XPathSequenceTypeExpr.java
+++ b/src/org/apache/xpath/composite/XPathSequenceTypeExpr.java
@@ -20,6 +20,7 @@ import java.util.Vector;
 
 import javax.xml.transform.TransformerException;
 
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xpath.Expression;
 import org.apache.xpath.ExpressionOwner;
 import org.apache.xpath.XPathContext;
@@ -38,28 +39,31 @@ public class XPathSequenceTypeExpr extends Expression {
 
     private static final long serialVersionUID = -7060682923984508436L;
     
-    private int fSequenceType;
+    private int builtInSequenceType;
     
-    private int fItemTypeOccurrenceIndicator;
+    private XSTypeDefinition xsTypeDefinition;
     
-    private SequenceTypeKindTest fSequenceTypeKindTest;
+    private int itemTypeOccurrenceIndicator;
     
-    private SequenceTypeFunctionTest fSequenceTypeFunctionTest;
+    private SequenceTypeKindTest sequenceTypeKindTest;
     
-    private SequenceTypeMapTest fSequenceTypeMapTest;
+    private SequenceTypeFunctionTest sequenceTypeFunctionTest;
     
-    private SequenceTypeArrayTest fSequenceTypeArrayTest;
+    private SequenceTypeMapTest sequenceTypeMapTest;
+    
+    private SequenceTypeArrayTest sequenceTypeArrayTest;
 
     @Override
     public XObject execute(XPathContext xctxt) throws TransformerException {
        SequenceTypeData sequenceTypeData = new SequenceTypeData();
        
-       sequenceTypeData.setSequenceType(fSequenceType);       
-       sequenceTypeData.setSequenceTypeKindTest(fSequenceTypeKindTest);       
-       sequenceTypeData.setItemTypeOccurrenceIndicator(fItemTypeOccurrenceIndicator);
-       sequenceTypeData.setSequenceTypeFunctionTest(fSequenceTypeFunctionTest);
-       sequenceTypeData.setSequenceTypeMapTest(fSequenceTypeMapTest);
-       sequenceTypeData.setSequenceTypeArrayTest(fSequenceTypeArrayTest);
+       sequenceTypeData.setBuiltInSequenceType(builtInSequenceType);
+       sequenceTypeData.setXsTypeDefinition(xsTypeDefinition);
+       sequenceTypeData.setSequenceTypeKindTest(sequenceTypeKindTest);       
+       sequenceTypeData.setItemTypeOccurrenceIndicator(itemTypeOccurrenceIndicator);
+       sequenceTypeData.setSequenceTypeFunctionTest(sequenceTypeFunctionTest);
+       sequenceTypeData.setSequenceTypeMapTest(sequenceTypeMapTest);
+       sequenceTypeData.setSequenceTypeArrayTest(sequenceTypeArrayTest);
        
        return sequenceTypeData;
     }
@@ -75,52 +79,60 @@ public class XPathSequenceTypeExpr extends Expression {
        return false;
     }
 
-    public int getSequenceType() {
-        return fSequenceType;
+    public int getBuiltInSequenceType() {
+        return builtInSequenceType;
     }
 
-    public void setSequenceType(int sequenceType) {
-        this.fSequenceType = sequenceType;
+    public void setBuiltInSequenceType(int sequenceType) {
+        this.builtInSequenceType = sequenceType;
     }
 
-    public int getItemTypeOccurrenceIndicator() {
-        return fItemTypeOccurrenceIndicator;
+    public XSTypeDefinition getXsSequenceTypeDefinition() {
+		return xsTypeDefinition;
+	}
+
+	public void setXsSequenceTypeDefinition(XSTypeDefinition xsSequenceTypeDefinition) {
+		this.xsTypeDefinition = xsSequenceTypeDefinition;
+	}
+
+	public int getItemTypeOccurrenceIndicator() {
+        return itemTypeOccurrenceIndicator;
     }
 
     public void setItemTypeOccurrenceIndicator(int itemTypeOccurrenceIndicator) {
-        this.fItemTypeOccurrenceIndicator = itemTypeOccurrenceIndicator;
+        this.itemTypeOccurrenceIndicator = itemTypeOccurrenceIndicator;
     }
     
     public SequenceTypeKindTest getSequenceTypeKindTest() {
-        return fSequenceTypeKindTest;
+        return sequenceTypeKindTest;
     }
 
     public void setSequenceTypeKindTest(SequenceTypeKindTest sequenceTypeKindTest) {
-        this.fSequenceTypeKindTest = sequenceTypeKindTest;
+        this.sequenceTypeKindTest = sequenceTypeKindTest;
     }
 
     public SequenceTypeFunctionTest getSequenceTypeFunctionTest() {
-		return fSequenceTypeFunctionTest;
+		return sequenceTypeFunctionTest;
 	}
 
 	public void setSequenceTypeFunctionTest(SequenceTypeFunctionTest sequenceTypeFunctionTest) {
-		this.fSequenceTypeFunctionTest = sequenceTypeFunctionTest;
+		this.sequenceTypeFunctionTest = sequenceTypeFunctionTest;
 	}
 	
     public SequenceTypeMapTest getSequenceTypeMapTest() {
-		return fSequenceTypeMapTest;
+		return sequenceTypeMapTest;
 	}
 
 	public void setSequenceTypeMapTest(SequenceTypeMapTest sequenceTypeMapTest) {
-		this.fSequenceTypeMapTest = sequenceTypeMapTest;
+		this.sequenceTypeMapTest = sequenceTypeMapTest;
 	}
 	
     public SequenceTypeArrayTest getSequenceTypeArrayTest() {
-		return fSequenceTypeArrayTest;
+		return sequenceTypeArrayTest;
 	}
 
 	public void setSequenceTypeArrayTest(SequenceTypeArrayTest sequenceTypeArrayTest) {
-		this.fSequenceTypeArrayTest = sequenceTypeArrayTest;
+		this.sequenceTypeArrayTest = sequenceTypeArrayTest;
 	}
 
 	@Override
diff --git a/src/org/apache/xpath/functions/FuncBoolean.java b/src/org/apache/xpath/functions/FuncBoolean.java
index 843596aee..f8011e9b2 100644
--- a/src/org/apache/xpath/functions/FuncBoolean.java
+++ b/src/org/apache/xpath/functions/FuncBoolean.java
@@ -70,8 +70,8 @@ public class FuncBoolean extends FunctionOneArg
    *
    * @throws javax.xml.transform.TransformerException
    */
-  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
-  {
+   public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
+   {
 	  XObject result = null;
 
 	  SourceLocator srcLocator = xctxt.getSAXLocator();
@@ -156,6 +156,6 @@ public class FuncBoolean extends FunctionOneArg
 	  } 
 
 	  return result;
-  }
+   }
   
 }
diff --git a/src/org/apache/xpath/functions/FuncDeepEqual.java b/src/org/apache/xpath/functions/FuncDeepEqual.java
index 69db33e37..c3e8f36be 100644
--- a/src/org/apache/xpath/functions/FuncDeepEqual.java
+++ b/src/org/apache/xpath/functions/FuncDeepEqual.java
@@ -211,13 +211,14 @@ public class FuncDeepEqual extends FunctionMultiArgs {
    * Check whether two XML DOM nodes are equal.
    */
   private boolean isTwoXmlDomNodesEqual(Node node1, Node node2, String collationUri) throws Exception {
-	 boolean isTwoDomNodesEqual = true;
+	 
+	 boolean isTwoXmlDomNodesEqual = true;
 	 
 	 if ((node1.getNodeType() == Node.ELEMENT_NODE) && 
 			                                     (node2.getNodeType() == Node.ELEMENT_NODE)) {
 		String xmlStr1 = XslTransformEvaluationHelper.serializeXmlDomElementNode(node1);
 		String xmlStr2 = XslTransformEvaluationHelper.serializeXmlDomElementNode(node2);
-		isTwoDomNodesEqual = isTwoXmlDocumentStrEqual(xmlStr1, xmlStr2, collationUri);
+		isTwoXmlDomNodesEqual = isTwoXmlDocumentStrEqual(xmlStr1, xmlStr2, collationUri);
 	 }
 	 else if ((node1.getNodeType() == Node.ATTRIBUTE_NODE) && 
 			                                     (node2.getNodeType() == Node.ATTRIBUTE_NODE)) {
@@ -227,24 +228,24 @@ public class FuncDeepEqual extends FunctionMultiArgs {
 		String nsUri2 = node2.getNamespaceURI();		
 		if (localName1.equals(localName2)) {
 		   if ((nsUri1 != null) && (nsUri2 != null) && !nsUri1.equals(nsUri2)) {
-			  isTwoDomNodesEqual = false;  
+			  isTwoXmlDomNodesEqual = false;  
 		   }
 		   else if (((nsUri1 != null) && (nsUri2 == null)) || 
 				                                ((nsUri1 == null) && (nsUri2 != null))) {
-			  isTwoDomNodesEqual = false; 
+			  isTwoXmlDomNodesEqual = false; 
 		   }
 		}
 		else {
-		   isTwoDomNodesEqual = false;
+		   isTwoXmlDomNodesEqual = false;
 		}
 		
-		if (isTwoDomNodesEqual) {
+		if (isTwoXmlDomNodesEqual) {
 		   String node1StrVal = node1.getNodeValue();
 		   String node2StrVal = node2.getNodeValue();
 		   int strComparisonResult = fXPathCollationSupport.compareStringsUsingCollation(node1StrVal, 
 					                                                                     node2StrVal, collationUri);
 		   if (strComparisonResult != 0) {
-			  isTwoDomNodesEqual = false;  
+			  isTwoXmlDomNodesEqual = false;  
 		   }
 		}		
 	 }
@@ -255,7 +256,7 @@ public class FuncDeepEqual extends FunctionMultiArgs {
 		int strComparisonResult = fXPathCollationSupport.compareStringsUsingCollation(node1StrVal, 
 					                                                                  node2StrVal, collationUri);
 		if (strComparisonResult != 0) {
-		   isTwoDomNodesEqual = false;  
+		   isTwoXmlDomNodesEqual = false;  
 		}
 	 }
 	 else if ((node1.getNodeType() == Node.COMMENT_NODE) && 
@@ -265,11 +266,11 @@ public class FuncDeepEqual extends FunctionMultiArgs {
 		int strComparisonResult = fXPathCollationSupport.compareStringsUsingCollation(node1StrVal, 
 						                                                              node2StrVal, collationUri);
 		if (strComparisonResult != 0) {
-		   isTwoDomNodesEqual = false;  
+		   isTwoXmlDomNodesEqual = false;  
 		}
 	 }
 	 
-	 return isTwoDomNodesEqual; 
+	 return isTwoXmlDomNodesEqual; 
   }
   
   /*
diff --git a/src/org/apache/xpath/functions/FuncNot.java b/src/org/apache/xpath/functions/FuncNot.java
index 58fb47e1c..51c046ba3 100644
--- a/src/org/apache/xpath/functions/FuncNot.java
+++ b/src/org/apache/xpath/functions/FuncNot.java
@@ -59,8 +59,8 @@ public class FuncNot extends FunctionOneArg
 	  }
  
 	  /**
-	   * Result of fn:not function is boolean negation of fn:boolean 
-	   * function's result. 
+	   * Result of function fn:not is, boolean negation of fn:boolean 
+	   * function's result on the same function argument. 
 	   */
 	  
 	  if (((XSBoolean)result).value()) {
diff --git a/src/org/apache/xpath/functions/XPathDynamicFunctionCall.java b/src/org/apache/xpath/functions/XPathDynamicFunctionCall.java
index dc4f7482a..cc500fcff 100644
--- a/src/org/apache/xpath/functions/XPathDynamicFunctionCall.java
+++ b/src/org/apache/xpath/functions/XPathDynamicFunctionCall.java
@@ -174,7 +174,7 @@ public class XPathDynamicFunctionCall extends Expression {
 	              
 	              if (paramType != null) {
 	                  try {
-	                     argValue = SequenceTypeSupport.convertXdmValueToAnotherType(argValue, null, paramType, null);                     
+	                     argValue = SequenceTypeSupport.castXdmValueToAnotherType(argValue, null, paramType, null);                     
 	                     if (argValue == null) {
 	                        throw new TransformerException("XTTE0505 : The item type of argument at position " + (idx + 1) + " of dynamic function call "
 	                                                                                                           + "$" + m_funcRefVarName + ", doesn't match "
@@ -211,7 +211,7 @@ public class XPathDynamicFunctionCall extends Expression {
 	           SequenceTypeData funcReturnType = inlineFunction.getReturnType();
 	           if (funcReturnType != null) {
 	              try {
-	                 evalResult = SequenceTypeSupport.convertXdmValueToAnotherType(evalResult, null, funcReturnType, null);
+	                 evalResult = SequenceTypeSupport.castXdmValueToAnotherType(evalResult, null, funcReturnType, null);
 	                 if (evalResult == null) {
 	                    throw new TransformerException("XTTE0505 : The item type of result of dynamic function call $"+ m_funcRefVarName + ", doesn't match an "
 	                                                                                                                                   + "expected type.", srcLocator);  
diff --git a/src/org/apache/xpath/functions/XSLConstructorStylesheetOrExtensionFunction.java b/src/org/apache/xpath/functions/XSLConstructorStylesheetOrExtensionFunction.java
index e489970c8..c36379986 100644
--- a/src/org/apache/xpath/functions/XSLConstructorStylesheetOrExtensionFunction.java
+++ b/src/org/apache/xpath/functions/XSLConstructorStylesheetOrExtensionFunction.java
@@ -40,6 +40,12 @@ import org.apache.xpath.res.XPATHMessages;
  * An object of this class represents an XPath constructor function, 
  * XSL stylesheet function or Xalan-J's extension function.
  * 
+ * @author Scott Boag <sc...@us.ibm.com>
+ * @author Christine Li <jy...@apache.org>, Morris Kwan <mk...@apache.org>
+ * 
+ * @author Mukul Gandhi <mu...@apache.org>
+ *         (XPath 3 specific changes, to this class)
+ * 
  * @xsl.usage advanced
  */
 public class XSLConstructorStylesheetOrExtensionFunction extends Function
diff --git a/src/org/apache/xpath/functions/XSLFunctionService.java b/src/org/apache/xpath/functions/XSLFunctionService.java
index 6336df0b9..ce0f29d74 100644
--- a/src/org/apache/xpath/functions/XSLFunctionService.java
+++ b/src/org/apache/xpath/functions/XSLFunctionService.java
@@ -45,6 +45,7 @@ import org.apache.xpath.ExpressionNode;
 import org.apache.xpath.XPathContext;
 import org.apache.xpath.compiler.Keywords;
 import org.apache.xpath.objects.ResultSequence;
+import org.apache.xpath.objects.XNodeSet;
 import org.apache.xpath.objects.XObject;
 import org.apache.xpath.types.XSByte;
 import org.apache.xpath.types.XSNegativeInteger;
@@ -87,7 +88,7 @@ import xml.xpath31.processor.types.XSYearMonthDuration;
 
 /**
  * An object of this class supports evaluation of an XPath 
- * constructor function call, or an XSL stylesheet function 
+ * constructor function call, and an XSL stylesheet function 
  * call.
  * 
  * @author Mukul Gandhi <mu...@apache.org>
@@ -96,13 +97,16 @@ import xml.xpath31.processor.types.XSYearMonthDuration;
  */
 public class XSLFunctionService {
 	
-	// Class fields, specifying constant values used by this 
-	// implementation.				
-	
-	public static final String UTF_16 = "UTF-16";
+	/**
+	  * Class field declarations, specifying constant values used by this
+	  * implementation.
+	  * 		
+	 */
 	
 	public static final String UTF_8 = "UTF-8";
 	
+	public static final String UTF_16 = "UTF-16";
+	
 	public static final String XML_DOM_FORMAT_PRETTY_PRINT = "format-pretty-print";
 	
 	public static final String XS_VALID_TRUE = "XS_VALID_TRUE";
@@ -135,11 +139,11 @@ public class XSLFunctionService {
     		String funcNamespace = funcObj.getNamespace();
     		
     		if (!(Constants.S_EXTENSIONS_JAVA_URL).equals(funcNamespace)) {
-    			// Both XPath constructor (prefix:typeName) and XSL stylesheet function 
+    			// both XPath constructor (prefix:typeName) and XSL stylesheet function 
     			// calls (xsl:function), are syntactically similar to Xalan-J XPath 
-    			// extension function calls (prefix:functionName). All the code within 
-    			// this code-block, need not run, when an XSL stylesheet specifies an 
-    			// Xalan-J XPath extension function.
+    			// extension function calls (prefix:functionName). The implementation
+    			// here need not run when an XSL stylesheet specifies Xalan-J XPath 
+    			// extension function.
     			ExpressionNode expressionNode = xpathExpr.getExpressionOwner();
     			ExpressionNode stylesheetRootNode = null;
     			while (expressionNode != null) {
@@ -161,7 +165,7 @@ public class XSLFunctionService {
     				// Evaluate XSL stylesheet function call
     				ResultSequence argSequence = new ResultSequence();
     				for (int idx = 0; idx < funcObj.getArgCount(); idx++) {
-    					XObject argVal = (funcObj.getArg(idx)).execute(xctxt);
+    					XObject argVal = (funcObj.getArg(idx)).execute(xctxt);    					
     					argSequence.add(argVal);
     				}
 
@@ -501,6 +505,7 @@ public class XSLFunctionService {
     			else {
     				// We check and evaluate below, XPath constructor function calls to 
     				// XML Schema user-defined simple types.
+    				
     				HashMap stylesheetAvailableElems = stylesheetRoot.getAvailableElements();
 
     				if (stylesheetAvailableElems.containsKey(new QName(Constants.S_XSLNAMESPACEURL, 
@@ -512,15 +517,16 @@ public class XSLFunctionService {
     					}
 
     					NodeList nodeList = elemTemplateElem.getChildNodes();
-    					Node xsSchemaTopMostNode = nodeList.item(0);
-
-    					XSModel xsModel = null;        		   
-    					XSLoaderImpl xsLoader = new XSLoaderImpl();
+    					Node xsSchemaTopMostNode = nodeList.item(0);    					
 
-    					if (xsSchemaTopMostNode != null) {
+    					if (xsSchemaTopMostNode != null) {    						
     						// xsl:import-schema instruction's child contents, has 
-    						// XML Schema document available as string.
+    						// XML Schema document available as string value.
+    						
     						String xmlSchemaDocumentStr = null;
+    						
+    						XSModel xsModel = null;        		   
+        					XSLoaderImpl xsLoader = new XSLoaderImpl();
 
     						try {
     							DOMImplementationLS domImplLS = (DOMImplementationLS)((DOMImplementationRegistry.newInstance()).getDOMImplementation("LS"));
@@ -564,6 +570,10 @@ public class XSLFunctionService {
     					else {
     						// Use an XML Schema document available, at the uri specified by xsl:import-schema 
     						// element's attribute 'schema-location'.
+    						
+    						XSModel xsModel = null;        		   
+        					XSLoaderImpl xsLoader = new XSLoaderImpl();
+        					
     						NamedNodeMap importSchemaNodeAttributes = ((Element)elemTemplateElem).getAttributes();        			   
 
     						if (importSchemaNodeAttributes != null) {
diff --git a/src/org/apache/xpath/objects/XObject.java b/src/org/apache/xpath/objects/XObject.java
index 002eb7d96..ac0a1eb26 100644
--- a/src/org/apache/xpath/objects/XObject.java
+++ b/src/org/apache/xpath/objects/XObject.java
@@ -27,6 +27,7 @@ import javax.xml.transform.TransformerException;
 
 import org.apache.xalan.res.XSLMessages;
 import org.apache.xalan.xslt.util.XslTransformEvaluationHelper;
+import org.apache.xerces.xs.XSTypeDefinition;
 import org.apache.xml.dtm.DTM;
 import org.apache.xml.dtm.DTMIterator;
 import org.apache.xml.utils.QName;
@@ -336,7 +337,12 @@ public class XObject extends Expression implements Serializable, Cloneable
   public static final int CLASS_UNSIGNED_BYTE = 36;
 
   /** Represents an unresolved variable type as an integer. */
-  public static final int CLASS_UNRESOLVEDVARIABLE = 600;    
+  public static final int CLASS_UNRESOLVEDVARIABLE = 600;
+  
+  /** An XDM item may have a type annotation conforming to this
+      schema type. A non-null value of this class field implies that,
+      this object instance has this type annotation. **/
+  private XSTypeDefinition xsTypeDefinition;
 
   /**
    * Tell what kind of class this is.
@@ -1585,4 +1591,12 @@ public class XObject extends Expression implements Serializable, Cloneable
 	 return m_QName; 
   }
 
+  public XSTypeDefinition getXsTypeDefinition() {
+	 return xsTypeDefinition;
+  }
+
+  public void setXsTypeDefinition(XSTypeDefinition xsTypeDefinition) {
+	 this.xsTypeDefinition = xsTypeDefinition;
+  }
+
 }
diff --git a/src/org/apache/xpath/operations/CastAs.java b/src/org/apache/xpath/operations/CastAs.java
index 51a31e0b6..2a0bb6520 100644
--- a/src/org/apache/xpath/operations/CastAs.java
+++ b/src/org/apache/xpath/operations/CastAs.java
@@ -20,6 +20,9 @@
  */
 package org.apache.xpath.operations;
 
+import org.apache.xalan.templates.ElemTemplateElement;
+import org.apache.xpath.ExpressionNode;
+import org.apache.xpath.XPathContext;
 import org.apache.xpath.composite.SequenceTypeData;
 import org.apache.xpath.composite.SequenceTypeSupport;
 import org.apache.xpath.objects.XObject;
@@ -53,7 +56,13 @@ public class CastAs extends Operation
       
       SequenceTypeData seqTypedData = (SequenceTypeData)right;
       
-      result = SequenceTypeSupport.castXdmValueToAnotherType(left, seqTypedData);
+      ExpressionNode exprNode = getExpressionOwner();
+      XPathContext xpathContext = null;
+      if (exprNode instanceof ElemTemplateElement) {
+    	 xpathContext = ((ElemTemplateElement)exprNode).getXPathContext();
+      }
+      
+      result = SequenceTypeSupport.castXdmValueToAnotherType(left, null, seqTypedData, xpathContext);
       
       return result;
   }
diff --git a/src/org/apache/xpath/operations/InstanceOf.java b/src/org/apache/xpath/operations/InstanceOf.java
index 048321209..45cc39478 100644
--- a/src/org/apache/xpath/operations/InstanceOf.java
+++ b/src/org/apache/xpath/operations/InstanceOf.java
@@ -33,7 +33,7 @@ import org.apache.xpath.composite.SequenceTypeData;
 import org.apache.xpath.composite.SequenceTypeKindTest;
 import org.apache.xpath.composite.SequenceTypeMapTest;
 import org.apache.xpath.composite.SequenceTypeSupport;
-import org.apache.xpath.composite.SequenceTypeSupport.OccurenceIndicator;
+import org.apache.xpath.composite.SequenceTypeSupport.OccurrenceIndicator;
 import org.apache.xpath.objects.ResultSequence;
 import org.apache.xpath.objects.XBoolean;
 import org.apache.xpath.objects.XNodeSet;
@@ -103,7 +103,7 @@ public class InstanceOf extends Operation
       
       SequenceTypeData seqTypedData = (SequenceTypeData)right;
       
-      int seqType = seqTypedData.getSequenceType();
+      int seqType = seqTypedData.getBuiltInSequenceType();
       if ((left instanceof ResultSequence) && ((ResultSequence)left).size() == 0) {
     	 if ((seqType != SequenceTypeSupport.EMPTY_SEQUENCE) && (seqType > 0)) {
     	    return XBoolean.S_FALSE; 
@@ -124,149 +124,149 @@ public class InstanceOf extends Operation
     boolean isInstanceOf = false;
       
     if ((xdmValue instanceof XSUntypedAtomic) && 
-          (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNTYPED_ATOMIC)) {
+          (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNTYPED_ATOMIC)) {
           isInstanceOf = true;  
       }
       else if ((xdmValue instanceof XSUntyped) && 
-              (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNTYPED)) {
+              (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNTYPED)) {
           isInstanceOf = true;
       }
       else if ((xdmValue instanceof XString || xdmValue instanceof XSString) && 
-              ((seqTypeData.getSequenceType() == SequenceTypeSupport.STRING) || (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+              ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.STRING) || (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSNormalizedString) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_NORMALIZED_STRING) || 
-    		                                                (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSNormalizedString) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_NORMALIZED_STRING) || 
+    		                                                (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSToken) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_TOKEN) || 
-    		                                     (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSToken) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_TOKEN) || 
+    		                                     (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSAnyURI) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_URI) || 
-    		                                      (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSAnyURI) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_URI) || 
+    		                                      (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSQName) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_QNAME) || 
-                                                 (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSQName) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_QNAME) || 
+                                                 (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if (((xdmValue instanceof XBoolean) || (xdmValue instanceof XSBoolean)) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.BOOLEAN) || 
-    		                                                                           (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if (((xdmValue instanceof XBoolean) || (xdmValue instanceof XSBoolean)) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.BOOLEAN) || 
+    		                                                                           (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
       else if (xdmValue instanceof XNumber) {          
-    	  if (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE) {
+    	  if (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE) {
     		 isInstanceOf = true;
     	  }
-    	  else if ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DECIMAL) ||
-    			   (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DOUBLE)) {
+    	  else if ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DECIMAL) ||
+    			   (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DOUBLE)) {
              isInstanceOf = true; 
           }
           else {
              double doubleVal = ((XNumber)xdmValue).num();
-             if ((doubleVal == (int)doubleVal) && (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_INTEGER)) {
+             if ((doubleVal == (int)doubleVal) && (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_INTEGER)) {
             	 isInstanceOf = true; 
              }
-             else if ((doubleVal == (float)doubleVal) && (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_FLOAT)) {
+             else if ((doubleVal == (float)doubleVal) && (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_FLOAT)) {
             	 isInstanceOf = true; 
              }
           }    	  
       }
-      else if ((xdmValue instanceof XSDouble) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DOUBLE) || 
-    		                                      (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDouble) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DOUBLE) || 
+    		                                      (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
          isInstanceOf = true; 
       }
-      else if ((xdmValue instanceof XSFloat) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_FLOAT) || 
-    		                                     (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSFloat) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_FLOAT) || 
+    		                                     (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
       else if (((xdmValue instanceof XSInteger) || (xdmValue instanceof XSNonNegativeInteger) || 
     		    (xdmValue instanceof XSPositiveInteger) || (xdmValue instanceof XSNonPositiveInteger) || 
     		    (xdmValue instanceof XSNegativeInteger) || (xdmValue instanceof XSLong) || 
     		    (xdmValue instanceof XSInt) || (xdmValue instanceof XSShort)) && 
-    		     ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_INTEGER) ||                                                   
-                  (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {          
+    		     ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_INTEGER) ||                                                   
+                  (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {          
     	  isInstanceOf = true;                    
       }
       else if (((xdmValue instanceof XSLong) || (xdmValue instanceof XSInt) || (xdmValue instanceof XSShort)) && 
-    		                                      ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_LONG) || 
-                                                   (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {          
+    		                                      ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_LONG) || 
+                                                   (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {          
     	  isInstanceOf = true;
       }
       else if (((xdmValue instanceof XSInt) || (xdmValue instanceof XSShort)) && 
-    		                                     ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_INT) || 
-    		                                      (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {    	  
+    		                                     ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_INT) || 
+    		                                      (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {    	  
     	  isInstanceOf = true;
       }      
-      else if ((xdmValue instanceof XSShort) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_SHORT) || 
-                                                 (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSShort) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_SHORT) || 
+                                                 (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSByte) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_BYTE) || 
-                                                (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSByte) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_BYTE) || 
+                                                (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSUnsignedLong) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNSIGNED_LONG) || 
-                                                        (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSUnsignedLong) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNSIGNED_LONG) || 
+                                                        (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSUnsignedInt) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNSIGNED_INT) || 
-                                                       (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSUnsignedInt) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNSIGNED_INT) || 
+                                                       (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSUnsignedShort) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNSIGNED_SHORT) || 
-                                                         (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSUnsignedShort) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNSIGNED_SHORT) || 
+                                                         (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSUnsignedByte) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_UNSIGNED_BYTE) || 
-                                                        (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSUnsignedByte) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_UNSIGNED_BYTE) || 
+                                                        (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
       else if (((xdmValue instanceof XSNonNegativeInteger) || (xdmValue instanceof XSPositiveInteger)) && 
-    		                                                   ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER) || 
-                                                                (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {    	  
+    		                                                   ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_NON_NEGATIVE_INTEGER) || 
+                                                                (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {    	  
     	  isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSPositiveInteger) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_POSITIVE_INTEGER) || 
-                                                           (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSPositiveInteger) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_POSITIVE_INTEGER) || 
+                                                           (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
       else if (((xdmValue instanceof XSNonPositiveInteger) || (xdmValue instanceof XSNegativeInteger)) && 
-    		   ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_NON_POSITIVE_INTEGER) || 
-                (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+    		   ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_NON_POSITIVE_INTEGER) || 
+                (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSNegativeInteger) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_NEGATIVE_INTEGER) || 
-                                                           (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSNegativeInteger) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_NEGATIVE_INTEGER) || 
+                                                           (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }      
-      else if ((xdmValue instanceof XSDecimal) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DECIMAL) || 
-    		                                       (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDecimal) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DECIMAL) || 
+    		                                       (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSDate) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DATE) || 
-    		                                    (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDate) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DATE) || 
+    		                                    (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSDateTime) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DATETIME) || 
-    		                                        (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDateTime) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DATETIME) || 
+    		                                        (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSTime) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_TIME) || 
-    		                                    (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSTime) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_TIME) || 
+    		                                    (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSDuration) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DURATION) || 
-    		                                        (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDuration) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DURATION) || 
+    		                                        (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSDayTimeDuration) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_DAYTIME_DURATION) || 
-    		                                               (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSDayTimeDuration) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_DAYTIME_DURATION) || 
+    		                                               (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
-      else if ((xdmValue instanceof XSYearMonthDuration) && ((seqTypeData.getSequenceType() == SequenceTypeSupport.XS_YEARMONTH_DURATION) || 
-    		                                                 (seqTypeData.getSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
+      else if ((xdmValue instanceof XSYearMonthDuration) && ((seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_YEARMONTH_DURATION) || 
+    		                                                 (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.XS_ANY_ATOMIC_TYPE))) {
           isInstanceOf = true;
       }
       else if (xdmValue instanceof XNodeSet) {
@@ -297,7 +297,7 @@ public class InstanceOf extends Operation
 	  int itemTypeOccurenceIndicator = seqTypeData.getItemTypeOccurrenceIndicator();
 	  SequenceTypeKindTest seqTypeKindTest = seqTypeData.getSequenceTypeKindTest();
 
-	  if ((nodeSetLen > 1) && ((itemTypeOccurenceIndicator == 0) || (itemTypeOccurenceIndicator == OccurenceIndicator.ZERO_OR_ONE))) {
+	  if ((nodeSetLen > 1) && ((itemTypeOccurenceIndicator == 0) || (itemTypeOccurenceIndicator == OccurrenceIndicator.ZERO_OR_ONE))) {
 		  isInstanceOf = false; 
 	  }
 	  else {
@@ -320,7 +320,7 @@ public class InstanceOf extends Operation
 					  }
 
 					  if ((seqTypeKindTest.getKindVal() == SequenceTypeSupport.ELEMENT_KIND) && (nodeName.equals(elemNodeKindTestNodeName)) 
-							  && (SequenceTypeSupport.isTwoXmlNamespacesEqual(nodeNsUri, seqTypeKindTest.getNodeNsUri()))) {
+							  && (SequenceTypeSupport.isTwoXmlNamespaceValuesEqual(nodeNsUri, seqTypeKindTest.getNodeNsUri()))) {
 						  nodeSetSequenceTypeKindTestResultList.add(Boolean.valueOf(true));  
 					  }
 					  else if ((seqTypeKindTest.getKindVal() == SequenceTypeSupport.NODE_KIND) || 
@@ -342,7 +342,7 @@ public class InstanceOf extends Operation
 					  }
 
 					  if ((seqTypeKindTest.getKindVal() == SequenceTypeSupport.ATTRIBUTE_KIND) && (nodeName.equals(attrNodeKindTestNodeName)) 
-							  && (SequenceTypeSupport.isTwoXmlNamespacesEqual(
+							  && (SequenceTypeSupport.isTwoXmlNamespaceValuesEqual(
 									  nodeNsUri, seqTypeKindTest.getNodeNsUri()))) {
 						  nodeSetSequenceTypeKindTestResultList.add(Boolean.valueOf(true));    
 					  }
@@ -387,13 +387,13 @@ public class InstanceOf extends Operation
 
 	  int seqLen = srcResultSeq.size();
 
-	  if ((seqLen == 0) && (seqTypeData.getItemTypeOccurrenceIndicator() == OccurenceIndicator.ONE_OR_MANY)) {
+	  if ((seqLen == 0) && (seqTypeData.getItemTypeOccurrenceIndicator() == OccurrenceIndicator.ONE_OR_MANY)) {
 		  isInstanceOf = false;  
 	  }
-	  else if ((seqLen > 0) && (seqTypeData.getSequenceType() == SequenceTypeSupport.EMPTY_SEQUENCE)) {
+	  else if ((seqLen > 0) && (seqTypeData.getBuiltInSequenceType() == SequenceTypeSupport.EMPTY_SEQUENCE)) {
 		  isInstanceOf = false;  
 	  }
-	  else if ((seqLen > 1) && (seqTypeData.getItemTypeOccurrenceIndicator() == OccurenceIndicator.ZERO_OR_ONE)) {
+	  else if ((seqLen > 1) && (seqTypeData.getItemTypeOccurrenceIndicator() == OccurrenceIndicator.ZERO_OR_ONE)) {
 		  isInstanceOf = false;
 	  }
 
@@ -402,7 +402,7 @@ public class InstanceOf extends Operation
 		  sequenceTypeDataNew.setSequenceTypeKindTest(seqTypeData.getSequenceTypeKindTest()); 
 	  }
 	  else {
-		  sequenceTypeDataNew.setSequenceType(seqTypeData.getSequenceType()); 
+		  sequenceTypeDataNew.setBuiltInSequenceType(seqTypeData.getBuiltInSequenceType()); 
 	  }
 
 	  boolean isInstanceOfOnSeqItem = true;
@@ -462,7 +462,7 @@ public class InstanceOf extends Operation
 				  }
 				  SequenceTypeData arrayItemTypeInfo = sequenceTypeArrayTest.getArrayItemTypeInfo();
 				  try {
-					  XObject arrayItemTypeCheckResult = SequenceTypeSupport.convertXdmValueToAnotherType(arrItem, null, arrayItemTypeInfo, null);
+					  XObject arrayItemTypeCheckResult = SequenceTypeSupport.castXdmValueToAnotherType(arrItem, null, arrayItemTypeInfo, null);
 					  if (arrayItemTypeCheckResult == null) {             				
 						  isInstanceOf = false;
 						  break;
diff --git a/src/org/apache/xpath/operations/Operation.java b/src/org/apache/xpath/operations/Operation.java
index 957d2f41a..a44b0fba4 100644
--- a/src/org/apache/xpath/operations/Operation.java
+++ b/src/org/apache/xpath/operations/Operation.java
@@ -23,12 +23,14 @@ package org.apache.xpath.operations;
 import javax.xml.XMLConstants;
 
 import org.apache.xpath.Expression;
+import org.apache.xpath.ExpressionNode;
 import org.apache.xpath.ExpressionOwner;
 import org.apache.xpath.XPathContext;
 import org.apache.xpath.XPathVisitor;
 import org.apache.xpath.axes.SelfIteratorNoPredicate;
 import org.apache.xpath.functions.XSLFunctionService;
 import org.apache.xpath.functions.XSLConstructorStylesheetOrExtensionFunction;
+import org.apache.xpath.objects.XNodeSet;
 import org.apache.xpath.objects.XObject;
 
 /**
diff --git a/src/org/apache/xpath/operations/CastAs.java b/src/org/apache/xpath/operations/TreatAs.java
similarity index 84%
copy from src/org/apache/xpath/operations/CastAs.java
copy to src/org/apache/xpath/operations/TreatAs.java
index 51a31e0b6..f8be26c15 100644
--- a/src/org/apache/xpath/operations/CastAs.java
+++ b/src/org/apache/xpath/operations/TreatAs.java
@@ -25,16 +25,16 @@ import org.apache.xpath.composite.SequenceTypeSupport;
 import org.apache.xpath.objects.XObject;
 
 /**
- * The XPath 3.1 "cast as" operation.
+ * The XPath 3.1 "treat as" operation.
  * 
  * @author Mukul Gandhi <mu...@apache.org>
  * 
  * @xsl.usage advanced
  */
-public class CastAs extends Operation
+public class TreatAs extends Operation
 {
 
-   private static final long serialVersionUID = -4194858144694864568L;
+   private static final long serialVersionUID = 8897640092248117520L;
 
   /**
    * Apply the operation to two operands, and return the result.
@@ -46,8 +46,7 @@ public class CastAs extends Operation
    *
    * @throws javax.xml.transform.TransformerException
    */
-  public XObject operate(XObject left, XObject right) 
-                                                 throws javax.xml.transform.TransformerException
+  public XObject operate(XObject left, XObject right) throws javax.xml.transform.TransformerException
   {
 	  XObject result = null;
       
diff --git a/tests/org/apache/xalan/xslt3/XSLImportSchemaTests.java b/tests/org/apache/xalan/xslt3/XSLImportSchemaTests.java
index 7007afdb4..7529b8c91 100644
--- a/tests/org/apache/xalan/xslt3/XSLImportSchemaTests.java
+++ b/tests/org/apache/xalan/xslt3/XSLImportSchemaTests.java
@@ -118,4 +118,24 @@ public class XSLImportSchemaTests extends XSLTransformTestsUtil {
         runXslTransformAndAssertOutput(xmlFilePath, xslFilePath, goldFilePath, null);   
     }
     
+    @Test
+    public void xslImportSchemaTest8() {
+        String xmlFilePath = XSL_TRANSFORM_INPUT_DIRPATH + "test2.xml"; 
+        String xslFilePath = XSL_TRANSFORM_INPUT_DIRPATH + "test8.xsl";
+        
+        String goldFilePath = XSL_TRANSFORM_GOLD_DIRPATH + "test8.out";                
+        
+        runXslTransformAndAssertOutput(xmlFilePath, xslFilePath, goldFilePath, null);   
+    }
+    
+    @Test
+    public void xslImportSchemaTest9() {
+        String xmlFilePath = XSL_TRANSFORM_INPUT_DIRPATH + "test2.xml"; 
+        String xslFilePath = XSL_TRANSFORM_INPUT_DIRPATH + "test9.xsl";
+        
+        String goldFilePath = XSL_TRANSFORM_GOLD_DIRPATH + "test8.out";                
+        
+        runXslTransformAndAssertOutput(xmlFilePath, xslFilePath, goldFilePath, null);   
+    }
+    
 }
diff --git a/tests/xsl_import_schema/address.xsd b/tests/xsl_import_schema/address.xsd
new file mode 100644
index 000000000..e44b5c5f7
--- /dev/null
+++ b/tests/xsl_import_schema/address.xsd
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+   <xs:complexType name="Address">
+      <xs:sequence>
+	     <xs:element name="fName" type="xs:string"/>
+		 <xs:element name="mName" type="xs:string" minOccurs="0"/>
+		 <xs:element name="lName" type="xs:string"/>
+		 <xs:element name="addressLine1" type="xs:string"/>
+		 <xs:element name="addressLine2" type="xs:string" minOccurs="0"/>
+		 <xs:element name="city" type="xs:string" minOccurs="0"/>
+		 <xs:element name="country" type="xs:string"/>
+		 <xs:element name="state" type="xs:string" minOccurs="0"/>
+		 <xs:element name="zip" type="xs:string" minOccurs="0"/>
+	  </xs:sequence>
+   </xs:complexType>
+   
+   <xs:complexType name="Person">
+      <xs:sequence>
+	     <xs:element name="fName" type="xs:string"/>
+		 <xs:element name="mName" type="xs:string" minOccurs="0"/>
+		 <xs:element name="lName" type="xs:string"/>
+	  </xs:sequence>
+   </xs:complexType>
+
+</xs:schema>
\ No newline at end of file
diff --git a/tests/xsl_import_schema/gold/test8.out b/tests/xsl_import_schema/gold/test8.out
new file mode 100644
index 000000000..30a9f953c
--- /dev/null
+++ b/tests/xsl_import_schema/gold/test8.out
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?><result>
+  <address id="id_1">
+    <person>
+      <fName>abc 1</fName>
+      <lName>mno 1</lName>
+    </person>
+  </address>
+  <address id="id_2">
+    <person>
+      <fName>abc 2</fName>
+      <lName>mno 2</lName>
+    </person>
+  </address>
+  <address id="id_3">
+    <person>
+      <fName>abc 3</fName>
+      <lName>mno 3</lName>
+    </person>
+  </address>
+</result>
diff --git a/tests/xsl_import_schema/test2.xml b/tests/xsl_import_schema/test2.xml
new file mode 100644
index 000000000..e734e6df7
--- /dev/null
+++ b/tests/xsl_import_schema/test2.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<info>
+   <address>
+      <fName>abc 1</fName>
+	  <lName>mno 1</lName>
+	  <addressLine1>address location details 1</addressLine1>
+	  <city>hello 1</city>
+	  <country>USA</country>
+	  <state>state 1</state>
+	  <zip>zip 1</zip>
+   </address>
+   <address>
+      <fName>abc 2</fName>
+	  <lName>mno 2</lName>
+	  <addressLine1>address location details 2</addressLine1>
+	  <city>hello 2</city>
+	  <country>USA</country>
+	  <state>state 2</state>
+	  <zip>zip 2</zip>
+   </address>
+   <address>
+      <fName>abc 3</fName>
+	  <lName>mno 3</lName>
+	  <addressLine1>address location details 2</addressLine1>
+	  <city>hello 3</city>
+	  <country>Singapore</country>
+   </address>
+</info>
\ No newline at end of file
diff --git a/tests/xsl_import_schema/test8.xsl b/tests/xsl_import_schema/test8.xsl
new file mode 100644
index 000000000..2ff130af2
--- /dev/null
+++ b/tests/xsl_import_schema/test8.xsl
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+				xmlns:fn0="http://ns0"
+				exclude-result-prefixes="fn0"
+                version="3.0">
+                
+  <!-- Author: mukulg@apache.org -->
+    
+  <!-- An XSL stylesheet test case, to test XSLT 3.0's xsl:import-schema 
+       instruction. 
+  -->                 			
+
+   <xsl:output method="xml" indent="yes"/>
+   
+   <!-- An XSL xsl:import-schema instruction, referring to an 
+        XML schema external document. -->
+   <xsl:import-schema schema-location="address.xsd"/>
+
+   <xsl:template match="/info">
+	  <result>
+	     <xsl:for-each select="address">
+		   <xsl:variable name="addressElem" select="."/>
+		   <address id="{'id_' || position()}">
+		      <xsl:variable name="person1" as="element(*, Person)">
+		         <xsl:copy-of select="fn0:getAddressInfo($addressElem cast as Address)"/>
+			  </xsl:variable>			  
+			  <xsl:copy-of select="$person1"/>
+		   </address>
+		 </xsl:for-each>
+	  </result>	  
+   </xsl:template>
+   
+   <xsl:function name="fn0:getAddressInfo" as="element(*, Person)">
+	  <xsl:param name="addressElem" as="element(*, Address)"/>
+	  <person>
+	     <xsl:copy-of select="$addressElem/fName | $addressElem/mName | $addressElem/lName"/>
+	  </person>
+   </xsl:function>
+   
+   <!--
+      * Licensed to the Apache Software Foundation (ASF) under one
+      * or more contributor license agreements. See the NOTICE file
+      * distributed with this work for additional information
+      * regarding copyright ownership. The ASF licenses this file
+      * to you under the Apache License, Version 2.0 (the  "License");
+      * you may not use this file except in compliance with the License.
+      * You may obtain a copy of the License at
+      *
+      *     http://www.apache.org/licenses/LICENSE-2.0
+      *
+      * Unless required by applicable law or agreed to in writing, software
+      * distributed under the License is distributed on an "AS IS" BASIS,
+      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      * See the License for the specific language governing permissions and
+      * limitations under the License.
+  -->
+
+</xsl:stylesheet>
diff --git a/tests/xsl_import_schema/test9.xsl b/tests/xsl_import_schema/test9.xsl
new file mode 100644
index 000000000..4267b2e1a
--- /dev/null
+++ b/tests/xsl_import_schema/test9.xsl
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+				xmlns:fn0="http://ns0"
+				exclude-result-prefixes="fn0"
+                version="3.0">
+                
+   <!-- Author: mukulg@apache.org -->
+    
+   <!-- An XSL stylesheet test case, to test XSLT 3.0's xsl:import-schema 
+        instruction. 
+   -->                 			
+
+   <xsl:output method="xml" indent="yes"/>
+   
+   <!-- An xsl:import-schema instruction, that has inline XML Schema 
+        definitions for complex types. -->
+   <xsl:import-schema>
+		<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">		   
+		   <xs:complexType name="Address">
+			  <xs:sequence>
+				 <xs:element name="fName" type="xs:string"/>
+				 <xs:element name="mName" type="xs:string" minOccurs="0"/>
+				 <xs:element name="lName" type="xs:string"/>
+				 <xs:element name="addressLine1" type="xs:string"/>
+				 <xs:element name="addressLine2" type="xs:string" minOccurs="0"/>
+				 <xs:element name="city" type="xs:string" minOccurs="0"/>
+				 <xs:element name="country" type="xs:string"/>
+				 <xs:element name="state" type="xs:string" minOccurs="0"/>
+				 <xs:element name="zip" type="xs:string" minOccurs="0"/>
+			  </xs:sequence>
+		   </xs:complexType>
+		   
+		   <xs:complexType name="Person">
+			  <xs:sequence>
+				 <xs:element name="fName" type="xs:string"/>
+				 <xs:element name="mName" type="xs:string" minOccurs="0"/>
+				 <xs:element name="lName" type="xs:string"/>
+			  </xs:sequence>
+		   </xs:complexType>
+		</xs:schema>
+   </xsl:import-schema>
+
+   <xsl:template match="/info">
+	  <result>
+	     <xsl:for-each select="address">
+		   <xsl:variable name="addressElem" select="."/>
+		   <address id="{'id_' || position()}">
+		      <xsl:variable name="person1" as="element(*, Person)">
+		         <xsl:copy-of select="fn0:getAddressInfo($addressElem cast as Address)"/>
+			  </xsl:variable>			  
+			  <xsl:copy-of select="$person1"/>
+		   </address>
+		 </xsl:for-each>
+	  </result>	  
+   </xsl:template>
+   
+   <xsl:function name="fn0:getAddressInfo" as="element(*, Person)">
+	  <xsl:param name="addressElem" as="element(*, Address)"/>
+	  <person>
+	     <xsl:copy-of select="$addressElem/fName | $addressElem/mName | $addressElem/lName"/>
+	  </person>
+   </xsl:function>
+   
+   <!--
+      * Licensed to the Apache Software Foundation (ASF) under one
+      * or more contributor license agreements. See the NOTICE file
+      * distributed with this work for additional information
+      * regarding copyright ownership. The ASF licenses this file
+      * to you under the Apache License, Version 2.0 (the  "License");
+      * you may not use this file except in compliance with the License.
+      * You may obtain a copy of the License at
+      *
+      *     http://www.apache.org/licenses/LICENSE-2.0
+      *
+      * Unless required by applicable law or agreed to in writing, software
+      * distributed under the License is distributed on an "AS IS" BASIS,
+      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      * See the License for the specific language governing permissions and
+      * limitations under the License.
+   -->
+
+</xsl:stylesheet>


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@xalan.apache.org
For additional commands, e-mail: commits-help@xalan.apache.org