1 /* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 */ 4 /* 5 * Licensed to the Apache Software Foundation (ASF) under one or more 6 * contributor license agreements. See the NOTICE file distributed with 7 * this work for additional information regarding copyright ownership. 8 * The ASF licenses this file to You under the Apache License, Version 2.0 9 * (the "License"); you may not use this file except in compliance with 10 * the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, software 15 * distributed under the License is distributed on an "AS IS" BASIS, 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 * See the License for the specific language governing permissions and 18 * limitations under the License. 19 */ 20 /* 21 * $Id: Parser.java,v 1.2.4.1 2005/09/13 12:14:32 pvedula Exp $ 22 */ 23 24 package com.sun.org.apache.xalan.internal.xsltc.compiler; 25 26 import com.sun.java_cup.internal.runtime.Symbol; 27 import com.sun.org.apache.xalan.internal.XalanConstants; 28 import com.sun.org.apache.xalan.internal.utils.FactoryImpl; 29 import com.sun.org.apache.xalan.internal.utils.ObjectFactory; 30 import com.sun.org.apache.xalan.internal.utils.SecuritySupport; 31 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager; 32 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; 33 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodType; 34 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type; 35 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError; 36 import com.sun.org.apache.xml.internal.serializer.utils.SystemIDResolver; 37 import java.io.File; 38 import java.io.IOException; 39 import java.io.StringReader; 40 import java.util.HashMap; 41 import java.util.Iterator; 42 import java.util.List; 43 import java.util.Map; 44 import java.util.Properties; 45 import java.util.Stack; 46 import java.util.StringTokenizer; 47 import java.util.Vector; 48 import javax.xml.XMLConstants; 49 import javax.xml.parsers.ParserConfigurationException; 50 import javax.xml.parsers.SAXParser; 51 import javax.xml.parsers.SAXParserFactory; 52 import org.xml.sax.Attributes; 53 import org.xml.sax.ContentHandler; 54 import org.xml.sax.InputSource; 55 import org.xml.sax.Locator; 56 import org.xml.sax.SAXException; 57 import org.xml.sax.SAXNotRecognizedException; 58 import org.xml.sax.SAXParseException; 59 import org.xml.sax.XMLReader; 60 import org.xml.sax.helpers.AttributesImpl; 61 62 /** 63 * @author Jacek Ambroziak 64 * @author Santiago Pericas-Geertsen 65 * @author G. Todd Miller 66 * @author Morten Jorgensen 67 * @author Erwin Bolwidt <ejb@klomp.org> 68 */ 69 public class Parser implements Constants, ContentHandler { 70 71 private static final String XSL = "xsl"; // standard prefix 72 private static final String TRANSLET = "translet"; // extension prefix 73 74 private Locator _locator = null; 75 76 private XSLTC _xsltc; // Reference to the compiler object. 77 private XPathParser _xpathParser; // Reference to the XPath parser. 78 private Vector _errors; // Contains all compilation errors 79 private Vector _warnings; // Contains all compilation errors 80 81 private Map<String, String> _instructionClasses; // Maps instructions to classes 82 private Map<String, String[]> _instructionAttrs; // reqd and opt attrs 83 private Map<String, QName> _qNames; 84 private Map<String, Map> _namespaces; 85 private QName _useAttributeSets; 86 private QName _excludeResultPrefixes; 87 private QName _extensionElementPrefixes; 88 private Map<String, Object> _variableScope; 89 private Stylesheet _currentStylesheet; 90 private SymbolTable _symbolTable; // Maps QNames to syntax-tree nodes 91 private Output _output; 92 private Template _template; // Reference to the template being parsed. 93 94 private boolean _rootNamespaceDef; // Used for validity check 95 96 private SyntaxTreeNode _root; 97 98 private String _target; 99 100 private int _currentImportPrecedence; 101 102 private boolean _useServicesMechanism = true; 103 104 public Parser(XSLTC xsltc, boolean useServicesMechanism) { 105 _xsltc = xsltc; 106 _useServicesMechanism = useServicesMechanism; 107 } 108 109 public void init() { 110 _qNames = new HashMap<>(512); 111 _namespaces = new HashMap<>(); 112 _instructionClasses = new HashMap<>(); 113 _instructionAttrs = new HashMap<>(); 114 _variableScope = new HashMap<>(); 115 _template = null; 116 _errors = new Vector(); 117 _warnings = new Vector(); 118 _symbolTable = new SymbolTable(); 119 _xpathParser = new XPathParser(this); 120 _currentStylesheet = null; 121 _output = null; 122 _root = null; 123 _rootNamespaceDef = false; 124 _currentImportPrecedence = 1; 125 126 initStdClasses(); 127 initInstructionAttrs(); 128 initExtClasses(); 129 initSymbolTable(); 130 131 _useAttributeSets = 132 getQName(XSLT_URI, XSL, "use-attribute-sets"); 133 _excludeResultPrefixes = 134 getQName(XSLT_URI, XSL, "exclude-result-prefixes"); 135 _extensionElementPrefixes = 136 getQName(XSLT_URI, XSL, "extension-element-prefixes"); 137 } 138 139 public void setOutput(Output output) { 140 if (_output != null) { 141 if (_output.getImportPrecedence() <= output.getImportPrecedence()) { 142 String cdata = _output.getCdata(); 143 output.mergeOutput(_output); 144 _output.disable(); 145 _output = output; 146 } 147 else { 148 output.disable(); 149 } 150 } 151 else { 152 _output = output; 153 } 154 } 155 156 public Output getOutput() { 157 return _output; 158 } 159 160 public Properties getOutputProperties() { 161 return getTopLevelStylesheet().getOutputProperties(); 162 } 163 164 public void addVariable(Variable var) { 165 addVariableOrParam(var); 166 } 167 168 public void addParameter(Param param) { 169 addVariableOrParam(param); 170 } 171 172 private void addVariableOrParam(VariableBase var) { 173 Object existing = _variableScope.get(var.getName().getStringRep()); 174 if (existing != null) { 175 if (existing instanceof Stack) { 176 Stack stack = (Stack)existing; 177 stack.push(var); 178 } 179 else if (existing instanceof VariableBase) { 180 Stack stack = new Stack(); 181 stack.push(existing); 182 stack.push(var); 183 _variableScope.put(var.getName().getStringRep(), stack); 184 } 185 } 186 else { 187 _variableScope.put(var.getName().getStringRep(), var); 188 } 189 } 190 191 public void removeVariable(QName name) { 192 Object existing = _variableScope.get(name.getStringRep()); 193 if (existing instanceof Stack) { 194 Stack stack = (Stack)existing; 195 if (!stack.isEmpty()) stack.pop(); 196 if (!stack.isEmpty()) return; 197 } 198 _variableScope.remove(name.getStringRep()); 199 } 200 201 public VariableBase lookupVariable(QName name) { 202 Object existing = _variableScope.get(name.getStringRep()); 203 if (existing instanceof VariableBase) { 204 return((VariableBase)existing); 205 } 206 else if (existing instanceof Stack) { 207 Stack stack = (Stack)existing; 208 return((VariableBase)stack.peek()); 209 } 210 return(null); 211 } 212 213 public void setXSLTC(XSLTC xsltc) { 214 _xsltc = xsltc; 215 } 216 217 public XSLTC getXSLTC() { 218 return _xsltc; 219 } 220 221 public int getCurrentImportPrecedence() { 222 return _currentImportPrecedence; 223 } 224 225 public int getNextImportPrecedence() { 226 return ++_currentImportPrecedence; 227 } 228 229 public void setCurrentStylesheet(Stylesheet stylesheet) { 230 _currentStylesheet = stylesheet; 231 } 232 233 public Stylesheet getCurrentStylesheet() { 234 return _currentStylesheet; 235 } 236 237 public Stylesheet getTopLevelStylesheet() { 238 return _xsltc.getStylesheet(); 239 } 240 241 public QName getQNameSafe(final String stringRep) { 242 // parse and retrieve namespace 243 final int colon = stringRep.lastIndexOf(':'); 244 if (colon != -1) { 245 final String prefix = stringRep.substring(0, colon); 246 final String localname = stringRep.substring(colon + 1); 247 String namespace = null; 248 249 // Get the namespace uri from the symbol table 250 if (prefix.equals(XMLNS_PREFIX) == false) { 251 namespace = _symbolTable.lookupNamespace(prefix); 252 if (namespace == null) namespace = EMPTYSTRING; 253 } 254 return getQName(namespace, prefix, localname); 255 } 256 else { 257 final String uri = stringRep.equals(XMLNS_PREFIX) ? null 258 : _symbolTable.lookupNamespace(EMPTYSTRING); 259 return getQName(uri, null, stringRep); 260 } 261 } 262 263 public QName getQName(final String stringRep) { 264 return getQName(stringRep, true, false); 265 } 266 267 public QName getQNameIgnoreDefaultNs(final String stringRep) { 268 return getQName(stringRep, true, true); 269 } 270 271 public QName getQName(final String stringRep, boolean reportError) { 272 return getQName(stringRep, reportError, false); 273 } 274 275 private QName getQName(final String stringRep, boolean reportError, 276 boolean ignoreDefaultNs) 277 { 278 // parse and retrieve namespace 279 final int colon = stringRep.lastIndexOf(':'); 280 if (colon != -1) { 281 final String prefix = stringRep.substring(0, colon); 282 final String localname = stringRep.substring(colon + 1); 283 String namespace = null; 284 285 // Get the namespace uri from the symbol table 286 if (prefix.equals(XMLNS_PREFIX) == false) { 287 namespace = _symbolTable.lookupNamespace(prefix); 288 if (namespace == null && reportError) { 289 final int line = getLineNumber(); 290 ErrorMsg err = new ErrorMsg(ErrorMsg.NAMESPACE_UNDEF_ERR, 291 line, prefix); 292 reportError(ERROR, err); 293 } 294 } 295 return getQName(namespace, prefix, localname); 296 } 297 else { 298 if (stringRep.equals(XMLNS_PREFIX)) { 299 ignoreDefaultNs = true; 300 } 301 final String defURI = ignoreDefaultNs ? null 302 : _symbolTable.lookupNamespace(EMPTYSTRING); 303 return getQName(defURI, null, stringRep); 304 } 305 } 306 307 public QName getQName(String namespace, String prefix, String localname) { 308 if (namespace == null || namespace.equals(EMPTYSTRING)) { 309 QName name = _qNames.get(localname); 310 if (name == null) { 311 name = new QName(null, prefix, localname); 312 _qNames.put(localname, name); 313 } 314 return name; 315 } 316 else { 317 Map<String, QName> space = _namespaces.get(namespace); 318 String lexicalQName = 319 (prefix == null || prefix.length() == 0) 320 ? localname 321 : (prefix + ':' + localname); 322 323 if (space == null) { 324 final QName name = new QName(namespace, prefix, localname); 325 _namespaces.put(namespace, space = new HashMap<>()); 326 space.put(lexicalQName, name); 327 return name; 328 } 329 else { 330 QName name = space.get(lexicalQName); 331 if (name == null) { 332 name = new QName(namespace, prefix, localname); 333 space.put(lexicalQName, name); 334 } 335 return name; 336 } 337 } 338 } 339 340 public QName getQName(String scope, String name) { 341 return getQName(scope + name); 342 } 343 344 public QName getQName(QName scope, QName name) { 345 return getQName(scope.toString() + name.toString()); 346 } 347 348 public QName getUseAttributeSets() { 349 return _useAttributeSets; 350 } 351 352 public QName getExtensionElementPrefixes() { 353 return _extensionElementPrefixes; 354 } 355 356 public QName getExcludeResultPrefixes() { 357 return _excludeResultPrefixes; 358 } 359 360 /** 361 * Create an instance of the <code>Stylesheet</code> class, 362 * and then parse, typecheck and compile the instance. 363 * Must be called after <code>parse()</code>. 364 */ 365 public Stylesheet makeStylesheet(SyntaxTreeNode element) 366 throws CompilerException { 367 try { 368 Stylesheet stylesheet; 369 370 if (element instanceof Stylesheet) { 371 stylesheet = (Stylesheet)element; 372 } 373 else { 374 stylesheet = new Stylesheet(); 375 stylesheet.setSimplified(); 376 stylesheet.addElement(element); 377 stylesheet.setAttributes((AttributesImpl) element.getAttributes()); 378 379 // Map the default NS if not already defined 380 if (element.lookupNamespace(EMPTYSTRING) == null) { 381 element.addPrefixMapping(EMPTYSTRING, EMPTYSTRING); 382 } 383 } 384 stylesheet.setParser(this); 385 return stylesheet; 386 } 387 catch (ClassCastException e) { 388 ErrorMsg err = new ErrorMsg(ErrorMsg.NOT_STYLESHEET_ERR, element); 389 throw new CompilerException(err.toString()); 390 } 391 } 392 393 /** 394 * Instanciates a SAX2 parser and generate the AST from the input. 395 */ 396 public void createAST(Stylesheet stylesheet) { 397 try { 398 if (stylesheet != null) { 399 stylesheet.parseContents(this); 400 final int precedence = stylesheet.getImportPrecedence(); 401 final Iterator<SyntaxTreeNode> elements = stylesheet.elements(); 402 while (elements.hasNext()) { 403 Object child = elements.next(); 404 if (child instanceof Text) { 405 final int l = getLineNumber(); 406 ErrorMsg err = 407 new ErrorMsg(ErrorMsg.ILLEGAL_TEXT_NODE_ERR,l,null); 408 reportError(ERROR, err); 409 } 410 } 411 if (!errorsFound()) { 412 stylesheet.typeCheck(_symbolTable); 413 } 414 } 415 } 416 catch (TypeCheckError e) { 417 reportError(ERROR, new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR, e)); 418 } 419 } 420 421 /** 422 * Parses a stylesheet and builds the internal abstract syntax tree 423 * @param reader A SAX2 SAXReader (parser) 424 * @param input A SAX2 InputSource can be passed to a SAX reader 425 * @return The root of the abstract syntax tree 426 */ 427 public SyntaxTreeNode parse(XMLReader reader, InputSource input) { 428 try { 429 // Parse the input document and build the abstract syntax tree 430 reader.setContentHandler(this); 431 reader.parse(input); 432 // Find the start of the stylesheet within the tree 433 return (SyntaxTreeNode)getStylesheet(_root); 434 } 435 catch (IOException e) { 436 if (_xsltc.debug()) e.printStackTrace(); 437 reportError(ERROR,new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR, e)); 438 } 439 catch (SAXException e) { 440 Throwable ex = e.getException(); 441 if (_xsltc.debug()) { 442 e.printStackTrace(); 443 if (ex != null) ex.printStackTrace(); 444 } 445 reportError(ERROR, new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR, e)); 446 } 447 catch (CompilerException e) { 448 if (_xsltc.debug()) e.printStackTrace(); 449 reportError(ERROR, new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR, e)); 450 } 451 catch (Exception e) { 452 if (_xsltc.debug()) e.printStackTrace(); 453 reportError(ERROR, new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR, e)); 454 } 455 return null; 456 } 457 458 /** 459 * Parses a stylesheet and builds the internal abstract syntax tree 460 * @param input A SAX2 InputSource can be passed to a SAX reader 461 * @return The root of the abstract syntax tree 462 */ 463 public SyntaxTreeNode parse(InputSource input) { 464 try { 465 // Create a SAX parser and get the XMLReader object it uses 466 final SAXParserFactory factory = FactoryImpl.getSAXFactory(_useServicesMechanism); 467 468 if (_xsltc.isSecureProcessing()) { 469 try { 470 factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 471 } 472 catch (SAXException e) {} 473 } 474 475 try { 476 factory.setFeature(Constants.NAMESPACE_FEATURE,true); 477 } 478 catch (Exception e) { 479 factory.setNamespaceAware(true); 480 } 481 final SAXParser parser = factory.newSAXParser(); 482 try { 483 parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, 484 _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD)); 485 } catch (SAXNotRecognizedException e) { 486 ErrorMsg err = new ErrorMsg(ErrorMsg.WARNING_MSG, 487 parser.getClass().getName() + ": " + e.getMessage()); 488 reportError(WARNING, err); 489 } 490 491 final XMLReader reader = parser.getXMLReader(); 492 try { 493 XMLSecurityManager securityManager = 494 (XMLSecurityManager)_xsltc.getProperty(XalanConstants.SECURITY_MANAGER); 495 for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) { 496 reader.setProperty(limit.apiProperty(), securityManager.getLimitValueAsString(limit)); 497 } 498 if (securityManager.printEntityCountInfo()) { 499 parser.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES); 500 } 501 } catch (SAXException se) { 502 System.err.println("Warning: " + reader.getClass().getName() + ": " 503 + se.getMessage()); 504 } 505 506 return(parse(reader, input)); 507 } 508 catch (ParserConfigurationException e) { 509 ErrorMsg err = new ErrorMsg(ErrorMsg.SAX_PARSER_CONFIG_ERR); 510 reportError(ERROR, err); 511 } 512 catch (SAXParseException e){ 513 reportError(ERROR, new ErrorMsg(e.getMessage(),e.getLineNumber())); 514 } 515 catch (SAXException e) { 516 reportError(ERROR, new ErrorMsg(e.getMessage())); 517 } 518 return null; 519 } 520 521 public SyntaxTreeNode getDocumentRoot() { 522 return _root; 523 } 524 525 private String _PImedia = null; 526 private String _PItitle = null; 527 private String _PIcharset = null; 528 529 /** 530 * Set the parameters to use to locate the correct <?xml-stylesheet ...?> 531 * processing instruction in the case where the input document is an 532 * XML document with one or more references to a stylesheet. 533 * @param media The media attribute to be matched. May be null, in which 534 * case the prefered templates will be used (i.e. alternate = no). 535 * @param title The value of the title attribute to match. May be null. 536 * @param charset The value of the charset attribute to match. May be null. 537 */ 538 protected void setPIParameters(String media, String title, String charset) { 539 _PImedia = media; 540 _PItitle = title; 541 _PIcharset = charset; 542 } 543 544 /** 545 * Extracts the DOM for the stylesheet. In the case of an embedded 546 * stylesheet, it extracts the DOM subtree corresponding to the 547 * embedded stylesheet that has an 'id' attribute whose value is the 548 * same as the value declared in the <?xml-stylesheet...?> processing 549 * instruction (P.I.). In the xml-stylesheet P.I. the value is labeled 550 * as the 'href' data of the P.I. The extracted DOM representing the 551 * stylesheet is returned as an Element object. 552 */ 553 private SyntaxTreeNode getStylesheet(SyntaxTreeNode root) 554 throws CompilerException { 555 556 // Assume that this is a pure XSL stylesheet if there is not 557 // <?xml-stylesheet ....?> processing instruction 558 if (_target == null) { 559 if (!_rootNamespaceDef) { 560 ErrorMsg msg = new ErrorMsg(ErrorMsg.MISSING_XSLT_URI_ERR); 561 throw new CompilerException(msg.toString()); 562 } 563 return(root); 564 } 565 566 // Find the xsl:stylesheet or xsl:transform with this reference 567 if (_target.charAt(0) == '#') { 568 SyntaxTreeNode element = findStylesheet(root, _target.substring(1)); 569 if (element == null) { 570 ErrorMsg msg = new ErrorMsg(ErrorMsg.MISSING_XSLT_TARGET_ERR, 571 _target, root); 572 throw new CompilerException(msg.toString()); 573 } 574 return(element); 575 } 576 else { 577 try { 578 String path = _target; 579 if (path.indexOf(":")==-1) { 580 path = "file:" + path; 581 } 582 path = SystemIDResolver.getAbsoluteURI(path); 583 String accessError = SecuritySupport.checkAccess(path, 584 (String)_xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET), 585 XalanConstants.ACCESS_EXTERNAL_ALL); 586 if (accessError != null) { 587 ErrorMsg msg = new ErrorMsg(ErrorMsg.ACCESSING_XSLT_TARGET_ERR, 588 SecuritySupport.sanitizePath(_target), accessError, 589 root); 590 throw new CompilerException(msg.toString()); 591 } 592 } catch (IOException ex) { 593 throw new CompilerException(ex); 594 } 595 596 return(loadExternalStylesheet(_target)); 597 } 598 } 599 600 /** 601 * Find a Stylesheet element with a specific ID attribute value. 602 * This method is used to find a Stylesheet node that is referred 603 * in a <?xml-stylesheet ... ?> processing instruction. 604 */ 605 private SyntaxTreeNode findStylesheet(SyntaxTreeNode root, String href) { 606 607 if (root == null) return null; 608 609 if (root instanceof Stylesheet) { 610 String id = root.getAttribute("id"); 611 if (id.equals(href)) return root; 612 } 613 List<SyntaxTreeNode> children = root.getContents(); 614 if (children != null) { 615 final int count = children.size(); 616 for (int i = 0; i < count; i++) { 617 SyntaxTreeNode child = children.get(i); 618 SyntaxTreeNode node = findStylesheet(child, href); 619 if (node != null) return node; 620 } 621 } 622 return null; 623 } 624 625 /** 626 * For embedded stylesheets: Load an external file with stylesheet 627 */ 628 private SyntaxTreeNode loadExternalStylesheet(String location) 629 throws CompilerException { 630 631 InputSource source; 632 633 // Check if the location is URL or a local file 634 if ((new File(location)).exists()) 635 source = new InputSource("file:"+location); 636 else 637 source = new InputSource(location); 638 639 SyntaxTreeNode external = (SyntaxTreeNode)parse(source); 640 return(external); 641 } 642 643 private void initAttrTable(String elementName, String[] attrs) { 644 _instructionAttrs.put(getQName(XSLT_URI, XSL, elementName).getStringRep(), 645 attrs); 646 } 647 648 private void initInstructionAttrs() { 649 initAttrTable("template", 650 new String[] {"match", "name", "priority", "mode"}); 651 initAttrTable("stylesheet", 652 new String[] {"id", "version", "extension-element-prefixes", 653 "exclude-result-prefixes"}); 654 initAttrTable("transform", 655 new String[] {"id", "version", "extension-element-prefixes", 656 "exclude-result-prefixes"}); 657 initAttrTable("text", new String[] {"disable-output-escaping"}); 658 initAttrTable("if", new String[] {"test"}); 659 initAttrTable("choose", new String[] {}); 660 initAttrTable("when", new String[] {"test"}); 661 initAttrTable("otherwise", new String[] {}); 662 initAttrTable("for-each", new String[] {"select"}); 663 initAttrTable("message", new String[] {"terminate"}); 664 initAttrTable("number", 665 new String[] {"level", "count", "from", "value", "format", "lang", 666 "letter-value", "grouping-separator", "grouping-size"}); 667 initAttrTable("comment", new String[] {}); 668 initAttrTable("copy", new String[] {"use-attribute-sets"}); 669 initAttrTable("copy-of", new String[] {"select"}); 670 initAttrTable("param", new String[] {"name", "select"}); 671 initAttrTable("with-param", new String[] {"name", "select"}); 672 initAttrTable("variable", new String[] {"name", "select"}); 673 initAttrTable("output", 674 new String[] {"method", "version", "encoding", 675 "omit-xml-declaration", "standalone", "doctype-public", 676 "doctype-system", "cdata-section-elements", "indent", 677 "media-type"}); 678 initAttrTable("sort", 679 new String[] {"select", "order", "case-order", "lang", "data-type"}); 680 initAttrTable("key", new String[] {"name", "match", "use"}); 681 initAttrTable("fallback", new String[] {}); 682 initAttrTable("attribute", new String[] {"name", "namespace"}); 683 initAttrTable("attribute-set", 684 new String[] {"name", "use-attribute-sets"}); 685 initAttrTable("value-of", 686 new String[] {"select", "disable-output-escaping"}); 687 initAttrTable("element", 688 new String[] {"name", "namespace", "use-attribute-sets"}); 689 initAttrTable("call-template", new String[] {"name"}); 690 initAttrTable("apply-templates", new String[] {"select", "mode"}); 691 initAttrTable("apply-imports", new String[] {}); 692 initAttrTable("decimal-format", 693 new String[] {"name", "decimal-separator", "grouping-separator", 694 "infinity", "minus-sign", "NaN", "percent", "per-mille", 695 "zero-digit", "digit", "pattern-separator"}); 696 initAttrTable("import", new String[] {"href"}); 697 initAttrTable("include", new String[] {"href"}); 698 initAttrTable("strip-space", new String[] {"elements"}); 699 initAttrTable("preserve-space", new String[] {"elements"}); 700 initAttrTable("processing-instruction", new String[] {"name"}); 701 initAttrTable("namespace-alias", 702 new String[] {"stylesheet-prefix", "result-prefix"}); 703 } 704 705 706 707 /** 708 * Initialize the _instructionClasses map, which maps XSL element 709 * names to Java classes in this package. 710 */ 711 private void initStdClasses() { 712 initStdClass("template", "Template"); 713 initStdClass("stylesheet", "Stylesheet"); 714 initStdClass("transform", "Stylesheet"); 715 initStdClass("text", "Text"); 716 initStdClass("if", "If"); 717 initStdClass("choose", "Choose"); 718 initStdClass("when", "When"); 719 initStdClass("otherwise", "Otherwise"); 720 initStdClass("for-each", "ForEach"); 721 initStdClass("message", "Message"); 722 initStdClass("number", "Number"); 723 initStdClass("comment", "Comment"); 724 initStdClass("copy", "Copy"); 725 initStdClass("copy-of", "CopyOf"); 726 initStdClass("param", "Param"); 727 initStdClass("with-param", "WithParam"); 728 initStdClass("variable", "Variable"); 729 initStdClass("output", "Output"); 730 initStdClass("sort", "Sort"); 731 initStdClass("key", "Key"); 732 initStdClass("fallback", "Fallback"); 733 initStdClass("attribute", "XslAttribute"); 734 initStdClass("attribute-set", "AttributeSet"); 735 initStdClass("value-of", "ValueOf"); 736 initStdClass("element", "XslElement"); 737 initStdClass("call-template", "CallTemplate"); 738 initStdClass("apply-templates", "ApplyTemplates"); 739 initStdClass("apply-imports", "ApplyImports"); 740 initStdClass("decimal-format", "DecimalFormatting"); 741 initStdClass("import", "Import"); 742 initStdClass("include", "Include"); 743 initStdClass("strip-space", "Whitespace"); 744 initStdClass("preserve-space", "Whitespace"); 745 initStdClass("processing-instruction", "ProcessingInstruction"); 746 initStdClass("namespace-alias", "NamespaceAlias"); 747 } 748 749 private void initStdClass(String elementName, String className) { 750 _instructionClasses.put(getQName(XSLT_URI, XSL, elementName).getStringRep(), 751 COMPILER_PACKAGE + '.' + className); 752 } 753 754 public boolean elementSupported(String namespace, String localName) { 755 return(_instructionClasses.get(getQName(namespace, XSL, localName).getStringRep()) != null); 756 } 757 758 public boolean functionSupported(String fname) { 759 return(_symbolTable.lookupPrimop(fname) != null); 760 } 761 762 private void initExtClasses() { 763 initExtClass("output", "TransletOutput"); 764 initExtClass(REDIRECT_URI, "write", "TransletOutput"); 765 } 766 767 private void initExtClass(String elementName, String className) { 768 _instructionClasses.put(getQName(TRANSLET_URI, TRANSLET, elementName).getStringRep(), 769 COMPILER_PACKAGE + '.' + className); 770 } 771 772 private void initExtClass(String namespace, String elementName, String className) { 773 _instructionClasses.put(getQName(namespace, TRANSLET, elementName).getStringRep(), 774 COMPILER_PACKAGE + '.' + className); 775 } 776 777 /** 778 * Add primops and base functions to the symbol table. 779 */ 780 private void initSymbolTable() { 781 MethodType I_V = new MethodType(Type.Int, Type.Void); 782 MethodType I_R = new MethodType(Type.Int, Type.Real); 783 MethodType I_S = new MethodType(Type.Int, Type.String); 784 MethodType I_D = new MethodType(Type.Int, Type.NodeSet); 785 MethodType R_I = new MethodType(Type.Real, Type.Int); 786 MethodType R_V = new MethodType(Type.Real, Type.Void); 787 MethodType R_R = new MethodType(Type.Real, Type.Real); 788 MethodType R_D = new MethodType(Type.Real, Type.NodeSet); 789 MethodType R_O = new MethodType(Type.Real, Type.Reference); 790 MethodType I_I = new MethodType(Type.Int, Type.Int); 791 MethodType D_O = new MethodType(Type.NodeSet, Type.Reference); 792 MethodType D_V = new MethodType(Type.NodeSet, Type.Void); 793 MethodType D_S = new MethodType(Type.NodeSet, Type.String); 794 MethodType D_D = new MethodType(Type.NodeSet, Type.NodeSet); 795 MethodType A_V = new MethodType(Type.Node, Type.Void); 796 MethodType S_V = new MethodType(Type.String, Type.Void); 797 MethodType S_S = new MethodType(Type.String, Type.String); 798 MethodType S_A = new MethodType(Type.String, Type.Node); 799 MethodType S_D = new MethodType(Type.String, Type.NodeSet); 800 MethodType S_O = new MethodType(Type.String, Type.Reference); 801 MethodType B_O = new MethodType(Type.Boolean, Type.Reference); 802 MethodType B_V = new MethodType(Type.Boolean, Type.Void); 803 MethodType B_B = new MethodType(Type.Boolean, Type.Boolean); 804 MethodType B_S = new MethodType(Type.Boolean, Type.String); 805 MethodType D_X = new MethodType(Type.NodeSet, Type.Object); 806 MethodType R_RR = new MethodType(Type.Real, Type.Real, Type.Real); 807 MethodType I_II = new MethodType(Type.Int, Type.Int, Type.Int); 808 MethodType B_RR = new MethodType(Type.Boolean, Type.Real, Type.Real); 809 MethodType B_II = new MethodType(Type.Boolean, Type.Int, Type.Int); 810 MethodType S_SS = new MethodType(Type.String, Type.String, Type.String); 811 MethodType S_DS = new MethodType(Type.String, Type.Real, Type.String); 812 MethodType S_SR = new MethodType(Type.String, Type.String, Type.Real); 813 MethodType O_SO = new MethodType(Type.Reference, Type.String, Type.Reference); 814 815 MethodType D_SS = 816 new MethodType(Type.NodeSet, Type.String, Type.String); 817 MethodType D_SD = 818 new MethodType(Type.NodeSet, Type.String, Type.NodeSet); 819 MethodType B_BB = 820 new MethodType(Type.Boolean, Type.Boolean, Type.Boolean); 821 MethodType B_SS = 822 new MethodType(Type.Boolean, Type.String, Type.String); 823 MethodType S_SD = 824 new MethodType(Type.String, Type.String, Type.NodeSet); 825 MethodType S_DSS = 826 new MethodType(Type.String, Type.Real, Type.String, Type.String); 827 MethodType S_SRR = 828 new MethodType(Type.String, Type.String, Type.Real, Type.Real); 829 MethodType S_SSS = 830 new MethodType(Type.String, Type.String, Type.String, Type.String); 831 832 /* 833 * Standard functions: implemented but not in this table concat(). 834 * When adding a new function make sure to uncomment 835 * the corresponding line in <tt>FunctionAvailableCall</tt>. 836 */ 837 838 // The following functions are inlined 839 840 _symbolTable.addPrimop("current", A_V); 841 _symbolTable.addPrimop("last", I_V); 842 _symbolTable.addPrimop("position", I_V); 843 _symbolTable.addPrimop("true", B_V); 844 _symbolTable.addPrimop("false", B_V); 845 _symbolTable.addPrimop("not", B_B); 846 _symbolTable.addPrimop("name", S_V); 847 _symbolTable.addPrimop("name", S_A); 848 _symbolTable.addPrimop("generate-id", S_V); 849 _symbolTable.addPrimop("generate-id", S_A); 850 _symbolTable.addPrimop("ceiling", R_R); 851 _symbolTable.addPrimop("floor", R_R); 852 _symbolTable.addPrimop("round", R_R); 853 _symbolTable.addPrimop("contains", B_SS); 854 _symbolTable.addPrimop("number", R_O); 855 _symbolTable.addPrimop("number", R_V); 856 _symbolTable.addPrimop("boolean", B_O); 857 _symbolTable.addPrimop("string", S_O); 858 _symbolTable.addPrimop("string", S_V); 859 _symbolTable.addPrimop("translate", S_SSS); 860 _symbolTable.addPrimop("string-length", I_V); 861 _symbolTable.addPrimop("string-length", I_S); 862 _symbolTable.addPrimop("starts-with", B_SS); 863 _symbolTable.addPrimop("format-number", S_DS); 864 _symbolTable.addPrimop("format-number", S_DSS); 865 _symbolTable.addPrimop("unparsed-entity-uri", S_S); 866 _symbolTable.addPrimop("key", D_SS); 867 _symbolTable.addPrimop("key", D_SD); 868 _symbolTable.addPrimop("id", D_S); 869 _symbolTable.addPrimop("id", D_D); 870 _symbolTable.addPrimop("namespace-uri", S_V); 871 _symbolTable.addPrimop("function-available", B_S); 872 _symbolTable.addPrimop("element-available", B_S); 873 _symbolTable.addPrimop("document", D_S); 874 _symbolTable.addPrimop("document", D_V); 875 876 // The following functions are implemented in the basis library 877 _symbolTable.addPrimop("count", I_D); 878 _symbolTable.addPrimop("sum", R_D); 879 _symbolTable.addPrimop("local-name", S_V); 880 _symbolTable.addPrimop("local-name", S_D); 881 _symbolTable.addPrimop("namespace-uri", S_V); 882 _symbolTable.addPrimop("namespace-uri", S_D); 883 _symbolTable.addPrimop("substring", S_SR); 884 _symbolTable.addPrimop("substring", S_SRR); 885 _symbolTable.addPrimop("substring-after", S_SS); 886 _symbolTable.addPrimop("substring-before", S_SS); 887 _symbolTable.addPrimop("normalize-space", S_V); 888 _symbolTable.addPrimop("normalize-space", S_S); 889 _symbolTable.addPrimop("system-property", S_S); 890 891 // Extensions 892 _symbolTable.addPrimop("nodeset", D_O); 893 _symbolTable.addPrimop("objectType", S_O); 894 _symbolTable.addPrimop("cast", O_SO); 895 896 // Operators +, -, *, /, % defined on real types. 897 _symbolTable.addPrimop("+", R_RR); 898 _symbolTable.addPrimop("-", R_RR); 899 _symbolTable.addPrimop("*", R_RR); 900 _symbolTable.addPrimop("/", R_RR); 901 _symbolTable.addPrimop("%", R_RR); 902 903 // Operators +, -, * defined on integer types. 904 // Operators / and % are not defined on integers (may cause exception) 905 _symbolTable.addPrimop("+", I_II); 906 _symbolTable.addPrimop("-", I_II); 907 _symbolTable.addPrimop("*", I_II); 908 909 // Operators <, <= >, >= defined on real types. 910 _symbolTable.addPrimop("<", B_RR); 911 _symbolTable.addPrimop("<=", B_RR); 912 _symbolTable.addPrimop(">", B_RR); 913 _symbolTable.addPrimop(">=", B_RR); 914 915 // Operators <, <= >, >= defined on int types. 916 _symbolTable.addPrimop("<", B_II); 917 _symbolTable.addPrimop("<=", B_II); 918 _symbolTable.addPrimop(">", B_II); 919 _symbolTable.addPrimop(">=", B_II); 920 921 // Operators <, <= >, >= defined on boolean types. 922 _symbolTable.addPrimop("<", B_BB); 923 _symbolTable.addPrimop("<=", B_BB); 924 _symbolTable.addPrimop(">", B_BB); 925 _symbolTable.addPrimop(">=", B_BB); 926 927 // Operators 'and' and 'or'. 928 _symbolTable.addPrimop("or", B_BB); 929 _symbolTable.addPrimop("and", B_BB); 930 931 // Unary minus. 932 _symbolTable.addPrimop("u-", R_R); 933 _symbolTable.addPrimop("u-", I_I); 934 } 935 936 public SymbolTable getSymbolTable() { 937 return _symbolTable; 938 } 939 940 public Template getTemplate() { 941 return _template; 942 } 943 944 public void setTemplate(Template template) { 945 _template = template; 946 } 947 948 private int _templateIndex = 0; 949 950 public int getTemplateIndex() { 951 return(_templateIndex++); 952 } 953 954 /** 955 * Creates a new node in the abstract syntax tree. This node can be 956 * o) a supported XSLT 1.0 element 957 * o) an unsupported XSLT element (post 1.0) 958 * o) a supported XSLT extension 959 * o) an unsupported XSLT extension 960 * o) a literal result element (not an XSLT element and not an extension) 961 * Unsupported elements do not directly generate an error. We have to wait 962 * until we have received all child elements of an unsupported element to 963 * see if any <xsl:fallback> elements exist. 964 */ 965 966 private boolean versionIsOne = true; 967 968 public SyntaxTreeNode makeInstance(String uri, String prefix, 969 String local, Attributes attributes) 970 { 971 SyntaxTreeNode node = null; 972 QName qname = getQName(uri, prefix, local); 973 String className = _instructionClasses.get(qname.getStringRep()); 974 975 if (className != null) { 976 try { 977 final Class clazz = ObjectFactory.findProviderClass(className, true); 978 node = (SyntaxTreeNode)clazz.newInstance(); 979 node.setQName(qname); 980 node.setParser(this); 981 if (_locator != null) { 982 node.setLineNumber(getLineNumber()); 983 } 984 if (node instanceof Stylesheet) { 985 _xsltc.setStylesheet((Stylesheet)node); 986 } 987 checkForSuperfluousAttributes(node, attributes); 988 } 989 catch (ClassNotFoundException e) { 990 ErrorMsg err = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, node); 991 reportError(ERROR, err); 992 } 993 catch (Exception e) { 994 ErrorMsg err = new ErrorMsg(ErrorMsg.INTERNAL_ERR, 995 e.getMessage(), node); 996 reportError(FATAL, err); 997 } 998 } 999 else { 1000 if (uri != null) { 1001 // Check if the element belongs in our namespace 1002 if (uri.equals(XSLT_URI)) { 1003 node = new UnsupportedElement(uri, prefix, local, false); 1004 UnsupportedElement element = (UnsupportedElement)node; 1005 ErrorMsg msg = new ErrorMsg(ErrorMsg.UNSUPPORTED_XSL_ERR, 1006 getLineNumber(),local); 1007 element.setErrorMessage(msg); 1008 if (versionIsOne) { 1009 reportError(UNSUPPORTED,msg); 1010 } 1011 } 1012 // Check if this is an XSLTC extension element 1013 else if (uri.equals(TRANSLET_URI)) { 1014 node = new UnsupportedElement(uri, prefix, local, true); 1015 UnsupportedElement element = (UnsupportedElement)node; 1016 ErrorMsg msg = new ErrorMsg(ErrorMsg.UNSUPPORTED_EXT_ERR, 1017 getLineNumber(),local); 1018 element.setErrorMessage(msg); 1019 } 1020 // Check if this is an extension of some other XSLT processor 1021 else { 1022 Stylesheet sheet = _xsltc.getStylesheet(); 1023 if ((sheet != null) && (sheet.isExtension(uri))) { 1024 if (sheet != (SyntaxTreeNode)_parentStack.peek()) { 1025 node = new UnsupportedElement(uri, prefix, local, true); 1026 UnsupportedElement elem = (UnsupportedElement)node; 1027 ErrorMsg msg = 1028 new ErrorMsg(ErrorMsg.UNSUPPORTED_EXT_ERR, 1029 getLineNumber(), 1030 prefix+":"+local); 1031 elem.setErrorMessage(msg); 1032 } 1033 } 1034 } 1035 } 1036 if (node == null) { 1037 node = new LiteralElement(); 1038 node.setLineNumber(getLineNumber()); 1039 } 1040 } 1041 if ((node != null) && (node instanceof LiteralElement)) { 1042 ((LiteralElement)node).setQName(qname); 1043 } 1044 return(node); 1045 } 1046 1047 /** 1048 * checks the list of attributes against a list of allowed attributes 1049 * for a particular element node. 1050 */ 1051 private void checkForSuperfluousAttributes(SyntaxTreeNode node, 1052 Attributes attrs) 1053 { 1054 QName qname = node.getQName(); 1055 boolean isStylesheet = (node instanceof Stylesheet); 1056 String[] legal = _instructionAttrs.get(qname.getStringRep()); 1057 if (versionIsOne && legal != null) { 1058 int j; 1059 final int n = attrs.getLength(); 1060 1061 for (int i = 0; i < n; i++) { 1062 final String attrQName = attrs.getQName(i); 1063 1064 if (isStylesheet && attrQName.equals("version")) { 1065 versionIsOne = attrs.getValue(i).equals("1.0"); 1066 } 1067 1068 // Ignore if special or if it has a prefix 1069 if (attrQName.startsWith("xml") || 1070 attrQName.indexOf(':') > 0) continue; 1071 1072 for (j = 0; j < legal.length; j++) { 1073 if (attrQName.equalsIgnoreCase(legal[j])) { 1074 break; 1075 } 1076 } 1077 if (j == legal.length) { 1078 final ErrorMsg err = 1079 new ErrorMsg(ErrorMsg.ILLEGAL_ATTRIBUTE_ERR, 1080 attrQName, node); 1081 // Workaround for the TCK failure ErrorListener.errorTests.error001.. 1082 err.setWarningError(true); 1083 reportError(WARNING, err); 1084 } 1085 } 1086 } 1087 } 1088 1089 1090 /** 1091 * Parse an XPath expression: 1092 * @param parent - XSL element where the expression occured 1093 * @param exp - textual representation of the expression 1094 */ 1095 public Expression parseExpression(SyntaxTreeNode parent, String exp) { 1096 return (Expression)parseTopLevel(parent, "<EXPRESSION>"+exp, null); 1097 } 1098 1099 /** 1100 * Parse an XPath expression: 1101 * @param parent - XSL element where the expression occured 1102 * @param attr - name of this element's attribute to get expression from 1103 * @param def - default expression (if the attribute was not found) 1104 */ 1105 public Expression parseExpression(SyntaxTreeNode parent, 1106 String attr, String def) { 1107 // Get the textual representation of the expression (if any) 1108 String exp = parent.getAttribute(attr); 1109 // Use the default expression if none was found 1110 if ((exp.length() == 0) && (def != null)) exp = def; 1111 // Invoke the XPath parser 1112 return (Expression)parseTopLevel(parent, "<EXPRESSION>"+exp, exp); 1113 } 1114 1115 /** 1116 * Parse an XPath pattern: 1117 * @param parent - XSL element where the pattern occured 1118 * @param pattern - textual representation of the pattern 1119 */ 1120 public Pattern parsePattern(SyntaxTreeNode parent, String pattern) { 1121 return (Pattern)parseTopLevel(parent, "<PATTERN>"+pattern, pattern); 1122 } 1123 1124 /** 1125 * Parse an XPath pattern: 1126 * @param parent - XSL element where the pattern occured 1127 * @param attr - name of this element's attribute to get pattern from 1128 * @param def - default pattern (if the attribute was not found) 1129 */ 1130 public Pattern parsePattern(SyntaxTreeNode parent, 1131 String attr, String def) { 1132 // Get the textual representation of the pattern (if any) 1133 String pattern = parent.getAttribute(attr); 1134 // Use the default pattern if none was found 1135 if ((pattern.length() == 0) && (def != null)) pattern = def; 1136 // Invoke the XPath parser 1137 return (Pattern)parseTopLevel(parent, "<PATTERN>"+pattern, pattern); 1138 } 1139 1140 /** 1141 * Parse an XPath expression or pattern using the generated XPathParser 1142 * The method will return a Dummy node if the XPath parser fails. 1143 */ 1144 private SyntaxTreeNode parseTopLevel(SyntaxTreeNode parent, String text, 1145 String expression) { 1146 int line = getLineNumber(); 1147 1148 try { 1149 _xpathParser.setScanner(new XPathLexer(new StringReader(text))); 1150 Symbol result = _xpathParser.parse(expression, line); 1151 if (result != null) { 1152 final SyntaxTreeNode node = (SyntaxTreeNode)result.value; 1153 if (node != null) { 1154 node.setParser(this); 1155 node.setParent(parent); 1156 node.setLineNumber(line); 1157 // System.out.println("e = " + text + " " + node); 1158 return node; 1159 } 1160 } 1161 reportError(ERROR, new ErrorMsg(ErrorMsg.XPATH_PARSER_ERR, 1162 expression, parent)); 1163 } 1164 catch (Exception e) { 1165 if (_xsltc.debug()) e.printStackTrace(); 1166 reportError(ERROR, new ErrorMsg(ErrorMsg.XPATH_PARSER_ERR, 1167 expression, parent)); 1168 } 1169 1170 // Return a dummy pattern (which is an expression) 1171 SyntaxTreeNode.Dummy.setParser(this); 1172 return SyntaxTreeNode.Dummy; 1173 } 1174 1175 /************************ ERROR HANDLING SECTION ************************/ 1176 1177 /** 1178 * Returns true if there were any errors during compilation 1179 */ 1180 public boolean errorsFound() { 1181 return _errors.size() > 0; 1182 } 1183 1184 /** 1185 * Prints all compile-time errors 1186 */ 1187 public void printErrors() { 1188 final int size = _errors.size(); 1189 if (size > 0) { 1190 System.err.println(new ErrorMsg(ErrorMsg.COMPILER_ERROR_KEY)); 1191 for (int i = 0; i < size; i++) { 1192 System.err.println(" " + _errors.elementAt(i)); 1193 } 1194 } 1195 } 1196 1197 /** 1198 * Prints all compile-time warnings 1199 */ 1200 public void printWarnings() { 1201 final int size = _warnings.size(); 1202 if (size > 0) { 1203 System.err.println(new ErrorMsg(ErrorMsg.COMPILER_WARNING_KEY)); 1204 for (int i = 0; i < size; i++) { 1205 System.err.println(" " + _warnings.elementAt(i)); 1206 } 1207 } 1208 } 1209 1210 /** 1211 * Common error/warning message handler 1212 */ 1213 public void reportError(final int category, final ErrorMsg error) { 1214 switch (category) { 1215 case Constants.INTERNAL: 1216 // Unexpected internal errors, such as null-ptr exceptions, etc. 1217 // Immediately terminates compilation, no translet produced 1218 _errors.addElement(error); 1219 break; 1220 case Constants.UNSUPPORTED: 1221 // XSLT elements that are not implemented and unsupported ext. 1222 // Immediately terminates compilation, no translet produced 1223 _errors.addElement(error); 1224 break; 1225 case Constants.FATAL: 1226 // Fatal error in the stylesheet input (parsing or content) 1227 // Immediately terminates compilation, no translet produced 1228 _errors.addElement(error); 1229 break; 1230 case Constants.ERROR: 1231 // Other error in the stylesheet input (parsing or content) 1232 // Does not terminate compilation, no translet produced 1233 _errors.addElement(error); 1234 break; 1235 case Constants.WARNING: 1236 // Other error in the stylesheet input (content errors only) 1237 // Does not terminate compilation, a translet is produced 1238 _warnings.addElement(error); 1239 break; 1240 } 1241 } 1242 1243 public Vector getErrors() { 1244 return _errors; 1245 } 1246 1247 public Vector getWarnings() { 1248 return _warnings; 1249 } 1250 1251 /************************ SAX2 ContentHandler INTERFACE *****************/ 1252 1253 private Stack _parentStack = null; 1254 private Map<String, String> _prefixMapping = null; 1255 1256 /** 1257 * SAX2: Receive notification of the beginning of a document. 1258 */ 1259 public void startDocument() { 1260 _root = null; 1261 _target = null; 1262 _prefixMapping = null; 1263 _parentStack = new Stack(); 1264 } 1265 1266 /** 1267 * SAX2: Receive notification of the end of a document. 1268 */ 1269 public void endDocument() { } 1270 1271 1272 /** 1273 * SAX2: Begin the scope of a prefix-URI Namespace mapping. 1274 * This has to be passed on to the symbol table! 1275 */ 1276 public void startPrefixMapping(String prefix, String uri) { 1277 if (_prefixMapping == null) { 1278 _prefixMapping = new HashMap<>(); 1279 } 1280 _prefixMapping.put(prefix, uri); 1281 } 1282 1283 /** 1284 * SAX2: End the scope of a prefix-URI Namespace mapping. 1285 * This has to be passed on to the symbol table! 1286 */ 1287 public void endPrefixMapping(String prefix) { } 1288 1289 /** 1290 * SAX2: Receive notification of the beginning of an element. 1291 * The parser may re-use the attribute list that we're passed so 1292 * we clone the attributes in our own Attributes implementation 1293 */ 1294 public void startElement(String uri, String localname, 1295 String qname, Attributes attributes) 1296 throws SAXException { 1297 final int col = qname.lastIndexOf(':'); 1298 final String prefix = (col == -1) ? null : qname.substring(0, col); 1299 1300 SyntaxTreeNode element = makeInstance(uri, prefix, 1301 localname, attributes); 1302 if (element == null) { 1303 ErrorMsg err = new ErrorMsg(ErrorMsg.ELEMENT_PARSE_ERR, 1304 prefix+':'+localname); 1305 throw new SAXException(err.toString()); 1306 } 1307 1308 // If this is the root element of the XML document we need to make sure 1309 // that it contains a definition of the XSL namespace URI 1310 if (_root == null) { 1311 if ((_prefixMapping == null) || 1312 (_prefixMapping.containsValue(Constants.XSLT_URI) == false)) 1313 _rootNamespaceDef = false; 1314 else 1315 _rootNamespaceDef = true; 1316 _root = element; 1317 } 1318 else { 1319 SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek(); 1320 parent.addElement(element); 1321 element.setParent(parent); 1322 } 1323 element.setAttributes(new AttributesImpl(attributes)); 1324 element.setPrefixMapping(_prefixMapping); 1325 1326 if (element instanceof Stylesheet) { 1327 // Extension elements and excluded elements have to be 1328 // handled at this point in order to correctly generate 1329 // Fallback elements from <xsl:fallback>s. 1330 getSymbolTable().setCurrentNode(element); 1331 ((Stylesheet)element).declareExtensionPrefixes(this); 1332 } 1333 1334 _prefixMapping = null; 1335 _parentStack.push(element); 1336 } 1337 1338 /** 1339 * SAX2: Receive notification of the end of an element. 1340 */ 1341 public void endElement(String uri, String localname, String qname) { 1342 _parentStack.pop(); 1343 } 1344 1345 /** 1346 * SAX2: Receive notification of character data. 1347 */ 1348 public void characters(char[] ch, int start, int length) { 1349 String string = new String(ch, start, length); 1350 SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek(); 1351 1352 if (string.length() == 0) return; 1353 1354 // If this text occurs within an <xsl:text> element we append it 1355 // as-is to the existing text element 1356 if (parent instanceof Text) { 1357 ((Text)parent).setText(string); 1358 return; 1359 } 1360 1361 // Ignore text nodes that occur directly under <xsl:stylesheet> 1362 if (parent instanceof Stylesheet) return; 1363 1364 SyntaxTreeNode bro = parent.lastChild(); 1365 if ((bro != null) && (bro instanceof Text)) { 1366 Text text = (Text)bro; 1367 if (!text.isTextElement()) { 1368 if ((length > 1) || ( ((int)ch[0]) < 0x100)) { 1369 text.setText(string); 1370 return; 1371 } 1372 } 1373 } 1374 1375 // Add it as a regular text node otherwise 1376 parent.addElement(new Text(string)); 1377 } 1378 1379 private String getTokenValue(String token) { 1380 final int start = token.indexOf('"'); 1381 final int stop = token.lastIndexOf('"'); 1382 return token.substring(start+1, stop); 1383 } 1384 1385 /** 1386 * SAX2: Receive notification of a processing instruction. 1387 * These require special handling for stylesheet PIs. 1388 */ 1389 public void processingInstruction(String name, String value) { 1390 // We only handle the <?xml-stylesheet ...?> PI 1391 if ((_target == null) && (name.equals("xml-stylesheet"))) { 1392 1393 String href = null; // URI of stylesheet found 1394 String media = null; // Media of stylesheet found 1395 String title = null; // Title of stylesheet found 1396 String charset = null; // Charset of stylesheet found 1397 1398 // Get the attributes from the processing instruction 1399 StringTokenizer tokens = new StringTokenizer(value); 1400 while (tokens.hasMoreElements()) { 1401 String token = (String)tokens.nextElement(); 1402 if (token.startsWith("href")) 1403 href = getTokenValue(token); 1404 else if (token.startsWith("media")) 1405 media = getTokenValue(token); 1406 else if (token.startsWith("title")) 1407 title = getTokenValue(token); 1408 else if (token.startsWith("charset")) 1409 charset = getTokenValue(token); 1410 } 1411 1412 // Set the target to this PI's href if the parameters are 1413 // null or match the corresponding attributes of this PI. 1414 if ( ((_PImedia == null) || (_PImedia.equals(media))) && 1415 ((_PItitle == null) || (_PImedia.equals(title))) && 1416 ((_PIcharset == null) || (_PImedia.equals(charset))) ) { 1417 _target = href; 1418 } 1419 } 1420 } 1421 1422 /** 1423 * IGNORED - all ignorable whitespace is ignored 1424 */ 1425 public void ignorableWhitespace(char[] ch, int start, int length) { } 1426 1427 /** 1428 * IGNORED - we do not have to do anything with skipped entities 1429 */ 1430 public void skippedEntity(String name) { } 1431 1432 /** 1433 * Store the document locator to later retrieve line numbers of all 1434 * elements from the stylesheet 1435 */ 1436 public void setDocumentLocator(Locator locator) { 1437 _locator = locator; 1438 } 1439 1440 /** 1441 * Get the line number, or zero 1442 * if there is no _locator. 1443 */ 1444 private int getLineNumber() { 1445 int line = 0; 1446 if (_locator != null) 1447 line = _locator.getLineNumber(); 1448 return line; 1449 } 1450 1451 }