Back to index

lightning-sunbird  0.9+nobinonly
txStandaloneStylesheetCompiler.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is TransforMiiX XSLT processor code.
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Axel Hecht.
00019  * Portions created by the Initial Developer are Copyright (C) 2003
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *   Axel Hecht <axel@pike.org>
00024  *
00025  * Alternatively, the contents of this file may be used under the terms of
00026  * either the GNU General Public License Version 2 or later (the "GPL"), or
00027  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00028  * in which case the provisions of the GPL or the LGPL are applicable instead
00029  * of those above. If you wish to allow use of your version of this file only
00030  * under the terms of either the GPL or the LGPL, and not to allow others to
00031  * use your version of this file under the terms of the MPL, indicate your
00032  * decision by deleting the provisions above and replace them with the notice
00033  * and other provisions required by the GPL or the LGPL. If you do not delete
00034  * the provisions above, a recipient may use your version of this file under
00035  * the terms of any one of the MPL, the GPL or the LGPL.
00036  *
00037  * ***** END LICENSE BLOCK ***** */
00038 
00039 #include "txStandaloneStylesheetCompiler.h"
00040 #include "TxLog.h"
00041 #include "txStylesheetCompiler.h"
00042 #include "txURIUtils.h"
00043 #include "expat_config.h"
00044 #include "expat.h"
00045 
00050 class txDriver : public txACompileObserver
00051 {
00052   public:
00053     nsresult parse(istream& aInputStream, const nsAString& aUri);
00054     const nsAString& getErrorString();
00055 
00059     void StartElement(const XML_Char *aName, const XML_Char **aAtts);
00060     void EndElement(const XML_Char* aName);
00061     void CharacterData(const XML_Char* aChars, int aLength);
00062     int ExternalEntityRef(const XML_Char *aContext, const XML_Char *aBase,
00063                           const XML_Char *aSystemId,
00064                           const XML_Char *aPublicId);
00065 
00066     TX_DECL_ACOMPILEOBSERVER;
00067 
00068     nsRefPtr<txStylesheetCompiler> mCompiler;
00069   protected:
00070     void createErrorString();
00071     nsString  mErrorString;
00072     // keep track of the nsresult returned by the handlers, expat forgets them
00073     nsresult mRV;
00074     XML_Parser mExpatParser;
00075     nsAutoRefCnt mRefCnt;
00076 };
00077 
00078 nsresult
00079 TX_CompileStylesheetPath(const txParsedURL& aURL, txStylesheet** aResult)
00080 {
00081     *aResult = nsnull;
00082     nsAutoString errMsg, filePath;
00083 
00084     aURL.getFile(filePath);
00085     PR_LOG(txLog::xslt, PR_LOG_ALWAYS,
00086            ("TX_CompileStylesheetPath: %s\n",
00087             NS_LossyConvertUCS2toASCII(filePath).get()));
00088     istream* xslInput = URIUtils::getInputStream(filePath, errMsg);
00089     if (!xslInput) {
00090         return NS_ERROR_FAILURE;
00091     }
00092     nsRefPtr<txDriver> driver = new txDriver();
00093     if (!driver) {
00094         return NS_ERROR_OUT_OF_MEMORY;
00095     }
00096     nsAutoString spec = filePath;
00097     if (!aURL.mRef.IsEmpty()) {
00098         spec.Append(PRUnichar('#'));
00099         spec.Append(aURL.mRef);
00100     }
00101     driver->mCompiler =  new txStylesheetCompiler(spec, driver);
00102     if (!driver->mCompiler) {
00103         return NS_ERROR_OUT_OF_MEMORY;
00104     }
00105     nsresult rv = driver->parse(*xslInput, filePath);
00106     if (NS_FAILED(rv)) {
00107         return rv;
00108     };
00109     *aResult = driver->mCompiler->getStylesheet();
00110     NS_ADDREF(*aResult);
00111     return NS_OK;
00112 }
00113 
00118 // shortcut macro for redirection into txDriver method calls
00119 #define TX_DRIVER(_userData) NS_STATIC_CAST(txDriver*, _userData)
00120 
00121 PR_STATIC_CALLBACK(void)
00122 startElement(void *aUserData, const XML_Char *aName, const XML_Char **aAtts)
00123 {
00124     if (!aUserData) {
00125         NS_WARNING("no userData in startElement handler");
00126         return;
00127     }
00128     TX_DRIVER(aUserData)->StartElement(aName, aAtts);
00129 }
00130 
00131 PR_STATIC_CALLBACK(void)
00132 endElement(void *aUserData, const XML_Char* aName)
00133 {
00134     if (!aUserData) {
00135         NS_WARNING("no userData in endElement handler");
00136         return;
00137     }
00138     TX_DRIVER(aUserData)->EndElement(aName);
00139 }
00140 
00141 PR_STATIC_CALLBACK(void)
00142 charData(void* aUserData, const XML_Char* aChars, int aLength)
00143 {
00144     if (!aUserData) {
00145         NS_WARNING("no userData in charData handler");
00146         return;
00147     }
00148     TX_DRIVER(aUserData)->CharacterData(aChars, aLength);
00149 }
00150 
00151 PR_STATIC_CALLBACK(int)
00152 externalEntityRefHandler(XML_Parser aParser,
00153                          const XML_Char *aContext,
00154                          const XML_Char *aBase,
00155                          const XML_Char *aSystemId,
00156                          const XML_Char *aPublicId)
00157 {
00158     // aParser is aUserData is the txDriver,
00159     // we set that in txDriver::parse
00160     NS_ENSURE_TRUE(aParser, XML_ERROR_NONE);
00161     return ((txDriver*)aParser)->ExternalEntityRef(aContext, aBase,
00162                                                    aSystemId, aPublicId);
00163 }
00164 
00165 
00170 nsresult
00171 txDriver::parse(istream& aInputStream, const nsAString& aUri)
00172 {
00173     mErrorString.Truncate();
00174     if (!aInputStream) {
00175         mErrorString.AppendLiteral("unable to parse xml: invalid or unopen stream encountered.");
00176         return NS_ERROR_FAILURE;
00177     }
00178     mExpatParser = XML_ParserCreate(nsnull);
00179     if (!mExpatParser) {
00180         return NS_ERROR_OUT_OF_MEMORY;
00181     }
00182 
00183     XML_SetUserData(mExpatParser, this);
00184     XML_SetElementHandler(mExpatParser, startElement, endElement);
00185     XML_SetCharacterDataHandler(mExpatParser, charData);
00186 #ifdef XML_DTD
00187     XML_SetParamEntityParsing(mExpatParser, XML_PARAM_ENTITY_PARSING_ALWAYS);
00188 #endif
00189     XML_SetExternalEntityRefHandler(mExpatParser, externalEntityRefHandler);
00190     XML_SetExternalEntityRefHandlerArg(mExpatParser, this);
00191     XML_SetBase(mExpatParser,
00192                 (const XML_Char*)(PromiseFlatString(aUri).get()));
00193 
00194     const int bufferSize = 1024;
00195     char buf[bufferSize];
00196     PRBool done;
00197     int success;
00198     mRV = NS_OK;
00199     do {
00200         aInputStream.read(buf, bufferSize);
00201         done = aInputStream.eof();
00202         success = XML_Parse(mExpatParser, buf, aInputStream.gcount(), done);
00203         // mRV is set in onDoneCompiling in case of an error
00204         if (!success || NS_FAILED(mRV)) {
00205             createErrorString();
00206             done = MB_TRUE;
00207         }
00208     } while (!done);
00209     aInputStream.clear();
00210 
00211     // clean up
00212     XML_ParserFree(mExpatParser);
00213     mCompiler->doneLoading();
00214     if (!success) {
00215         return NS_ERROR_FAILURE;
00216     }
00217     return mRV;
00218 }
00219 
00220 const nsAString&
00221 txDriver::getErrorString()
00222 {
00223     return mErrorString;
00224 }
00225 
00226 void
00227 txDriver::StartElement(const XML_Char *aName, const XML_Char **aAtts)
00228 {
00229     PRInt32 attcount = 0;
00230     const XML_Char** atts = aAtts;
00231     while (*atts) {
00232         ++atts;
00233         ++attcount;
00234     }
00235     PRInt32 idOffset = XML_GetIdAttributeIndex(mExpatParser);
00236     nsresult rv =
00237         mCompiler->startElement(NS_STATIC_CAST(const PRUnichar*, aName), 
00238                                 NS_STATIC_CAST(const PRUnichar**, aAtts),
00239                                 attcount/2, idOffset);
00240     if (NS_FAILED(rv)) {
00241         PR_LOG(txLog::xslt, PR_LOG_ALWAYS, 
00242                ("compile failed at %i with %x\n",
00243                 XML_GetCurrentLineNumber(mExpatParser), rv));
00244         mCompiler->cancel(rv);
00245     }
00246 }
00247 
00248 void
00249 txDriver::EndElement(const XML_Char* aName)
00250 {
00251     nsresult rv = mCompiler->endElement();
00252     if (NS_FAILED(rv)) {
00253         mCompiler->cancel(rv);
00254     }
00255 }
00256 
00257 void
00258 txDriver::CharacterData(const XML_Char* aChars, int aLength)
00259 {
00260     const PRUnichar* pChars = NS_STATIC_CAST(const PRUnichar*, aChars);
00261     // ignore rv, as this expat handler returns void
00262     nsresult rv = mCompiler->characters(Substring(pChars, pChars + aLength));
00263     if (NS_FAILED(rv)) {
00264         mCompiler->cancel(rv);
00265     }
00266 }
00267 
00268 int
00269 txDriver::ExternalEntityRef(const XML_Char *aContext, const XML_Char *aBase,
00270                             const XML_Char *aSystemId,
00271                             const XML_Char *aPublicId)
00272 {
00273     if (aPublicId) {
00274         // not supported, this is "http://some.site.net/foo.dtd" stuff
00275         return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
00276     }
00277     nsAutoString absUrl;
00278     URIUtils::resolveHref(nsDependentString((PRUnichar*)aSystemId),
00279                           nsDependentString((PRUnichar*)aBase), absUrl);
00280     istream* extInput = URIUtils::getInputStream(absUrl, mErrorString);
00281     if (!extInput) {
00282         return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
00283     }
00284     XML_Parser parent = mExpatParser;
00285     mExpatParser = 
00286         XML_ExternalEntityParserCreate(mExpatParser, aContext, nsnull);
00287     if (!mExpatParser) {
00288         mExpatParser = parent;
00289         delete extInput;
00290         return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
00291     }
00292     XML_SetBase(mExpatParser, absUrl.get());
00293 
00294     const int bufSize = 1024;
00295     char buffer[bufSize];
00296     int result;
00297     PRBool done;
00298     do {
00299         extInput->read(buffer, bufSize);
00300         done = extInput->eof();
00301         if (!(result =
00302               XML_Parse(mExpatParser, buffer,  extInput->gcount(), done))) {
00303             createErrorString();
00304             mErrorString.Append(PRUnichar('\n'));
00305             done = MB_TRUE;
00306         }
00307     } while (!done);
00308 
00309     delete extInput;
00310     XML_ParserFree(mExpatParser);
00311 
00312     mExpatParser = parent;
00313 
00314     return result;
00315 }
00316 
00317 void
00318 txDriver::createErrorString()
00319 {
00320     XML_Error errCode = XML_GetErrorCode(mExpatParser);
00321     mErrorString.AppendWithConversion(XML_ErrorString(errCode));
00322     mErrorString.AppendLiteral(" at line ");
00323     mErrorString.AppendInt(XML_GetCurrentLineNumber(mExpatParser));
00324     mErrorString.AppendLiteral(" in ");
00325     mErrorString.Append((const PRUnichar*)XML_GetBase(mExpatParser));
00326 }
00327 
00332 nsrefcnt
00333 txDriver::AddRef()
00334 {
00335     return ++mRefCnt;
00336 }
00337 
00338 nsrefcnt
00339 txDriver::Release()
00340 {
00341     if (--mRefCnt == 0) {
00342         mRefCnt = 1; //stabilize
00343         delete this;
00344         return 0;
00345     }
00346     return mRefCnt;
00347 }
00348 
00349 void
00350 txDriver::onDoneCompiling(txStylesheetCompiler* aCompiler, nsresult aResult,
00351                           const PRUnichar *aErrorText, const PRUnichar *aParam)
00352 {
00353     // store the nsresult as expat forgets about it
00354     mRV = aResult;
00355 }
00356 
00357 nsresult
00358 txDriver::loadURI(const nsAString& aUri, const nsAString& aReferrerUri,
00359                   txStylesheetCompiler* aCompiler)
00360 {
00361     nsAutoString errMsg;
00362     istream* xslInput = URIUtils::getInputStream(aUri, errMsg);
00363     if (!xslInput) {
00364         return NS_ERROR_FAILURE;
00365     }
00366     nsRefPtr<txDriver> driver = new txDriver();
00367     if (!driver) {
00368         return NS_ERROR_OUT_OF_MEMORY;
00369     }
00370     driver->mCompiler = aCompiler;
00371     return driver->parse(*xslInput, aUri);
00372 }