xref: /trunk/main/formula/source/core/api/FormulaCompiler.cxx (revision 195598447694ec8542914a9b51ae9942e8ebacd9) !
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 #include "precompiled_formula.hxx"
24 #include "formula/FormulaCompiler.hxx"
25 #include "formula/errorcodes.hxx"
26 #include "formula/token.hxx"
27 #include "formula/tokenarray.hxx"
28 #include "core_resource.hxx"
29 #include "core_resource.hrc"
30 
31 #include <svl/zforlist.hxx>
32 #include <tools/rc.hxx>
33 #include <tools/rcid.h>
34 #include <com/sun/star/sheet/FormulaOpCodeMapEntry.hpp>
35 #include <com/sun/star/sheet/FormulaMapGroup.hpp>
36 #include <com/sun/star/sheet/FormulaMapGroupSpecialOffset.hpp>
37 #include <stdio.h>
38 
39 // =============================================================================
40 namespace formula
41 {
42 // =============================================================================
43     using namespace ::com::sun::star;
44 
45     static const sal_Char* pInternal[ 1 ] = { "TTT" };
46 
47 // =============================================================================
48 namespace
49 {
50 // =============================================================================
51 class FormulaCompilerRecursionGuard
52 {
53 private:
54             short&              rRecursion;
55 public:
FormulaCompilerRecursionGuard(short & rRec)56                                 FormulaCompilerRecursionGuard( short& rRec )
57                                     : rRecursion( rRec ) { ++rRecursion; }
~FormulaCompilerRecursionGuard()58                                 ~FormulaCompilerRecursionGuard() { --rRecursion; }
59 };
60 
lcl_GetRetFormat(OpCode eOpCode)61 short lcl_GetRetFormat( OpCode eOpCode )
62 {
63     switch (eOpCode)
64     {
65         case ocEqual:
66         case ocNotEqual:
67         case ocLess:
68         case ocGreater:
69         case ocLessEqual:
70         case ocGreaterEqual:
71         case ocAnd:
72         case ocOr:
73         case ocNot:
74         case ocTrue:
75         case ocFalse:
76         case ocIsEmpty:
77         case ocIsString:
78         case ocIsNonString:
79         case ocIsLogical:
80         case ocIsRef:
81         case ocIsValue:
82         case ocIsFormula:
83         case ocIsNA:
84         case ocIsErr:
85         case ocIsError:
86         case ocIsEven:
87         case ocIsOdd:
88         case ocExact:
89             return NUMBERFORMAT_LOGICAL;
90         case ocGetActDate:
91         case ocGetDate:
92         case ocEasterSunday :
93             return NUMBERFORMAT_DATE;
94         case ocGetActTime:
95             return NUMBERFORMAT_DATETIME;
96         case ocGetTime:
97             return NUMBERFORMAT_TIME;
98         case ocNPV:
99         case ocBW:
100         case ocDIA:
101         case ocGDA:
102         case ocGDA2:
103         case ocVBD:
104         case ocLIA:
105         case ocRMZ:
106         case ocZW:
107         case ocZinsZ:
108         case ocKapz:
109         case ocKumZinsZ:
110         case ocKumKapZ:
111             return NUMBERFORMAT_CURRENCY;
112         case ocZins:
113         case ocIRR:
114         case ocMIRR:
115         case ocZGZ:
116         case ocEffektiv:
117         case ocNominal:
118         case ocPercentSign:
119             return NUMBERFORMAT_PERCENT;
120 //      case ocSum:
121 //      case ocSumSQ:
122 //      case ocProduct:
123 //      case ocAverage:
124 //          return -1;
125         default:
126             return NUMBERFORMAT_NUMBER;
127     }
128     return NUMBERFORMAT_NUMBER;
129 }
130 
lclPushOpCodeMapEntry(::std::vector<sheet::FormulaOpCodeMapEntry> & rVec,const String * pTable,sal_uInt16 nOpCode)131 inline void lclPushOpCodeMapEntry( ::std::vector< sheet::FormulaOpCodeMapEntry >& rVec, const String* pTable, sal_uInt16 nOpCode )
132 {
133     sheet::FormulaOpCodeMapEntry aEntry;
134     aEntry.Token.OpCode = nOpCode;
135     aEntry.Name = pTable[nOpCode];
136     rVec.push_back( aEntry);
137 }
138 
lclPushOpCodeMapEntries(::std::vector<sheet::FormulaOpCodeMapEntry> & rVec,const String * pTable,sal_uInt16 nOpCodeBeg,sal_uInt16 nOpCodeEnd)139 void lclPushOpCodeMapEntries( ::std::vector< sheet::FormulaOpCodeMapEntry >& rVec, const String* pTable, sal_uInt16 nOpCodeBeg, sal_uInt16 nOpCodeEnd )
140 {
141     for (sal_uInt16 nOpCode = nOpCodeBeg; nOpCode < nOpCodeEnd; ++nOpCode)
142         lclPushOpCodeMapEntry( rVec, pTable, nOpCode );
143 }
144 
lclPushOpCodeMapEntries(::std::vector<sheet::FormulaOpCodeMapEntry> & rVec,const String * pTable,const sal_uInt16 * pnOpCodes,size_t nCount)145 void lclPushOpCodeMapEntries( ::std::vector< sheet::FormulaOpCodeMapEntry >& rVec, const String* pTable, const sal_uInt16* pnOpCodes, size_t nCount )
146 {
147     for (const sal_uInt16* pnEnd = pnOpCodes + nCount; pnOpCodes < pnEnd; ++pnOpCodes)
148         lclPushOpCodeMapEntry( rVec, pTable, *pnOpCodes );
149 }
150 
151 class OpCodeList : public Resource        // temp object for resource
152 {
153 public:
154 
155     OpCodeList( sal_uInt16, FormulaCompiler::NonConstOpCodeMapPtr );
156 
157 private:
158     bool getOpCodeString( String& rStr, sal_uInt16 nOp );
159     void putDefaultOpCode( FormulaCompiler::NonConstOpCodeMapPtr xMap, sal_uInt16 nOp );
160 
161 private:
162     enum SeparatorType
163     {
164         SEMICOLON_BASE,
165         COMMA_BASE
166     };
167     SeparatorType meSepType;
168 };
169 
OpCodeList(sal_uInt16 nRID,FormulaCompiler::NonConstOpCodeMapPtr xMap)170 OpCodeList::OpCodeList( sal_uInt16 nRID, FormulaCompiler::NonConstOpCodeMapPtr xMap ) :
171     Resource( ResId(nRID,*ResourceManager::getResManager()) )
172     ,meSepType(SEMICOLON_BASE)
173 {
174      for (sal_uInt16 i = 0; i <= SC_OPCODE_LAST_OPCODE_ID; ++i)
175     {
176         String aOpStr;
177         if ( getOpCodeString(aOpStr, i) )
178             xMap->putOpCode(aOpStr, OpCode(i));
179         else
180             putDefaultOpCode(xMap, i);
181     }
182 
183     FreeResource();
184 }
185 
getOpCodeString(String & rStr,sal_uInt16 nOp)186 bool OpCodeList::getOpCodeString( String& rStr, sal_uInt16 nOp )
187 {
188     switch (nOp)
189     {
190         case SC_OPCODE_SEP:
191         {
192             if (meSepType == COMMA_BASE)
193             {
194                 rStr = String::CreateFromAscii(",");
195                 return true;
196             }
197             else if (meSepType == SEMICOLON_BASE)
198             {
199                 rStr = String::CreateFromAscii(";");
200                 return true;
201             }
202         }
203         break;
204         case SC_OPCODE_ARRAY_COL_SEP:
205         {
206             if (meSepType == COMMA_BASE)
207             {
208                 rStr = String::CreateFromAscii(",");
209                 return true;
210             }
211             else if (meSepType == SEMICOLON_BASE)
212             {
213                 rStr = String::CreateFromAscii(";");
214                 return true;
215             }
216         }
217         break;
218         case SC_OPCODE_ARRAY_ROW_SEP:
219         {
220             if (meSepType == COMMA_BASE)
221             {
222                 rStr = String::CreateFromAscii(";");
223                 return true;
224             }
225             else if (meSepType == SEMICOLON_BASE)
226             {
227                 rStr = String::CreateFromAscii("|");
228                 return true;
229             }
230         }
231         break;
232     }
233 
234     return false;
235 }
236 
putDefaultOpCode(FormulaCompiler::NonConstOpCodeMapPtr xMap,sal_uInt16 nOp)237 void OpCodeList::putDefaultOpCode( FormulaCompiler::NonConstOpCodeMapPtr xMap, sal_uInt16 nOp )
238 {
239     ResId aRes(nOp,*ResourceManager::getResManager());
240     aRes.SetRT(RSC_STRING);
241     if (IsAvailableRes(aRes))
242         xMap->putOpCode(aRes, OpCode(nOp));
243 }
244 // -----------------------------------------------------------------------------
245 // static
lcl_UnicodeStrChr(const sal_Unicode * pStr,sal_Unicode c)246 const sal_Unicode* lcl_UnicodeStrChr( const sal_Unicode* pStr,sal_Unicode c )
247 {
248     if ( !pStr )
249         return NULL;
250     while ( *pStr )
251     {
252         if ( *pStr == c )
253             return pStr;
254         pStr++;
255     }
256     return NULL;
257 }
258 // =============================================================================
259 } // empty
260 // =============================================================================
261 
putExternal(const String & rSymbol,const String & rAddIn)262 void FormulaCompiler::OpCodeMap::putExternal( const String & rSymbol, const String & rAddIn )
263 {
264     bool bOk = mpExternalHashMap->insert( ExternalHashMap::value_type( rSymbol, rAddIn)).second;
265     if (bOk)
266         bOk = mpReverseExternalHashMap->insert( ExternalHashMap::value_type( rAddIn, rSymbol)).second;
267     DBG_ASSERT( bOk, "OpCodeMap::putExternal: symbol not inserted");
268 }
269 
putExternalSoftly(const String & rSymbol,const String & rAddIn)270 void FormulaCompiler::OpCodeMap::putExternalSoftly( const String & rSymbol, const String & rAddIn )
271 {
272     bool bOk = mpReverseExternalHashMap->insert( ExternalHashMap::value_type( rAddIn, rSymbol)).second;
273     if (bOk)
274         mpExternalHashMap->insert( ExternalHashMap::value_type( rSymbol, rAddIn)).second;
275 }
createSequenceOfFormulaTokens(const FormulaCompiler & _rCompiler,const uno::Sequence<::rtl::OUString> & rNames) const276 uno::Sequence< sheet::FormulaToken > FormulaCompiler::OpCodeMap::createSequenceOfFormulaTokens(const FormulaCompiler& _rCompiler,const uno::Sequence< ::rtl::OUString >& rNames ) const
277 {
278     const sal_Int32 nLen = rNames.getLength();
279     uno::Sequence< sheet::FormulaToken > aTokens( nLen);
280     sheet::FormulaToken* pToken = aTokens.getArray();
281     ::rtl::OUString const * pName = rNames.getConstArray();
282     ::rtl::OUString const * const pStop = pName + nLen;
283     for ( ; pName < pStop; ++pName, ++pToken)
284     {
285         OpCodeHashMap::const_iterator iLook( mpHashMap->find( *pName));
286         if (iLook != mpHashMap->end())
287             pToken->OpCode = (*iLook).second;
288         else
289         {
290             ::rtl::OUString aIntName;
291             if (hasExternals())
292             {
293                 ExternalHashMap::const_iterator iExt( mpExternalHashMap->find( *pName));
294                 if (iExt != mpExternalHashMap->end())
295                     aIntName = (*iExt).second;
296                 // Check for existence not needed here, only name-mapping is of
297                 // interest.
298             }
299             if (!aIntName.getLength())
300                 aIntName = _rCompiler.FindAddInFunction(*pName, !isEnglish());    // bLocalFirst=sal_False for english
301             if (!aIntName.getLength())
302                 pToken->OpCode = getOpCodeUnknown();
303             else
304             {
305                 pToken->OpCode = ocExternal;
306                 pToken->Data <<= aIntName;
307             }
308         }
309     }
310     return aTokens;
311 }
createSequenceOfAvailableMappings(const FormulaCompiler & _rCompiler,const sal_Int32 nGroups) const312 uno::Sequence< sheet::FormulaOpCodeMapEntry > FormulaCompiler::OpCodeMap::createSequenceOfAvailableMappings(const FormulaCompiler& _rCompiler,const sal_Int32 nGroups ) const
313 {
314     using namespace sheet;
315 
316     // Unfortunately uno::Sequence can't grow without cumbersome reallocs. As
317     // we don't know in advance how many elements it will have we use a
318     // temporary vector to add elements and then copy to Sequence :-(
319     ::std::vector< FormulaOpCodeMapEntry > aVec;
320 
321     if (nGroups == FormulaMapGroup::SPECIAL)
322     {
323         // Use specific order, keep in sync with
324         // offapi/com/sun/star/sheet/FormulaMapGroupSpecialOffset.idl
325         static const struct
326         {
327             sal_Int32 nOff;
328             OpCode    eOp;
329         } aMap[] = {
330             { FormulaMapGroupSpecialOffset::PUSH              , ocPush }           ,
331             { FormulaMapGroupSpecialOffset::CALL              , ocCall }           ,
332             { FormulaMapGroupSpecialOffset::STOP              , ocStop }           ,
333             { FormulaMapGroupSpecialOffset::EXTERNAL          , ocExternal }       ,
334             { FormulaMapGroupSpecialOffset::NAME              , ocName }           ,
335             { FormulaMapGroupSpecialOffset::NO_NAME           , ocNoName }         ,
336             { FormulaMapGroupSpecialOffset::MISSING           , ocMissing }        ,
337             { FormulaMapGroupSpecialOffset::BAD               , ocBad }            ,
338             { FormulaMapGroupSpecialOffset::SPACES            , ocSpaces }         ,
339             { FormulaMapGroupSpecialOffset::MAT_REF           , ocMatRef }         ,
340             { FormulaMapGroupSpecialOffset::DB_AREA           , ocDBArea }         ,
341             { FormulaMapGroupSpecialOffset::MACRO             , ocMacro }          ,
342             { FormulaMapGroupSpecialOffset::COL_ROW_NAME      , ocColRowName }
343         };
344         const size_t nCount = sizeof(aMap)/sizeof(aMap[0]);
345         // Preallocate vector elements.
346         if (aVec.size() < nCount)
347         {
348             FormulaOpCodeMapEntry aEntry;
349             aEntry.Token.OpCode = getOpCodeUnknown();
350             aVec.resize( nCount, aEntry);
351         } // if (aVec.size() < nCount)
352 
353         FormulaOpCodeMapEntry aEntry;
354         for (size_t i=0; i < nCount; ++i)
355         {
356             size_t nIndex = static_cast< size_t >( aMap[i].nOff );
357             if (aVec.size() <= nIndex)
358             {
359                 // The offsets really should be aligned with the size, so if
360                 // the vector was preallocated above this code to resize it is
361                 // just a measure in case the table isn't in sync with the API,
362                 // usually it isn't executed.
363                 aEntry.Token.OpCode = getOpCodeUnknown();
364                 aVec.resize( nIndex + 1, aEntry );
365             }
366             aEntry.Token.OpCode = aMap[i].eOp;
367             aVec[nIndex] = aEntry;
368         }
369     }
370     else
371     {
372         /* FIXME: Once we support error constants in formulas we'll need a map
373          * group for that, e.g. FormulaMapGroup::ERROR_CONSTANTS, and fill
374          * SC_OPCODE_START_ERRORS to SC_OPCODE_STOP_ERRORS. */
375 
376         // Anything else but SPECIAL.
377         if ((nGroups & FormulaMapGroup::SEPARATORS) != 0)
378         {
379             static const sal_uInt16 aOpCodes[] = {
380                 SC_OPCODE_OPEN,
381                 SC_OPCODE_CLOSE,
382                 SC_OPCODE_SEP,
383             };
384             lclPushOpCodeMapEntries( aVec, mpTable, aOpCodes, sizeof(aOpCodes)/sizeof(aOpCodes[0]) );
385         }
386         if ((nGroups & FormulaMapGroup::ARRAY_SEPARATORS) != 0)
387         {
388             static const sal_uInt16 aOpCodes[] = {
389                 SC_OPCODE_ARRAY_OPEN,
390                 SC_OPCODE_ARRAY_CLOSE,
391                 SC_OPCODE_ARRAY_ROW_SEP,
392                 SC_OPCODE_ARRAY_COL_SEP
393             };
394             lclPushOpCodeMapEntries( aVec, mpTable, aOpCodes, sizeof(aOpCodes)/sizeof(aOpCodes[0]) );
395         }
396         if ((nGroups & FormulaMapGroup::UNARY_OPERATORS) != 0)
397         {
398             // Due to the nature of the percent operator following its operand
399             // it isn't sorted into unary operators for compiler interna.
400             lclPushOpCodeMapEntry( aVec, mpTable, ocPercentSign );
401             // "+" can be used as unary operator too, push only if binary group is not set
402             if ((nGroups & FormulaMapGroup::BINARY_OPERATORS) == 0)
403                 lclPushOpCodeMapEntry( aVec, mpTable, ocAdd );
404             // regular unary operators
405             for (sal_uInt16 nOp = SC_OPCODE_START_UN_OP; nOp < SC_OPCODE_STOP_UN_OP && nOp < mnSymbols; ++nOp)
406             {
407                 switch (nOp)
408                 {
409                     // NOT and NEG in fact are functions but for legacy reasons
410                     // are sorted into unary operators for compiler interna.
411                     case SC_OPCODE_NOT :
412                     case SC_OPCODE_NEG :
413                         break;   // nothing,
414                     default:
415                         lclPushOpCodeMapEntry( aVec, mpTable, nOp );
416                 }
417             }
418         }
419         if ((nGroups & FormulaMapGroup::BINARY_OPERATORS) != 0)
420         {
421             for (sal_uInt16 nOp = SC_OPCODE_START_BIN_OP; nOp < SC_OPCODE_STOP_BIN_OP && nOp < mnSymbols; ++nOp)
422             {
423                 switch (nOp)
424                 {
425                     // AND and OR in fact are functions but for legacy reasons
426                     // are sorted into binary operators for compiler interna.
427                     case SC_OPCODE_AND :
428                     case SC_OPCODE_OR :
429                         break;   // nothing,
430                     default:
431                         lclPushOpCodeMapEntry( aVec, mpTable, nOp );
432                 }
433             }
434         }
435         if ((nGroups & FormulaMapGroup::FUNCTIONS) != 0)
436         {
437             // Function names are not consecutive, skip the gaps between
438             // functions with no parameter, functions with 1 parameter
439             lclPushOpCodeMapEntries( aVec, mpTable, SC_OPCODE_START_NO_PAR, ::std::min< sal_uInt16 >( SC_OPCODE_STOP_NO_PAR, mnSymbols ) );
440             lclPushOpCodeMapEntries( aVec, mpTable, SC_OPCODE_START_1_PAR, ::std::min< sal_uInt16 >( SC_OPCODE_STOP_1_PAR, mnSymbols ) );
441             // Additional functions not within range of functions.
442             static const sal_uInt16 aOpCodes[] = {
443                 SC_OPCODE_IF,
444                 SC_OPCODE_CHOSE,
445                 SC_OPCODE_AND,
446                 SC_OPCODE_OR,
447                 SC_OPCODE_NOT,
448                 SC_OPCODE_NEG
449             };
450             lclPushOpCodeMapEntries( aVec, mpTable, aOpCodes, sizeof(aOpCodes)/sizeof(aOpCodes[0]) );
451             // functions with 2 or more parameters.
452             for (sal_uInt16 nOp = SC_OPCODE_START_2_PAR; nOp < SC_OPCODE_STOP_2_PAR && nOp < mnSymbols; ++nOp)
453             {
454                 switch (nOp)
455                 {
456                     // NO_NAME is in SPECIAL.
457                     case SC_OPCODE_NO_NAME :
458                         break;   // nothing,
459                     default:
460                         lclPushOpCodeMapEntry( aVec, mpTable, nOp );
461                 }
462             }
463             // If AddIn functions are present in this mapping, use them, and only those.
464             if (hasExternals())
465             {
466                 for (ExternalHashMap::const_iterator it( mpExternalHashMap->begin());it != mpExternalHashMap->end(); ++it)
467                 {
468                     FormulaOpCodeMapEntry aEntry;
469                     aEntry.Name = (*it).first;
470                     aEntry.Token.Data <<= ::rtl::OUString( (*it).second);
471                     aEntry.Token.OpCode = ocExternal;
472                     aVec.push_back( aEntry);
473                 }
474             }
475             else
476             {
477                 //DBG_ASSERT( isCore(), "FormulaCompiler::OpCodeMap::createSequenceOfAvailableMappings: AddIn mapping from collection only implemented for core languages");
478                 _rCompiler.fillAddInToken(aVec,isEnglish());
479             }
480         }
481     }
482     const FormulaOpCodeMapEntry* pRet = aVec.empty() ? 0 : &aVec[0];
483     return uno::Sequence< FormulaOpCodeMapEntry >(pRet, aVec.size());
484 }
485 //-----------------------------------------------------------------------------
486 
putOpCode(const String & rStr,const OpCode eOp)487 void FormulaCompiler::OpCodeMap::putOpCode( const String & rStr, const OpCode eOp )
488 {
489     DBG_ASSERT( 0 < eOp && sal_uInt16(eOp) < mnSymbols, "OpCodeMap::putOpCode: OpCode out of range");
490     if (0 < eOp && sal_uInt16(eOp) < mnSymbols)
491     {
492         DBG_ASSERT( (mpTable[eOp].Len() == 0) || (mpTable[eOp] == rStr) || (eOp == ocCurrency),
493             ByteString( "OpCodeMap::putOpCode: reusing OpCode ").
494             Append( ByteString::CreateFromInt32( sal_Int32( eOp))).Append( " (").
495             Append( ByteString( rStr, RTL_TEXTENCODING_ASCII_US)).Append( ')').GetBuffer());
496         mpTable[eOp] = rStr;
497         mpHashMap->insert( OpCodeHashMap::value_type( rStr, eOp));
498     }
499 }
putOpCodeAlias(const String & rStr,const OpCode eOp)500 void FormulaCompiler::OpCodeMap::putOpCodeAlias( const String & rStr, const OpCode eOp )
501 {
502     DBG_ASSERT( 0 < eOp && sal_uInt16(eOp) < mnSymbols, "OpCodeMap::putOpCodeAlias: OpCode out of range");
503     if (0 < eOp && sal_uInt16(eOp) < mnSymbols)
504         mpHashMap->insert( OpCodeHashMap::value_type( rStr, eOp));
505 }
506 // -----------------------------------------------------------------------------
507 // class FormulaCompiler
508 // -----------------------------------------------------------------------------
DBG_NAME(FormulaCompiler)509 DBG_NAME(FormulaCompiler)
510 FormulaCompiler::FormulaCompiler(FormulaTokenArray& _rArr)
511         :
512         pArr( &_rArr ),
513         pExternalRef(NULL),
514         pStack( NULL ),
515         nRecursion(0),
516         nNumFmt( NUMBERFORMAT_UNDEFINED ),
517         meGrammar( formula::FormulaGrammar::GRAM_UNSPECIFIED ),
518         bAutoCorrect( sal_False ),
519         bCorrected( sal_False ),
520         bCompileForFAP( sal_False ),
521         bIgnoreErrors( sal_False )
522 
523 {
524     DBG_CTOR(FormulaCompiler,NULL);
525 }
FormulaCompiler()526 FormulaCompiler::FormulaCompiler()
527         :
528         pArr( NULL ),
529         pExternalRef(NULL),
530         pStack( NULL ),
531         nRecursion(0),
532         nNumFmt( NUMBERFORMAT_UNDEFINED ),
533         meGrammar( formula::FormulaGrammar::GRAM_UNSPECIFIED ),
534         bAutoCorrect( sal_False ),
535         bCorrected( sal_False ),
536         bCompileForFAP( sal_False ),
537         bIgnoreErrors( sal_False )
538 
539 {
540     DBG_CTOR(FormulaCompiler,NULL);
541 }
~FormulaCompiler()542 FormulaCompiler::~FormulaCompiler()
543 {
544     DBG_DTOR(FormulaCompiler,NULL);
545 }
546 
GetOpCodeMap(const sal_Int32 nLanguage) const547 FormulaCompiler::OpCodeMapPtr FormulaCompiler::GetOpCodeMap( const sal_Int32 nLanguage ) const
548 {
549     FormulaCompiler::OpCodeMapPtr xMap;
550     using namespace sheet;
551     switch (nLanguage)
552     {
553         case FormulaLanguage::ODFF :
554             if (!mxSymbolsODFF)
555                 InitSymbolsODFF();
556             xMap = mxSymbolsODFF;
557             break;
558         case FormulaLanguage::ODF_11 :
559             if (!mxSymbolsPODF)
560                 InitSymbolsPODF();
561             xMap = mxSymbolsPODF;
562             break;
563         case FormulaLanguage::ENGLISH :
564             if (!mxSymbolsEnglish)
565                 InitSymbolsEnglish();
566             xMap = mxSymbolsEnglish;
567             break;
568         case FormulaLanguage::NATIVE :
569             if (!mxSymbolsNative)
570                 InitSymbolsNative();
571             xMap = mxSymbolsNative;
572             break;
573         default:
574             ;   // nothing, NULL map returned
575     }
576     return xMap;
577 }
578 // -----------------------------------------------------------------------------
579 
FindAddInFunction(const String &,sal_Bool) const580 String FormulaCompiler::FindAddInFunction( const String& /*rUpperName*/, sal_Bool /*bLocalFirst*/ ) const
581 {
582     return String();
583 }
584 // -----------------------------------------------------------------------------
CreateOpCodeMap(const uno::Sequence<const sheet::FormulaOpCodeMapEntry> & rMapping,bool bEnglish)585 FormulaCompiler::OpCodeMapPtr FormulaCompiler::CreateOpCodeMap(
586         const uno::Sequence<
587         const sheet::FormulaOpCodeMapEntry > & rMapping,
588         bool bEnglish )
589 {
590     using sheet::FormulaOpCodeMapEntry;
591     // Filter / API maps are never Core
592     NonConstOpCodeMapPtr xMap( new OpCodeMap( SC_OPCODE_LAST_OPCODE_ID + 1,false, FormulaGrammar::mergeToGrammar( FormulaGrammar::setEnglishBit(FormulaGrammar::GRAM_EXTERNAL, bEnglish),FormulaGrammar::CONV_UNSPECIFIED)));
593     FormulaOpCodeMapEntry const * pArr2 = rMapping.getConstArray();
594     FormulaOpCodeMapEntry const * const pStop = pArr2 + rMapping.getLength();
595     for ( ; pArr2 < pStop; ++pArr2)
596     {
597         OpCode eOp = OpCode(pArr2->Token.OpCode);
598         if (eOp != ocExternal)
599             xMap->putOpCode( pArr2->Name, eOp);
600         else
601         {
602             ::rtl::OUString aExternalName;
603             if (pArr2->Token.Data >>= aExternalName)
604                 xMap->putExternal( pArr2->Name, aExternalName);
605             else
606             {
607                 DBG_ERRORFILE( "FormulaCompiler::CreateOpCodeMap: no Token.Data external name");
608             }
609         }
610     }
611     return xMap;
612 }
613 
614 // -----------------------------------------------------------------------------
lcl_fillNativeSymbols(FormulaCompiler::NonConstOpCodeMapPtr & _xMap,bool _destroy=false)615 void lcl_fillNativeSymbols(FormulaCompiler::NonConstOpCodeMapPtr& _xMap,bool _destroy = false)
616 {
617     static FormulaCompiler::NonConstOpCodeMapPtr s_SymbolMap;
618     if ( _destroy )
619     {
620         s_SymbolMap.reset();
621     } // if ( _destroy )
622     else if ( !s_SymbolMap.get() )
623     {
624         // Core
625         s_SymbolMap.reset( new FormulaCompiler::OpCodeMap( SC_OPCODE_LAST_OPCODE_ID + 1, true, FormulaGrammar::GRAM_NATIVE_UI));
626         OModuleClient aModuleClient;
627         OpCodeList aOpCodeListNative( RID_STRLIST_FUNCTION_NAMES, s_SymbolMap );
628         // No AddInMap for native core mapping.
629     } // if ( !s_SymbolMap.get() )
630     _xMap = s_SymbolMap;
631 }
632 // -----------------------------------------------------------------------------
GetNativeSymbol(OpCode eOp)633 const String& FormulaCompiler::GetNativeSymbol( OpCode eOp )
634 {
635     NonConstOpCodeMapPtr xSymbolsNative;
636     lcl_fillNativeSymbols(xSymbolsNative);
637     return xSymbolsNative->getSymbol( eOp );
638 }
639 // -----------------------------------------------------------------------------
InitSymbolsNative() const640 void FormulaCompiler::InitSymbolsNative() const
641 {
642     if (mxSymbolsNative.get())
643         return;
644     //! Experimental!
645     //  Use English function names and separators instead of native in UI.
646     static const sal_Char aEnvVarName[] = "OOO_CALC_USE_ENGLISH_FORMULAS";
647     const char* pEnv = getenv( aEnvVarName);
648     if (pEnv && (*pEnv == 'Y' || *pEnv == 'y' || *pEnv == '1') )
649     {
650         fprintf( stderr, "%s=%s => UI uses English function names and separators in formulas.\n",
651                 aEnvVarName, pEnv);
652         InitSymbolsEnglish();
653         mxSymbolsNative = mxSymbolsEnglish;
654         return;
655     }
656     static NonConstOpCodeMapPtr s_sSymbol;
657     if ( !s_sSymbol.get() )
658         lcl_fillNativeSymbols(s_sSymbol);
659     mxSymbolsNative = s_sSymbol;
660 }
661 // -----------------------------------------------------------------------------
InitSymbolsEnglish() const662 void FormulaCompiler::InitSymbolsEnglish() const
663 {
664     static NonConstOpCodeMapPtr s_sSymbol;
665     if ( !s_sSymbol.get() )
666         loadSymbols(RID_STRLIST_FUNCTION_NAMES_ENGLISH,FormulaGrammar::GRAM_ENGLISH,s_sSymbol);
667     mxSymbolsEnglish = s_sSymbol;
668 }
669 // -----------------------------------------------------------------------------
InitSymbolsPODF() const670 void FormulaCompiler::InitSymbolsPODF() const
671 {
672     static NonConstOpCodeMapPtr s_sSymbol;
673     if ( !s_sSymbol.get() )
674         loadSymbols(RID_STRLIST_FUNCTION_NAMES_ENGLISH,FormulaGrammar::GRAM_PODF,s_sSymbol);
675     mxSymbolsPODF = s_sSymbol;
676 }
677 // -----------------------------------------------------------------------------
InitSymbolsODFF() const678 void FormulaCompiler::InitSymbolsODFF() const
679 {
680     static NonConstOpCodeMapPtr s_sSymbol;
681     if ( !s_sSymbol.get() )
682         loadSymbols(RID_STRLIST_FUNCTION_NAMES_ENGLISH_ODFF,FormulaGrammar::GRAM_ODFF,s_sSymbol);
683     mxSymbolsODFF = s_sSymbol;
684 }
685 // -----------------------------------------------------------------------------
loadSymbols(sal_uInt16 _nSymbols,FormulaGrammar::Grammar _eGrammar,NonConstOpCodeMapPtr & _xMap) const686 void FormulaCompiler::loadSymbols(sal_uInt16 _nSymbols,FormulaGrammar::Grammar _eGrammar,NonConstOpCodeMapPtr& _xMap) const
687 {
688     if ( !_xMap.get() )
689     {
690         // not Core
691         _xMap.reset( new OpCodeMap( SC_OPCODE_LAST_OPCODE_ID + 1, _eGrammar != FormulaGrammar::GRAM_ODFF, _eGrammar ));
692         OModuleClient aModuleClient;
693         OpCodeList aOpCodeList( _nSymbols, _xMap );
694         // Files and API callers before RRI got its ODF name used ZGZ.
695         _xMap->putOpCodeAlias( String::CreateFromAscii("ZGZ"), ocZGZ);
696 
697         fillFromAddInMap( _xMap, _eGrammar);
698         // Fill from collection for AddIns not already present.
699         if ( FormulaGrammar::GRAM_ENGLISH != _eGrammar )
700             fillFromAddInCollectionUpperName( _xMap);
701         else
702             fillFromAddInCollectionEnglishName( _xMap);
703     }
704 }
705 // -----------------------------------------------------------------------------
fillFromAddInCollectionUpperName(NonConstOpCodeMapPtr) const706 void FormulaCompiler::fillFromAddInCollectionUpperName( NonConstOpCodeMapPtr /*xMap */) const
707 {
708 }
709 // -----------------------------------------------------------------------------
fillFromAddInCollectionEnglishName(NonConstOpCodeMapPtr) const710 void FormulaCompiler::fillFromAddInCollectionEnglishName( NonConstOpCodeMapPtr /*xMap */) const
711 {
712 }
713 // -----------------------------------------------------------------------------
fillFromAddInMap(NonConstOpCodeMapPtr,FormulaGrammar::Grammar) const714 void FormulaCompiler::fillFromAddInMap( NonConstOpCodeMapPtr /*xMap*/, FormulaGrammar::Grammar /*_eGrammar */) const
715 {
716 }
717 // -----------------------------------------------------------------------------
GetEnglishOpCode(const String & rName) const718 OpCode FormulaCompiler::GetEnglishOpCode( const String& rName ) const
719 {
720     FormulaCompiler::OpCodeMapPtr xMap = GetOpCodeMap(sheet::FormulaLanguage::ENGLISH);
721 
722     formula::OpCodeHashMap::const_iterator iLook( xMap->getHashMap()->find( rName ) );
723     bool bFound = (iLook != xMap->getHashMap()->end());
724     return bFound ? (*iLook).second : OpCode(ocNone);
725 }
726 
727 // Remove quotes, escaped quotes are unescaped.
DeQuote(String & rStr)728 sal_Bool FormulaCompiler::DeQuote( String& rStr )
729 {
730     xub_StrLen nLen = rStr.Len();
731     if ( nLen > 1 && rStr.GetChar(0) == '\'' && rStr.GetChar( nLen-1 ) == '\'' )
732     {
733         rStr.Erase( nLen-1, 1 );
734         rStr.Erase( 0, 1 );
735         xub_StrLen nPos = 0;
736         while ( (nPos = rStr.SearchAscii( "\\\'", nPos)) != STRING_NOTFOUND )
737         {
738             rStr.Erase( nPos, 1 );
739             ++nPos;
740         }
741         return sal_True;
742     }
743     return sal_False;
744 }
745 // -----------------------------------------------------------------------------
fillAddInToken(::std::vector<sheet::FormulaOpCodeMapEntry> &,bool) const746 void FormulaCompiler::fillAddInToken(::std::vector< sheet::FormulaOpCodeMapEntry >& /*_rVec*/,bool /*_bIsEnglish*/) const
747 {
748 }
749 // -----------------------------------------------------------------------------
IsMatrixFunction(OpCode _eOpCode)750 sal_Bool FormulaCompiler::IsMatrixFunction(OpCode _eOpCode)
751 {
752     switch ( _eOpCode )
753     {
754         case ocDde :
755         case ocGrowth :
756         case ocTrend :
757         case ocRKP :
758         case ocRGP :
759         case ocFrequency :
760         case ocMatTrans :
761         case ocMatMult :
762         case ocMatInv :
763         case ocMatrixUnit :
764             return sal_True;
765         default:
766         {
767             // added to avoid warnings
768         }
769     }
770     return sal_False;
771 }
772 
773 // -----------------------------------------------------------------------------
~OpCodeMap()774 FormulaCompiler::OpCodeMap::~OpCodeMap()
775 {
776     delete mpReverseExternalHashMap;
777     delete mpExternalHashMap;
778     delete [] mpTable;
779     delete mpHashMap;
780 }
781 // -----------------------------------------------------------------------------
getOpCodeUnknown()782 sal_Int32 FormulaCompiler::OpCodeMap::getOpCodeUnknown()
783 {
784     static const sal_Int32 kOpCodeUnknown = -1;
785     return kOpCodeUnknown;
786 }
787 // -----------------------------------------------------------------------------
GetToken()788 sal_Bool FormulaCompiler::GetToken()
789 {
790     static const short nRecursionMax = 42;
791     FormulaCompilerRecursionGuard aRecursionGuard( nRecursion );
792     if ( nRecursion > nRecursionMax )
793     {
794         SetError( errStackOverflow );
795         pToken = new FormulaByteToken( ocStop );
796         return sal_False;
797     }
798     if ( bAutoCorrect && !pStack )
799     {   // #61426# don't merge stacked subroutine code into entered formula
800         aCorrectedFormula += aCorrectedSymbol;
801         aCorrectedSymbol.Erase();
802     }
803     sal_Bool bStop = sal_False;
804     if( pArr->GetCodeError() && !bIgnoreErrors )
805         bStop = sal_True;
806     else
807     {
808         short nWasColRowName;
809         if ( pArr->nIndex
810           && pArr->pCode[ pArr->nIndex-1 ]->GetOpCode() == ocColRowName )
811              nWasColRowName = 1;
812         else
813              nWasColRowName = 0;
814         pToken = pArr->Next();
815         while( pToken && pToken->GetOpCode() == ocSpaces )
816         {
817             if ( nWasColRowName )
818                 nWasColRowName++;
819             if ( bAutoCorrect && !pStack )
820                 CreateStringFromToken( aCorrectedFormula, pToken, sal_False );
821             pToken = pArr->Next();
822         }
823         if ( bAutoCorrect && !pStack && pToken )
824             CreateStringFromToken( aCorrectedSymbol, pToken, sal_False );
825         if( !pToken )
826         {
827             if( pStack )
828             {
829                 PopTokenArray();
830                 return GetToken();
831             }
832             else
833                 bStop = sal_True;
834         }
835         else
836         {
837             if ( nWasColRowName >= 2 && pToken->GetOpCode() == ocColRowName )
838             {   // convert an ocSpaces to ocIntersect in RPN
839                 pToken = new FormulaByteToken( ocIntersect );
840                 pArr->nIndex--;     // we advanced to the second ocColRowName, step back
841             }
842         }
843     }
844     if( bStop )
845     {
846         pToken = new FormulaByteToken( ocStop );
847         return sal_False;
848     }
849     if( pToken->GetOpCode() == ocSubTotal )
850         glSubTotal = sal_True;
851     else if ( pToken->GetOpCode() == ocExternalRef )
852     {
853         return HandleExternalReference(*pToken);
854     }
855     else if( pToken->GetOpCode() == ocName )
856     {
857         return HandleRange();
858     }
859     else if( pToken->GetOpCode() == ocColRowName )
860     {
861         return HandleSingleRef();
862     }
863     else if( pToken->GetOpCode() == ocDBArea )
864     {
865         return HandleDbData();
866     }
867     else if( pToken->GetType() == svSingleRef )
868     {
869         pArr->nRefs++;
870     }
871     else if( pToken->GetType() == svDoubleRef )
872     {
873         pArr->nRefs++;
874     }
875     return sal_True;
876 }
877 //---------------------------------------------------------------------------
878 // RPN creation by recursion
879 //---------------------------------------------------------------------------
880 
Factor()881 void FormulaCompiler::Factor()
882 {
883     if ( pArr->GetCodeError() && !bIgnoreErrors )
884         return;
885 
886     CurrentFactor pFacToken( this );
887 
888     OpCode eOp = pToken->GetOpCode();
889     if( eOp == ocPush || eOp == ocColRowNameAuto || eOp == ocMatRef ||
890             eOp == ocDBArea
891             || (bCompileForFAP && ((eOp == ocName) || (eOp == ocDBArea)
892             || (eOp == ocColRowName) || (eOp == ocBad)))
893         )
894     {
895         PutCode( pToken );
896         eOp = NextToken();
897         if( eOp == ocOpen )
898         {
899             // PUSH( is an error that may be caused by an unknown function.
900             SetError(
901                 ( pToken->GetType() == svString
902                || pToken->GetType() == svSingleRef )
903                ? errNoName : errOperatorExpected );
904             if ( bAutoCorrect && !pStack )
905             {   // assume multiplication
906                 aCorrectedFormula += mxSymbols->getSymbol(ocMul);
907                 bCorrected = sal_True;
908                 NextToken();
909                 eOp = Expression();
910                 if( eOp != ocClose )
911                     SetError(errPairExpected);
912                 else
913                     eOp = NextToken();
914             }
915         }
916     }
917     else if( eOp == ocOpen )
918     {
919         NextToken();
920         eOp = Expression();
921         while ((eOp == ocSep) && (!pArr->GetCodeError() || bIgnoreErrors))
922         {   // range list  (A1;A2)  converted to  (A1~A2)
923             pFacToken = pToken;
924             NextToken();
925             eOp = Expression();
926             // Do not ignore error here, regardless of bIgnoreErrors, otherwise
927             // errors like =(1;) would also result in display of =(1~)
928             if (!pArr->GetCodeError())
929             {
930                 pFacToken->NewOpCode( ocUnion,FormulaToken::PrivateAccess());
931                 PutCode( pFacToken);
932             }
933         }
934         if (eOp != ocClose)
935             SetError(errPairExpected);
936         else
937             eOp = NextToken();
938     }
939     else
940     {
941         if( nNumFmt == NUMBERFORMAT_UNDEFINED )
942             nNumFmt = lcl_GetRetFormat( eOp );
943         // Functions that have to be always recalculated
944         switch( eOp )
945         {
946             // no parameters:
947             case ocRandom:
948             case ocGetActDate:
949             case ocGetActTime:
950             // one parameter:
951             case ocFormula:
952             case ocInfo:
953             // more than one parameters:
954                 // ocIndirect/ocIndirectXL otherwise would have to do
955                 // StopListening and StartListening on a reference for every
956                 // interpreted value.
957             case ocIndirect:
958             case ocIndirectXL:
959                 // ocOffset results in indirect references.
960             case ocOffset:
961                 pArr->SetRecalcModeAlways();
962             break;
963                 // Functions recalculated on every document load.
964                 // Don't use SetRecalcModeOnLoad() which would override
965                 // ModeAlways.
966             case ocConvert :
967                 pArr->AddRecalcMode( RECALCMODE_ONLOAD );
968             break;
969                 // If the referred cell is moved the value changes.
970             case ocColumn :
971             case ocRow :
972                 // ocCell needs recalc on move for some possible type values.
973             case ocCell :
974                 pArr->SetRecalcModeOnRefMove();
975             break;
976             case ocHyperLink :
977                 pArr->SetHyperLink(sal_True);
978             break;
979             default:
980                 ;   // nothing
981         }
982         if (SC_OPCODE_START_NO_PAR <= eOp && eOp < SC_OPCODE_STOP_NO_PAR)
983         {
984             pFacToken = pToken;
985             eOp = NextToken();
986             if (eOp != ocOpen)
987             {
988                 SetError(errPairExpected);
989                 PutCode( pFacToken );
990             }
991             else
992             {
993                 eOp = NextToken();
994                 if (eOp != ocClose)
995                     SetError(errPairExpected);
996                 PutCode(pFacToken);
997                 eOp = NextToken();
998             }
999         }
1000         // special cases NOT() and NEG()
1001         else if( eOp == ocNot || eOp == ocNeg
1002               || (SC_OPCODE_START_1_PAR <= eOp && eOp < SC_OPCODE_STOP_1_PAR) )
1003         {
1004             pFacToken = pToken;
1005             eOp = NextToken();
1006             if( nNumFmt == NUMBERFORMAT_UNDEFINED && eOp == ocNot )
1007                 nNumFmt = NUMBERFORMAT_LOGICAL;
1008             if (eOp == ocOpen)
1009             {
1010                 NextToken();
1011                 eOp = Expression();
1012             }
1013             else
1014                 SetError(errPairExpected);
1015             if (eOp != ocClose)
1016                 SetError(errPairExpected);
1017             else if ( !pArr->GetCodeError() )
1018                 pFacToken->SetByte( 1 );
1019             PutCode( pFacToken );
1020             eOp = NextToken();
1021         }
1022         else if ((SC_OPCODE_START_2_PAR <= eOp && eOp < SC_OPCODE_STOP_2_PAR
1023                     && ((eOp != ocIfna && eOp != ocIfError) || bCompileForFAP))
1024                 || eOp == ocExternal
1025                 || eOp == ocMacro
1026                 || eOp == ocAnd
1027                 || eOp == ocOr
1028                 || eOp == ocBad
1029                 || ( eOp >= ocInternalBegin && eOp <= ocInternalEnd )
1030                 || (bCompileForFAP && ((eOp == ocIf) || (eOp == ocChose)))
1031             )
1032         {
1033             pFacToken = pToken;
1034             OpCode eMyLastOp = eOp;
1035             eOp = NextToken();
1036             bool bNoParam = false;
1037             bool bBadName = false;
1038             if (eOp == ocOpen)
1039             {
1040                 eOp = NextToken();
1041                 if (eOp == ocClose)
1042                     bNoParam = true;
1043                 else
1044                     eOp = Expression();
1045             }
1046             else if (eMyLastOp == ocBad)
1047             {
1048                 // Just a bad name, not an unknown function, no parameters, no
1049                 // closing expected.
1050                 bBadName = true;
1051                 bNoParam = true;
1052             }
1053             else
1054                 SetError(errPairExpected);
1055             sal_uInt8 nSepCount = 0;
1056             if( !bNoParam )
1057             {
1058                 nSepCount++;
1059                 while ( (eOp == ocSep) && (!pArr->GetCodeError() || bIgnoreErrors) )
1060                 {
1061                     if ( nSepCount == 255 )
1062                         SetError( errCodeOverflow );    // the count is kept in a byte
1063                     else
1064                         nSepCount++;
1065                     NextToken();
1066                     eOp = Expression();
1067                 }
1068             }
1069             if (bBadName)
1070                 ;   // nothing, keep current token for return
1071             else if (eOp != ocClose)
1072                 SetError(errPairExpected);
1073             else
1074                 eOp = NextToken();
1075             // Jumps are just normal functions for the FunctionAutoPilot tree view
1076             if ( bCompileForFAP && pFacToken->GetType() == svJump )
1077                 pFacToken = new FormulaFAPToken( pFacToken->GetOpCode(), nSepCount, pFacToken );
1078             else
1079                 pFacToken->SetByte( nSepCount );
1080             // ODF ISOWEEKNUM has one argument; AOO wrote WEEKNUM to ODF as
1081             // ISOWEEKNUM with two, so only the two argument form stays ocWeek.
1082             if ( nSepCount == 1 && pFacToken->GetOpCode() == ocWeek && mxSymbols->isODFF() )
1083                 pFacToken->NewOpCode( ocIsoWeekNum, FormulaToken::PrivateAccess());
1084             // EASTERSUNDAY() without a year depends on today's date
1085             if ( bNoParam && pFacToken->GetOpCode() == ocEasterSunday )
1086                 pArr->SetRecalcModeAlways();
1087             PutCode( pFacToken );
1088         }
1089         else if (eOp == ocIf || eOp == ocChose || eOp == ocIfna || eOp == ocIfError)
1090         {
1091             // the PC counters are -1
1092             pFacToken = pToken;
1093             if ( eOp == ocIf )
1094                 pFacToken->GetJump()[ 0 ] = 3;  // if, else, behind
1095             else if ( eOp == ocIfna || eOp == ocIfError )
1096                 pFacToken->GetJump()[ 0 ] = 2;  // fallback, behind
1097             else
1098                 pFacToken->GetJump()[ 0 ] = MAXJUMPCOUNT+1;
1099             eOp = NextToken();
1100             if (eOp == ocOpen)
1101             {
1102                 NextToken();
1103                 eOp = Expression();
1104             }
1105             else
1106                 SetError(errPairExpected);
1107             short nJumpCount = 0;
1108             PutCode( pFacToken );
1109             // #36253# during AutoCorrect (since pArr->GetCodeError() is
1110             // ignored) an unlimited ocIf would crash because
1111             // ScRawToken::Clone() allocates the JumpBuffer according to
1112             // nJump[0]*2+2, which is 3*2+2 on ocIf.
1113             const short nJumpMax =
1114                 (pFacToken->GetOpCode() == ocIf ? 3 :
1115                  ((pFacToken->GetOpCode() == ocIfna || pFacToken->GetOpCode() == ocIfError) ? 2 : MAXJUMPCOUNT));
1116             while ( (nJumpCount < (MAXJUMPCOUNT - 1)) && (eOp == ocSep)
1117                     && (!pArr->GetCodeError() || bIgnoreErrors) )
1118             {
1119                 if ( ++nJumpCount <= nJumpMax )
1120                     pFacToken->GetJump()[nJumpCount] = pc-1;
1121                 NextToken();
1122                 if ( pFacToken->GetOpCode() == ocIf && pToken->GetOpCode() == ocClose )
1123                 {   // ODF 1.3: IF(c;), IF(c;;) and IF(c;T;) have an empty last parameter
1124                     FormulaTokenRef xMissing( new FormulaMissingToken );
1125                     PutCode( xMissing );
1126                     eOp = ocClose;
1127                 }
1128                 else
1129                     eOp = Expression();
1130                 // ocSep or ocClose terminate the subexpression
1131                 PutCode( pToken );
1132             }
1133             if (eOp != ocClose)
1134                 SetError(errPairExpected);
1135             else
1136             {
1137                 eOp = NextToken();
1138                 // always limit to nJumpMax, no arbitrary overwrites
1139                 if ( ++nJumpCount <= nJumpMax )
1140                     pFacToken->GetJump()[ nJumpCount ] = pc-1;
1141                 if ((pFacToken->GetOpCode() == ocIf && (nJumpCount > 3)) ||
1142                         ((pFacToken->GetOpCode() == ocIfna || pFacToken->GetOpCode() == ocIfError) && (nJumpCount != 2)) ||
1143                                  (nJumpCount >= MAXJUMPCOUNT))
1144                     SetError(errIllegalParameter);
1145                 else
1146                     pFacToken->GetJump()[ 0 ] = nJumpCount;
1147             }
1148         }
1149         else if ( eOp == ocMissing )
1150         {
1151             PutCode( pToken );
1152             eOp = NextToken();
1153         }
1154         else if ( eOp == ocClose )
1155         {
1156             SetError( errParameterExpected );
1157         }
1158         else if ( eOp == ocSep )
1159         {   // Subsequent ocSep
1160             SetError( errParameterExpected );
1161             if ( bAutoCorrect && !pStack )
1162             {
1163                 aCorrectedSymbol.Erase();
1164                 bCorrected = sal_True;
1165             }
1166         }
1167         else if ( eOp == ocExternalRef )
1168         {
1169             PutCode(pToken);
1170             eOp = NextToken();
1171         }
1172         else
1173         {
1174             SetError( errUnknownToken );
1175             if ( bAutoCorrect && !pStack )
1176             {
1177                 if ( eOp == ocStop )
1178                 {   // trailing operator w/o operand
1179                     xub_StrLen nLen = aCorrectedFormula.Len();
1180                     if ( nLen )
1181                         aCorrectedFormula.Erase( nLen - 1 );
1182                     aCorrectedSymbol.Erase();
1183                     bCorrected = sal_True;
1184                 }
1185             }
1186         }
1187     }
1188 }
1189 
1190 //---------------------------------------------------------------------------
1191 
RangeLine()1192 void FormulaCompiler::RangeLine()
1193 {
1194     Factor();
1195     while (pToken->GetOpCode() == ocRange)
1196     {
1197         FormulaToken** pCode1 = pCode - 1;
1198         FormulaTokenRef p = pToken;
1199         NextToken();
1200         Factor();
1201         FormulaToken** pCode2 = pCode - 1;
1202         if (!MergeRangeReference( pCode1, pCode2))
1203             PutCode(p);
1204     }
1205 }
1206 
1207 //---------------------------------------------------------------------------
1208 
IntersectionLine()1209 void FormulaCompiler::IntersectionLine()
1210 {
1211     RangeLine();
1212     while (pToken->GetOpCode() == ocIntersect)
1213     {
1214         FormulaTokenRef p = pToken;
1215         NextToken();
1216         RangeLine();
1217         PutCode(p);
1218     }
1219 }
1220 
1221 //---------------------------------------------------------------------------
1222 
UnionLine()1223 void FormulaCompiler::UnionLine()
1224 {
1225     IntersectionLine();
1226     while (pToken->GetOpCode() == ocUnion)
1227     {
1228         FormulaTokenRef p = pToken;
1229         NextToken();
1230         IntersectionLine();
1231         PutCode(p);
1232     }
1233 }
1234 
1235 //---------------------------------------------------------------------------
1236 
UnaryLine()1237 void FormulaCompiler::UnaryLine()
1238 {
1239     if( pToken->GetOpCode() == ocAdd )
1240         GetToken();
1241     else if (SC_OPCODE_START_UN_OP <= pToken->GetOpCode() &&
1242             pToken->GetOpCode() < SC_OPCODE_STOP_UN_OP)
1243     {
1244         FormulaTokenRef p = pToken;
1245         NextToken();
1246         UnaryLine();
1247         PutCode( p );
1248     }
1249     else
1250         UnionLine();
1251 }
1252 
1253 //---------------------------------------------------------------------------
1254 
PostOpLine()1255 void FormulaCompiler::PostOpLine()
1256 {
1257     UnaryLine();
1258     while ( pToken->GetOpCode() == ocPercentSign )
1259     {   // this operator _follows_ its operand
1260         PutCode( pToken );
1261         NextToken();
1262     }
1263 }
1264 
1265 //---------------------------------------------------------------------------
1266 
PowLine()1267 void FormulaCompiler::PowLine()
1268 {
1269     PostOpLine();
1270     while (pToken->GetOpCode() == ocPow)
1271     {
1272         FormulaTokenRef p = pToken;
1273         NextToken();
1274         PostOpLine();
1275         PutCode(p);
1276     }
1277 }
1278 
1279 //---------------------------------------------------------------------------
1280 
MulDivLine()1281 void FormulaCompiler::MulDivLine()
1282 {
1283     PowLine();
1284     while (pToken->GetOpCode() == ocMul || pToken->GetOpCode() == ocDiv)
1285     {
1286         FormulaTokenRef p = pToken;
1287         NextToken();
1288         PowLine();
1289         PutCode(p);
1290     }
1291 }
1292 
1293 //---------------------------------------------------------------------------
1294 
AddSubLine()1295 void FormulaCompiler::AddSubLine()
1296 {
1297     MulDivLine();
1298     while (pToken->GetOpCode() == ocAdd || pToken->GetOpCode() == ocSub)
1299     {
1300         FormulaTokenRef p = pToken;
1301         NextToken();
1302         MulDivLine();
1303         PutCode(p);
1304     }
1305 }
1306 
1307 //---------------------------------------------------------------------------
1308 
ConcatLine()1309 void FormulaCompiler::ConcatLine()
1310 {
1311     AddSubLine();
1312     while (pToken->GetOpCode() == ocAmpersand)
1313     {
1314         FormulaTokenRef p = pToken;
1315         NextToken();
1316         AddSubLine();
1317         PutCode(p);
1318     }
1319 }
1320 
1321 //---------------------------------------------------------------------------
1322 
CompareLine()1323 void FormulaCompiler::CompareLine()
1324 {
1325     ConcatLine();
1326     while (pToken->GetOpCode() >= ocEqual && pToken->GetOpCode() <= ocGreaterEqual)
1327     {
1328         FormulaTokenRef p = pToken;
1329         NextToken();
1330         ConcatLine();
1331         PutCode(p);
1332     }
1333 }
1334 
1335 //---------------------------------------------------------------------------
1336 
NotLine()1337 void FormulaCompiler::NotLine()
1338 {
1339     CompareLine();
1340     while (pToken->GetOpCode() == ocNot)
1341     {
1342         FormulaTokenRef p = pToken;
1343         NextToken();
1344         CompareLine();
1345         PutCode(p);
1346     }
1347 }
1348 
1349 //---------------------------------------------------------------------------
1350 
Expression()1351 OpCode FormulaCompiler::Expression()
1352 {
1353     static const short nRecursionMax = 42;
1354     FormulaCompilerRecursionGuard aRecursionGuard( nRecursion );
1355     if ( nRecursion > nRecursionMax )
1356     {
1357         SetError( errStackOverflow );
1358         return ocStop;      //! generate token instead?
1359     }
1360     NotLine();
1361     while (pToken->GetOpCode() == ocAnd || pToken->GetOpCode() == ocOr)
1362     {
1363         FormulaTokenRef p = pToken;
1364         pToken->SetByte( 2 );       // 2 parameters!
1365         NextToken();
1366         NotLine();
1367         PutCode(p);
1368     }
1369     return pToken->GetOpCode();
1370 }
1371 // -----------------------------------------------------------------------------
SetError(sal_uInt16)1372 void FormulaCompiler::SetError(sal_uInt16 /*nError*/)
1373 {
1374 }
1375 // -----------------------------------------------------------------------------
ExtendRangeReference(FormulaToken &,FormulaToken &,bool)1376 FormulaTokenRef FormulaCompiler::ExtendRangeReference( FormulaToken & /*rTok1*/, FormulaToken & /*rTok2*/, bool /*bReuseDoubleRef*/ )
1377 {
1378     return FormulaTokenRef();
1379 }
1380 // -----------------------------------------------------------------------------
MergeRangeReference(FormulaToken ** const pCode1,FormulaToken * const * const pCode2)1381 bool FormulaCompiler::MergeRangeReference(FormulaToken * * const pCode1, FormulaToken * const * const pCode2 )
1382 {
1383     FormulaToken *p1, *p2;
1384     if (pc < 2 || !pCode1 || !pCode2 ||
1385             (pCode2 - pCode1 != 1) || (pCode - pCode2 != 1) ||
1386             ((p1 = *pCode1) == 0) || ((p2 = *pCode2) == 0) )
1387         return false;
1388 
1389     FormulaTokenRef p = ExtendRangeReference( *p1, *p2, true);
1390     if (!p)
1391         return false;
1392 
1393     p->IncRef();
1394     p1->DecRef();
1395     p2->DecRef();
1396     *pCode1 = p;
1397     --pCode, --pc;
1398     pArr->nRefs--;
1399 
1400     return true;
1401 }
1402 // -----------------------------------------------------------------------------
CompileTokenArray()1403 sal_Bool FormulaCompiler::CompileTokenArray()
1404 {
1405     glSubTotal = sal_False;
1406     bCorrected = sal_False;
1407     if( !pArr->GetCodeError() || bIgnoreErrors )
1408     {
1409         if ( bAutoCorrect )
1410         {
1411             aCorrectedFormula.Erase();
1412             aCorrectedSymbol.Erase();
1413         }
1414         pArr->nRefs = 0;    // count from start
1415         pArr->DelRPN();
1416         pStack = NULL;
1417         FormulaToken* pData[ MAXCODE ];
1418         pCode = pData;
1419         sal_Bool bWasForced = pArr->IsRecalcModeForced();
1420         if ( bWasForced )
1421         {
1422             if ( bAutoCorrect )
1423                 aCorrectedFormula = '=';
1424         }
1425         pArr->ClearRecalcMode();
1426         pArr->Reset();
1427         eLastOp = ocOpen;
1428         pc = 0;
1429         NextToken();
1430         OpCode eOp = Expression();
1431         // Some trailing garbage that doesn't form an expression?
1432         if (eOp != ocStop)
1433             SetError( errOperatorExpected);
1434 
1435         sal_uInt16 nErrorBeforePop = pArr->GetCodeError();
1436 
1437         while( pStack )
1438             PopTokenArray();
1439         if( pc )
1440         {
1441             pArr->pRPN = new FormulaToken*[ pc ];
1442             pArr->nRPN = pc;
1443             memcpy( pArr->pRPN, pData, pc * sizeof( FormulaToken* ) );
1444         }
1445 
1446         // once an error, always an error
1447         if( !pArr->GetCodeError() && nErrorBeforePop )
1448             pArr->SetCodeError( nErrorBeforePop);
1449 
1450         if( pArr->GetCodeError() && !bIgnoreErrors )
1451         {
1452             pArr->DelRPN();
1453             pArr->SetHyperLink(sal_False);
1454         }
1455 
1456         if ( bWasForced )
1457             pArr->SetRecalcModeForced();
1458     }
1459     if( nNumFmt == NUMBERFORMAT_UNDEFINED )
1460         nNumFmt = NUMBERFORMAT_NUMBER;
1461     return glSubTotal;
1462 }
1463 // -----------------------------------------------------------------------------
PopTokenArray()1464 void FormulaCompiler::PopTokenArray()
1465 {
1466     if( pStack )
1467     {
1468         FormulaArrayStack* p = pStack;
1469         pStack = p->pNext;
1470         p->pArr->nRefs = sal::static_int_cast<short>( p->pArr->nRefs + pArr->nRefs );
1471         // obtain special RecalcMode from SharedFormula
1472         if ( pArr->IsRecalcModeAlways() )
1473             p->pArr->SetRecalcModeAlways();
1474         else if ( !pArr->IsRecalcModeNormal() && p->pArr->IsRecalcModeNormal() )
1475             p->pArr->SetMaskedRecalcMode( pArr->GetRecalcMode() );
1476         p->pArr->SetCombinedBitsRecalcMode( pArr->GetRecalcMode() );
1477         if( p->bTemp )
1478             delete pArr;
1479         pArr = p->pArr;
1480         delete p;
1481     }
1482 }
1483 // -----------------------------------------------------------------------------
CreateStringFromTokenArray(String & rFormula)1484 void FormulaCompiler::CreateStringFromTokenArray( String& rFormula )
1485 {
1486     rtl::OUStringBuffer aBuffer( pArr->GetLen() * 5 );
1487     CreateStringFromTokenArray( aBuffer );
1488     rFormula = aBuffer;
1489 }
1490 
CreateStringFromTokenArray(rtl::OUStringBuffer & rBuffer)1491 void FormulaCompiler::CreateStringFromTokenArray( rtl::OUStringBuffer& rBuffer )
1492 {
1493     rBuffer.setLength(0);
1494     if( !pArr->GetLen() )
1495         return;
1496 
1497     FormulaTokenArray* pSaveArr = pArr;
1498     bool bODFF = FormulaGrammar::isODFF( meGrammar);
1499     if (bODFF || FormulaGrammar::isPODF( meGrammar) )
1500     {
1501         // Scan token array for missing args and re-write if present.
1502         MissingConvention aConv( bODFF);
1503         if (pArr->NeedsPofRewrite( aConv))
1504             pArr = pArr->RewriteMissingToPof( aConv);
1505     }
1506 
1507     // At least one character per token, plus some are references, some are
1508     // function names, some are numbers, ...
1509     rBuffer.ensureCapacity( pArr->GetLen() * 5 );
1510 
1511     if ( pArr->IsRecalcModeForced() )
1512         rBuffer.append(sal_Unicode('='));
1513     FormulaToken* t = pArr->First();
1514     sal_uInt16 nOpen = 0;
1515     while( t )
1516     {
1517         OpCode eOp = t->GetOpCode();
1518         if (eOp == ocOpen)
1519             ++nOpen;
1520         else if (eOp == ocClose && nOpen)
1521             --nOpen;
1522         else if (bODFF && eOp == ocSep && !nOpen)
1523         {
1524             // The Excel import joins ranges with ocSep; outside parentheses ODFF has no
1525             // separator, the union operator is meant.
1526             rBuffer.append( mxSymbols->getSymbol( ocUnion));
1527             t = pArr->Next();
1528             continue;
1529         }
1530         t = CreateStringFromToken( rBuffer, t, sal_True );
1531     }
1532 
1533     if (pSaveArr != pArr)
1534     {
1535         delete pArr;
1536         pArr = pSaveArr;
1537     }
1538 }
1539 // -----------------------------------------------------------------------------
CreateStringFromToken(String & rFormula,FormulaToken * pTokenP,sal_Bool bAllowArrAdvance)1540 FormulaToken* FormulaCompiler::CreateStringFromToken( String& rFormula, FormulaToken* pTokenP,sal_Bool bAllowArrAdvance )
1541 {
1542     rtl::OUStringBuffer aBuffer;
1543     FormulaToken* p = CreateStringFromToken( aBuffer, pTokenP, bAllowArrAdvance );
1544     rFormula += aBuffer;
1545     return p;
1546 }
1547 
CreateStringFromToken(rtl::OUStringBuffer & rBuffer,FormulaToken * pTokenP,sal_Bool bAllowArrAdvance)1548 FormulaToken* FormulaCompiler::CreateStringFromToken( rtl::OUStringBuffer& rBuffer, FormulaToken* pTokenP,sal_Bool bAllowArrAdvance )
1549 {
1550     sal_Bool bNext = sal_True;
1551     sal_Bool bSpaces = sal_False;
1552     FormulaToken* t = pTokenP;
1553     OpCode eOp = t->GetOpCode();
1554     if( eOp >= ocAnd && eOp <= ocOr )
1555     {
1556         // AND, OR infix?
1557         if ( bAllowArrAdvance )
1558             t = pArr->Next();
1559         else
1560             t = pArr->PeekNext();
1561         bNext = sal_False;
1562         bSpaces = ( !t || t->GetOpCode() != ocOpen );
1563     }
1564     if( bSpaces )
1565         rBuffer.append(sal_Unicode(' '));
1566 
1567     if( eOp == ocSpaces )
1568     {
1569         bool bIntersectionOp = mxSymbols->isODFF();
1570         if (bIntersectionOp)
1571         {
1572             const FormulaToken* p = pArr->PeekPrevNoSpaces();
1573             bIntersectionOp = (p && p->GetOpCode() == ocColRowName);
1574             if (bIntersectionOp)
1575             {
1576                 p = pArr->PeekNextNoSpaces();
1577                 bIntersectionOp = (p && p->GetOpCode() == ocColRowName);
1578             }
1579         }
1580         if (bIntersectionOp)
1581             rBuffer.appendAscii( "!!");
1582         else
1583         {
1584             // most times it's just one blank
1585             sal_uInt8 n = t->GetByte();
1586             for ( sal_uInt8 j=0; j<n; ++j )
1587             {
1588                 rBuffer.append(sal_Unicode(' '));
1589             }
1590         }
1591     }
1592     else if( eOp >= ocInternalBegin && eOp <= ocInternalEnd )
1593         rBuffer.appendAscii( pInternal[ eOp - ocInternalBegin ] );
1594     else if( (sal_uInt16) eOp < mxSymbols->getSymbolCount())        // Keyword:
1595         rBuffer.append(mxSymbols->getSymbol(eOp));
1596     else
1597     {
1598         DBG_ERRORFILE("unknown OpCode");
1599         rBuffer.append(GetNativeSymbol( ocErrName ));
1600     }
1601     if( bNext )
1602     {
1603         if (eOp == ocExternalRef)
1604         {
1605             CreateStringFromExternal(rBuffer, pTokenP);
1606         }
1607         else
1608         {
1609             switch( t->GetType() )
1610             {
1611             case svDouble:
1612                 AppendDouble( rBuffer, t->GetDouble() );
1613             break;
1614 
1615             case svString:
1616                 if( eOp == ocBad )
1617                     rBuffer.append(t->GetString());
1618                 else
1619                     AppendString( rBuffer, t->GetString() );
1620                 break;
1621             case svSingleRef:
1622                 CreateStringFromSingleRef(rBuffer,t);
1623                 break;
1624             case svDoubleRef:
1625                 CreateStringFromDoubleRef(rBuffer,t);
1626                 break;
1627             case svMatrix:
1628                 CreateStringFromMatrix( rBuffer, t );
1629                 break;
1630 
1631             case svIndex:
1632                 CreateStringFromIndex( rBuffer, t );
1633                 break;
1634             case svExternal:
1635             {
1636                 // mapped or translated name of AddIns
1637                 String aAddIn( t->GetExternal() );
1638                 bool bMapped = mxSymbols->isPODF();     // ODF 1.1 directly uses programmatical name
1639                 if (!bMapped && mxSymbols->hasExternals())
1640                 {
1641                     ExternalHashMap::const_iterator iLook = mxSymbols->getReverseExternalHashMap()->find( aAddIn);
1642                     if (iLook != mxSymbols->getReverseExternalHashMap()->end())
1643                     {
1644                         aAddIn = (*iLook).second;
1645                         bMapped = true;
1646                     }
1647                 }
1648                 if (!bMapped && !mxSymbols->isEnglish())
1649                      LocalizeString( aAddIn );
1650                  rBuffer.append(aAddIn);
1651              }
1652             break;
1653             case svByte:
1654             case svJump:
1655             case svFAP:
1656             case svMissing:
1657             case svSep:
1658                 break;      // Opcodes
1659             default:
1660                 DBG_ERROR("FormulaCompiler:: GetStringFromToken errUnknownVariable");
1661             } // of switch
1662         }
1663     }
1664     if( bSpaces )
1665         rBuffer.append(sal_Unicode(' '));
1666     if ( bAllowArrAdvance )
1667     {
1668         if( bNext )
1669             t = pArr->Next();
1670         return t;
1671     }
1672     return pTokenP;
1673 }
1674 // -----------------------------------------------------------------------------
1675 
AppendDouble(rtl::OUStringBuffer & rBuffer,double fVal)1676 void FormulaCompiler::AppendDouble( rtl::OUStringBuffer& rBuffer, double fVal )
1677 {
1678     if ( mxSymbols->isEnglish() )
1679     {
1680         ::rtl::math::doubleToUStringBuffer( rBuffer, fVal,
1681                 rtl_math_StringFormat_Automatic,
1682                 rtl_math_DecimalPlaces_Max, '.', sal_True );
1683     }
1684     else
1685     {
1686         SvtSysLocale aSysLocale;
1687         ::rtl::math::doubleToUStringBuffer( rBuffer, fVal,
1688                 rtl_math_StringFormat_Automatic,
1689                 rtl_math_DecimalPlaces_Max,
1690                 aSysLocale.GetLocaleDataPtr()->getNumDecimalSep().GetChar(0),
1691                 sal_True );
1692     }
1693 }
1694 // -----------------------------------------------------------------------------
AppendBoolean(rtl::OUStringBuffer & rBuffer,bool bVal)1695 void FormulaCompiler::AppendBoolean( rtl::OUStringBuffer& rBuffer, bool bVal )
1696 {
1697     rBuffer.append( mxSymbols->getSymbol(static_cast<OpCode>(bVal ? ocTrue : ocFalse)) );
1698 }
1699 // -----------------------------------------------------------------------------
IsImportingXML() const1700 sal_Bool FormulaCompiler::IsImportingXML() const
1701 {
1702     return sal_False;
1703 }
1704 // -----------------------------------------------------------------------------
AppendString(rtl::OUStringBuffer & rBuffer,const String & rStr)1705 void FormulaCompiler::AppendString( rtl::OUStringBuffer& rBuffer, const String & rStr )
1706 {
1707     if (IsImportingXML())
1708         rBuffer.append( rStr );
1709     else
1710     {
1711         rBuffer.append(sal_Unicode('"'));
1712         if ( lcl_UnicodeStrChr( rStr.GetBuffer(), '"' ) == NULL )
1713             rBuffer.append( rStr );
1714         else
1715         {
1716             String aStr( rStr );
1717             aStr.SearchAndReplaceAll( '"', String( RTL_CONSTASCII_USTRINGPARAM( "\"\"")));
1718             rBuffer.append(aStr);
1719         }
1720         rBuffer.append(sal_Unicode('"'));
1721     }
1722 }
1723 // -----------------------------------------------------------------------------
NextToken()1724 OpCode FormulaCompiler::NextToken()
1725 {
1726     if( !GetToken() )
1727         return ocStop;
1728     OpCode eOp = pToken->GetOpCode();
1729     // There must be an operator before a push
1730     if ( (eOp == ocPush || eOp == ocColRowNameAuto) &&
1731             !( (eLastOp == ocOpen) || (eLastOp == ocSep) ||
1732                 (SC_OPCODE_START_BIN_OP <= eLastOp && eLastOp < SC_OPCODE_STOP_UN_OP)) )
1733         SetError(errOperatorExpected);
1734     // Operator and Plus => operator
1735     if (eOp == ocAdd && (eLastOp == ocOpen || eLastOp == ocSep ||
1736                 (SC_OPCODE_START_BIN_OP <= eLastOp && eLastOp < SC_OPCODE_STOP_UN_OP)))
1737         eOp = NextToken();
1738     else
1739     {
1740         // Before an operator there must not be another operator, with the
1741         // exception of AND and OR.
1742         if ( eOp != ocAnd && eOp != ocOr &&
1743                 (SC_OPCODE_START_BIN_OP <= eOp && eOp < SC_OPCODE_STOP_BIN_OP )
1744                 && (eLastOp == ocOpen || eLastOp == ocSep ||
1745                     (SC_OPCODE_START_BIN_OP <= eLastOp && eLastOp < SC_OPCODE_STOP_UN_OP)))
1746         {
1747             SetError(errVariableExpected);
1748             if ( bAutoCorrect && !pStack )
1749             {
1750                 if ( eOp == eLastOp || eLastOp == ocOpen )
1751                 {   // throw away duplicated operator
1752                     aCorrectedSymbol.Erase();
1753                     bCorrected = sal_True;
1754                 }
1755                 else
1756                 {
1757                     xub_StrLen nPos = aCorrectedFormula.Len();
1758                     if ( nPos )
1759                     {
1760                         nPos--;
1761                         sal_Unicode c = aCorrectedFormula.GetChar( nPos );
1762                         switch ( eOp )
1763                         {   // swap operators
1764                             case ocGreater:
1765                                 if ( c == mxSymbols->getSymbol(ocEqual).GetChar(0) )
1766                                 {   // >= instead of =>
1767                                     aCorrectedFormula.SetChar( nPos,
1768                                         mxSymbols->getSymbol(ocGreater).GetChar(0) );
1769                                     aCorrectedSymbol = c;
1770                                     bCorrected = sal_True;
1771                                 }
1772                             break;
1773                             case ocLess:
1774                                 if ( c == mxSymbols->getSymbol(ocEqual).GetChar(0) )
1775                                 {   // <= instead of =<
1776                                     aCorrectedFormula.SetChar( nPos,
1777                                         mxSymbols->getSymbol(ocLess).GetChar(0) );
1778                                     aCorrectedSymbol = c;
1779                                     bCorrected = sal_True;
1780                                 }
1781                                 else if ( c == mxSymbols->getSymbol(ocGreater).GetChar(0) )
1782                                 {   // <> instead of ><
1783                                     aCorrectedFormula.SetChar( nPos,
1784                                         mxSymbols->getSymbol(ocLess).GetChar(0) );
1785                                     aCorrectedSymbol = c;
1786                                     bCorrected = sal_True;
1787                                 }
1788                             break;
1789                             case ocMul:
1790                                 if ( c == mxSymbols->getSymbol(ocSub).GetChar(0) )
1791                                 {   // *- instead of -*
1792                                     aCorrectedFormula.SetChar( nPos,
1793                                         mxSymbols->getSymbol(ocMul).GetChar(0) );
1794                                     aCorrectedSymbol = c;
1795                                     bCorrected = sal_True;
1796                                 }
1797                             break;
1798                             case ocDiv:
1799                                 if ( c == mxSymbols->getSymbol(ocSub).GetChar(0) )
1800                                 {   // /- instead of -/
1801                                     aCorrectedFormula.SetChar( nPos,
1802                                         mxSymbols->getSymbol(ocDiv).GetChar(0) );
1803                                     aCorrectedSymbol = c;
1804                                     bCorrected = sal_True;
1805                                 }
1806                             break;
1807                             default:
1808                                 ;   // nothing
1809                         }
1810                     }
1811                 }
1812             }
1813         }
1814         eLastOp = eOp;
1815     }
1816     return eOp;
1817 }
PutCode(FormulaTokenRef & p)1818 void FormulaCompiler::PutCode( FormulaTokenRef& p )
1819 {
1820     if( pc >= MAXCODE-1 )
1821     {
1822         if ( pc == MAXCODE-1 )
1823         {
1824             p = new FormulaByteToken( ocStop );
1825             p->IncRef();
1826             *pCode++ = p;
1827             ++pc;
1828         }
1829         SetError(errCodeOverflow);
1830         return;
1831     }
1832     if( pArr->GetCodeError() && !bCompileForFAP )
1833         return;
1834     ForceArrayOperator( p, pCurrentFactorToken);
1835     p->IncRef();
1836     *pCode++ = p;
1837     pc++;
1838 }
1839 
1840 // -----------------------------------------------------------------------------
HandleExternalReference(const FormulaToken &)1841 sal_Bool FormulaCompiler::HandleExternalReference(const FormulaToken& /*_aToken*/)
1842 {
1843     return sal_True;
1844 }
1845 // -----------------------------------------------------------------------------
HandleRange()1846 sal_Bool FormulaCompiler::HandleRange()
1847 {
1848     return sal_True;
1849 }
1850 // -----------------------------------------------------------------------------
HandleSingleRef()1851 sal_Bool FormulaCompiler::HandleSingleRef()
1852 {
1853     return sal_True;
1854 }
1855 // -----------------------------------------------------------------------------
HandleDbData()1856 sal_Bool FormulaCompiler::HandleDbData()
1857 {
1858     return sal_True;
1859 }
1860 // -----------------------------------------------------------------------------
CreateStringFromSingleRef(rtl::OUStringBuffer &,FormulaToken *)1861 void FormulaCompiler::CreateStringFromSingleRef(rtl::OUStringBuffer& /*rBuffer*/,FormulaToken* /*pTokenP*/)
1862 {
1863 }
1864 // -----------------------------------------------------------------------------
CreateStringFromDoubleRef(rtl::OUStringBuffer &,FormulaToken *)1865 void FormulaCompiler::CreateStringFromDoubleRef(rtl::OUStringBuffer& /*rBuffer*/,FormulaToken* /*pTokenP*/)
1866 {
1867 }
1868 // -----------------------------------------------------------------------------
CreateStringFromIndex(rtl::OUStringBuffer &,FormulaToken *)1869 void FormulaCompiler::CreateStringFromIndex(rtl::OUStringBuffer& /*rBuffer*/,FormulaToken* /*pTokenP*/)
1870 {
1871 }
1872 // -----------------------------------------------------------------------------
CreateStringFromMatrix(rtl::OUStringBuffer &,FormulaToken *)1873 void FormulaCompiler::CreateStringFromMatrix(rtl::OUStringBuffer& /*rBuffer*/,FormulaToken* /*pTokenP*/)
1874 {
1875 }
1876 // -----------------------------------------------------------------------------
CreateStringFromExternal(rtl::OUStringBuffer &,FormulaToken *)1877 void FormulaCompiler::CreateStringFromExternal(rtl::OUStringBuffer& /*rBuffer*/,FormulaToken* /*pTokenP*/)
1878 {
1879 }
1880 // -----------------------------------------------------------------------------
LocalizeString(String &)1881 void FormulaCompiler::LocalizeString( String& /*rName*/ )
1882 {
1883 }
PushTokenArray(FormulaTokenArray * pa,sal_Bool bTemp)1884 void FormulaCompiler::PushTokenArray( FormulaTokenArray* pa, sal_Bool bTemp )
1885 {
1886     if ( bAutoCorrect && !pStack )
1887     {   // #61426# don't merge stacked subroutine code into entered formula
1888         aCorrectedFormula += aCorrectedSymbol;
1889         aCorrectedSymbol.Erase();
1890     }
1891     FormulaArrayStack* p = new FormulaArrayStack;
1892     p->pNext      = pStack;
1893     p->pArr       = pArr;
1894     p->bTemp      = bTemp;
1895     pStack        = p;
1896     pArr          = pa;
1897 }
1898 
1899 // =============================================================================
1900 } // formula
1901 // =============================================================================
1902