Beispiel #1
0
/**
 * Creates a PathExpr using the given txExprLexer
 * @param lexer the txExprLexer for retrieving Tokens
 */
nsresult
txExprParser::createUnionExpr(txExprLexer& lexer, txIParseContext* aContext,
                              Expr** aResult)
{
    *aResult = nullptr;

    nsAutoPtr<Expr> expr;
    nsresult rv = createPathExpr(lexer, aContext, getter_Transfers(expr));
    NS_ENSURE_SUCCESS(rv, rv);
    
    if (lexer.peek()->mType != Token::UNION_OP) {
        *aResult = expr.forget();
        return NS_OK;
    }

    nsAutoPtr<UnionExpr> unionExpr(new UnionExpr());

    rv = unionExpr->addExpr(expr);
    NS_ENSURE_SUCCESS(rv, rv);

    expr.forget();

    while (lexer.peek()->mType == Token::UNION_OP) {
        lexer.nextToken(); //-- eat token

        rv = createPathExpr(lexer, aContext, getter_Transfers(expr));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = unionExpr->addExpr(expr.forget());
        NS_ENSURE_SUCCESS(rv, rv);
    }

    *aResult = unionExpr.forget();
    return NS_OK;
}
nsresult txUnknownHandler::createHandlerAndFlush(bool aHTMLRoot,
                                                 const nsSubstring& aName,
                                                 const int32_t aNsID)
{
    NS_ENSURE_TRUE(mBuffer, NS_ERROR_NOT_INITIALIZED);

    txOutputFormat format;
    format.merge(*(mEs->mStylesheet->getOutputFormat()));
    if (format.mMethod == eMethodNotSet) {
        format.mMethod = aHTMLRoot ? eHTMLOutput : eXMLOutput;
    }

    nsAutoPtr<txAXMLEventHandler> handler;
    nsresult rv = mEs->mOutputHandlerFactory->createHandlerWith(&format, aName,
                                                                aNsID,
                                                                getter_Transfers(handler));
    NS_ENSURE_SUCCESS(rv, rv);

    mEs->mOutputHandler = handler;
    mEs->mResultHandler = handler.forget();
    // Let the executionstate delete us. We need to stay alive because we might
    // need to forward hooks to mEs->mResultHandler if someone is currently
    // flushing a buffer to mEs->mResultHandler.
    mEs->mObsoleteHandler = this;

    mFlushed = true;

    // Let go of out buffer as soon as we're done flushing it, we're not going
    // to need it anymore from this point on (all hooks get forwarded to
    // mEs->mResultHandler.
    nsAutoPtr<txResultBuffer> buffer(mBuffer);
    return buffer->flushToHandler(mEs->mResultHandler);
}
nsresult
HTMLFrameSetElement::GetColSpec(int32_t *aNumValues,
                                const nsFramesetSpec** aSpecs)
{
  NS_PRECONDITION(aNumValues, "Must have a pointer to an integer here!");
  NS_PRECONDITION(aSpecs, "Must have a pointer to an array of nsFramesetSpecs");
  *aNumValues = 0;
  *aSpecs = nullptr;

  if (!mColSpecs) {
    const nsAttrValue* value = GetParsedAttr(nsGkAtoms::cols);
    if (value && value->Type() == nsAttrValue::eString) {
      nsresult rv = ParseRowCol(value->GetStringValue(), mNumCols,
                                getter_Transfers(mColSpecs));
      NS_ENSURE_SUCCESS(rv, rv);
    }

    if (!mColSpecs) {  // we may not have had an attr or had an empty attr
      mColSpecs = new nsFramesetSpec[1];
      if (!mColSpecs) {
        mNumCols = 0;
        return NS_ERROR_OUT_OF_MEMORY;
      }
      mNumCols = 1;
      mColSpecs[0].mUnit  = eFramesetUnit_Relative;
      mColSpecs[0].mValue = 1;
    }
  }

  *aSpecs = mColSpecs;
  *aNumValues = mNumCols;
  return NS_OK;
}
nsRefPtr<MediaDecoderReader::MetadataPromise>
MediaDecoderReader::AsyncReadMetadata()
{
  typedef ReadMetadataFailureReason Reason;

  MOZ_ASSERT(OnTaskQueue());
  mDecoder->GetReentrantMonitor().AssertNotCurrentThreadIn();
  DECODER_LOG("MediaDecoderReader::AsyncReadMetadata");

  // PreReadMetadata causes us to try to allocate various hardware and OS
  // resources, which may not be available at the moment.
  PreReadMetadata();
  if (IsWaitingMediaResources()) {
    return MetadataPromise::CreateAndReject(Reason::WAITING_FOR_RESOURCES, __func__);
  }

  // Attempt to read the metadata.
  nsRefPtr<MetadataHolder> metadata = new MetadataHolder();
  nsresult rv = ReadMetadata(&metadata->mInfo, getter_Transfers(metadata->mTags));

  // Reading metadata can cause us to discover that we need resources (a hardware
  // resource initialized but not yet ready for use).
  if (IsWaitingMediaResources()) {
    return MetadataPromise::CreateAndReject(Reason::WAITING_FOR_RESOURCES, __func__);
  }

  // We're not waiting for anything. If we didn't get the metadata, that's an error.
  if (NS_FAILED(rv) || !metadata->mInfo.HasValidMedia()) {
    DECODER_WARN("ReadMetadata failed, rv=%x HasValidMedia=%d", rv, metadata->mInfo.HasValidMedia());
    return MetadataPromise::CreateAndReject(Reason::METADATA_ERROR, __func__);
  }

  // Success!
  return MetadataPromise::CreateAndResolve(metadata, __func__);
}
nsresult txPatternParser::createPattern(const nsString& aPattern,
                                        txIParseContext* aContext,
                                        txPattern** aResult)
{
    txExprLexer lexer;
    nsresult rv = lexer.parse(aPattern);
    if (NS_FAILED(rv)) {
        // XXX error report parsing error
        return rv;
    }
    nsAutoPtr<txPattern> pattern;
    rv = createUnionPattern(lexer, aContext, *getter_Transfers(pattern));
    if (NS_FAILED(rv)) {
        // XXX error report parsing error
        return rv;
    }

    txPatternOptimizer optimizer;
    txPattern* newPattern = nullptr;
    rv = optimizer.optimize(pattern, &newPattern);
    NS_ENSURE_SUCCESS(rv, rv);

    *aResult = newPattern ? newPattern : pattern.forget();

    return NS_OK;
}
NS_IMETHODIMP nsMsgSearchDBView::DoCommand(nsMsgViewCommandTypeValue command)
{
  mCommand = command;
  if (command == nsMsgViewCommandType::deleteMsg ||
      command == nsMsgViewCommandType::deleteNoTrash ||
      command == nsMsgViewCommandType::selectAll ||
      command == nsMsgViewCommandType::selectThread ||
      command == nsMsgViewCommandType::expandAll ||
      command == nsMsgViewCommandType::collapseAll)
    return nsMsgDBView::DoCommand(command);
  nsresult rv = NS_OK;
  nsMsgViewIndexArray selection;
  GetSelectedIndices(selection);

  nsMsgViewIndex *indices = selection.Elements();
  int32_t numIndices = selection.Length();

  // we need to break apart the selection by folders, and then call
  // ApplyCommandToIndices with the command and the indices in the
  // selection that are from that folder.

  nsAutoArrayPtr<nsTArray<uint32_t> > indexArrays;
  int32_t numArrays;
  rv = PartitionSelectionByFolder(indices, numIndices, getter_Transfers(indexArrays), &numArrays);
  NS_ENSURE_SUCCESS(rv, rv);
  for (int32_t folderIndex = 0; folderIndex < numArrays; folderIndex++)
  {
    rv = ApplyCommandToIndices(command, indexArrays[folderIndex].Elements(), indexArrays[folderIndex].Length());
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return rv;
}
Beispiel #7
0
/**
 * Using the given lexer, parses the tokens if they represent a parameter list
 * If an error occurs a non-zero String pointer will be returned containing the
 * error message.
 * @param list, the List to add parameter expressions to
 * @param lexer the txExprLexer to use for parsing tokens
 * @return NS_OK if successful, or another rv otherwise
 */
nsresult
txExprParser::parseParameters(FunctionCall* aFnCall, txExprLexer& lexer,
                              txIParseContext* aContext)
{
    if (lexer.peek()->mType == Token::R_PAREN) {
        lexer.nextToken();
        return NS_OK;
    }

    nsAutoPtr<Expr> expr;
    nsresult rv = NS_OK;
    while (1) {
        rv = createExpr(lexer, aContext, getter_Transfers(expr));
        NS_ENSURE_SUCCESS(rv, rv);

        if (aFnCall) {
            rv = aFnCall->addParam(expr.forget());
            NS_ENSURE_SUCCESS(rv, rv);
        }
                    
        switch (lexer.peek()->mType) {
            case Token::R_PAREN :
                lexer.nextToken();
                return NS_OK;
            case Token::COMMA: //-- param separator
                lexer.nextToken();
                break;
            default:
                return NS_ERROR_XPATH_PAREN_EXPECTED;
        }
    }

    NS_NOTREACHED("internal xpath parser error");
    return NS_ERROR_UNEXPECTED;
}
Beispiel #8
0
/**
 * Using the given lexer, parses the tokens if they represent a predicate list
 * If an error occurs a non-zero String pointer will be returned containing the
 * error message.
 * @param predicateList, the PredicateList to add predicate expressions to
 * @param lexer the txExprLexer to use for parsing tokens
 * @return 0 if successful, or a String pointer to the error message
 */
nsresult
txExprParser::parsePredicates(PredicateList* aPredicateList,
                              txExprLexer& lexer, txIParseContext* aContext)
{
    nsAutoPtr<Expr> expr;
    nsresult rv = NS_OK;
    while (lexer.peek()->mType == Token::L_BRACKET) {
        //-- eat Token
        lexer.nextToken();

        rv = createExpr(lexer, aContext, getter_Transfers(expr));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = aPredicateList->add(expr);
        NS_ENSURE_SUCCESS(rv, rv);

        expr.forget();

        if (lexer.peek()->mType != Token::R_BRACKET) {
            return NS_ERROR_XPATH_BRACKET_EXPECTED;
        }
        lexer.nextToken();
    }
    return NS_OK;
}
Beispiel #9
0
NS_IMETHODIMP
nsBoxObject::SetProperty(const PRUnichar* aPropertyName, const PRUnichar* aPropertyValue)
{
  if (!mPresState)
    NS_NewPresState(getter_Transfers(mPresState));

  nsDependentString propertyName(aPropertyName);
  nsDependentString propertyValue(aPropertyValue);
  return mPresState->SetStateProperty(propertyName, propertyValue);
}
Beispiel #10
0
nsresult
txExprParser::createFunctionCall(txExprLexer& lexer, txIParseContext* aContext,
                                 Expr** aResult)
{
    *aResult = nsnull;

    nsAutoPtr<FunctionCall> fnCall;

    Token* tok = lexer.nextToken();
    NS_ASSERTION(tok->mType == Token::FUNCTION_NAME_AND_PAREN,
                 "FunctionCall expected");

    //-- compare function names
    nsCOMPtr<nsIAtom> prefix, lName;
    PRInt32 namespaceID;
    nsresult rv = resolveQName(tok->Value(), getter_AddRefs(prefix), aContext,
                               getter_AddRefs(lName), namespaceID);
    NS_ENSURE_SUCCESS(rv, rv);

    txCoreFunctionCall::eType type;
    if (namespaceID == kNameSpaceID_None &&
        txCoreFunctionCall::getTypeFromAtom(lName, type)) {
        // It is a known built-in function.
        fnCall = new txCoreFunctionCall(type);
        NS_ENSURE_TRUE(fnCall, NS_ERROR_OUT_OF_MEMORY);
    }

    // check extension functions and xslt
    if (!fnCall) {
        rv = aContext->resolveFunctionCall(lName, namespaceID,
                                           getter_Transfers(fnCall));

        if (rv == NS_ERROR_NOT_IMPLEMENTED) {
            // this should just happen for unparsed-entity-uri()
            NS_ASSERTION(!fnCall, "Now is it implemented or not?");
            rv = parseParameters(0, lexer, aContext);
            NS_ENSURE_SUCCESS(rv, rv);

            *aResult = new txLiteralExpr(tok->Value() +
                                         NS_LITERAL_STRING(" not implemented."));
            NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);

            return NS_OK;
        }

        NS_ENSURE_SUCCESS(rv, rv);
    }

    //-- handle parametes
    rv = parseParameters(fnCall, lexer, aContext);
    NS_ENSURE_SUCCESS(rv, rv);

    *aResult = fnCall.forget();
    return NS_OK;
}
nsresult
HTMLFrameSetElement::SetAttr(int32_t aNameSpaceID,
                             nsIAtom* aAttribute,
                             nsIAtom* aPrefix,
                             const nsAString& aValue,
                             bool aNotify)
{
  nsresult rv;
  /* The main goal here is to see whether the _number_ of rows or
   *  columns has changed.  If it has, we need to reframe; otherwise
   *  we want to reflow.  So we set mCurrentRowColHint here, then call
   *  nsGenericHTMLElement::SetAttr, which will end up calling
   *  GetAttributeChangeHint and notifying layout with that hint.
   *  Once nsGenericHTMLElement::SetAttr returns, we want to go back to our
   *  normal hint, which is NS_STYLE_HINT_REFLOW.
   */
  if (aAttribute == nsGkAtoms::rows && aNameSpaceID == kNameSpaceID_None) {
    int32_t oldRows = mNumRows;
    ParseRowCol(aValue, mNumRows, getter_Transfers(mRowSpecs));
    
    if (mNumRows != oldRows) {
      mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE;
    }
  } else if (aAttribute == nsGkAtoms::cols &&
             aNameSpaceID == kNameSpaceID_None) {
    int32_t oldCols = mNumCols;
    ParseRowCol(aValue, mNumCols, getter_Transfers(mColSpecs));

    if (mNumCols != oldCols) {
      mCurrentRowColHint = NS_STYLE_HINT_FRAMECHANGE;
    }
  }
  
  rv = nsGenericHTMLElement::SetAttr(aNameSpaceID, aAttribute, aPrefix,
                                     aValue, aNotify);
  mCurrentRowColHint = NS_STYLE_HINT_REFLOW;
  
  return rv;
}
Beispiel #12
0
nsresult
DASHReader::ReadMetadata(VideoInfo* aInfo,
                         MetadataTags** aTags)
{
  NS_ASSERTION(mDecoder->OnDecodeThread(), "Should be on decode thread.");

  // Wait for MPD to be parsed and child readers created.
  LOG1("Waiting for metadata download.");
  nsresult rv = WaitForMetadata();
  // If we get an abort, return silently; the decoder is shutting down.
  if (NS_ERROR_ABORT == rv) {
    return NS_OK;
  }
  // Verify no other errors before continuing.
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ASSERTION(aTags, "Called with null MetadataTags**.");
  *aTags = nullptr;

  // Get metadata from child readers.
  VideoInfo audioInfo, videoInfo;

  // Read metadata for all video streams.
  for (uint i = 0; i < mVideoReaders.Length(); i++) {
    // Use an nsAutoPtr here to ensure |tags| memory does not leak.
    nsAutoPtr<nsHTMLMediaElement::MetadataTags> tags;
    rv = mVideoReaders[i]->ReadMetadata(&videoInfo, getter_Transfers(tags));
    NS_ENSURE_SUCCESS(rv, rv);
    // Use metadata from current video sub reader to populate aInfo.
    if (mVideoReaders[i] == mVideoReader) {
      mInfo.mHasVideo      = videoInfo.mHasVideo;
      mInfo.mDisplay       = videoInfo.mDisplay;
    }
  }
  // Read metadata for audio stream.
  // Note: Getting metadata tags from audio reader only for now.
  // XXX Audio stream switching not yet supported.
  if (mAudioReader) {
    rv = mAudioReader->ReadMetadata(&audioInfo, aTags);
    NS_ENSURE_SUCCESS(rv, rv);
    mInfo.mHasAudio      = audioInfo.mHasAudio;
    mInfo.mAudioRate     = audioInfo.mAudioRate;
    mInfo.mAudioChannels = audioInfo.mAudioChannels;
    mInfo.mStereoMode    = audioInfo.mStereoMode;
  }

  *aInfo = mInfo;

  return NS_OK;
}
nsresult
nsXPathEvaluator::CreateExpression(const nsAString & aExpression,
                                   nsIDOMXPathNSResolver *aResolver,
                                   nsTArray<int32_t> *aNamespaceIDs,
                                   nsTArray<nsCString> *aContractIDs,
                                   nsCOMArray<nsISupports> *aState,
                                   nsIDOMXPathExpression **aResult)
{
    nsresult rv;
    if (!mRecycler) {
        nsRefPtr<txResultRecycler> recycler = new txResultRecycler;
        NS_ENSURE_TRUE(recycler, NS_ERROR_OUT_OF_MEMORY);
        
        rv = recycler->init();
        NS_ENSURE_SUCCESS(rv, rv);
        
        mRecycler = recycler;
    }

    nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocument);
    nsXPathEvaluatorParseContext pContext(aResolver, aNamespaceIDs,
                                          aContractIDs, aState,
                                          !(doc && doc->IsHTML()));

    nsAutoPtr<Expr> expression;
    rv = txExprParser::createExpr(PromiseFlatString(aExpression), &pContext,
                                  getter_Transfers(expression));
    if (NS_FAILED(rv)) {
        if (rv == NS_ERROR_DOM_NAMESPACE_ERR) {
            return NS_ERROR_DOM_NAMESPACE_ERR;
        }

        return NS_ERROR_DOM_INVALID_EXPRESSION_ERR;
    }

    nsCOMPtr<nsIDOMDocument> document = do_QueryReferent(mDocument);

    *aResult = new nsXPathExpression(expression, mRecycler, document);
    if (!*aResult) {
        return NS_ERROR_OUT_OF_MEMORY;
    }

    NS_ADDREF(*aResult);
    return NS_OK;
}
RefPtr<MediaDecoderReader::MetadataPromise>
MediaDecoderReader::AsyncReadMetadata()
{
  MOZ_ASSERT(OnTaskQueue());
  DECODER_LOG("MediaDecoderReader::AsyncReadMetadata");

  // Attempt to read the metadata.
  RefPtr<MetadataHolder> metadata = new MetadataHolder();
  nsresult rv = ReadMetadata(&metadata->mInfo, getter_Transfers(metadata->mTags));
  metadata->mInfo.AssertValid();

  // We're not waiting for anything. If we didn't get the metadata, that's an
  // error.
  if (NS_FAILED(rv) || !metadata->mInfo.HasValidMedia()) {
    DECODER_WARN("ReadMetadata failed, rv=%x HasValidMedia=%d", rv, metadata->mInfo.HasValidMedia());
    return MetadataPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_METADATA_ERR, __func__);
  }

  // Success!
  return MetadataPromise::CreateAndResolve(metadata, __func__);
}
const txXPathNode*
txExecutionState::retrieveDocument(const nsAString& aUri)
{
    NS_ASSERTION(aUri.FindChar(PRUnichar('#')) == kNotFound,
                 "Remove the fragment.");

    if (mDisableLoads) {
        return nsnull;
    }

    PR_LOG(txLog::xslt, PR_LOG_DEBUG,
           ("Retrieve Document %s", NS_LossyConvertUTF16toASCII(aUri).get()));

    // try to get already loaded document
    txLoadedDocumentEntry *entry = mLoadedDocuments.PutEntry(aUri);
    if (!entry) {
        return nsnull;
    }

    if (!entry->mDocument) {
        // open URI
        nsAutoString errMsg;
        // XXX we should get the loader from the actual node
        // triggering the load, but this will do for the time being
        nsresult rv;
        rv = txParseDocumentFromURI(aUri, *mLoadedDocuments.mSourceDocument,
                                    errMsg,
                                    getter_Transfers(entry->mDocument));

        if (NS_FAILED(rv) || !entry->mDocument) {
            mLoadedDocuments.RawRemoveEntry(entry);
            receiveError(NS_LITERAL_STRING("Couldn't load document '") +
                         aUri + NS_LITERAL_STRING("': ") + errMsg, rv);

            return nsnull;
        }
    }

    return entry->mDocument;
}
Beispiel #16
0
nsRefPtr<MediaDecoderReader::MetadataPromise>
MediaDecoderReader::AsyncReadMetadata()
{
  typedef ReadMetadataFailureReason Reason;

  MOZ_ASSERT(OnTaskQueue());
  mDecoder->GetReentrantMonitor().AssertNotCurrentThreadIn();
  DECODER_LOG("MediaDecoderReader::AsyncReadMetadata");

  // Attempt to read the metadata.
  nsRefPtr<MetadataHolder> metadata = new MetadataHolder();
  nsresult rv = ReadMetadata(&metadata->mInfo, getter_Transfers(metadata->mTags));

  // We're not waiting for anything. If we didn't get the metadata, that's an
  // error.
  if (NS_FAILED(rv) || !metadata->mInfo.HasValidMedia()) {
    DECODER_WARN("ReadMetadata failed, rv=%x HasValidMedia=%d", rv, metadata->mInfo.HasValidMedia());
    return MetadataPromise::CreateAndReject(Reason::METADATA_ERROR, __func__);
  }

  // Success!
  return MetadataPromise::CreateAndResolve(metadata, __func__);
}
Beispiel #17
0
XPathExpression*
XPathEvaluator::CreateExpression(const nsAString & aExpression,
                                 txIParseContext* aContext,
                                 nsIDocument* aDocument,
                                 ErrorResult& aRv)
{
    if (!mRecycler) {
        mRecycler = new txResultRecycler;
    }

    nsAutoPtr<Expr> expression;
    aRv = txExprParser::createExpr(PromiseFlatString(aExpression), aContext,
                                   getter_Transfers(expression));
    if (aRv.Failed()) {
        if (aRv.ErrorCode() != NS_ERROR_DOM_NAMESPACE_ERR) {
            aRv.Throw(NS_ERROR_DOM_INVALID_EXPRESSION_ERR);
        }

        return nullptr;
    }

    return new XPathExpression(Move(expression), mRecycler, aDocument);
}
Beispiel #18
0
const txXPathNode*
txExecutionState::retrieveDocument(const nsAString& aUri)
{
    NS_ASSERTION(!aUri.Contains(char16_t('#')),
                 "Remove the fragment.");

    if (mDisableLoads) {
        return nullptr;
    }

    MOZ_LOG(txLog::xslt, LogLevel::Debug,
           ("Retrieve Document %s", NS_LossyConvertUTF16toASCII(aUri).get()));

    // try to get already loaded document
    txLoadedDocumentEntry *entry = mLoadedDocuments.PutEntry(aUri);
    if (!entry) {
        return nullptr;
    }

    if (!entry->mDocument && !entry->LoadingFailed()) {
        // open URI
        nsAutoString errMsg;
        // XXX we should get the loader from the actual node
        // triggering the load, but this will do for the time being
        entry->mLoadResult =
            txParseDocumentFromURI(aUri, *mLoadedDocuments.mSourceDocument,
                                   errMsg, getter_Transfers(entry->mDocument));

        if (entry->LoadingFailed()) {
            receiveError(NS_LITERAL_STRING("Couldn't load document '") +
                         aUri + NS_LITERAL_STRING("': ") + errMsg,
                         entry->mLoadResult);
        }
    }

    return entry->mDocument;
}
Beispiel #19
0
NS_IMETHODIMP
nsXPathEvaluator::CreateExpression(const nsAString & aExpression,
                                   nsIDOMXPathNSResolver *aResolver,
                                   nsIDOMXPathExpression **aResult)
{
    nsresult rv = NS_OK;
    if (!mRecycler) {
        nsRefPtr<txResultRecycler> recycler = new txResultRecycler;
        NS_ENSURE_TRUE(recycler, NS_ERROR_OUT_OF_MEMORY);
        
        rv = recycler->init();
        NS_ENSURE_SUCCESS(rv, rv);
        
        mRecycler = recycler;
    }

    nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocument);
    ParseContextImpl pContext(aResolver, !doc || doc->IsCaseSensitive());
    nsAutoPtr<Expr> expression;
    rv = txExprParser::createExpr(PromiseFlatString(aExpression), &pContext,
                                  getter_Transfers(expression));
    if (NS_FAILED(rv)) {
        if (rv == NS_ERROR_DOM_NAMESPACE_ERR) {
            return NS_ERROR_DOM_NAMESPACE_ERR;
        }

        return NS_ERROR_DOM_INVALID_EXPRESSION_ERR;
    }

    *aResult = new nsXPathExpression(expression, mRecycler);
    if (!*aResult) {
        return NS_ERROR_OUT_OF_MEMORY;
    }

    NS_ADDREF(*aResult);
    return NS_OK;
}
Beispiel #20
0
nsresult
txExprParser::createExprInternal(const nsSubstring& aExpression,
                                 uint32_t aSubStringPos,
                                 txIParseContext* aContext, Expr** aExpr)
{
    NS_ENSURE_ARG_POINTER(aExpr);
    *aExpr = nullptr;
    txExprLexer lexer;
    nsresult rv = lexer.parse(aExpression);
    if (NS_FAILED(rv)) {
        nsASingleFragmentString::const_char_iterator start;
        aExpression.BeginReading(start);
        aContext->SetErrorOffset(lexer.mPosition - start + aSubStringPos);
        return rv;
    }
    nsAutoPtr<Expr> expr;
    rv = createExpr(lexer, aContext, getter_Transfers(expr));
    if (NS_SUCCEEDED(rv) && lexer.peek()->mType != Token::END) {
        rv = NS_ERROR_XPATH_BINARY_EXPECTED;
    }
    if (NS_FAILED(rv)) {
        nsASingleFragmentString::const_char_iterator start;
        aExpression.BeginReading(start);
        aContext->SetErrorOffset(lexer.peek()->mStart - start + aSubStringPos);

        return rv;
    }

    txXPathOptimizer optimizer;
    Expr* newExpr = nullptr;
    rv = optimizer.optimize(expr, &newExpr);
    NS_ENSURE_SUCCESS(rv, rv);

    *aExpr = newExpr ? newExpr : expr.forget();

    return NS_OK;
}
Beispiel #21
0
NS_IMETHODIMP
nsBoxObject::SetPropertyAsSupports(const PRUnichar* aPropertyName, nsISupports* aValue)
{
#ifdef DEBUG
  if (aValue) {
    nsIFrame* frame;
    CallQueryInterface(aValue, &frame);
    NS_ASSERTION(!frame,
                 "Calling SetPropertyAsSupports on a frame.  Prepare to crash "
                 "and be exploited any time some random website decides to "
                 "exploit you");
  }
#endif

  NS_ENSURE_ARG(aPropertyName && *aPropertyName);
  
  if (!mPresState) {
    NS_NewPresState(getter_Transfers(mPresState));
    NS_ENSURE_TRUE(mPresState, NS_ERROR_OUT_OF_MEMORY);
  }

  nsDependentString propertyName(aPropertyName);
  return mPresState->SetStatePropertyAsSupports(propertyName, aValue);
}
void
MediaDecodeTask::Decode()
{
  MOZ_ASSERT(!mThreadPool == NS_IsMainThread(),
             "We should be on the main thread only if we don't have a thread pool");

  mBufferDecoder->BeginDecoding(NS_GetCurrentThread());

  // Tell the decoder reader that we are not going to play the data directly,
  // and that we should not reject files with more channels than the audio
  // bakend support.
  mDecoderReader->SetIgnoreAudioOutputFormat();

  mDecoderReader->OnDecodeThreadStart();

  MediaInfo mediaInfo;
  nsAutoPtr<MetadataTags> tags;
  nsresult rv = mDecoderReader->ReadMetadata(&mediaInfo, getter_Transfers(tags));
  if (NS_FAILED(rv)) {
    ReportFailureOnMainThread(WebAudioDecodeJob::InvalidContent);
    return;
  }

  if (!mDecoderReader->HasAudio()) {
    ReportFailureOnMainThread(WebAudioDecodeJob::NoAudio);
    return;
  }

  while (mDecoderReader->DecodeAudioData()) {
    // consume all of the buffer
    continue;
  }

  mDecoderReader->OnDecodeThreadFinish();

  MediaQueue<AudioData>& audioQueue = mDecoderReader->AudioQueue();
  uint32_t frameCount = audioQueue.FrameCount();
  uint32_t channelCount = mediaInfo.mAudio.mChannels;
  uint32_t sampleRate = mediaInfo.mAudio.mRate;

  if (!frameCount || !channelCount || !sampleRate) {
    ReportFailureOnMainThread(WebAudioDecodeJob::InvalidContent);
    return;
  }

  const uint32_t destSampleRate = mDecodeJob.mContext->SampleRate();
  AutoResampler resampler;

  uint32_t resampledFrames = frameCount;
  if (sampleRate != destSampleRate) {
    resampledFrames = static_cast<uint32_t>(
        static_cast<uint64_t>(destSampleRate) *
        static_cast<uint64_t>(frameCount) /
        static_cast<uint64_t>(sampleRate)
      );

    resampler = speex_resampler_init(channelCount,
                                     sampleRate,
                                     destSampleRate,
                                     SPEEX_RESAMPLER_QUALITY_DEFAULT, nullptr);
    speex_resampler_skip_zeros(resampler);
    resampledFrames += speex_resampler_get_output_latency(resampler);
  }

  // Allocate the channel buffers.  Note that if we end up resampling, we may
  // write fewer bytes than mResampledFrames to the output buffer, in which
  // case mWriteIndex will tell us how many valid samples we have.
  static const fallible_t fallible = fallible_t();
  bool memoryAllocationSuccess = true;
  if (!mDecodeJob.mChannelBuffers.SetLength(channelCount)) {
    memoryAllocationSuccess = false;
  } else {
    for (uint32_t i = 0; i < channelCount; ++i) {
      mDecodeJob.mChannelBuffers[i] = new(fallible) float[resampledFrames];
      if (!mDecodeJob.mChannelBuffers[i]) {
        memoryAllocationSuccess = false;
        break;
      }
    }
  }
  if (!memoryAllocationSuccess) {
    ReportFailureOnMainThread(WebAudioDecodeJob::UnknownError);
    return;
  }

  nsAutoPtr<AudioData> audioData;
  while ((audioData = audioQueue.PopFront())) {
    audioData->EnsureAudioBuffer(); // could lead to a copy :(
    AudioDataValue* bufferData = static_cast<AudioDataValue*>
      (audioData->mAudioBuffer->Data());

    if (sampleRate != destSampleRate) {
      const uint32_t maxOutSamples = resampledFrames - mDecodeJob.mWriteIndex;

      for (uint32_t i = 0; i < audioData->mChannels; ++i) {
        uint32_t inSamples = audioData->mFrames;
        uint32_t outSamples = maxOutSamples;

        WebAudioUtils::SpeexResamplerProcess(
            resampler, i, &bufferData[i * audioData->mFrames], &inSamples,
            mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
            &outSamples);

        if (i == audioData->mChannels - 1) {
          mDecodeJob.mWriteIndex += outSamples;
          MOZ_ASSERT(mDecodeJob.mWriteIndex <= resampledFrames);
          MOZ_ASSERT(inSamples == audioData->mFrames);
        }
      }
    } else {
      for (uint32_t i = 0; i < audioData->mChannels; ++i) {
        ConvertAudioSamples(&bufferData[i * audioData->mFrames],
                            mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
                            audioData->mFrames);

        if (i == audioData->mChannels - 1) {
          mDecodeJob.mWriteIndex += audioData->mFrames;
        }
      }
    }
  }

  if (sampleRate != destSampleRate) {
    uint32_t inputLatency = speex_resampler_get_input_latency(resampler);
    const uint32_t maxOutSamples = resampledFrames - mDecodeJob.mWriteIndex;
    for (uint32_t i = 0; i < channelCount; ++i) {
      uint32_t inSamples = inputLatency;
      uint32_t outSamples = maxOutSamples;

      WebAudioUtils::SpeexResamplerProcess(
          resampler, i, (AudioDataValue*)nullptr, &inSamples,
          mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
          &outSamples);

      if (i == channelCount - 1) {
        mDecodeJob.mWriteIndex += outSamples;
        MOZ_ASSERT(mDecodeJob.mWriteIndex <= resampledFrames);
        MOZ_ASSERT(inSamples == inputLatency);
      }
    }
  }

  mPhase = PhaseEnum::AllocateBuffer;
  RunNextPhase();
}
Beispiel #23
0
nsresult
txExprParser::createExpr(txExprLexer& lexer, txIParseContext* aContext,
                         Expr** aResult)
{
    *aResult = nsnull;

    nsresult rv = NS_OK;
    MBool done = MB_FALSE;

    nsAutoPtr<Expr> expr;

    txStack exprs;
    txStack ops;

    while (!done) {

        MBool unary = MB_FALSE;
        while (lexer.peek()->mType == Token::SUBTRACTION_OP) {
            unary = !unary;
            lexer.nextToken();
        }

        rv = createUnionExpr(lexer, aContext, getter_Transfers(expr));
        if (NS_FAILED(rv)) {
            break;
        }

        if (unary) {
            Expr* unaryExpr = new UnaryExpr(expr);
            if (!unaryExpr) {
                rv = NS_ERROR_OUT_OF_MEMORY;
                break;
            }
            
            expr.forget();
            expr = unaryExpr;
        }

        Token* tok = lexer.nextToken();
        short tokPrecedence = precedence(tok);
        if (tokPrecedence != 0) {
            while (!exprs.isEmpty() && tokPrecedence
                   <= precedence(static_cast<Token*>(ops.peek()))) {
                // can't use expr as argument due to order of evaluation
                nsAutoPtr<Expr> left(static_cast<Expr*>(exprs.pop()));
                nsAutoPtr<Expr> right(expr);
                rv = createBinaryExpr(left, right,
                                      static_cast<Token*>(ops.pop()),
                                      getter_Transfers(expr));
                if (NS_FAILED(rv)) {
                    done = PR_TRUE;
                    break;
                }
            }
            exprs.push(expr.forget());
            ops.push(tok);
        }
        else {
            lexer.pushBack();
            done = PR_TRUE;
        }
    }

    while (NS_SUCCEEDED(rv) && !exprs.isEmpty()) {
        nsAutoPtr<Expr> left(static_cast<Expr*>(exprs.pop()));
        nsAutoPtr<Expr> right(expr);
        rv = createBinaryExpr(left, right, static_cast<Token*>(ops.pop()),
                              getter_Transfers(expr));
    }
    // clean up on error
    while (!exprs.isEmpty()) {
        delete static_cast<Expr*>(exprs.pop());
    }
    NS_ENSURE_SUCCESS(rv, rv);

    *aResult = expr.forget();
    return NS_OK;
}
Beispiel #24
0
nsresult
txExprParser::createLocationStep(txExprLexer& lexer, txIParseContext* aContext,
                                 Expr** aExpr)
{
    *aExpr = nullptr;

    //-- child axis is default
    LocationStep::LocationStepType axisIdentifier = LocationStep::CHILD_AXIS;
    nsAutoPtr<txNodeTest> nodeTest;

    //-- get Axis Identifier or AbbreviatedStep, if present
    Token* tok = lexer.peek();
    switch (tok->mType) {
        case Token::AXIS_IDENTIFIER:
        {
            //-- eat token
            lexer.nextToken();
            nsCOMPtr<nsIAtom> axis = do_GetAtom(tok->Value());
            if (axis == nsGkAtoms::ancestor) {
                axisIdentifier = LocationStep::ANCESTOR_AXIS;
            }
            else if (axis == nsGkAtoms::ancestorOrSelf) {
                axisIdentifier = LocationStep::ANCESTOR_OR_SELF_AXIS;
            }
            else if (axis == nsGkAtoms::attribute) {
                axisIdentifier = LocationStep::ATTRIBUTE_AXIS;
            }
            else if (axis == nsGkAtoms::child) {
                axisIdentifier = LocationStep::CHILD_AXIS;
            }
            else if (axis == nsGkAtoms::descendant) {
                axisIdentifier = LocationStep::DESCENDANT_AXIS;
            }
            else if (axis == nsGkAtoms::descendantOrSelf) {
                axisIdentifier = LocationStep::DESCENDANT_OR_SELF_AXIS;
            }
            else if (axis == nsGkAtoms::following) {
                axisIdentifier = LocationStep::FOLLOWING_AXIS;
            }
            else if (axis == nsGkAtoms::followingSibling) {
                axisIdentifier = LocationStep::FOLLOWING_SIBLING_AXIS;
            }
            else if (axis == nsGkAtoms::_namespace) {
                axisIdentifier = LocationStep::NAMESPACE_AXIS;
            }
            else if (axis == nsGkAtoms::parent) {
                axisIdentifier = LocationStep::PARENT_AXIS;
            }
            else if (axis == nsGkAtoms::preceding) {
                axisIdentifier = LocationStep::PRECEDING_AXIS;
            }
            else if (axis == nsGkAtoms::precedingSibling) {
                axisIdentifier = LocationStep::PRECEDING_SIBLING_AXIS;
            }
            else if (axis == nsGkAtoms::self) {
                axisIdentifier = LocationStep::SELF_AXIS;
            }
            else {
                return NS_ERROR_XPATH_INVALID_AXIS;
            }
            break;
        }
        case Token::AT_SIGN:
            //-- eat token
            lexer.nextToken();
            axisIdentifier = LocationStep::ATTRIBUTE_AXIS;
            break;
        case Token::PARENT_NODE :
            //-- eat token
            lexer.nextToken();
            axisIdentifier = LocationStep::PARENT_AXIS;
            nodeTest = new txNodeTypeTest(txNodeTypeTest::NODE_TYPE);
            break;
        case Token::SELF_NODE :
            //-- eat token
            lexer.nextToken();
            axisIdentifier = LocationStep::SELF_AXIS;
            nodeTest = new txNodeTypeTest(txNodeTypeTest::NODE_TYPE);
            break;
        default:
            break;
    }

    //-- get NodeTest unless an AbbreviatedStep was found
    nsresult rv = NS_OK;
    if (!nodeTest) {
        tok = lexer.peek();

        if (tok->mType == Token::CNAME) {
            lexer.nextToken();
            // resolve QName
            nsCOMPtr<nsIAtom> prefix, lName;
            int32_t nspace;
            rv = resolveQName(tok->Value(), getter_AddRefs(prefix),
                              aContext, getter_AddRefs(lName),
                              nspace, true);
            NS_ENSURE_SUCCESS(rv, rv);

            nodeTest =
              new txNameTest(prefix, lName, nspace,
                             axisIdentifier == LocationStep::ATTRIBUTE_AXIS ?
                             static_cast<uint16_t>(txXPathNodeType::ATTRIBUTE_NODE) :
                             static_cast<uint16_t>(txXPathNodeType::ELEMENT_NODE));
        }
        else {
            rv = createNodeTypeTest(lexer, getter_Transfers(nodeTest));
            NS_ENSURE_SUCCESS(rv, rv);
        }
    }
    
    nsAutoPtr<LocationStep> lstep(new LocationStep(nodeTest, axisIdentifier));

    nodeTest.forget();

    //-- handle predicates
    rv = parsePredicates(lstep, lexer, aContext);
    NS_ENSURE_SUCCESS(rv, rv);

    *aExpr = lstep.forget();
    return NS_OK;
}
Beispiel #25
0
/**
 * Creates an Attribute Value Template using the given value
 * This should move to XSLProcessor class
 */
