LCOV - code coverage report
Current view: top level - usr/local/src/libreoffice/include/formula - FormulaCompiler.hxx (source / functions) Hit Total Coverage
Test: libreoffice_filtered.info Lines: 42 54 77.8 %
Date: 2013-07-09 Functions: 19 24 79.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
       2             : /*
       3             :  * This file is part of the LibreOffice project.
       4             :  *
       5             :  * This Source Code Form is subject to the terms of the Mozilla Public
       6             :  * License, v. 2.0. If a copy of the MPL was not distributed with this
       7             :  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
       8             :  *
       9             :  * This file incorporates work covered by the following license notice:
      10             :  *
      11             :  *   Licensed to the Apache Software Foundation (ASF) under one or more
      12             :  *   contributor license agreements. See the NOTICE file distributed
      13             :  *   with this work for additional information regarding copyright
      14             :  *   ownership. The ASF licenses this file to you under the Apache
      15             :  *   License, Version 2.0 (the "License"); you may not use this file
      16             :  *   except in compliance with the License. You may obtain a copy of
      17             :  *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
      18             :  */
      19             : 
      20             : #ifndef FORMULA_COMPILER_HXX_INCLUDED
      21             : #define FORMULA_COMPILER_HXX_INCLUDED
      22             : 
      23             : #include "formula/formuladllapi.h"
      24             : #include <tools/string.hxx>
      25             : #include <tools/debug.hxx>
      26             : #include <rtl/ustrbuf.hxx>
      27             : 
      28             : #include <boost/shared_ptr.hpp>
      29             : #include <boost/unordered_map.hpp>
      30             : 
      31             : #include <com/sun/star/uno/Sequence.hxx>
      32             : 
      33             : #include "formula/opcode.hxx"
      34             : #include "formula/grammar.hxx"
      35             : #include "formula/token.hxx"
      36             : #include "formula/ExternalReferenceHelper.hxx"
      37             : 
      38             : 
      39             : #define FORMULA_MAXJUMPCOUNT    32  /* maximum number of jumps (ocChose) */
      40             : #define FORMULA_MAXTOKENS     8192  /* maximum number of tokens in formula */
      41             : 
      42             : 
      43             : namespace com { namespace sun { namespace star {
      44             :     namespace sheet {
      45             :         struct FormulaOpCodeMapEntry;
      46             :         struct FormulaToken;
      47             :     }
      48             : }}}
      49             : 
      50             : 
      51             : namespace formula
      52             : {
      53             :     class FormulaTokenArray;
      54             : 
      55             : struct FormulaArrayStack
      56             : {
      57             :     FormulaArrayStack*  pNext;
      58             :     FormulaTokenArray*  pArr;
      59             :     bool bTemp;
      60             : };
      61             : 
      62             : 
      63             : struct FORMULA_DLLPUBLIC StringHashCode
      64             : {
      65      146938 :     size_t operator()( const String& rStr ) const
      66             :     {
      67      146938 :         return rtl_ustr_hashCode_WithLength( rStr.GetBuffer(), rStr.Len() );
      68             :     }
      69             : };
      70             : 
      71             : typedef ::boost::unordered_map< String, OpCode, StringHashCode, ::std::equal_to< String > > OpCodeHashMap;
      72             : typedef ::boost::unordered_map< String, String, StringHashCode, ::std::equal_to< String > > ExternalHashMap;
      73             : 
      74             : class FORMULA_DLLPUBLIC FormulaCompiler
      75             : {
      76             : public:
      77             :     FormulaCompiler();
      78             :     FormulaCompiler(FormulaTokenArray& _rArr);
      79             :     virtual ~FormulaCompiler();
      80             : 
      81             :     // SUNWS8 needs a forward declared friend, otherwise members of the outer
      82             :     // class are not accessible.
      83             :     class OpCodeMap;
      84             :     friend class FormulaCompiler::OpCodeMap;
      85             : 
      86             :     /** Mappings from strings to OpCodes and vice versa. */
      87             :     class FORMULA_DLLPUBLIC OpCodeMap
      88             :     {
      89             :         OpCodeHashMap         * mpHashMap;                 /// Hash map of symbols, String -> OpCode
      90             :         String              *   mpTable;                   /// Array of symbols, OpCode -> String, offset==OpCode
      91             :         ExternalHashMap       * mpExternalHashMap;         /// Hash map of ocExternal, Filter String -> AddIn String
      92             :         ExternalHashMap       * mpReverseExternalHashMap;  /// Hash map of ocExternal, AddIn String -> Filter String
      93             :         FormulaGrammar::Grammar meGrammar;                  /// Grammar, language and reference convention
      94             :         sal_uInt16                  mnSymbols;                  /// Count of OpCode symbols
      95             :         bool                    mbCore      : 1;            /// If mapping was setup by core, not filters
      96             :         bool                    mbEnglish   : 1;            /// If English symbols and external names
      97             : 
      98             :         OpCodeMap();                              // prevent usage
      99             :         OpCodeMap( const OpCodeMap& );            // prevent usage
     100             :         OpCodeMap& operator=( const OpCodeMap& ); // prevent usage
     101             : 
     102             :     public:
     103             : 
     104         374 :         OpCodeMap(sal_uInt16 nSymbols, bool bCore, FormulaGrammar::Grammar eGrammar ) :
     105         374 :             mpHashMap( new OpCodeHashMap( nSymbols)),
     106         748 :             mpTable( new String[ nSymbols ]),
     107         374 :             mpExternalHashMap( new ExternalHashMap),
     108         374 :             mpReverseExternalHashMap( new ExternalHashMap),
     109             :             meGrammar( eGrammar),
     110             :             mnSymbols( nSymbols),
     111        2244 :             mbCore( bCore)
     112             :         {
     113         374 :             mbEnglish = FormulaGrammar::isEnglish( meGrammar);
     114         374 :         }
     115             :         virtual ~OpCodeMap();
     116             : 
     117             :         void copyFrom( const OpCodeMap& r );
     118             : 
     119             :         /// Get the symbol String -> OpCode hash map for finds.
     120       10794 :         inline const OpCodeHashMap* getHashMap() const { return mpHashMap; }
     121             : 
     122             :         /// Get the symbol String -> AddIn String hash map for finds.
     123          80 :         inline const ExternalHashMap* getExternalHashMap() const { return mpExternalHashMap; }
     124             : 
     125             :         /// Get the AddIn String -> symbol String hash map for finds.
     126           0 :         inline const ExternalHashMap* getReverseExternalHashMap() const { return mpReverseExternalHashMap; }
     127             : 
     128             :         /// Get the symbol string matching an OpCode.
     129       87941 :         inline const String& getSymbol( const OpCode eOp ) const
     130             :         {
     131             :             DBG_ASSERT( sal_uInt16(eOp) < mnSymbols, "OpCodeMap::getSymbol: OpCode out of range");
     132       87941 :             if (sal_uInt16(eOp) < mnSymbols)
     133       87941 :                 return mpTable[ eOp ];
     134           0 :             static String s_sEmpty;
     135           0 :             return s_sEmpty;
     136             :         }
     137             : 
     138             :         /// Get the grammar.
     139       32902 :         inline FormulaGrammar::Grammar getGrammar() const { return meGrammar; }
     140             : 
     141             :         /// Get the symbol count.
     142       25164 :         inline sal_uInt16 getSymbolCount() const { return mnSymbols; }
     143             : 
     144             :         /** Are these English symbols, as opposed to native language (which may
     145             :             be English as well)? */
     146       50907 :         inline bool isEnglish() const { return mbEnglish; }
     147             : 
     148             :         /// Is it an internal core mapping, or setup by filters?
     149             :         inline bool isCore() const { return mbCore; }
     150             : 
     151             :         /// Is it an ODF 1.1 compatibility mapping?
     152           0 :         inline bool isPODF() const { return FormulaGrammar::isPODF( meGrammar); }
     153             : 
     154             :         /// Is it an ODFF / ODF 1.2 mapping?
     155        2142 :         inline bool isODFF() const { return FormulaGrammar::isODFF( meGrammar); }
     156             : 
     157             :         /// Does it have external symbol/name mappings?
     158        2165 :         inline bool hasExternals() const { return !mpExternalHashMap->empty(); }
     159             : 
     160             :         /// Put entry of symbol String and OpCode pair.
     161             :         void putOpCode( const String & rStr, const OpCode eOp );
     162             : 
     163             :         /// Put entry of symbol String and AddIn international String pair.
     164             :         void putExternal( const String & rSymbol, const String & rAddIn );
     165             : 
     166             :         /** Put entry of symbol String and AddIn international String pair,
     167             :             failing silently if rAddIn name already exists. */
     168             :         void putExternalSoftly( const String & rSymbol, const String & rAddIn );
     169             : 
     170             :         /// Core implementation of XFormulaOpCodeMapper::getMappings()
     171             :         ::com::sun::star::uno::Sequence< ::com::sun::star::sheet::FormulaToken >
     172             :             createSequenceOfFormulaTokens(const FormulaCompiler& _rCompiler,
     173             :                     const ::com::sun::star::uno::Sequence< OUString >& rNames ) const;
     174             : 
     175             :         /// Core implementation of XFormulaOpCodeMapper::getAvailableMappings()
     176             :         ::com::sun::star::uno::Sequence<
     177             :             ::com::sun::star::sheet::FormulaOpCodeMapEntry >
     178             :             createSequenceOfAvailableMappings( const FormulaCompiler& _rCompiler,const sal_Int32 nGroup ) const;
     179             : 
     180             :         /** The value used in createSequenceOfAvailableMappings() and thus in
     181             :             XFormulaOpCodeMapper::getMappings() for an unknown symbol. */
     182             :         static sal_Int32 getOpCodeUnknown();
     183             :     };
     184             : 
     185             : public:
     186             :     typedef ::boost::shared_ptr< const OpCodeMap >  OpCodeMapPtr;
     187             :     typedef ::boost::shared_ptr< OpCodeMap >        NonConstOpCodeMapPtr;
     188             : 
     189             :     /** Get OpCodeMap for formula language.
     190             :         @param nLanguage
     191             :             One of ::com::sun::star::sheet::FormulaLanguage constants.
     192             :         @return Map for nLanguage. If nLanguage is unknown, a NULL map is returned.
     193             :      */
     194             :     OpCodeMapPtr GetOpCodeMap( const sal_Int32 nLanguage ) const;
     195             : 
     196             :     /** Create an internal symbol map from API mapping.
     197             :         @param bEnglish
     198             :             Use English number parser / formatter instead of native.
     199             :      */
     200             :     OpCodeMapPtr CreateOpCodeMap(
     201             :             const ::com::sun::star::uno::Sequence<
     202             :             const ::com::sun::star::sheet::FormulaOpCodeMapEntry > & rMapping,
     203             :             bool bEnglish );
     204             : 
     205             :     /** Get current OpCodeMap in effect. */
     206           0 :     inline OpCodeMapPtr GetCurrentOpCodeMap() const { return mxSymbols; }
     207             : 
     208             :     /** Get OpCode for English symbol.
     209             :         Used in XFunctionAccess to create token array.
     210             :         @param rName
     211             :             Symbol to lookup. MUST be upper case.
     212             :      */
     213             :     OpCode GetEnglishOpCode( const String& rName ) const;
     214             : 
     215             :     sal_uInt16 GetErrorConstant( const String& rName ) const;
     216             : 
     217          59 :     void            SetCompileForFAP( bool bVal )
     218          59 :                         { bCompileForFAP = bVal; bIgnoreErrors = bVal; }
     219             : 
     220             :     static bool IsOpCodeVolatile( OpCode eOp );
     221             : 
     222             :     static bool DeQuote( String& rStr );
     223             : 
     224             : 
     225             :     static const String&    GetNativeSymbol( OpCode eOp );
     226             :     static  bool            IsMatrixFunction(OpCode _eOpCode);   // if a function _always_ returns a Matrix
     227             : 
     228        4999 :     short GetNumFormatType() const { return nNumFmt; }
     229             :     bool  CompileTokenArray();
     230             : 
     231             :     void CreateStringFromTokenArray( String& rFormula );
     232             :     void CreateStringFromTokenArray( OUStringBuffer& rBuffer );
     233             :     FormulaToken* CreateStringFromToken( String& rFormula, FormulaToken* pToken,
     234             :                                     bool bAllowArrAdvance = false );
     235             :     FormulaToken* CreateStringFromToken( OUStringBuffer& rBuffer, FormulaToken* pToken,
     236             :                                     bool bAllowArrAdvance = false );
     237             : 
     238             :     void AppendBoolean( OUStringBuffer& rBuffer, bool bVal );
     239             :     void AppendDouble( OUStringBuffer& rBuffer, double fVal );
     240             :     void AppendString( OUStringBuffer& rBuffer, const String & rStr );
     241             : 
     242             :     /** Set symbol map corresponding to one of predefined formula::FormulaGrammar::Grammar,
     243             :         including an address reference convention. */
     244      132360 :     inline  FormulaGrammar::Grammar   GetGrammar() const { return meGrammar; }
     245             : 
     246             :     static void UpdateSeparatorsNative( const OUString& rSep, const OUString& rArrayColSep, const OUString& rArrayRowSep );
     247             :     static void ResetNativeSymbols();
     248             :     static void SetNativeSymbols( const OpCodeMapPtr& xMap );
     249             : protected:
     250             :     virtual String FindAddInFunction( const String& rUpperName, bool bLocalFirst ) const;
     251             :     virtual void fillFromAddInCollectionUpperName( NonConstOpCodeMapPtr xMap ) const;
     252             :     virtual void fillFromAddInMap( NonConstOpCodeMapPtr xMap, FormulaGrammar::Grammar _eGrammar ) const;
     253             :     virtual void fillFromAddInCollectionEnglishName( NonConstOpCodeMapPtr xMap ) const;
     254             :     virtual void fillAddInToken(::std::vector< ::com::sun::star::sheet::FormulaOpCodeMapEntry >& _rVec,bool _bIsEnglish) const;
     255             : 
     256             :     virtual void SetError(sal_uInt16 nError);
     257             :     virtual FormulaTokenRef ExtendRangeReference( FormulaToken & rTok1, FormulaToken & rTok2, bool bReuseDoubleRef );
     258             :     virtual bool HandleExternalReference(const FormulaToken& _aToken);
     259             :     virtual bool HandleRange();
     260             :     virtual bool HandleSingleRef();
     261             :     virtual bool HandleDbData();
     262             : 
     263             :     virtual void CreateStringFromExternal(OUStringBuffer& rBuffer, FormulaToken* pTokenP);
     264             :     virtual void CreateStringFromSingleRef(OUStringBuffer& rBuffer,FormulaToken* pTokenP);
     265             :     virtual void CreateStringFromDoubleRef(OUStringBuffer& rBuffer,FormulaToken* pTokenP);
     266             :     virtual void CreateStringFromMatrix(OUStringBuffer& rBuffer,FormulaToken* pTokenP);
     267             :     virtual void CreateStringFromIndex(OUStringBuffer& rBuffer,FormulaToken* pTokenP);
     268             :     virtual void LocalizeString( String& rName );   // modify rName - input: exact name
     269             : 
     270             :     void AppendErrorConstant( OUStringBuffer& rBuffer, sal_uInt16 nError );
     271             : 
     272             :     bool   GetToken();
     273             :     OpCode NextToken();
     274             :     void PutCode( FormulaTokenRef& );
     275             :     void Factor();
     276             :     void RangeLine();
     277             :     void UnionLine();
     278             :     void IntersectionLine();
     279             :     void UnaryLine();
     280             :     void PostOpLine();
     281             :     void PowLine();
     282             :     void MulDivLine();
     283             :     void AddSubLine();
     284             :     void ConcatLine();
     285             :     void CompareLine();
     286             :     void NotLine();
     287             :     OpCode Expression();
     288             :     void PopTokenArray();
     289             :     void PushTokenArray( FormulaTokenArray*, bool = false );
     290             : 
     291             :     bool MergeRangeReference( FormulaToken * * const pCode1, FormulaToken * const * const pCode2 );
     292             : 
     293             :     String              aCorrectedFormula;      // autocorrected Formula
     294             :     String              aCorrectedSymbol;       // autocorrected Symbol
     295             : 
     296             :     OpCodeMapPtr        mxSymbols;              // which symbols are used
     297             : 
     298             :     FormulaTokenRef     mpToken;                // current token
     299             :     FormulaTokenRef     pCurrentFactorToken;    // current factor token (of Factor() method)
     300             :     FormulaTokenArray*  pArr;
     301             :     ExternalReferenceHelper* pExternalRef;
     302             : 
     303             :     FormulaToken**      pCode;
     304             :     FormulaArrayStack*  pStack;
     305             : 
     306             :     OpCode              eLastOp;
     307             :     short               nRecursion;             // GetToken() recursions
     308             :     short               nNumFmt;                // set during CompileTokenArray()
     309             :     sal_uInt16          pc;                     // program counter
     310             : 
     311             :     FormulaGrammar::Grammar meGrammar;          // The grammar used, language plus convention.
     312             : 
     313             :     bool                bAutoCorrect;           // whether to apply AutoCorrection
     314             :     bool                bCorrected;             // AutoCorrection was applied
     315             :     bool                bCompileForFAP;         //! not real RPN but names, for FunctionAutoPilot
     316             :                                                 // will not be resolved
     317             :     bool                bIgnoreErrors;          // on AutoCorrect and CompileForFAP
     318             :                                                 // ignore errors and create RPN nevertheless
     319             :     bool                glSubTotal;             // if code contains one or more subtotal functions
     320             : private:
     321             :     void InitSymbolsNative() const;    /// only SymbolsNative, on first document creation
     322             :     void InitSymbolsEnglish() const;   /// only SymbolsEnglish, maybe later
     323             :     void InitSymbolsPODF() const;      /// only SymbolsPODF, on demand
     324             :     void InitSymbolsODFF() const;      /// only SymbolsODFF, on demand
     325             :     void InitSymbolsEnglishXL() const; /// only SymbolsEnglishXL, on demand
     326             : 
     327             :     void loadSymbols(sal_uInt16 _nSymbols,FormulaGrammar::Grammar _eGrammar,NonConstOpCodeMapPtr& _xMap) const;
     328             : 
     329       26626 :     static inline void ForceArrayOperator( FormulaTokenRef& rCurr, const FormulaTokenRef& rPrev )
     330             :         {
     331       64289 :             if ( rPrev && rPrev->HasForceArray() &&
     332           3 :                     rCurr->GetType() == svByte && rCurr->GetOpCode() != ocPush
     333       26627 :                     && !rCurr->HasForceArray() )
     334           0 :                 rCurr->SetForceArray( true);
     335       26626 :         }
     336             : 
     337             :     // SUNWS7 needs a forward declared friend, otherwise members of the outer
     338             :     // class are not accessible.
     339             :     class CurrentFactor;
     340             :     friend class FormulaCompiler::CurrentFactor;
     341             :     class CurrentFactor
     342             :     {
     343             :         FormulaTokenRef  pPrevFac;
     344             :         FormulaCompiler* pCompiler;
     345             :         // not implemented
     346             :         CurrentFactor( const CurrentFactor& );
     347             :         CurrentFactor& operator=( const CurrentFactor& );
     348             :     public:
     349       18574 :         explicit CurrentFactor( FormulaCompiler* pComp )
     350             :             : pPrevFac( pComp->pCurrentFactorToken )
     351       18574 :             , pCompiler( pComp )
     352       18574 :             {}
     353       18574 :         ~CurrentFactor()
     354       18574 :             { pCompiler->pCurrentFactorToken = pPrevFac; }
     355             :         // yes, this operator= may modify the RValue
     356        3808 :         void operator=( FormulaTokenRef& r )
     357             :             {
     358        3808 :                 ForceArrayOperator( r, pPrevFac);
     359        3808 :                 pCompiler->pCurrentFactorToken = r;
     360        3808 :             }
     361           0 :         void operator=( FormulaToken* p )
     362             :             {
     363           0 :                 FormulaTokenRef xTemp( p );
     364           0 :                 *this = xTemp;
     365           0 :             }
     366        3808 :         operator FormulaTokenRef&()
     367        3808 :             { return pCompiler->pCurrentFactorToken; }
     368        3959 :         FormulaToken* operator->()
     369        3959 :             { return pCompiler->pCurrentFactorToken.operator->(); }
     370           0 :         operator FormulaToken*()
     371           0 :             { return operator->(); }
     372             :     };
     373             : 
     374             : 
     375             :     mutable NonConstOpCodeMapPtr  mxSymbolsODFF;                          // ODFF symbols
     376             :     mutable NonConstOpCodeMapPtr  mxSymbolsPODF;                          // ODF 1.1 symbols
     377             :     mutable NonConstOpCodeMapPtr  mxSymbolsNative;                        // native symbols
     378             :     mutable NonConstOpCodeMapPtr  mxSymbolsEnglish;                       // English symbols
     379             :     mutable NonConstOpCodeMapPtr  mxSymbolsEnglishXL;                     // English Excel symbols (for VBA formula parsing)
     380             : };
     381             : // =============================================================================
     382             : } // formula
     383             : // =============================================================================
     384             : 
     385             : #endif // FORMULA_COMPILER_HXX_INCLUDED
     386             : 
     387             : 
     388             : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */

Generated by: LCOV version 1.10