nsresult
txExprParser::createAVT(const nsSubstring& aAttrValue,
                        txIParseContext* aContext,
                        Expr** aResult)
{
    *aResult = nullptr;
    nsresult rv = NS_OK;
    nsAutoPtr<Expr> expr;
    FunctionCall* concat = nullptr;

    nsAutoString literalString;
    bool inExpr = false;
    nsSubstring::const_char_iterator iter, start, end, avtStart;
    aAttrValue.BeginReading(iter);
    aAttrValue.EndReading(end);
    avtStart = iter;

    while (iter != end) {
        // Every iteration through this loop parses either a literal section
        // or an expression
        start = iter;
        nsAutoPtr<Expr> newExpr;
        if (!inExpr) {
            // Parse literal section
            literalString.Truncate();
            while (iter != end) {
                PRUnichar q = *iter;
                if (q == '{' || q == '}') {
                    // Store what we've found so far and set a new |start| to
                    // skip the (first) brace
                    literalString.Append(Substring(start, iter));
                    start = ++iter;
                    // Unless another brace follows we've found the start of
                    // an expression (in case of '{') or an unbalanced brace
                    // (in case of '}')
                    if (iter == end || *iter != q) {
                        if (q == '}') {
                            aContext->SetErrorOffset(iter - avtStart);
                            return NS_ERROR_XPATH_UNBALANCED_CURLY_BRACE;
                        }

                        inExpr = true;
                        break;
                    }
                    // We found a second brace, let that be part of the next
                    // literal section being parsed and continue looping
                }
                ++iter;
            }

            if (start == iter && literalString.IsEmpty()) {
                // Restart the loop since we didn't create an expression
                continue;
            }
            newExpr = new txLiteralExpr(literalString +
                                        Substring(start, iter));
        }
        else {
            // Parse expressions, iter is already past the initial '{' when
            // we get here.
            while (iter != end) {
                if (*iter == '}') {
                    rv = createExprInternal(Substring(start, iter),
                                            start - avtStart, aContext,
                                            getter_Transfers(newExpr));
                    NS_ENSURE_SUCCESS(rv, rv);

                    inExpr = false;
                    ++iter; // skip closing '}'
                    break;
                }
                else if (*iter == '\'' || *iter == '"') {
                    PRUnichar q = *iter;
                    while (++iter != end && *iter != q) {} /* do nothing */
                    if (iter == end) {
                        break;
                    }
                }
                ++iter;
            }

            if (inExpr) {
                aContext->SetErrorOffset(start - avtStart);
                return NS_ERROR_XPATH_UNBALANCED_CURLY_BRACE;
            }
        }
        
        // Add expression, create a concat() call if necessary
        if (!expr) {
            expr = newExpr;
        }
        else {
            if (!concat) {
                concat = new txCoreFunctionCall(txCoreFunctionCall::CONCAT);
                NS_ENSURE_TRUE(concat, NS_ERROR_OUT_OF_MEMORY);

                rv = concat->addParam(expr.forget());
                expr = concat;
                NS_ENSURE_SUCCESS(rv, rv);
            }

            rv = concat->addParam(newExpr.forget());
            NS_ENSURE_SUCCESS(rv, rv);
        }
    }

    if (inExpr) {
        aContext->SetErrorOffset(iter - avtStart);
        return NS_ERROR_XPATH_UNBALANCED_CURLY_BRACE;
    }

    if (!expr) {
        expr = new txLiteralExpr(EmptyString());
    }

    *aResult = expr.forget();

    return NS_OK;
}
Beispiel #26
0
nsresult
txExprParser::createExpr(txExprLexer& lexer, txIParseContext* aContext,
                         Expr** aResult)
{
    *aResult = nullptr;

    nsresult rv = NS_OK;
    bool done = false;

    nsAutoPtr<Expr> expr;

    txStack exprs;
    txStack ops;

    while (!done) {

        uint16_t negations = 0;
        while (lexer.peek()->mType == Token::SUBTRACTION_OP) {
            negations++;
            lexer.nextToken();
        }

        rv = createUnionExpr(lexer, aContext, getter_Transfers(expr));
        if (NS_FAILED(rv)) {
            break;
        }

        if (negations > 0) {
            if (negations % 2 == 0) {
                FunctionCall* fcExpr = new txCoreFunctionCall(txCoreFunctionCall::NUMBER);
                
                rv = fcExpr->addParam(expr);
                if (NS_FAILED(rv))
                    return rv;
                expr.forget();
                expr = fcExpr;
            }
            else {
                expr = new UnaryExpr(expr.forget());
            }
        }

        short tokPrecedence = precedence(lexer.peek());
        if (tokPrecedence != 0) {
            Token* tok = lexer.nextToken();
            while (!exprs.isEmpty() && tokPrecedence
                   <= precedence(static_cast<Token*>(ops.peek()))) {
                // can't use expr as argument due to order of evaluation
                nsAutoPtr<Expr> left(static_cast<Expr*>(exprs.pop()));
                nsAutoPtr<Expr> right(expr);
                rv = createBinaryExpr(left, right,
                                      static_cast<Token*>(ops.pop()),
                                      getter_Transfers(expr));
                if (NS_FAILED(rv)) {
                    done = true;
                    break;
                }
            }
            exprs.push(expr.forget());
            ops.push(tok);
        }
        else {
            done = true;
        }
    }

    while (NS_SUCCEEDED(rv) && !exprs.isEmpty()) {
        nsAutoPtr<Expr> left(static_cast<Expr*>(exprs.pop()));
        nsAutoPtr<Expr> right(expr);
        rv = createBinaryExpr(left, right, static_cast<Token*>(ops.pop()),
                              getter_Transfers(expr));
    }
    // clean up on error
    while (!exprs.isEmpty()) {
        delete static_cast<Expr*>(exprs.pop());
    }
    NS_ENSURE_SUCCESS(rv, rv);

    *aResult = expr.forget();
    return NS_OK;
}
Beispiel #27
0
static nsresult
getHelper(nsCameraControl *aCameraControl, PRUint32 aKey, JSContext *cx, JS::Value *aValue)
{
  nsAutoArrayPtr<nsCameraControl::CameraRegion> regions;
  PRUint32 length = 0;

  aCameraControl->GetParameter(aKey, getter_Transfers(regions), &length);
  if (!regions && length > 0) {
    DOM_CAMERA_LOGE("%s:%d : got length %d, but no regions\n", __func__, __LINE__, length);
    return NS_ERROR_UNEXPECTED;
  }

  JSObject *array = JS_NewArrayObject(cx, 0, nsnull);
  if (!array) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  
  DOM_CAMERA_LOGI("%s:%d : got %d regions\n", __func__, __LINE__, length);

  for (PRUint32 i = 0; i < length; ++i) {
    JS::Value v;

    JSObject *o = JS_NewObject(cx, nsnull, nsnull, nsnull);
    if (!o) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    DOM_CAMERA_LOGI("mLeft=%d\n", regions[i].mTop);
    v = INT_TO_JSVAL(regions[i].mTop);
    if (!JS_SetProperty(cx, o, "top", &v)) {
      return NS_ERROR_FAILURE;
    }
    DOM_CAMERA_LOGI("mLeft=%d\n", regions[i].mLeft);
    v = INT_TO_JSVAL(regions[i].mLeft);
    if (!JS_SetProperty(cx, o, "left", &v)) {
      return NS_ERROR_FAILURE;
    }
    DOM_CAMERA_LOGI("mBottom=%d\n", regions[i].mBottom);
    v = INT_TO_JSVAL(regions[i].mBottom);
    if (!JS_SetProperty(cx, o, "bottom", &v)) {
      return NS_ERROR_FAILURE;
    }
    DOM_CAMERA_LOGI("mRight=%d\n", regions[i].mRight);
    v = INT_TO_JSVAL(regions[i].mRight);
    if (!JS_SetProperty(cx, o, "right", &v)) {
      return NS_ERROR_FAILURE;
    }
    DOM_CAMERA_LOGI("mWeight=%d\n", regions[i].mWeight);
    v = INT_TO_JSVAL(regions[i].mWeight);
    if (!JS_SetProperty(cx, o, "weight", &v)) {
      return NS_ERROR_FAILURE;
    }

    v = OBJECT_TO_JSVAL(o);
    if (!JS_SetElement(cx, array, i, &v)) {
      return NS_ERROR_FAILURE;
    }
  }

  *aValue = JS::ObjectValue(*array);
  return NS_OK;
}
Beispiel #28
0
/**
 * Creates a PathExpr using the given txExprLexer
 * @param lexer the txExprLexer for retrieving Tokens
 */
nsresult
txExprParser::createPathExpr(txExprLexer& lexer, txIParseContext* aContext,
                             Expr** aResult)
{
    *aResult = nullptr;

    nsAutoPtr<Expr> expr;

    Token* tok = lexer.peek();

    // is this a root expression?
    if (tok->mType == Token::PARENT_OP) {
        if (!isLocationStepToken(lexer.peekAhead())) {
            lexer.nextToken();
            *aResult = new RootExpr();
            return NS_OK;
        }
    }

    // parse first step (possibly a FilterExpr)
    nsresult rv = NS_OK;
    if (tok->mType != Token::PARENT_OP &&
        tok->mType != Token::ANCESTOR_OP) {
        rv = createFilterOrStep(lexer, aContext, getter_Transfers(expr));
        NS_ENSURE_SUCCESS(rv, rv);

        // is this a singlestep path expression?
        tok = lexer.peek();
        if (tok->mType != Token::PARENT_OP &&
            tok->mType != Token::ANCESTOR_OP) {
            *aResult = expr.forget();
            return NS_OK;
        }
    }
    else {
        expr = new RootExpr();

#ifdef TX_TO_STRING
        static_cast<RootExpr*>(expr.get())->setSerialize(false);
#endif
    }
    
    // We have a PathExpr containing several steps
    nsAutoPtr<PathExpr> pathExpr(new PathExpr());

    rv = pathExpr->addExpr(expr, PathExpr::RELATIVE_OP);
    NS_ENSURE_SUCCESS(rv, rv);

    expr.forget();

    // this is ugly
    while (1) {
        PathExpr::PathOperator pathOp;
        switch (lexer.peek()->mType) {
            case Token::ANCESTOR_OP :
                pathOp = PathExpr::DESCENDANT_OP;
                break;
            case Token::PARENT_OP :
                pathOp = PathExpr::RELATIVE_OP;
                break;
            default:
                *aResult = pathExpr.forget();
                return NS_OK;
        }
        lexer.nextToken();

        rv = createLocationStep(lexer, aContext, getter_Transfers(expr));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = pathExpr->addExpr(expr, pathOp);
        NS_ENSURE_SUCCESS(rv, rv);

        expr.forget();
    }
    NS_NOTREACHED("internal xpath parser error");
    return NS_ERROR_UNEXPECTED;
}
int main()
{
    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj( new TestObject() );
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj( new TestObject() );
        printf("Should create one |TestObject| and then destroy one:\n");
        pobj = new TestObject();
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        nsAutoArrayPtr<TestObject> pobj( new TestObject[3] );
        printf("Should create 5 |TestObject|s and then destroy 3:\n");
        pobj = new TestObject[5];
        printf("Should destroy 5 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj( new TestRefObject() );
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj( new TestRefObject() );
        printf("Should create and AddRef one |TestRefObject| and then Release and destroy one:\n");
        pobj = new TestRefObject();
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        printf("Should AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> p2( p1 );
        printf("Should Release twice and destroy one |TestRefObject|:\n");
    }

    printf("\nTesting equality (with all const-ness combinations):\n");

    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        nsRefPtr<TestRefObject> p2( p1 );
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        nsRefPtr<TestRefObject> p2( p1 );
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2)) ? "OK" : "broken");
    }

    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const nsRefPtr<TestRefObject> p2( p1 );
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const nsRefPtr<TestRefObject> p2( p1 );
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2)) ? "OK" : "broken");
    }

    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        TestRefObject * p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        TestRefObject * p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

#if 0 /* MSVC++ 6.0 can't be coaxed to accept this */
    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        TestRefObject * const p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        TestRefObject * const p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }
#endif /* Things that MSVC++ 6.0 can't be coaxed to accept */

    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const TestRefObject * p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const TestRefObject * p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    {
        nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const TestRefObject * const p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    {
        const nsRefPtr<TestRefObject> p1( new TestRefObject() );
        const TestRefObject * const p2 = p1;
        printf("equality %s.\n",
               ((p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1)) ? "OK" : "broken");
    }

    printf("\nTesting getter_Transfers and getter_AddRefs.\n");

    {
        nsAutoPtr<TestObject> ptr;
        printf("Should create one |TestObject|:\n");
        CreateTestObject(getter_Transfers(ptr));
        printf("Should destroy one |TestObject|:\n");
    }

    {
        nsRefPtr<TestRefObject> ptr;
        printf("Should create and AddRef one |TestRefObject|:\n");
        CreateTestRefObject(getter_AddRefs(ptr));
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    printf("\nTesting casts and equality tests.\n");

    if ((void*)(TestObject*)0x1000 ==
        (void*)(TestObjectBaseB*)(TestObject*)0x1000)
        printf("\n\nAll these tests are meaningless!\n\n\n");

    {
        nsAutoPtr<TestObject> p1(new TestObject());
        TestObjectBaseB *p2 = p1;
        printf("equality %s.\n",
               ((static_cast<void*>(p1) != static_cast<void*>(p2)) &&
                (p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1))
               ? "OK" : "broken");
    }

    {
        TestObject *p1 = new TestObject();
        nsAutoPtr<TestObjectBaseB> p2(p1);
        printf("equality %s.\n",
               ((static_cast<void*>(p1) != static_cast<void*>(p2)) &&
                (p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1))
               ? "OK" : "broken");
    }

    {
        nsRefPtr<TestRefObject> p1 = new TestRefObject();
        // nsCOMPtr requires a |get| for something like this as well
        nsRefPtr<TestRefObjectBaseB> p2 = p1.get();
        printf("equality %s.\n",
               ((static_cast<void*>(p1) != static_cast<void*>(p2)) &&
                (p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1))
               ? "OK" : "broken");
    }

    {
        nsRefPtr<TestRefObject> p1 = new TestRefObject();
        TestRefObjectBaseB *p2 = p1;
        printf("equality %s.\n",
               ((static_cast<void*>(p1) != static_cast<void*>(p2)) &&
                (p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1))
               ? "OK" : "broken");
    }

    {
        TestRefObject *p1 = new TestRefObject();
        nsRefPtr<TestRefObjectBaseB> p2 = p1;
        printf("equality %s.\n",
               ((static_cast<void*>(p1) != static_cast<void*>(p2)) &&
                (p1 == p2) && !(p1 != p2) && (p2 == p1) && !(p2 != p1))
               ? "OK" : "broken");
    }

    printf("\nTesting |forget()|.\n");

    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj( new TestObject() );
        printf("Should do nothing:\n");
        nsAutoPtr<TestObject> pobj2( pobj.forget() );
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        nsAutoArrayPtr<TestObject> pobj( new TestObject[3] );
        printf("Should do nothing:\n");
        nsAutoArrayPtr<TestObject> pobj2( pobj.forget() );
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj( new TestRefObject() );
        printf("Should do nothing:\n");
        nsRefPtr<TestRefObject> pobj2( pobj.forget() );
        printf("Should destroy one |TestRefObject|:\n");
    }


    printf("\nTesting construction.\n");

    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj(new TestObject());
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        nsAutoArrayPtr<TestObject> pobj(new TestObject[3]);
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj = new TestRefObject();
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    printf("\nTesting calling of functions (including array access and casts).\n");

    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj(new TestObject());
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(pobj);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(pobj);
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        nsAutoArrayPtr<TestObject> pobj(new TestObject[3]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(&pobj[2]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(&pobj[1]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(pobj + 2);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(pobj + 1);
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj = new TestRefObject();
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithTestRefObject(pobj);
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithConstTestRefObject(pobj);
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    {
        printf("Should create one |TestObject|:\n");
        nsAutoPtr<TestObject> pobj(new TestObject());
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(pobj);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(pobj);
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        nsAutoArrayPtr<TestObject> pobj(new TestObject[3]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(&pobj[2]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(&pobj[1]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(pobj + 2);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(pobj + 1);
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        nsRefPtr<TestRefObject> pobj = new TestRefObject();
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithTestRefObjectBaseB(pobj);
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithConstTestRefObjectBaseB(pobj);
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    {
        printf("Should create one |TestObject|:\n");
        const nsAutoPtr<TestObject> pobj(new TestObject());
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(pobj);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(pobj);
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        const nsAutoArrayPtr<TestObject> pobj(new TestObject[3]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(&pobj[2]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(&pobj[1]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObject(pobj + 2);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObject(pobj + 1);
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        const nsRefPtr<TestRefObject> pobj = new TestRefObject();
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithTestRefObject(pobj);
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithConstTestRefObject(pobj);
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    {
        printf("Should create one |TestObject|:\n");
        const nsAutoPtr<TestObject> pobj(new TestObject());
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(pobj);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(pobj);
        printf("Should destroy one |TestObject|:\n");
    }

    {
        printf("Should create 3 |TestObject|s:\n");
        const nsAutoArrayPtr<TestObject> pobj(new TestObject[3]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(&pobj[2]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(&pobj[1]);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithTestObjectBaseB(pobj + 2);
        printf("Should do something with one |TestObject|:\n");
        DoSomethingWithConstTestObjectBaseB(pobj + 1);
        printf("Should destroy 3 |TestObject|s:\n");
    }

    {
        printf("Should create and AddRef one |TestRefObject|:\n");
        const nsRefPtr<TestRefObject> pobj = new TestRefObject();
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithTestRefObjectBaseB(pobj);
        printf("Should do something with one |TestRefObject|:\n");
        DoSomethingWithConstTestRefObjectBaseB(pobj);
        printf("Should Release and destroy one |TestRefObject|:\n");
    }

    return 0;
}
Beispiel #30
0
nsresult
txExprParser::createFilterOrStep(txExprLexer& lexer, txIParseContext* aContext,
                                 Expr** aResult)
{
    *aResult = nullptr;

    nsresult rv = NS_OK;
    Token* tok = lexer.peek();

    nsAutoPtr<Expr> expr;
    switch (tok->mType) {
        case Token::FUNCTION_NAME_AND_PAREN:
            rv = createFunctionCall(lexer, aContext, getter_Transfers(expr));
            NS_ENSURE_SUCCESS(rv, rv);
            break;
        case Token::VAR_REFERENCE :
            lexer.nextToken();
            {
                nsCOMPtr<nsIAtom> prefix, lName;
                int32_t nspace;
                nsresult rv = resolveQName(tok->Value(), getter_AddRefs(prefix),
                                           aContext, getter_AddRefs(lName),
                                           nspace);
                NS_ENSURE_SUCCESS(rv, rv);
                expr = new VariableRefExpr(prefix, lName, nspace);
            }
            break;
        case Token::L_PAREN:
            lexer.nextToken();
            rv = createExpr(lexer, aContext, getter_Transfers(expr));
            NS_ENSURE_SUCCESS(rv, rv);

            if (lexer.peek()->mType != Token::R_PAREN) {
                return NS_ERROR_XPATH_PAREN_EXPECTED;
            }
            lexer.nextToken();
            break;
        case Token::LITERAL :
            lexer.nextToken();
            expr = new txLiteralExpr(tok->Value());
            break;
        case Token::NUMBER:
        {
            lexer.nextToken();
            expr = new txLiteralExpr(txDouble::toDouble(tok->Value()));
            break;
        }
        default:
            return createLocationStep(lexer, aContext, aResult);
    }

    if (lexer.peek()->mType == Token::L_BRACKET) {
        nsAutoPtr<FilterExpr> filterExpr(new FilterExpr(expr));

        expr.forget();

        //-- handle predicates
        rv = parsePredicates(filterExpr, lexer, aContext);
        NS_ENSURE_SUCCESS(rv, rv);
        expr = filterExpr.forget();
    }

    *aResult = expr.forget();
    return NS_OK;
}