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
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_sc.hxx"
26
27 // INCLUDE ---------------------------------------------------------------
28
29 #include <sfx2/app.hxx>
30 #include <sfx2/objsh.hxx>
31 #include <basic/sbmeth.hxx>
32 #include <basic/sbstar.hxx>
33 #include <svl/zforlist.hxx>
34 #include <tools/rcid.h>
35 #include <tools/rc.hxx>
36 #include <tools/solar.h>
37 #include <unotools/charclass.hxx>
38 #include <com/sun/star/lang/Locale.hpp>
39 #include <com/sun/star/sheet/FormulaOpCodeMapEntry.hpp>
40 #include <com/sun/star/sheet/FormulaLanguage.hpp>
41 #include <com/sun/star/sheet/FormulaMapGroup.hpp>
42 #include <comphelper/processfactory.hxx>
43 #include <unotools/transliterationwrapper.hxx>
44 #include <tools/urlobj.hxx>
45 #include <rtl/math.hxx>
46 #include <ctype.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <math.h>
51 #include "compiler.hxx"
52 #include "rangenam.hxx"
53 #include "dbcolect.hxx"
54 #include "document.hxx"
55 #include "callform.hxx"
56 #include "addincol.hxx"
57 #include "refupdat.hxx"
58 #include "scresid.hxx"
59 #include "sc.hrc"
60 #include "globstr.hrc"
61 #include "cell.hxx"
62 #include "dociter.hxx"
63 #include "docoptio.hxx"
64 #include <formula/errorcodes.hxx>
65 #include "parclass.hxx"
66 #include "autonamecache.hxx"
67 #include "externalrefmgr.hxx"
68 #include "rangeutl.hxx"
69 #include "convuno.hxx"
70 #include "tokenuno.hxx"
71 #include "formulaparserpool.hxx"
72
73 using namespace formula;
74 using namespace ::com::sun::star;
75 using rtl::OUString;
76 using ::std::vector;
77
78 #if OSL_DEBUG_LEVEL > 1
79 // For some unknown reason the identical dbg_dump utilities in
80 // tools/source/string/debugprint.cxx tend to crash when called from within
81 // gdb. Having them here also comes handy as libtl*.so doesn't have to be
82 // replaced.
dbg_sc_dump(const ByteString & rStr)83 const char* dbg_sc_dump( const ByteString & rStr )
84 {
85 static ByteString aStr;
86 aStr = rStr;
87 aStr.Append(static_cast<char>(0));
88 return aStr.GetBuffer();
89 }
dbg_sc_dump(const UniString & rStr)90 const char* dbg_sc_dump( const UniString & rStr )
91 {
92 return dbg_sc_dump(ByteString(rStr, RTL_TEXTENCODING_UTF8));
93 }
dbg_sc_dump(const sal_Unicode * pBuf)94 const char* dbg_sc_dump( const sal_Unicode * pBuf )
95 {
96 return dbg_sc_dump( UniString( pBuf));
97 }
dbg_sc_dump(const sal_Unicode c)98 const char* dbg_sc_dump( const sal_Unicode c )
99 {
100 return dbg_sc_dump( UniString( c));
101 }
102 #endif
103
104 CharClass* ScCompiler::pCharClassEnglish = NULL;
105 const ScCompiler::Convention* ScCompiler::pConventions[ ] = { NULL, NULL, NULL, NULL, NULL, NULL };
106
107 enum ScanState
108 {
109 ssGetChar,
110 ssGetBool,
111 ssGetValue,
112 ssGetString,
113 ssSkipString,
114 ssGetIdent,
115 ssGetReference,
116 ssSkipReference,
117 ssStop
118 };
119
120 static const sal_Char* pInternal[ 1 ] = { "TTT" };
121
122 using namespace ::com::sun::star::i18n;
123
124 /////////////////////////////////////////////////////////////////////////
125
126
127
128 class ScCompilerRecursionGuard
129 {
130 private:
131 short& rRecursion;
132 public:
ScCompilerRecursionGuard(short & rRec)133 ScCompilerRecursionGuard( short& rRec )
134 : rRecursion( rRec ) { ++rRecursion; }
~ScCompilerRecursionGuard()135 ~ScCompilerRecursionGuard() { --rRecursion; }
136 };
137
138
fillFromAddInMap(NonConstOpCodeMapPtr xMap,FormulaGrammar::Grammar _eGrammar) const139 void ScCompiler::fillFromAddInMap( NonConstOpCodeMapPtr xMap,FormulaGrammar::Grammar _eGrammar ) const
140 {
141 size_t nSymbolOffset;
142 switch( _eGrammar )
143 {
144 case FormulaGrammar::GRAM_PODF:
145 nSymbolOffset = offsetof( AddInMap, pUpper);
146 break;
147 default:
148 case FormulaGrammar::GRAM_ODFF:
149 nSymbolOffset = offsetof( AddInMap, pODFF);
150 break;
151 case FormulaGrammar::GRAM_ENGLISH:
152 nSymbolOffset = offsetof( AddInMap, pEnglish);
153 break;
154 }
155 const AddInMap* pMap = GetAddInMap();
156 const AddInMap* const pStop = pMap + GetAddInMapCount();
157 for ( ; pMap < pStop; ++pMap)
158 {
159 char const * const * ppSymbol =
160 reinterpret_cast< char const * const * >(
161 reinterpret_cast< char const * >(pMap) + nSymbolOffset);
162 xMap->putExternal( String::CreateFromAscii( *ppSymbol),
163 String::CreateFromAscii( pMap->pOriginal));
164 }
165 }
166
fillFromAddInCollectionUpperName(NonConstOpCodeMapPtr xMap) const167 void ScCompiler::fillFromAddInCollectionUpperName( NonConstOpCodeMapPtr xMap ) const
168 {
169 ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
170 long nCount = pColl->GetFuncCount();
171 for (long i=0; i < nCount; ++i)
172 {
173 const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
174 if (pFuncData)
175 xMap->putExternalSoftly( pFuncData->GetUpperName(),
176 pFuncData->GetOriginalName());
177 }
178 }
179
fillFromAddInCollectionEnglishName(NonConstOpCodeMapPtr xMap) const180 void ScCompiler::fillFromAddInCollectionEnglishName( NonConstOpCodeMapPtr xMap ) const
181 {
182 ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
183 long nCount = pColl->GetFuncCount();
184 for (long i=0; i < nCount; ++i)
185 {
186 const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
187 if (pFuncData)
188 {
189 String aName;
190 if (pFuncData->GetExcelName( LANGUAGE_ENGLISH_US, aName))
191 xMap->putExternalSoftly( aName, pFuncData->GetOriginalName());
192 else
193 xMap->putExternalSoftly( pFuncData->GetUpperName(),
194 pFuncData->GetOriginalName());
195 }
196 }
197 }
198
199
200 #ifdef erGENERATEMAPPING
201 // Run in en-US UI by calling from within gdb, edit pODFF entries afterwards.
dbg_call_generateMappingODFF()202 void dbg_call_generateMappingODFF()
203 {
204 // static ScCompiler members
205 fprintf( stdout, "%s", "static struct AddInMap\n{\n const char* pODFF;\n const char* pEnglish;\n bool bMapDupToInternal;\n const char* pOriginal;\n const char* pUpper;\n} maAddInMap[];\n");
206 fprintf( stdout, "%s", "static const AddInMap* GetAddInMap();\n");
207 fprintf( stdout, "%s", "static size_t GetAddInMapCount();\n");
208 fprintf( stdout, "addinfuncdata___:%s", "ScCompiler::AddInMap ScCompiler::maAddInMap[] =\n{\n");
209 ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
210 long nCount = pColl->GetFuncCount();
211 for (long i=0; i < nCount; ++i)
212 {
213 const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
214 if (pFuncData)
215 {
216 #define out(rStr) (ByteString( rStr, RTL_TEXTENCODING_UTF8).GetBuffer())
217 String aL = pFuncData->GetUpperLocal();
218 String aP = pFuncData->GetOriginalName();
219 String aU = pFuncData->GetUpperName();
220 fprintf( stdout, "addinfuncdata%3ld: { \"%s\", \"%s\", false, \"%s\", \"%s\" },\n",
221 i, out(aL), out(aL), out(aP), out(aU));
222 #undef out
223 }
224 }
225 fprintf( stdout, "addinfuncdata___:%s", "};\n");
226 fprintf( stdout, "%s", "\n// static\nconst ScCompiler::AddInMap* ScCompiler::GetAddInMap()\n{\n return maAddInMap;\n}\n");
227 fprintf( stdout, "%s", "\n// static\nsize_t ScCompiler::GetAddInMapCount()\n{\n return sizeof(maAddInMap)/sizeof(maAddInMap[0]);\n}\n");
228 fflush( stdout);
229 }
230 #endif // erGENERATEMAPPING
231
232 #ifdef erGENERATEMAPPINGDIFF
233 // Run in en-US UI by calling from within gdb.
dbg_call_generateMappingDiff()234 void dbg_call_generateMappingDiff()
235 {
236 using namespace ::com::sun::star::sheet;
237 ScCompiler::OpCodeMapPtr xPODF = ScCompiler::GetOpCodeMap(
238 FormulaLanguage::ODF_11);
239 ScCompiler::OpCodeMapPtr xODFF = ScCompiler::GetOpCodeMap(
240 FormulaLanguage::ODFF);
241 ScCompiler::OpCodeMapPtr xENUS = ScCompiler::GetOpCodeMap(
242 FormulaLanguage::ENGLISH);
243 sal_uInt16 nPODF = xPODF->getSymbolCount();
244 sal_uInt16 nODFF = xODFF->getSymbolCount();
245 sal_uInt16 nENUS = xENUS->getSymbolCount();
246 printf( "%s\n", "This is a semicolon separated file, you may import it as such to Calc.");
247 printf( "%s\n", "Spreadsheet functions name differences between PODF (ODF < 1.2) and ODFF (ODF >= 1.2), plus English UI names.");
248 printf( "\nInternal OpCodes; PODF: %d; ODFF: %d; ENUS: %d\n",
249 (int)nPODF, (int)nODFF, (int)nENUS);
250 sal_uInt16 nMax = ::std::max( ::std::max( nPODF, nODFF), nENUS);
251 #define out(rStr) (ByteString( rStr, RTL_TEXTENCODING_UTF8).GetBuffer())
252 for (sal_uInt16 i=0; i < nMax; ++i)
253 {
254 const String& rPODF = xPODF->getSymbol(static_cast<OpCode>(i));
255 const String& rODFF = xODFF->getSymbol(static_cast<OpCode>(i));
256 const String& rENUS = xENUS->getSymbol(static_cast<OpCode>(i));
257 if (rPODF != rODFF)
258 printf( "%d;%s;%s;%s\n", (int)i, out(rPODF), out(rODFF), out(rENUS));
259 }
260 // Actually they should all differ, so we could simply list them all, but
261 // this is correct and we would find odd things, if any.
262 const ExternalHashMap* pPODF = xPODF->getReverseExternalHashMap();
263 const ExternalHashMap* pODFF = xODFF->getReverseExternalHashMap();
264 const ExternalHashMap* pENUS = xENUS->getReverseExternalHashMap();
265 printf( "\n%s\n", "Add-In mapping");
266 for (ExternalHashMap::const_iterator it = pPODF->begin(); it != pPODF->end(); ++it)
267 {
268 ExternalHashMap::const_iterator iLookODFF = pODFF->find( (*it).first);
269 ExternalHashMap::const_iterator iLookENUS = pENUS->find( (*it).first);
270 String aNative( iLookENUS == pENUS->end() ?
271 String::CreateFromAscii( "ENGLISH_SYMBOL_NOT_FOUND") :
272 (*iLookENUS).second);
273 if (iLookODFF == pODFF->end())
274 printf( "NOT FOUND;%s;;%s\n", out((*it).first), out(aNative));
275 else if((*it).second == (*iLookODFF).second) // upper equal
276 printf( "EQUAL;%s;%s;%s\n", out((*it).first), out((*iLookODFF).second), out(aNative));
277 else
278 printf( ";%s;%s;%s\n", out((*it).first), out((*iLookODFF).second), out(aNative));
279 }
280 #undef out
281 fflush( stdout);
282 }
283 #endif // erGENERATEMAPPINGDIFF
284
285 // static
DeInit()286 void ScCompiler::DeInit()
287 {
288 if (pCharClassEnglish)
289 {
290 delete pCharClassEnglish;
291 pCharClassEnglish = NULL;
292 }
293 }
294
IsEnglishSymbol(const String & rName)295 bool ScCompiler::IsEnglishSymbol( const String& rName )
296 {
297 // function names are always case-insensitive
298 String aUpper( ScGlobal::pCharClass->upper( rName ) );
299
300 // 1. built-in function name
301 OpCode eOp = ScCompiler::GetEnglishOpCode( aUpper );
302 if ( eOp != ocNone )
303 {
304 return true;
305 }
306 // 2. old add in functions
307 sal_uInt16 nIndex;
308 if ( ScGlobal::GetFuncCollection()->SearchFunc( aUpper, nIndex ) )
309 {
310 return true;
311 }
312
313 // 3. new (uno) add in functions
314 String aIntName(ScGlobal::GetAddInCollection()->FindFunction( aUpper, sal_False ));
315 if (aIntName.Len())
316 {
317 return true;
318 }
319 return false; // no valid function name
320 }
321
322 // static
InitCharClassEnglish()323 void ScCompiler::InitCharClassEnglish()
324 {
325 ::com::sun::star::lang::Locale aLocale(
326 OUString( RTL_CONSTASCII_USTRINGPARAM( "en")),
327 OUString( RTL_CONSTASCII_USTRINGPARAM( "US")),
328 OUString());
329 pCharClassEnglish = new CharClass(
330 ::comphelper::getProcessServiceFactory(), aLocale);
331 }
332
333
SetGrammar(const FormulaGrammar::Grammar eGrammar)334 void ScCompiler::SetGrammar( const FormulaGrammar::Grammar eGrammar )
335 {
336 DBG_ASSERT( eGrammar != FormulaGrammar::GRAM_UNSPECIFIED, "ScCompiler::SetGrammar: don't pass FormulaGrammar::GRAM_UNSPECIFIED");
337 if (eGrammar == GetGrammar())
338 return; // nothing to be done
339
340 if( eGrammar == FormulaGrammar::GRAM_EXTERNAL )
341 {
342 meGrammar = eGrammar;
343 mxSymbols = GetOpCodeMap( ::com::sun::star::sheet::FormulaLanguage::NATIVE);
344 }
345 else
346 {
347 FormulaGrammar::Grammar eMyGrammar = eGrammar;
348 const sal_Int32 nFormulaLanguage = FormulaGrammar::extractFormulaLanguage( eMyGrammar);
349 OpCodeMapPtr xMap = GetOpCodeMap( nFormulaLanguage);
350 DBG_ASSERT( xMap, "ScCompiler::SetGrammar: unknown formula language");
351 if (!xMap)
352 {
353 xMap = GetOpCodeMap( ::com::sun::star::sheet::FormulaLanguage::NATIVE);
354 eMyGrammar = xMap->getGrammar();
355 }
356
357 // Save old grammar for call to SetGrammarAndRefConvention().
358 FormulaGrammar::Grammar eOldGrammar = GetGrammar();
359 // This also sets the grammar associated with the map!
360 SetFormulaLanguage( xMap);
361
362 // Override if necessary.
363 if (eMyGrammar != GetGrammar())
364 SetGrammarAndRefConvention( eMyGrammar, eOldGrammar);
365 }
366 }
367
SetEncodeUrlMode(EncodeUrlMode eMode)368 void ScCompiler::SetEncodeUrlMode( EncodeUrlMode eMode )
369 {
370 meEncodeUrlMode = eMode;
371 }
372
GetEncodeUrlMode() const373 ScCompiler::EncodeUrlMode ScCompiler::GetEncodeUrlMode() const
374 {
375 return meEncodeUrlMode;
376 }
377
SetFormulaLanguage(const ScCompiler::OpCodeMapPtr & xMap)378 void ScCompiler::SetFormulaLanguage( const ScCompiler::OpCodeMapPtr & xMap )
379 {
380 if (xMap.get())
381 {
382 mxSymbols = xMap;
383 if (mxSymbols->isEnglish())
384 {
385 if (!pCharClassEnglish)
386 InitCharClassEnglish();
387 pCharClass = pCharClassEnglish;
388 }
389 else
390 pCharClass = ScGlobal::pCharClass;
391 SetGrammarAndRefConvention( mxSymbols->getGrammar(), GetGrammar());
392 }
393 }
394
395
SetGrammarAndRefConvention(const FormulaGrammar::Grammar eNewGrammar,const FormulaGrammar::Grammar eOldGrammar)396 void ScCompiler::SetGrammarAndRefConvention(
397 const FormulaGrammar::Grammar eNewGrammar, const FormulaGrammar::Grammar eOldGrammar )
398 {
399 meGrammar = eNewGrammar; //! SetRefConvention needs the new grammar set!
400 FormulaGrammar::AddressConvention eConv = FormulaGrammar::extractRefConvention( meGrammar);
401 if (eConv == FormulaGrammar::CONV_UNSPECIFIED && eOldGrammar == FormulaGrammar::GRAM_UNSPECIFIED)
402 {
403 if (pDoc)
404 SetRefConvention( pDoc->GetAddressConvention());
405 else
406 SetRefConvention( pConvOOO_A1);
407 }
408 else
409 SetRefConvention( eConv );
410 }
411
FindAddInFunction(const String & rUpperName,sal_Bool bLocalFirst) const412 String ScCompiler::FindAddInFunction( const String& rUpperName, sal_Bool bLocalFirst ) const
413 {
414 return ScGlobal::GetAddInCollection()->FindFunction(rUpperName, bLocalFirst); // bLocalFirst=sal_False for english
415 }
416
417
418 #ifdef erDEBUG
dbg_call_testcreatemapping()419 void dbg_call_testcreatemapping()
420 {
421 using namespace ::com::sun::star::sheet;
422 ScCompiler::OpCodeMapPtr xMap = ScCompiler::GetOpCodeMap( FormulaLanguage::ODFF);
423 xMap->createSequenceOfAvailableMappings( FormulaMapGroup::FUNCTIONS);
424 }
425 #endif
426
427 //-----------------------------------------------------------------------------
428
~Convention()429 ScCompiler::Convention::~Convention()
430 {
431 delete [] mpCharTable;
432 mpCharTable = NULL;
433 }
434
Convention(FormulaGrammar::AddressConvention eConv)435 ScCompiler::Convention::Convention( FormulaGrammar::AddressConvention eConv )
436 :
437 meConv( eConv )
438 {
439 int i;
440 sal_uLong *t= new sal_uLong [128];
441
442 ScCompiler::pConventions[ meConv ] = this;
443 mpCharTable = t;
444
445 for (i = 0; i < 128; i++)
446 t[i] = SC_COMPILER_C_ILLEGAL;
447
448 /* */ t[32] = SC_COMPILER_C_CHAR_DONTCARE | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
449 /* ! */ t[33] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
450 if (FormulaGrammar::CONV_ODF == meConv)
451 /* ! */ t[33] |= SC_COMPILER_C_ODF_LABEL_OP;
452 /* " */ t[34] = SC_COMPILER_C_CHAR_STRING | SC_COMPILER_C_STRING_SEP;
453 /* # */ t[35] = SC_COMPILER_C_WORD_SEP;
454 /* $ */ t[36] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT;
455 if (FormulaGrammar::CONV_ODF == meConv)
456 /* $ */ t[36] |= SC_COMPILER_C_ODF_NAME_MARKER;
457 /* % */ t[37] = SC_COMPILER_C_VALUE;
458 /* & */ t[38] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
459 /* ' */ t[39] = SC_COMPILER_C_NAME_SEP;
460 /* ( */ t[40] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
461 /* ) */ t[41] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
462 /* * */ t[42] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
463 /* + */ t[43] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_SIGN;
464 /* , */ t[44] = SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_VALUE;
465 /* - */ t[45] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_SIGN;
466 /* . */ t[46] = SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_VALUE | SC_COMPILER_C_IDENT | SC_COMPILER_C_NAME;
467 /* / */ t[47] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
468
469 for (i = 48; i < 58; i++)
470 /* 0-9 */ t[i] = SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_WORD | SC_COMPILER_C_VALUE | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_VALUE | SC_COMPILER_C_IDENT | SC_COMPILER_C_NAME;
471
472 /* : */ t[58] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD;
473 /* ; */ t[59] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
474 /* < */ t[60] = SC_COMPILER_C_CHAR_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
475 /* = */ t[61] = SC_COMPILER_C_CHAR | SC_COMPILER_C_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
476 /* > */ t[62] = SC_COMPILER_C_CHAR_BOOL | SC_COMPILER_C_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
477 /* ? */ t[63] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_NAME;
478 /* @ */ // FREE
479
480 for (i = 65; i < 91; i++)
481 /* A-Z */ t[i] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
482
483 if (FormulaGrammar::CONV_ODF == meConv)
484 {
485 /* [ */ t[91] = SC_COMPILER_C_ODF_LBRACKET;
486 /* \ */ // FREE
487 /* ] */ t[93] = SC_COMPILER_C_ODF_RBRACKET;
488 }
489 else
490 {
491 /* [ */ // FREE
492 /* \ */ // FREE
493 /* ] */ // FREE
494 }
495 /* ^ */ t[94] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
496 /* _ */ t[95] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
497 /* ` */ // FREE
498
499 for (i = 97; i < 123; i++)
500 /* a-z */ t[i] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
501
502 /* { */ t[123] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array open
503 /* | */ t[124] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array row sep (Should be OOo specific)
504 /* } */ t[125] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array close
505 /* ~ */ t[126] = SC_COMPILER_C_CHAR; // OOo specific
506 /* 127 */ // FREE
507
508 if( FormulaGrammar::CONV_XL_A1 == meConv || FormulaGrammar::CONV_XL_R1C1 == meConv || FormulaGrammar::CONV_XL_OOX == meConv )
509 {
510 /* */ t[32] |= SC_COMPILER_C_WORD;
511 /* ! */ t[33] |= SC_COMPILER_C_IDENT | SC_COMPILER_C_WORD;
512 /* " */ t[34] |= SC_COMPILER_C_WORD;
513 /* # */ t[35] &= (~SC_COMPILER_C_WORD_SEP);
514 /* # */ t[35] |= SC_COMPILER_C_WORD;
515 /* % */ t[37] |= SC_COMPILER_C_WORD;
516 /* ' */ t[39] |= SC_COMPILER_C_WORD;
517
518 /* % */ t[37] |= SC_COMPILER_C_WORD;
519 /* & */ t[38] |= SC_COMPILER_C_WORD;
520 /* ' */ t[39] |= SC_COMPILER_C_WORD;
521 /* ( */ t[40] |= SC_COMPILER_C_WORD;
522 /* ) */ t[41] |= SC_COMPILER_C_WORD;
523 /* * */ t[42] |= SC_COMPILER_C_WORD;
524 /* + */ t[43] |= SC_COMPILER_C_WORD;
525 #if 0 /* this really needs to be locale specific. */
526 /* , */ t[44] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
527 #else
528 /* , */ t[44] |= SC_COMPILER_C_WORD;
529 #endif
530 /* - */ t[45] |= SC_COMPILER_C_WORD;
531
532 /* ; */ t[59] |= SC_COMPILER_C_WORD;
533 /* < */ t[60] |= SC_COMPILER_C_WORD;
534 /* = */ t[61] |= SC_COMPILER_C_WORD;
535 /* > */ t[62] |= SC_COMPILER_C_WORD;
536 /* ? */ // question really is not permitted in sheet name
537 /* @ */ t[64] |= SC_COMPILER_C_WORD;
538 /* [ */ t[91] |= SC_COMPILER_C_WORD;
539 /* ] */ t[93] |= SC_COMPILER_C_WORD;
540 /* { */ t[123]|= SC_COMPILER_C_WORD;
541 /* | */ t[124]|= SC_COMPILER_C_WORD;
542 /* } */ t[125]|= SC_COMPILER_C_WORD;
543 /* ~ */ t[126]|= SC_COMPILER_C_WORD;
544
545 if( FormulaGrammar::CONV_XL_R1C1 == meConv )
546 {
547 /* - */ t[45] |= SC_COMPILER_C_IDENT;
548 /* [ */ t[91] |= SC_COMPILER_C_IDENT;
549 /* ] */ t[93] |= SC_COMPILER_C_IDENT;
550 }
551 if( FormulaGrammar::CONV_XL_OOX == meConv )
552 {
553 /* [ */ t[91] |= SC_COMPILER_C_CHAR_IDENT;
554 /* ] */ t[93] |= SC_COMPILER_C_IDENT;
555 }
556 }
557 }
558
559 //-----------------------------------------------------------------------------
560
lcl_isValidQuotedText(const String & rFormula,xub_StrLen nSrcPos,ParseResult & rRes)561 static bool lcl_isValidQuotedText( const String& rFormula, xub_StrLen nSrcPos, ParseResult& rRes )
562 {
563 // Tokens that start at ' can have anything in them until a final '
564 // but '' marks an escaped '
565 // We've earlier guaranteed that a string containing '' will be
566 // surrounded by '
567 if (rFormula.GetChar(nSrcPos) == '\'')
568 {
569 xub_StrLen nPos = nSrcPos+1;
570 while (nPos < rFormula.Len())
571 {
572 if (rFormula.GetChar(nPos) == '\'')
573 {
574 if ( (nPos+1 == rFormula.Len()) || (rFormula.GetChar(nPos+1) != '\'') )
575 {
576 rRes.TokenType = KParseType::SINGLE_QUOTE_NAME;
577 rRes.EndPos = nPos+1;
578 return true;
579 }
580 ++nPos;
581 }
582 ++nPos;
583 }
584 }
585
586 return false;
587 }
588
lcl_parseExternalName(const String & rSymbol,String & rFile,String & rName,const sal_Unicode cSep,const ScDocument * pDoc=NULL,const uno::Sequence<const sheet::ExternalLinkInfo> * pExternalLinks=NULL)589 static bool lcl_parseExternalName(
590 const String& rSymbol,
591 String& rFile,
592 String& rName,
593 const sal_Unicode cSep,
594 const ScDocument* pDoc = NULL,
595 const uno::Sequence< const sheet::ExternalLinkInfo > * pExternalLinks = NULL )
596 {
597 /* TODO: future versions will have to support sheet-local names too, thus
598 * return a possible sheet name as well. */
599 const sal_Unicode* const pStart = rSymbol.GetBuffer();
600 const sal_Unicode* p = pStart;
601 xub_StrLen nLen = rSymbol.Len();
602 sal_Unicode cPrev = 0;
603 String aTmpFile, aTmpName;
604 xub_StrLen i = 0;
605 bool bInName = false;
606 if (cSep == '!')
607 {
608 // For XL use existing parser that resolves bracketed and quoted and
609 // indexed external document names.
610 ScRange aRange;
611 String aStartTabName, aEndTabName;
612 sal_uInt16 nFlags = 0;
613 p = aRange.Parse_XL_Header( p, pDoc, aTmpFile, aStartTabName,
614 aEndTabName, nFlags, true, pExternalLinks );
615 if (!p || p == pStart)
616 return false;
617 i = xub_StrLen(p - pStart);
618 cPrev = *(p-1);
619 }
620 for ( ; i < nLen; ++i, ++p)
621 {
622 sal_Unicode c = *p;
623 if (i == 0)
624 {
625 if (c == '.' || c == cSep)
626 return false;
627
628 if (c == '\'')
629 {
630 // Move to the next chart and loop until the second single
631 // quote.
632 cPrev = c;
633 ++i; ++p;
634 for (xub_StrLen j = i; j < nLen; ++j, ++p)
635 {
636 c = *p;
637 if (c == '\'')
638 {
639 if (j == i)
640 {
641 // empty quote e.g. (=''!Name)
642 return false;
643 }
644
645 if (cPrev == '\'')
646 {
647 // two consecutive quotes equals a single
648 // quote in the file name.
649 aTmpFile.Append(c);
650 cPrev = 'a';
651 }
652 else
653 cPrev = c;
654
655 continue;
656 }
657
658 if (cPrev == '\'' && j != i)
659 {
660 // this is not a quote but the previous one
661 // is. This ends the parsing of the quoted
662 // segment.
663
664 i = j;
665 bInName = true;
666 break;
667 }
668 aTmpFile.Append(c);
669 cPrev = c;
670 }
671
672 if (!bInName)
673 {
674 // premature ending of the quoted segment.
675 return false;
676 }
677
678 if (c != cSep)
679 {
680 // only the separator is allowed after the closing quote.
681 return false;
682 }
683
684 cPrev = c;
685 continue;
686 }
687 }
688
689 if (bInName)
690 {
691 if (c == cSep)
692 {
693 // A second separator ? Not a valid external name.
694 return false;
695 }
696 aTmpName.Append(c);
697 }
698 else
699 {
700 if (c == cSep)
701 {
702 bInName = true;
703 }
704 else
705 {
706 do
707 {
708 if (CharClass::isAsciiAlphaNumeric(c))
709 // allowed.
710 break;
711
712 if (c > 128)
713 // non-ASCII character is allowed.
714 break;
715
716 bool bValid = false;
717 switch (c)
718 {
719 case '_':
720 case '-':
721 case '.':
722 // these special characters are allowed.
723 bValid = true;
724 break;
725 }
726 if (bValid)
727 break;
728
729 return false;
730 }
731 while (false);
732 aTmpFile.Append(c);
733 }
734 }
735 cPrev = c;
736 }
737
738 if (!bInName)
739 {
740 // No name found - most likely the symbol has no '!'s.
741 return false;
742 }
743
744 rFile = aTmpFile;
745 rName = aTmpName;
746 return true;
747 }
748
lcl_makeExternalNameStr(const String & rFile,const String & rName,const sal_Unicode cSep,bool bODF)749 static String lcl_makeExternalNameStr( const String& rFile, const String& rName,
750 const sal_Unicode cSep, bool bODF )
751 {
752 String aFile( rFile), aName( rName), aEscQuote( RTL_CONSTASCII_USTRINGPARAM("''"));
753 aFile.SearchAndReplaceAllAscii( "'", aEscQuote);
754 if (bODF)
755 aName.SearchAndReplaceAllAscii( "'", aEscQuote);
756 rtl::OUStringBuffer aBuf( aFile.Len() + aName.Len() + 9);
757 if (bODF)
758 aBuf.append( sal_Unicode( '['));
759 aBuf.append( sal_Unicode( '\''));
760 aBuf.append( aFile);
761 aBuf.append( sal_Unicode( '\''));
762 aBuf.append( cSep);
763 if (bODF)
764 aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "$$'"));
765 aBuf.append( aName);
766 if (bODF)
767 aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "']"));
768 return String( aBuf.makeStringAndClear());
769 }
770
lcl_getLastTabName(String & rTabName2,const String & rTabName1,const vector<String> & rTabNames,const ScComplexRefData & rRef)771 static bool lcl_getLastTabName( String& rTabName2, const String& rTabName1,
772 const vector<String>& rTabNames, const ScComplexRefData& rRef )
773 {
774 SCsTAB nTabSpan = rRef.Ref2.nTab - rRef.Ref1.nTab;
775 if (nTabSpan > 0)
776 {
777 size_t nCount = rTabNames.size();
778 vector<String>::const_iterator itrBeg = rTabNames.begin(), itrEnd = rTabNames.end();
779 vector<String>::const_iterator itr = ::std::find(itrBeg, itrEnd, rTabName1);
780 if (itr == rTabNames.end())
781 {
782 rTabName2 = ScGlobal::GetRscString(STR_NO_REF_TABLE);
783 return false;
784 }
785
786 size_t nDist = ::std::distance(itrBeg, itr);
787 if (nDist + static_cast<size_t>(nTabSpan) >= nCount)
788 {
789 rTabName2 = ScGlobal::GetRscString(STR_NO_REF_TABLE);
790 return false;
791 }
792
793 rTabName2 = rTabNames[nDist+nTabSpan];
794 }
795 else
796 rTabName2 = rTabName1;
797
798 return true;
799 }
800
801 struct Convention_A1 : public ScCompiler::Convention
802 {
Convention_A1Convention_A1803 Convention_A1( FormulaGrammar::AddressConvention eConv ) : ScCompiler::Convention( eConv ) { }
804 static void MakeColStr( rtl::OUStringBuffer& rBuffer, SCCOL nCol );
805 static void MakeRowStr( rtl::OUStringBuffer& rBuffer, SCROW nRow );
806
parseAnyTokenConvention_A1807 ParseResult parseAnyToken( const String& rFormula,
808 xub_StrLen nSrcPos,
809 const CharClass* pCharClass) const
810 {
811 ParseResult aRet;
812 if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
813 return aRet;
814
815 static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
816 KParseTokens::ASC_UNDERSCORE | KParseTokens::ASC_DOLLAR;
817 static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
818 // '?' allowed in range names because of Xcl :-/
819 static const String aAddAllowed(String::CreateFromAscii("?#"));
820 return pCharClass->parseAnyToken( rFormula,
821 nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
822 }
823 };
824
MakeColStr(rtl::OUStringBuffer & rBuffer,SCCOL nCol)825 void Convention_A1::MakeColStr( rtl::OUStringBuffer& rBuffer, SCCOL nCol )
826 {
827 if ( !ValidCol( nCol) )
828 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
829 else
830 ::ScColToAlpha( rBuffer, nCol);
831 }
832
MakeRowStr(rtl::OUStringBuffer & rBuffer,SCROW nRow)833 void Convention_A1::MakeRowStr( rtl::OUStringBuffer& rBuffer, SCROW nRow )
834 {
835 if ( !ValidRow(nRow) )
836 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
837 else
838 rBuffer.append(sal_Int32(nRow + 1));
839 }
840
841 //-----------------------------------------------------------------------------
842
843 struct ConventionOOO_A1 : public Convention_A1
844 {
ConventionOOO_A1ConventionOOO_A1845 ConventionOOO_A1() : Convention_A1 (FormulaGrammar::CONV_OOO) { }
ConventionOOO_A1ConventionOOO_A1846 ConventionOOO_A1( FormulaGrammar::AddressConvention eConv ) : Convention_A1 (eConv) { }
MakeTabStrConventionOOO_A1847 static String MakeTabStr( const ScCompiler& rComp, SCTAB nTab, String& aDoc )
848 {
849 String aString;
850 if (!rComp.GetDoc()->GetName( nTab, aString ))
851 aString = ScGlobal::GetRscString(STR_NO_REF_TABLE);
852 else
853 {
854 // "'Doc'#Tab"
855 xub_StrLen nPos = ScCompiler::GetDocTabPos( aString);
856 if (nPos != STRING_NOTFOUND)
857 {
858 aDoc = aString.Copy( 0, nPos + 1 );
859 aString.Erase( 0, nPos + 1 );
860 aDoc = INetURLObject::decode( aDoc, INET_HEX_ESCAPE,
861 INetURLObject::DECODE_UNAMBIGUOUS );
862 }
863 else
864 aDoc.Erase();
865 ScCompiler::CheckTabQuotes( aString, FormulaGrammar::CONV_OOO );
866 }
867 aString += '.';
868 return aString;
869 }
870
MakeRefStrImplConventionOOO_A1871 void MakeRefStrImpl( rtl::OUStringBuffer& rBuffer,
872 const ScCompiler& rComp,
873 const ScComplexRefData& rRef,
874 bool bSingleRef,
875 bool bODF ) const
876 {
877 if (bODF)
878 rBuffer.append(sal_Unicode('['));
879 ScComplexRefData aRef( rRef );
880 // In case absolute/relative positions weren't separately available:
881 // transform relative to absolute!
882 // AdjustReference( aRef.Ref1 );
883 // if( !bSingleRef )
884 // AdjustReference( aRef.Ref2 );
885 aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
886 if( !bSingleRef )
887 aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
888 if (bODF)
889 {
890 // OpenFormula has no spelling for a part of a reference that was deleted: the whole reference is [#REF!]
891 bool bBroken = aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() ||
892 (aRef.Ref1.IsFlag3D() && aRef.Ref1.IsTabDeleted());
893 if (!bSingleRef)
894 bBroken = bBroken || aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() ||
895 ((aRef.Ref2.IsFlag3D() || aRef.Ref2.nTab != aRef.Ref1.nTab) && aRef.Ref2.IsTabDeleted());
896 if (bBroken)
897 {
898 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
899 rBuffer.append(sal_Unicode(']'));
900 return;
901 }
902 }
903 if( aRef.Ref1.IsFlag3D() )
904 {
905 if (aRef.Ref1.IsTabDeleted())
906 {
907 if (!aRef.Ref1.IsTabRel())
908 rBuffer.append(sal_Unicode('$'));
909 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
910 rBuffer.append(sal_Unicode('.'));
911 }
912 else
913 {
914 String aDoc;
915 String aRefStr( MakeTabStr( rComp, aRef.Ref1.nTab, aDoc ) );
916 rBuffer.append(aDoc);
917 if (!aRef.Ref1.IsTabRel()) rBuffer.append(sal_Unicode('$'));
918 rBuffer.append(aRefStr);
919 }
920 }
921 else if (bODF)
922 rBuffer.append(sal_Unicode('.'));
923 if (!aRef.Ref1.IsColRel())
924 rBuffer.append(sal_Unicode('$'));
925 if ( aRef.Ref1.IsColDeleted() )
926 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
927 else
928 MakeColStr(rBuffer, aRef.Ref1.nCol );
929 if (!aRef.Ref1.IsRowRel())
930 rBuffer.append(sal_Unicode('$'));
931 if ( aRef.Ref1.IsRowDeleted() )
932 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
933 else
934 MakeRowStr( rBuffer, aRef.Ref1.nRow );
935 if (!bSingleRef)
936 {
937 rBuffer.append(sal_Unicode(':'));
938 if (aRef.Ref2.IsFlag3D() || aRef.Ref2.nTab != aRef.Ref1.nTab)
939 {
940 if (aRef.Ref2.IsTabDeleted())
941 {
942 if (!aRef.Ref2.IsTabRel())
943 rBuffer.append(sal_Unicode('$'));
944 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
945 rBuffer.append(sal_Unicode('.'));
946 }
947 else
948 {
949 String aDoc;
950 String aRefStr( MakeTabStr( rComp, aRef.Ref2.nTab, aDoc ) );
951 rBuffer.append(aDoc);
952 if (!aRef.Ref2.IsTabRel()) rBuffer.append(sal_Unicode('$'));
953 rBuffer.append(aRefStr);
954 }
955 }
956 else if (bODF)
957 rBuffer.append(sal_Unicode('.'));
958 if (!aRef.Ref2.IsColRel())
959 rBuffer.append(sal_Unicode('$'));
960 if ( aRef.Ref2.IsColDeleted() )
961 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
962 else
963 MakeColStr( rBuffer, aRef.Ref2.nCol );
964 if (!aRef.Ref2.IsRowRel())
965 rBuffer.append(sal_Unicode('$'));
966 if ( aRef.Ref2.IsRowDeleted() )
967 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
968 else
969 MakeRowStr( rBuffer, aRef.Ref2.nRow );
970 }
971 if (bODF)
972 rBuffer.append(sal_Unicode(']'));
973 }
974
MakeRefStrConventionOOO_A1975 void MakeRefStr( rtl::OUStringBuffer& rBuffer,
976 const ScCompiler& rComp,
977 const ScComplexRefData& rRef,
978 sal_Bool bSingleRef ) const
979 {
980 MakeRefStrImpl( rBuffer, rComp, rRef, bSingleRef, false);
981 }
982
getSpecialSymbolConventionOOO_A1983 virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
984 {
985 switch (eSymType)
986 {
987 case ScCompiler::Convention::ABS_SHEET_PREFIX:
988 return '$';
989 case ScCompiler::Convention::SHEET_SEPARATOR:
990 return '.';
991 }
992
993 return sal_Unicode(0);
994 }
995
parseExternalNameConventionOOO_A1996 virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
997 const ScDocument* pDoc,
998 const ::com::sun::star::uno::Sequence<
999 const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
1000 {
1001 return lcl_parseExternalName(rSymbol, rFile, rName, sal_Unicode('#'), pDoc, pExternalLinks);
1002 }
1003
makeExternalNameStrConventionOOO_A11004 virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
1005 {
1006 return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('#'), false);
1007 }
1008
makeExternalSingleRefStrConventionOOO_A11009 bool makeExternalSingleRefStr( ::rtl::OUStringBuffer& rBuffer, sal_uInt16 nFileId,
1010 const String& rTabName, const ScSingleRefData& rRef,
1011 ScExternalRefManager* pRefMgr, bool bDisplayTabName, bool bEncodeUrl ) const
1012 {
1013 if (bDisplayTabName)
1014 {
1015 String aFile;
1016 const String* p = pRefMgr->getExternalFileName(nFileId);
1017 if (p)
1018 {
1019 if (bEncodeUrl)
1020 aFile = *p;
1021 else
1022 aFile = INetURLObject::decode(*p, INET_HEX_ESCAPE, INetURLObject::DECODE_UNAMBIGUOUS);
1023 }
1024 aFile.SearchAndReplaceAllAscii("'", String::CreateFromAscii("''"));
1025
1026 rBuffer.append(sal_Unicode('\''));
1027 rBuffer.append(aFile);
1028 rBuffer.append(sal_Unicode('\''));
1029 rBuffer.append(sal_Unicode('#'));
1030
1031 if (!rRef.IsTabRel())
1032 rBuffer.append(sal_Unicode('$'));
1033 ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
1034
1035 rBuffer.append(sal_Unicode('.'));
1036 }
1037
1038 if (!rRef.IsColRel())
1039 rBuffer.append(sal_Unicode('$'));
1040 MakeColStr( rBuffer, rRef.nCol);
1041 if (!rRef.IsRowRel())
1042 rBuffer.append(sal_Unicode('$'));
1043 MakeRowStr( rBuffer, rRef.nRow);
1044
1045 return true;
1046 }
1047
makeExternalRefStrImplConventionOOO_A11048 void makeExternalRefStrImpl( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1049 sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
1050 ScExternalRefManager* pRefMgr, bool bODF ) const
1051 {
1052 ScSingleRefData aRef(rRef);
1053 aRef.CalcAbsIfRel(rCompiler.GetPos());
1054
1055 if (bODF)
1056 rBuffer.append( sal_Unicode('['));
1057
1058 bool bEncodeUrl = true;
1059 switch (rCompiler.GetEncodeUrlMode())
1060 {
1061 case ScCompiler::ENCODE_BY_GRAMMAR:
1062 bEncodeUrl = bODF;
1063 break;
1064 case ScCompiler::ENCODE_ALWAYS:
1065 bEncodeUrl = true;
1066 break;
1067 case ScCompiler::ENCODE_NEVER:
1068 bEncodeUrl = false;
1069 break;
1070 default:
1071 ;
1072 }
1073 makeExternalSingleRefStr(rBuffer, nFileId, rTabName, aRef, pRefMgr, true, bEncodeUrl);
1074 if (bODF)
1075 rBuffer.append( sal_Unicode(']'));
1076 }
1077
makeExternalRefStrConventionOOO_A11078 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1079 sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
1080 ScExternalRefManager* pRefMgr ) const
1081 {
1082 makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, false);
1083 }
1084
makeExternalRefStrImplConventionOOO_A11085 void makeExternalRefStrImpl( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1086 sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
1087 ScExternalRefManager* pRefMgr, bool bODF ) const
1088 {
1089 ScComplexRefData aRef(rRef);
1090 aRef.CalcAbsIfRel(rCompiler.GetPos());
1091
1092 if (bODF)
1093 rBuffer.append( sal_Unicode('['));
1094 // Ensure that there's always a closing bracket, no premature returns.
1095 bool bEncodeUrl = true;
1096 switch (rCompiler.GetEncodeUrlMode())
1097 {
1098 case ScCompiler::ENCODE_BY_GRAMMAR:
1099 bEncodeUrl = bODF;
1100 break;
1101 case ScCompiler::ENCODE_ALWAYS:
1102 bEncodeUrl = true;
1103 break;
1104 case ScCompiler::ENCODE_NEVER:
1105 bEncodeUrl = false;
1106 break;
1107 default:
1108 ;
1109 }
1110
1111 do
1112 {
1113 if (!makeExternalSingleRefStr(rBuffer, nFileId, rTabName, aRef.Ref1, pRefMgr, true, bEncodeUrl))
1114 break;
1115
1116 rBuffer.append(sal_Unicode(':'));
1117
1118 String aLastTabName;
1119 bool bDisplayTabName = (aRef.Ref1.nTab != aRef.Ref2.nTab);
1120 if (bDisplayTabName)
1121 {
1122 // Get the name of the last table.
1123 vector<String> aTabNames;
1124 pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
1125 if (aTabNames.empty())
1126 {
1127 DBG_ERROR1( "ConventionOOO_A1::makeExternalRefStrImpl: no sheet names for document ID %s", nFileId);
1128 }
1129
1130 if (!lcl_getLastTabName(aLastTabName, rTabName, aTabNames, aRef))
1131 {
1132 DBG_ERROR( "ConventionOOO_A1::makeExternalRefStrImpl: sheet name not found");
1133 // aLastTabName contains #REF!, proceed.
1134 }
1135 }
1136 else if (bODF)
1137 rBuffer.append( sal_Unicode('.')); // need at least the sheet separator in ODF
1138 makeExternalSingleRefStr( rBuffer, nFileId, aLastTabName,
1139 aRef.Ref2, pRefMgr, bDisplayTabName, bEncodeUrl);
1140 } while (0);
1141 if (bODF)
1142 rBuffer.append( sal_Unicode(']'));
1143 }
1144
makeExternalRefStrConventionOOO_A11145 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1146 sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
1147 ScExternalRefManager* pRefMgr ) const
1148 {
1149 makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, false);
1150 }
1151 };
1152
1153
1154 static const ConventionOOO_A1 ConvOOO_A1;
1155 const ScCompiler::Convention * const ScCompiler::pConvOOO_A1 = &ConvOOO_A1;
1156
1157 //-----------------------------------------------------------------------------
1158
1159 struct ConventionOOO_A1_ODF : public ConventionOOO_A1
1160 {
ConventionOOO_A1_ODFConventionOOO_A1_ODF1161 ConventionOOO_A1_ODF() : ConventionOOO_A1 (FormulaGrammar::CONV_ODF) { }
MakeRefStrConventionOOO_A1_ODF1162 void MakeRefStr( rtl::OUStringBuffer& rBuffer,
1163 const ScCompiler& rComp,
1164 const ScComplexRefData& rRef,
1165 sal_Bool bSingleRef ) const
1166 {
1167 MakeRefStrImpl( rBuffer, rComp, rRef, bSingleRef, true);
1168 }
1169
makeExternalNameStrConventionOOO_A1_ODF1170 virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
1171 {
1172 return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('#'), true);
1173 }
1174
makeExternalRefStrConventionOOO_A1_ODF1175 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1176 sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
1177 ScExternalRefManager* pRefMgr ) const
1178 {
1179 makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, true);
1180 }
1181
makeExternalRefStrConventionOOO_A1_ODF1182 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1183 sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
1184 ScExternalRefManager* pRefMgr ) const
1185 {
1186 makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, true);
1187 }
1188 };
1189
1190 static const ConventionOOO_A1_ODF ConvOOO_A1_ODF;
1191 const ScCompiler::Convention * const ScCompiler::pConvOOO_A1_ODF = &ConvOOO_A1_ODF;
1192
1193 //-----------------------------------------------------------------------------
1194
1195 struct ConventionXL
1196 {
GetDocAndTabConventionXL1197 static bool GetDocAndTab( const ScCompiler& rComp,
1198 const ScSingleRefData& rRef,
1199 String& rDocName,
1200 String& rTabName )
1201 {
1202 bool bHasDoc = false;
1203
1204 rDocName.Erase();
1205 if (rRef.IsTabDeleted() ||
1206 !rComp.GetDoc()->GetName( rRef.nTab, rTabName ))
1207 {
1208 rTabName = ScGlobal::GetRscString( STR_NO_REF_TABLE );
1209 return false;
1210 }
1211
1212 // Cheesy hack to unparse the OOO style "'Doc'#Tab"
1213 xub_StrLen nPos = ScCompiler::GetDocTabPos( rTabName);
1214 if (nPos != STRING_NOTFOUND)
1215 {
1216 rDocName = rTabName.Copy( 0, nPos );
1217 // TODO : More research into how XL escapes the doc path
1218 rDocName = INetURLObject::decode( rDocName, INET_HEX_ESCAPE,
1219 INetURLObject::DECODE_UNAMBIGUOUS );
1220 rTabName.Erase( 0, nPos + 1 );
1221 bHasDoc = true;
1222 }
1223
1224 // XL uses the same sheet name quoting conventions in both modes
1225 // it is safe to use A1 here
1226 ScCompiler::CheckTabQuotes( rTabName, FormulaGrammar::CONV_XL_A1 );
1227 return bHasDoc;
1228 }
1229
MakeDocStrConventionXL1230 static void MakeDocStr( rtl::OUStringBuffer& rBuf,
1231 const ScCompiler& rComp,
1232 const ScComplexRefData& rRef,
1233 bool bSingleRef )
1234 {
1235 if( rRef.Ref1.IsFlag3D() )
1236 {
1237 String aStartTabName, aStartDocName, aEndTabName, aEndDocName;
1238 bool bStartHasDoc = false, bEndHasDoc = false;
1239
1240 bStartHasDoc = GetDocAndTab( rComp, rRef.Ref1,
1241 aStartDocName, aStartTabName);
1242
1243 if( !bSingleRef && rRef.Ref2.IsFlag3D() )
1244 {
1245 bEndHasDoc = GetDocAndTab( rComp, rRef.Ref2,
1246 aEndDocName, aEndTabName);
1247 }
1248 else
1249 bEndHasDoc = bStartHasDoc;
1250
1251 if( bStartHasDoc )
1252 {
1253 // A ref across multiplied workbooks ?
1254 if( !bEndHasDoc )
1255 return;
1256
1257 rBuf.append( sal_Unicode( '[' ) );
1258 rBuf.append( aStartDocName );
1259 rBuf.append( sal_Unicode( ']' ) );
1260 }
1261
1262 rBuf.append( aStartTabName );
1263 if( !bSingleRef && rRef.Ref2.IsFlag3D() && aStartTabName != aEndTabName )
1264 {
1265 rBuf.append( sal_Unicode( ':' ) );
1266 rBuf.append( aEndTabName );
1267 }
1268
1269 rBuf.append( sal_Unicode( '!' ) );
1270 }
1271 }
1272
getSpecialSymbolConventionXL1273 static sal_Unicode getSpecialSymbol( ScCompiler::Convention::SpecialSymbolType eSymType )
1274 {
1275 switch (eSymType)
1276 {
1277 case ScCompiler::Convention::ABS_SHEET_PREFIX:
1278 return sal_Unicode(0);
1279 case ScCompiler::Convention::SHEET_SEPARATOR:
1280 return '!';
1281 }
1282 return sal_Unicode(0);
1283 }
1284
parseExternalNameConventionXL1285 static bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
1286 const ScDocument* pDoc,
1287 const ::com::sun::star::uno::Sequence<
1288 const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks )
1289 {
1290 return lcl_parseExternalName( rSymbol, rFile, rName, sal_Unicode('!'), pDoc, pExternalLinks);
1291 }
1292
makeExternalNameStrConventionXL1293 static String makeExternalNameStr( const String& rFile, const String& rName )
1294 {
1295 return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('!'), false);
1296 }
1297
makeExternalDocStrConventionXL1298 static void makeExternalDocStr( ::rtl::OUStringBuffer& rBuffer, const String& rFullName, bool bEncodeUrl )
1299 {
1300 // Format that is easier to deal with inside OOo, because we use file
1301 // URL, and all characetrs are allowed. Check if it makes sense to do
1302 // it the way Gnumeric does it. Gnumeric doesn't use the URL form
1303 // and allows relative file path.
1304 //
1305 // ['file:///path/to/source/filename.xls']
1306
1307 rBuffer.append(sal_Unicode('['));
1308 rBuffer.append(sal_Unicode('\''));
1309 String aFullName;
1310 if (bEncodeUrl)
1311 aFullName = rFullName;
1312 else
1313 aFullName = INetURLObject::decode(rFullName, INET_HEX_ESCAPE, INetURLObject::DECODE_UNAMBIGUOUS);
1314
1315 const sal_Unicode* pBuf = aFullName.GetBuffer();
1316 xub_StrLen nLen = aFullName.Len();
1317 for (xub_StrLen i = 0; i < nLen; ++i)
1318 {
1319 const sal_Unicode c = pBuf[i];
1320 if (c == sal_Unicode('\''))
1321 rBuffer.append(c);
1322 rBuffer.append(c);
1323 }
1324 rBuffer.append(sal_Unicode('\''));
1325 rBuffer.append(sal_Unicode(']'));
1326 }
1327
makeExternalTabNameRangeConventionXL1328 static void makeExternalTabNameRange( ::rtl::OUStringBuffer& rBuf, const String& rTabName,
1329 const vector<String>& rTabNames,
1330 const ScComplexRefData& rRef )
1331 {
1332 String aLastTabName;
1333 if (!lcl_getLastTabName(aLastTabName, rTabName, rTabNames, rRef))
1334 {
1335 ScRangeStringConverter::AppendTableName(rBuf, aLastTabName);
1336 return;
1337 }
1338
1339 ScRangeStringConverter::AppendTableName(rBuf, rTabName);
1340 if (rTabName != aLastTabName)
1341 {
1342 rBuf.append(sal_Unicode(':'));
1343 ScRangeStringConverter::AppendTableName(rBuf, rTabName);
1344 }
1345 }
1346
parseExternalDocNameConventionXL1347 static void parseExternalDocName( const String& rFormula, xub_StrLen& rSrcPos )
1348 {
1349 xub_StrLen nLen = rFormula.Len();
1350 const sal_Unicode* p = rFormula.GetBuffer();
1351 sal_Unicode cPrev = 0;
1352 for (xub_StrLen i = rSrcPos; i < nLen; ++i)
1353 {
1354 sal_Unicode c = p[i];
1355 if (i == rSrcPos)
1356 {
1357 // first character must be '['.
1358 if (c != '[')
1359 return;
1360 }
1361 else if (i == rSrcPos + 1)
1362 {
1363 // second character must be a single quote.
1364 if (c != '\'')
1365 return;
1366 }
1367 else if (c == '\'')
1368 {
1369 if (cPrev == '\'')
1370 // two successive single quote is treated as a single
1371 // valid character.
1372 c = 'a';
1373 }
1374 else if (c == ']')
1375 {
1376 if (cPrev == '\'')
1377 {
1378 // valid source document path found. Increment the
1379 // current position to skip the source path.
1380 rSrcPos = i + 1;
1381 if (rSrcPos >= nLen)
1382 rSrcPos = nLen - 1;
1383 return;
1384 }
1385 else
1386 return;
1387 }
1388 else
1389 {
1390 // any other character
1391 if (i > rSrcPos + 2 && cPrev == '\'')
1392 // unless it's the 3rd character, a normal character
1393 // following immediately a single quote is invalid.
1394 return;
1395 }
1396 cPrev = c;
1397 }
1398 }
1399 };
1400
1401 struct ConventionXL_A1 : public Convention_A1, public ConventionXL
1402 {
ConventionXL_A1ConventionXL_A11403 ConventionXL_A1() : Convention_A1( FormulaGrammar::CONV_XL_A1 ) { }
ConventionXL_A1ConventionXL_A11404 ConventionXL_A1( FormulaGrammar::AddressConvention eConv ) : Convention_A1( eConv ) { }
1405
makeSingleCellStrConventionXL_A11406 void makeSingleCellStr( ::rtl::OUStringBuffer& rBuf, const ScSingleRefData& rRef ) const
1407 {
1408 if (!rRef.IsColRel())
1409 rBuf.append(sal_Unicode('$'));
1410 MakeColStr(rBuf, rRef.nCol);
1411 if (!rRef.IsRowRel())
1412 rBuf.append(sal_Unicode('$'));
1413 MakeRowStr(rBuf, rRef.nRow);
1414 }
1415
MakeRefStrConventionXL_A11416 void MakeRefStr( rtl::OUStringBuffer& rBuf,
1417 const ScCompiler& rComp,
1418 const ScComplexRefData& rRef,
1419 sal_Bool bSingleRef ) const
1420 {
1421 ScComplexRefData aRef( rRef );
1422
1423 // Play fast and loose with invalid refs. There is not much point in producing
1424 // Foo!A1:#REF! versus #REF! at this point
1425 aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
1426
1427 MakeDocStr( rBuf, rComp, aRef, bSingleRef );
1428
1429 if( aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() )
1430 {
1431 rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
1432 return;
1433 }
1434
1435 if( !bSingleRef )
1436 {
1437 aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
1438 if( aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() )
1439 {
1440 rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
1441 return;
1442 }
1443
1444 if( aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL )
1445 {
1446 if (!aRef.Ref1.IsRowRel())
1447 rBuf.append(sal_Unicode( '$' ));
1448 MakeRowStr( rBuf, aRef.Ref1.nRow );
1449 rBuf.append(sal_Unicode( ':' ));
1450 if (!aRef.Ref2.IsRowRel())
1451 rBuf.append(sal_Unicode( '$' ));
1452 MakeRowStr( rBuf, aRef.Ref2.nRow );
1453 return;
1454 }
1455
1456 if( aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW )
1457 {
1458 if (!aRef.Ref1.IsColRel())
1459 rBuf.append(sal_Unicode( '$' ));
1460 MakeColStr(rBuf, aRef.Ref1.nCol );
1461 rBuf.append(sal_Unicode( ':' ));
1462 if (!aRef.Ref2.IsColRel())
1463 rBuf.append(sal_Unicode( '$' ));
1464 MakeColStr(rBuf, aRef.Ref2.nCol );
1465 return;
1466 }
1467 }
1468
1469 makeSingleCellStr(rBuf, aRef.Ref1);
1470 if (!bSingleRef)
1471 {
1472 rBuf.append(sal_Unicode( ':' ));
1473 makeSingleCellStr(rBuf, aRef.Ref2);
1474 }
1475 }
1476
parseAnyTokenConventionXL_A11477 virtual ParseResult parseAnyToken( const String& rFormula,
1478 xub_StrLen nSrcPos,
1479 const CharClass* pCharClass) const
1480 {
1481 ParseResult aRet;
1482 if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
1483 return aRet;
1484
1485 static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
1486 KParseTokens::ASC_UNDERSCORE | KParseTokens::ASC_DOLLAR;
1487 static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
1488 // '?' allowed in range names
1489 static const String aAddAllowed = String::CreateFromAscii("?!");
1490 return pCharClass->parseAnyToken( rFormula,
1491 nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
1492 }
1493
getSpecialSymbolConventionXL_A11494 virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
1495 {
1496 return ConventionXL::getSpecialSymbol(eSymType);
1497 }
1498
parseExternalNameConventionXL_A11499 virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
1500 const ScDocument* pDoc,
1501 const ::com::sun::star::uno::Sequence<
1502 const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
1503 {
1504 return ConventionXL::parseExternalName( rSymbol, rFile, rName, pDoc, pExternalLinks);
1505 }
1506
makeExternalNameStrConventionXL_A11507 virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
1508 {
1509 return ConventionXL::makeExternalNameStr(rFile, rName);
1510 }
1511
makeExternalRefStrConventionXL_A11512 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1513 sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
1514 ScExternalRefManager* pRefMgr ) const
1515 {
1516 // ['file:///path/to/file/filename.xls']'Sheet Name'!$A$1
1517 // This is a little different from the format Excel uses, as Excel
1518 // puts [] only around the file name. But we need to enclose the
1519 // whole file path with [] because the file name can contain any
1520 // characters.
1521
1522 const String* pFullName = pRefMgr->getExternalFileName(nFileId);
1523 if (!pFullName)
1524 return;
1525
1526 ScSingleRefData aRef(rRef);
1527 aRef.CalcAbsIfRel(rCompiler.GetPos());
1528
1529 ConventionXL::makeExternalDocStr(
1530 rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
1531 ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
1532 rBuffer.append(sal_Unicode('!'));
1533
1534 makeSingleCellStr(rBuffer, aRef);
1535 }
1536
makeExternalRefStrConventionXL_A11537 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1538 sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
1539 ScExternalRefManager* pRefMgr ) const
1540 {
1541 const String* pFullName = pRefMgr->getExternalFileName(nFileId);
1542 if (!pFullName)
1543 return;
1544
1545 vector<String> aTabNames;
1546 pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
1547 if (aTabNames.empty())
1548 return;
1549
1550 ScComplexRefData aRef(rRef);
1551 aRef.CalcAbsIfRel(rCompiler.GetPos());
1552
1553 ConventionXL::makeExternalDocStr(
1554 rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
1555 ConventionXL::makeExternalTabNameRange(rBuffer, rTabName, aTabNames, aRef);
1556 rBuffer.append(sal_Unicode('!'));
1557
1558 makeSingleCellStr(rBuffer, aRef.Ref1);
1559 if (aRef.Ref1 != aRef.Ref2)
1560 {
1561 rBuffer.append(sal_Unicode(':'));
1562 makeSingleCellStr(rBuffer, aRef.Ref2);
1563 }
1564 }
1565 };
1566
1567 static const ConventionXL_A1 ConvXL_A1;
1568 const ScCompiler::Convention * const ScCompiler::pConvXL_A1 = &ConvXL_A1;
1569
1570
1571 struct ConventionXL_OOX : public ConventionXL_A1
1572 {
ConventionXL_OOXConventionXL_OOX1573 ConventionXL_OOX() : ConventionXL_A1( FormulaGrammar::CONV_XL_OOX ) { }
1574 };
1575
1576 static const ConventionXL_OOX ConvXL_OOX;
1577 const ScCompiler::Convention * const ScCompiler::pConvXL_OOX = &ConvXL_OOX;
1578
1579
1580 //-----------------------------------------------------------------------------
1581
1582 static void
r1c1_add_col(rtl::OUStringBuffer & rBuf,const ScSingleRefData & rRef)1583 r1c1_add_col( rtl::OUStringBuffer &rBuf, const ScSingleRefData& rRef )
1584 {
1585 rBuf.append( sal_Unicode( 'C' ) );
1586 if( rRef.IsColRel() )
1587 {
1588 if (rRef.nRelCol != 0)
1589 {
1590 rBuf.append( sal_Unicode( '[' ) );
1591 rBuf.append( String::CreateFromInt32( rRef.nRelCol ) );
1592 rBuf.append( sal_Unicode( ']' ) );
1593 }
1594 }
1595 else
1596 rBuf.append( String::CreateFromInt32( rRef.nCol + 1 ) );
1597 }
1598 static void
r1c1_add_row(rtl::OUStringBuffer & rBuf,const ScSingleRefData & rRef)1599 r1c1_add_row( rtl::OUStringBuffer &rBuf, const ScSingleRefData& rRef )
1600 {
1601 rBuf.append( sal_Unicode( 'R' ) );
1602 if( rRef.IsRowRel() )
1603 {
1604 if (rRef.nRelRow != 0)
1605 {
1606 rBuf.append( sal_Unicode( '[' ) );
1607 rBuf.append( String::CreateFromInt32( rRef.nRelRow ) );
1608 rBuf.append( sal_Unicode( ']' ) );
1609 }
1610 }
1611 else
1612 rBuf.append( String::CreateFromInt32( rRef.nRow + 1 ) );
1613 }
1614
1615 struct ConventionXL_R1C1 : public ScCompiler::Convention, public ConventionXL
1616 {
ConventionXL_R1C1ConventionXL_R1C11617 ConventionXL_R1C1() : ScCompiler::Convention( FormulaGrammar::CONV_XL_R1C1 ) { }
MakeRefStrConventionXL_R1C11618 void MakeRefStr( rtl::OUStringBuffer& rBuf,
1619 const ScCompiler& rComp,
1620 const ScComplexRefData& rRef,
1621 sal_Bool bSingleRef ) const
1622 {
1623 ScComplexRefData aRef( rRef );
1624
1625 MakeDocStr( rBuf, rComp, aRef, bSingleRef );
1626
1627 // Play fast and loose with invalid refs. There is not much point in producing
1628 // Foo!A1:#REF! versus #REF! at this point
1629 aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
1630 if( aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() )
1631 {
1632 rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
1633 return;
1634 }
1635
1636 if( !bSingleRef )
1637 {
1638 aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
1639 if( aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() )
1640 {
1641 rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
1642 return;
1643 }
1644
1645 if( aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL )
1646 {
1647 r1c1_add_row( rBuf, rRef.Ref1 );
1648 if( rRef.Ref1.nRow != rRef.Ref2.nRow ||
1649 rRef.Ref1.IsRowRel() != rRef.Ref2.IsRowRel() ) {
1650 rBuf.append (sal_Unicode ( ':' ) );
1651 r1c1_add_row( rBuf, rRef.Ref2 );
1652 }
1653 return;
1654
1655 }
1656
1657 if( aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW )
1658 {
1659 r1c1_add_col( rBuf, rRef.Ref1 );
1660 if( rRef.Ref1.nCol != rRef.Ref2.nCol ||
1661 rRef.Ref1.IsColRel() != rRef.Ref2.IsColRel() )
1662 {
1663 rBuf.append (sal_Unicode ( ':' ) );
1664 r1c1_add_col( rBuf, rRef.Ref2 );
1665 }
1666 return;
1667 }
1668 }
1669
1670 r1c1_add_row( rBuf, rRef.Ref1 );
1671 r1c1_add_col( rBuf, rRef.Ref1 );
1672 if (!bSingleRef)
1673 {
1674 rBuf.append (sal_Unicode ( ':' ) );
1675 r1c1_add_row( rBuf, rRef.Ref2 );
1676 r1c1_add_col( rBuf, rRef.Ref2 );
1677 }
1678 }
1679
parseAnyTokenConventionXL_R1C11680 ParseResult parseAnyToken( const String& rFormula,
1681 xub_StrLen nSrcPos,
1682 const CharClass* pCharClass) const
1683 {
1684 ConventionXL::parseExternalDocName(rFormula, nSrcPos);
1685
1686 ParseResult aRet;
1687 if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
1688 return aRet;
1689
1690 static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
1691 KParseTokens::ASC_UNDERSCORE ;
1692 static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
1693 // '?' allowed in range names
1694 static const String aAddAllowed = String::CreateFromAscii( "?-[]!" );
1695
1696 return pCharClass->parseAnyToken( rFormula,
1697 nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
1698 }
1699
getSpecialSymbolConventionXL_R1C11700 virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
1701 {
1702 return ConventionXL::getSpecialSymbol(eSymType);
1703 }
1704
parseExternalNameConventionXL_R1C11705 virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
1706 const ScDocument* pDoc,
1707 const ::com::sun::star::uno::Sequence<
1708 const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
1709 {
1710 return ConventionXL::parseExternalName( rSymbol, rFile, rName, pDoc, pExternalLinks);
1711 }
1712
makeExternalNameStrConventionXL_R1C11713 virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
1714 {
1715 return ConventionXL::makeExternalNameStr(rFile, rName);
1716 }
1717
makeExternalRefStrConventionXL_R1C11718 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1719 sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
1720 ScExternalRefManager* pRefMgr ) const
1721 {
1722 // ['file:///path/to/file/filename.xls']'Sheet Name'!$A$1
1723 // This is a little different from the format Excel uses, as Excel
1724 // puts [] only around the file name. But we need to enclose the
1725 // whole file path with [] because the file name can contain any
1726 // characters.
1727
1728 const String* pFullName = pRefMgr->getExternalFileName(nFileId);
1729 if (!pFullName)
1730 return;
1731
1732 ScSingleRefData aRef(rRef);
1733 aRef.CalcAbsIfRel(rCompiler.GetPos());
1734
1735 ConventionXL::makeExternalDocStr(
1736 rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
1737 ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
1738 rBuffer.append(sal_Unicode('!'));
1739
1740 r1c1_add_row(rBuffer, aRef);
1741 r1c1_add_col(rBuffer, aRef);
1742 }
1743
makeExternalRefStrConventionXL_R1C11744 virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
1745 sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
1746 ScExternalRefManager* pRefMgr ) const
1747 {
1748 const String* pFullName = pRefMgr->getExternalFileName(nFileId);
1749 if (!pFullName)
1750 return;
1751
1752 vector<String> aTabNames;
1753 pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
1754 if (aTabNames.empty())
1755 return;
1756
1757 ScComplexRefData aRef(rRef);
1758 aRef.CalcAbsIfRel(rCompiler.GetPos());
1759
1760 ConventionXL::makeExternalDocStr(
1761 rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
1762 ConventionXL::makeExternalTabNameRange(rBuffer, rTabName, aTabNames, aRef);
1763 rBuffer.append(sal_Unicode('!'));
1764
1765 if (aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted())
1766 {
1767 rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
1768 return;
1769 }
1770
1771 if (aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL)
1772 {
1773 r1c1_add_row(rBuffer, rRef.Ref1);
1774 if (rRef.Ref1.nRow != rRef.Ref2.nRow || rRef.Ref1.IsRowRel() != rRef.Ref2.IsRowRel())
1775 {
1776 rBuffer.append (sal_Unicode(':'));
1777 r1c1_add_row(rBuffer, rRef.Ref2);
1778 }
1779 return;
1780 }
1781
1782 if (aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW)
1783 {
1784 r1c1_add_col(rBuffer, aRef.Ref1);
1785 if (aRef.Ref1.nCol != aRef.Ref2.nCol || aRef.Ref1.IsColRel() != aRef.Ref2.IsColRel())
1786 {
1787 rBuffer.append (sal_Unicode(':'));
1788 r1c1_add_col(rBuffer, aRef.Ref2);
1789 }
1790 return;
1791 }
1792
1793 r1c1_add_row(rBuffer, aRef.Ref1);
1794 r1c1_add_col(rBuffer, aRef.Ref1);
1795 rBuffer.append (sal_Unicode (':'));
1796 r1c1_add_row(rBuffer, aRef.Ref2);
1797 r1c1_add_col(rBuffer, aRef.Ref2);
1798 }
1799 };
1800
1801 static const ConventionXL_R1C1 ConvXL_R1C1;
1802 const ScCompiler::Convention * const ScCompiler::pConvXL_R1C1 = &ConvXL_R1C1;
1803
1804 //-----------------------------------------------------------------------------
ScCompiler(ScDocument * pDocument,const ScAddress & rPos,ScTokenArray & rArr)1805 ScCompiler::ScCompiler( ScDocument* pDocument, const ScAddress& rPos,ScTokenArray& rArr)
1806 : FormulaCompiler(rArr),
1807 pDoc( pDocument ),
1808 aPos( rPos ),
1809 pCharClass( ScGlobal::pCharClass ),
1810 mnPredetectedReference(0),
1811 mnRangeOpPosInSymbol(-1),
1812 pConv( pConvOOO_A1 ),
1813 meEncodeUrlMode( ENCODE_BY_GRAMMAR ),
1814 mbCloseBrackets( true ),
1815 mbExtendedErrorDetection( false ),
1816 mbRewind( false )
1817 {
1818 cSymbol = new sal_Unicode[ MAXSYMLEN ];
1819 nMaxTab = pDoc ? pDoc->GetTableCount() - 1 : 0;
1820 }
1821
ScCompiler(ScDocument * pDocument,const ScAddress & rPos)1822 ScCompiler::ScCompiler( ScDocument* pDocument, const ScAddress& rPos)
1823 :
1824 pDoc( pDocument ),
1825 aPos( rPos ),
1826 pCharClass( ScGlobal::pCharClass ),
1827 mnPredetectedReference(0),
1828 mnRangeOpPosInSymbol(-1),
1829 pConv( pConvOOO_A1 ),
1830 meEncodeUrlMode( ENCODE_BY_GRAMMAR ),
1831 mbCloseBrackets( true ),
1832 mbExtendedErrorDetection( false ),
1833 mbRewind( false )
1834 {
1835 cSymbol = new sal_Unicode[ MAXSYMLEN ];
1836 nMaxTab = pDoc ? pDoc->GetTableCount() - 1 : 0;
1837 }
1838
~ScCompiler()1839 ScCompiler::~ScCompiler()
1840 {
1841 delete [] cSymbol;
1842 }
1843
CheckTabQuotes(String & rString,const FormulaGrammar::AddressConvention eConv)1844 void ScCompiler::CheckTabQuotes( String& rString,
1845 const FormulaGrammar::AddressConvention eConv )
1846 {
1847 using namespace ::com::sun::star::i18n;
1848 sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER | KParseTokens::ASC_UNDERSCORE;
1849 sal_Int32 nContFlags = nStartFlags;
1850 ParseResult aRes = ScGlobal::pCharClass->parsePredefinedToken(
1851 KParseType::IDENTNAME, rString, 0, nStartFlags, EMPTY_STRING, nContFlags, EMPTY_STRING);
1852 bool bNeedsQuote = !((aRes.TokenType & KParseType::IDENTNAME) && aRes.EndPos == rString.Len());
1853
1854 switch ( eConv )
1855 {
1856 default :
1857 case FormulaGrammar::CONV_UNSPECIFIED :
1858 break;
1859 case FormulaGrammar::CONV_OOO :
1860 case FormulaGrammar::CONV_XL_A1 :
1861 case FormulaGrammar::CONV_XL_R1C1 :
1862 case FormulaGrammar::CONV_XL_OOX :
1863 if( bNeedsQuote )
1864 {
1865 static const String one_quote = static_cast<sal_Unicode>( '\'' );
1866 static const String two_quote = String::CreateFromAscii( "''" );
1867 // escape embedded quotes
1868 rString.SearchAndReplaceAll( one_quote, two_quote );
1869 }
1870 break;
1871 }
1872
1873 if ( !bNeedsQuote && CharClass::isAsciiNumeric( rString ) )
1874 {
1875 // Prevent any possible confusion resulting from pure numeric sheet names.
1876 bNeedsQuote = true;
1877 }
1878
1879 if( bNeedsQuote )
1880 {
1881 rString.Insert( '\'', 0 );
1882 rString += '\'';
1883 }
1884 }
1885
1886
GetDocTabPos(const String & rString)1887 xub_StrLen ScCompiler::GetDocTabPos( const String& rString )
1888 {
1889 if (rString.GetChar(0) != '\'')
1890 return STRING_NOTFOUND;
1891 xub_StrLen nPos = ScGlobal::FindUnquoted( rString, SC_COMPILER_FILE_TAB_SEP);
1892 // it must be 'Doc'#
1893 if (nPos != STRING_NOTFOUND && rString.GetChar(nPos-1) != '\'')
1894 nPos = STRING_NOTFOUND;
1895 return nPos;
1896 }
1897
1898 //---------------------------------------------------------------------------
1899
SetRefConvention(FormulaGrammar::AddressConvention eConv)1900 void ScCompiler::SetRefConvention( FormulaGrammar::AddressConvention eConv )
1901 {
1902 switch ( eConv ) {
1903 case FormulaGrammar::CONV_UNSPECIFIED :
1904 break;
1905 default :
1906 case FormulaGrammar::CONV_OOO : SetRefConvention( pConvOOO_A1 ); break;
1907 case FormulaGrammar::CONV_ODF : SetRefConvention( pConvOOO_A1_ODF ); break;
1908 case FormulaGrammar::CONV_XL_A1 : SetRefConvention( pConvXL_A1 ); break;
1909 case FormulaGrammar::CONV_XL_R1C1 : SetRefConvention( pConvXL_R1C1 ); break;
1910 case FormulaGrammar::CONV_XL_OOX : SetRefConvention( pConvXL_OOX ); break;
1911 }
1912 }
1913
SetRefConvention(const ScCompiler::Convention * pConvP)1914 void ScCompiler::SetRefConvention( const ScCompiler::Convention *pConvP )
1915 {
1916 pConv = pConvP;
1917 meGrammar = FormulaGrammar::mergeToGrammar( meGrammar, pConv->meConv);
1918 DBG_ASSERT( FormulaGrammar::isSupported( meGrammar),
1919 "ScCompiler::SetRefConvention: unsupported grammar resulting");
1920 }
1921
SetError(sal_uInt16 nError)1922 void ScCompiler::SetError(sal_uInt16 nError)
1923 {
1924 if( !pArr->GetCodeError() )
1925 pArr->SetCodeError( nError);
1926 }
1927
1928
lcl_UnicodeStrNCpy(sal_Unicode * pDst,const sal_Unicode * pSrc,xub_StrLen nMax)1929 sal_Unicode* lcl_UnicodeStrNCpy( sal_Unicode* pDst, const sal_Unicode* pSrc, xub_StrLen nMax )
1930 {
1931 const sal_Unicode* const pStop = pDst + nMax;
1932 while ( *pSrc && pDst < pStop )
1933 {
1934 *pDst++ = *pSrc++;
1935 }
1936 *pDst = 0;
1937 return pDst;
1938 }
1939
1940
1941 //---------------------------------------------------------------------------
1942 // NextSymbol
1943 //---------------------------------------------------------------------------
1944 // Zerlegt die Formel in einzelne Symbole fuer die weitere
1945 // Verarbeitung (Turing-Maschine).
1946 //---------------------------------------------------------------------------
1947 // Ausgangs Zustand = GetChar
1948 //---------------+-------------------+-----------------------+---------------
1949 // Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
1950 //---------------+-------------------+-----------------------+---------------
1951 // GetChar | ;()+-*/^=& | Symbol=Zeichen | Stop
1952 // | <> | Symbol=Zeichen | GetBool
1953 // | $ Buchstabe | Symbol=Zeichen | GetWord
1954 // | Ziffer | Symbol=Zeichen | GetValue
1955 // | " | Keine | GetString
1956 // | Sonst | Keine | GetChar
1957 //---------------+-------------------+-----------------------+---------------
1958 // GetBool | => | Symbol=Symbol+Zeichen | Stop
1959 // | Sonst | Dec(CharPos) | Stop
1960 //---------------+-------------------+-----------------------+---------------
1961 // GetWord | SepSymbol | Dec(CharPos) | Stop
1962 // | ()+-*/^=<>&~ | |
1963 // | Leerzeichen | Dec(CharPos) | Stop
1964 // | $_:. | |
1965 // | Buchstabe,Ziffer | Symbol=Symbol+Zeichen | GetWord
1966 // | Sonst | Fehler | Stop
1967 //---------------|-------------------+-----------------------+---------------
1968 // GetValue | ;()*/^=<>& | |
1969 // | Leerzeichen | Dec(CharPos) | Stop
1970 // | Ziffer E+-%,. | Symbol=Symbol+Zeichen | GetValue
1971 // | Sonst | Fehler | Stop
1972 //---------------+-------------------+-----------------------+---------------
1973 // GetString | " | Keine | Stop
1974 // | Sonst | Symbol=Symbol+Zeichen | GetString
1975 //---------------+-------------------+-----------------------+---------------
1976
NextSymbol(bool bInArray)1977 xub_StrLen ScCompiler::NextSymbol(bool bInArray)
1978 {
1979 cSymbol[MAXSYMLEN-1] = 0; // Stopper
1980 sal_Unicode* pSym = cSymbol;
1981 const sal_Unicode* const pStart = aFormula.GetBuffer();
1982 const sal_Unicode* pSrc = pStart + nSrcPos;
1983 bool bi18n = false;
1984 sal_Unicode c = *pSrc;
1985 sal_Unicode cLast = 0;
1986 bool bQuote = false;
1987 mnRangeOpPosInSymbol = -1;
1988 ScanState eState = ssGetChar;
1989 xub_StrLen nSpaces = 0;
1990 sal_Unicode cSep = mxSymbols->getSymbol( ocSep).GetChar(0);
1991 sal_Unicode cArrayColSep = mxSymbols->getSymbol( ocArrayColSep).GetChar(0);
1992 sal_Unicode cArrayRowSep = mxSymbols->getSymbol( ocArrayRowSep).GetChar(0);
1993 sal_Unicode cDecSep = (mxSymbols->isEnglish() ? '.' :
1994 ScGlobal::pLocaleData->getNumDecimalSep().GetChar(0));
1995
1996 // special symbols specific to address convention used
1997 sal_Unicode cSheetPrefix = pConv->getSpecialSymbol(ScCompiler::Convention::ABS_SHEET_PREFIX);
1998 sal_Unicode cSheetSep = pConv->getSpecialSymbol(ScCompiler::Convention::SHEET_SEPARATOR);
1999
2000 int nDecSeps = 0;
2001 bool bAutoIntersection = false;
2002 int nRefInName = 0;
2003 mnPredetectedReference = 0;
2004 // try to parse simple tokens before calling i18n parser
2005 while ((c != 0) && (eState != ssStop) )
2006 {
2007 pSrc++;
2008 sal_uLong nMask = GetCharTableFlags( c );
2009 // The parameter separator and the array column and row separators end
2010 // things unconditionally if not in string or reference.
2011 if (c == cSep || (bInArray && (c == cArrayColSep || c == cArrayRowSep)))
2012 {
2013 switch (eState)
2014 {
2015 // these are to be continued
2016 case ssGetString:
2017 case ssSkipString:
2018 case ssGetReference:
2019 case ssSkipReference:
2020 break;
2021 default:
2022 if (eState == ssGetChar)
2023 *pSym++ = c;
2024 else
2025 pSrc--;
2026 eState = ssStop;
2027 }
2028 }
2029 Label_MaskStateMachine:
2030 switch (eState)
2031 {
2032 case ssGetChar :
2033 {
2034 // Order is important!
2035 if( nMask & SC_COMPILER_C_ODF_LABEL_OP )
2036 {
2037 // '!!' automatic intersection
2038 if (GetCharTableFlags( pSrc[0] ) & SC_COMPILER_C_ODF_LABEL_OP)
2039 {
2040 /* TODO: For now the UI "space operator" is used, this
2041 * could be enhanced using a specialized OpCode to get
2042 * rid of the space ambiguity, which would need some
2043 * places to be adapted though. And we would still need
2044 * to support the ambiguous space operator for UI
2045 * purposes anyway. However, we then could check for
2046 * invalid usage of '!!', which currently isn't
2047 * possible. */
2048 if (!bAutoIntersection)
2049 {
2050 ++pSrc;
2051 nSpaces += 2; // must match the character count
2052 bAutoIntersection = true;
2053 }
2054 else
2055 {
2056 pSrc--;
2057 eState = ssStop;
2058 }
2059 }
2060 else
2061 {
2062 nMask &= ~SC_COMPILER_C_ODF_LABEL_OP;
2063 goto Label_MaskStateMachine;
2064 }
2065 }
2066 else if( nMask & SC_COMPILER_C_ODF_NAME_MARKER )
2067 {
2068 // '$$' defined name marker
2069 if (GetCharTableFlags( pSrc[0] ) & SC_COMPILER_C_ODF_NAME_MARKER)
2070 {
2071 // both eaten, not added to pSym
2072 ++pSrc;
2073 }
2074 else
2075 {
2076 nMask &= ~SC_COMPILER_C_ODF_NAME_MARKER;
2077 goto Label_MaskStateMachine;
2078 }
2079 }
2080 else if( nMask & SC_COMPILER_C_CHAR )
2081 {
2082 *pSym++ = c;
2083 eState = ssStop;
2084 }
2085 else if( nMask & SC_COMPILER_C_ODF_LBRACKET )
2086 {
2087 // eaten, not added to pSym
2088 eState = ssGetReference;
2089 mnPredetectedReference = 1;
2090 }
2091 else if( nMask & SC_COMPILER_C_CHAR_BOOL )
2092 {
2093 *pSym++ = c;
2094 eState = ssGetBool;
2095 }
2096 else if( nMask & SC_COMPILER_C_CHAR_VALUE )
2097 {
2098 *pSym++ = c;
2099 eState = ssGetValue;
2100 }
2101 else if( nMask & SC_COMPILER_C_CHAR_STRING )
2102 {
2103 *pSym++ = c;
2104 eState = ssGetString;
2105 }
2106 else if( nMask & SC_COMPILER_C_CHAR_DONTCARE )
2107 {
2108 nSpaces++;
2109 }
2110 else if( nMask & SC_COMPILER_C_CHAR_IDENT )
2111 { // try to get a simple ASCII identifier before calling
2112 // i18n, to gain performance during import
2113 *pSym++ = c;
2114 eState = ssGetIdent;
2115 }
2116 else
2117 {
2118 bi18n = true;
2119 eState = ssStop;
2120 }
2121 }
2122 break;
2123 case ssGetIdent:
2124 {
2125 if ( nMask & SC_COMPILER_C_IDENT )
2126 { // This catches also $Sheet1.A$1, for example.
2127 if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
2128 {
2129 SetError(errStringOverflow);
2130 eState = ssStop;
2131 }
2132 else
2133 *pSym++ = c;
2134 }
2135 else if (c == ':' && mnRangeOpPosInSymbol < 0)
2136 {
2137 // One range operator may form Sheet1.A:A, which we need to
2138 // pass as one entity to IsReference().
2139 mnRangeOpPosInSymbol = pSym - &cSymbol[0];
2140 if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
2141 {
2142 SetError(errStringOverflow);
2143 eState = ssStop;
2144 }
2145 else
2146 *pSym++ = c;
2147 }
2148 else if ( 128 <= c || '\'' == c )
2149 { // High values need reparsing with i18n,
2150 // single quoted $'sheet' names too (otherwise we'd had to
2151 // implement everything twice).
2152 bi18n = true;
2153 eState = ssStop;
2154 }
2155 else
2156 {
2157 pSrc--;
2158 eState = ssStop;
2159 }
2160 }
2161 break;
2162 case ssGetBool :
2163 {
2164 if( nMask & SC_COMPILER_C_BOOL )
2165 {
2166 *pSym++ = c;
2167 eState = ssStop;
2168 }
2169 else
2170 {
2171 pSrc--;
2172 eState = ssStop;
2173 }
2174 }
2175 break;
2176 case ssGetValue :
2177 {
2178 if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
2179 {
2180 SetError(errStringOverflow);
2181 eState = ssStop;
2182 }
2183 else if (c == cDecSep)
2184 {
2185 if (++nDecSeps > 1)
2186 {
2187 // reparse with i18n, may be numeric sheet name as well
2188 bi18n = true;
2189 eState = ssStop;
2190 }
2191 else
2192 *pSym++ = c;
2193 }
2194 else if( nMask & SC_COMPILER_C_VALUE )
2195 *pSym++ = c;
2196 else if( nMask & SC_COMPILER_C_VALUE_SEP )
2197 {
2198 pSrc--;
2199 eState = ssStop;
2200 }
2201 else if (c == 'E' || c == 'e')
2202 {
2203 if (GetCharTableFlags( pSrc[0] ) & SC_COMPILER_C_VALUE_EXP)
2204 *pSym++ = c;
2205 else
2206 {
2207 // reparse with i18n
2208 bi18n = true;
2209 eState = ssStop;
2210 }
2211 }
2212 else if( nMask & SC_COMPILER_C_VALUE_SIGN )
2213 {
2214 if (((cLast == 'E') || (cLast == 'e')) &&
2215 (GetCharTableFlags( pSrc[0] ) & SC_COMPILER_C_VALUE_VALUE))
2216 {
2217 *pSym++ = c;
2218 }
2219 else
2220 {
2221 pSrc--;
2222 eState = ssStop;
2223 }
2224 }
2225 else
2226 {
2227 // reparse with i18n
2228 bi18n = true;
2229 eState = ssStop;
2230 }
2231 }
2232 break;
2233 case ssGetString :
2234 {
2235 if( nMask & SC_COMPILER_C_STRING_SEP )
2236 {
2237 if ( !bQuote )
2238 {
2239 if ( *pSrc == '"' )
2240 bQuote = true; // "" => literal "
2241 else
2242 eState = ssStop;
2243 }
2244 else
2245 bQuote = false;
2246 }
2247 if ( !bQuote )
2248 {
2249 if( pSym == &cSymbol[ MAXSYMLEN-1 ] )
2250 {
2251 SetError(errStringOverflow);
2252 eState = ssSkipString;
2253 }
2254 else
2255 *pSym++ = c;
2256 }
2257 }
2258 break;
2259 case ssSkipString:
2260 if( nMask & SC_COMPILER_C_STRING_SEP )
2261 eState = ssStop;
2262 break;
2263 case ssGetReference:
2264 if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
2265 {
2266 SetError( errStringOverflow);
2267 eState = ssSkipReference;
2268 }
2269 // fall through and follow logic
2270 case ssSkipReference:
2271 // ODF reference: ['External'#$'Sheet'.A1:.B2] with dots being
2272 // mandatory also if no sheet name. 'External'# is optional,
2273 // sheet name is optional, quotes around sheet name are
2274 // optional if no quote contained.
2275 // 2nd usage: ['Sheet'.$$'DefinedName']
2276 // 3rd usage: ['External'#$$'DefinedName']
2277 // 4th usage: ['External'#$'Sheet'.$$'DefinedName']
2278 // Also for all these names quotes are optional if no quote
2279 // contained.
2280 {
2281
2282 // nRefInName: 0 := not in sheet name yet. 'External'
2283 // is parsed as if it was a sheet name and nRefInName
2284 // is reset when # is encountered immediately after closing
2285 // quote. Same with 'DefinedName', nRefInName is cleared
2286 // when : is encountered.
2287
2288 // Encountered leading $ before sheet name.
2289 static const int kDollar = (1 << 1);
2290 // Encountered ' opening quote, which may be after $ or
2291 // not.
2292 static const int kOpen = (1 << 2);
2293 // Somewhere in name.
2294 static const int kName = (1 << 3);
2295 // Encountered ' in name, will be cleared if double or
2296 // transformed to kClose if not, in which case kOpen is
2297 // cleared.
2298 static const int kQuote = (1 << 4);
2299 // Past ' closing quote.
2300 static const int kClose = (1 << 5);
2301 // Encountered # file/sheet separator.
2302 static const int kFileSep = (1 << 6);
2303 // Past . sheet name separator.
2304 static const int kPast = (1 << 7);
2305 // Marked name $$ follows sheet name separator, detected
2306 // while we're still on the separator. Will be cleared when
2307 // entering the name.
2308 static const int kMarkAhead = (1 << 8);
2309 // In marked defined name.
2310 static const int kDefName = (1 << 9);
2311
2312 bool bAddToSymbol = true;
2313 if ((nMask & SC_COMPILER_C_ODF_RBRACKET) && !(nRefInName & kOpen))
2314 {
2315 DBG_ASSERT( (nRefInName & (kPast | kDefName)) || (pSym - cSymbol == 5 &&
2316 cSymbol[0] == '#' && cSymbol[1] == 'R' && cSymbol[2] == 'E' && cSymbol[3] == 'F' && cSymbol[4] == '!'),
2317 "ScCompiler::NextSymbol: reference: "
2318 "closing bracket ']' without prior sheet name separator '.' violates ODF spec");
2319 // eaten, not added to pSym
2320 bAddToSymbol = false;
2321 eState = ssStop;
2322 }
2323 else if (cSheetSep == c && nRefInName == 0)
2324 {
2325 // eat it, no sheet name [.A1]
2326 bAddToSymbol = false;
2327 nRefInName |= kPast;
2328 if ('$' == pSrc[0] && '$' == pSrc[1])
2329 nRefInName |= kMarkAhead;
2330 }
2331 else if (!(nRefInName & kPast) || (nRefInName & (kMarkAhead | kDefName)))
2332 {
2333 // Not in col/row yet.
2334
2335 if (SC_COMPILER_FILE_TAB_SEP == c && (nRefInName & kFileSep))
2336 nRefInName = 0;
2337 else if ('$' == c && '$' == pSrc[0] && !(nRefInName & kOpen))
2338 {
2339 nRefInName &= ~kMarkAhead;
2340 if (!(nRefInName & kDefName))
2341 {
2342 // eaten, not added to pSym (2 chars)
2343 bAddToSymbol = false;
2344 ++pSrc;
2345 nRefInName &= kPast;
2346 nRefInName |= kDefName;
2347 }
2348 else
2349 {
2350 // ScAddress::Parse() will recognize this as
2351 // invalid later.
2352 if (eState != ssSkipReference)
2353 {
2354 if (pSym > &cSymbol[ MAXSTRLEN-3 ])
2355 {
2356 // two characters would step past the overflow test above
2357 SetError( errStringOverflow);
2358 eState = ssSkipReference;
2359 }
2360 else
2361 {
2362 *pSym++ = c;
2363 *pSym++ = *pSrc++;
2364 }
2365 }
2366 bAddToSymbol = false;
2367 }
2368 }
2369 else if (cSheetPrefix == c && nRefInName == 0)
2370 nRefInName |= kDollar;
2371 else if ('\'' == c)
2372 {
2373 // TODO: The conventions' parseExternalName()
2374 // should handle quoted names, but as long as they
2375 // don't remove non-embedded quotes here.
2376 if (!(nRefInName & kName))
2377 {
2378 nRefInName |= (kOpen | kName);
2379 bAddToSymbol = !(nRefInName & kDefName);
2380 }
2381 else if (!(nRefInName & kOpen))
2382 {
2383 DBG_ERRORFILE("ScCompiler::NextSymbol: reference: "
2384 "a ''' without the name being enclosed in '...' violates ODF spec");
2385 }
2386 else if (nRefInName & kQuote)
2387 {
2388 // escaped embedded quote
2389 nRefInName &= ~kQuote;
2390 }
2391 else
2392 {
2393 switch (pSrc[0])
2394 {
2395 case '\'':
2396 // escapes embedded quote
2397 nRefInName |= kQuote;
2398 break;
2399 case SC_COMPILER_FILE_TAB_SEP:
2400 // sheet name should follow
2401 nRefInName |= kFileSep;
2402 // fallthru
2403 default:
2404 // quote not followed by quote => close
2405 nRefInName |= kClose;
2406 nRefInName &= ~kOpen;
2407 }
2408 bAddToSymbol = !(nRefInName & kDefName);
2409 }
2410 }
2411 else if (cSheetSep == c && !(nRefInName & kOpen))
2412 {
2413 // unquoted sheet name separator
2414 nRefInName |= kPast;
2415 if ('$' == pSrc[0] && '$' == pSrc[1])
2416 nRefInName |= kMarkAhead;
2417 }
2418 else if (':' == c && !(nRefInName & kOpen))
2419 {
2420 DBG_ERRORFILE("ScCompiler::NextSymbol: reference: "
2421 "range operator ':' without prior sheet name separator '.' violates ODF spec");
2422 nRefInName = 0;
2423 ++mnPredetectedReference;
2424 }
2425 else if (!(nRefInName & kName))
2426 {
2427 // start unquoted name
2428 nRefInName |= kName;
2429 }
2430 }
2431 else if (':' == c)
2432 {
2433 // range operator
2434 nRefInName = 0;
2435 ++mnPredetectedReference;
2436 }
2437 if (bAddToSymbol && eState != ssSkipReference)
2438 *pSym++ = c; // everything is part of reference
2439 }
2440 break;
2441 case ssStop:
2442 ; // nothing, prevent warning
2443 break;
2444 }
2445 cLast = c;
2446 c = *pSrc;
2447 }
2448 if ( bi18n )
2449 {
2450 nSrcPos = sal::static_int_cast<xub_StrLen>( nSrcPos + nSpaces );
2451 String aSymbol;
2452 mnRangeOpPosInSymbol = -1;
2453 sal_uInt16 nErr = 0;
2454 do
2455 {
2456 bi18n = false;
2457 // special case (e.g. $'sheetname' in OOO A1)
2458 if ( pStart[nSrcPos] == cSheetPrefix && pStart[nSrcPos+1] == '\'' )
2459 aSymbol += pStart[nSrcPos++];
2460
2461 ParseResult aRes = pConv->parseAnyToken( aFormula, nSrcPos, pCharClass );
2462
2463 if ( !aRes.TokenType )
2464 SetError( nErr = errIllegalChar ); // parsed chars as string
2465 if ( aRes.EndPos <= nSrcPos )
2466 { // ?!?
2467 SetError( nErr = errIllegalChar );
2468 nSrcPos = aFormula.Len();
2469 aSymbol.Erase();
2470 }
2471 else
2472 {
2473 aSymbol.Append( pStart + nSrcPos, (xub_StrLen)aRes.EndPos - nSrcPos );
2474 nSrcPos = (xub_StrLen) aRes.EndPos;
2475 c = pStart[nSrcPos];
2476 if ( aRes.TokenType & KParseType::SINGLE_QUOTE_NAME )
2477 { // special cases (e.g. 'sheetname'. or 'filename'# in OOO A1)
2478 bi18n = (c == cSheetSep || c == SC_COMPILER_FILE_TAB_SEP);
2479 }
2480 // One range operator restarts parsing for second reference.
2481 if (c == ':' && mnRangeOpPosInSymbol < 0)
2482 {
2483 mnRangeOpPosInSymbol = aSymbol.Len();
2484 bi18n = true;
2485 }
2486 if ( bi18n )
2487 aSymbol += pStart[nSrcPos++];
2488 }
2489 } while ( bi18n && !nErr );
2490 xub_StrLen nLen = aSymbol.Len();
2491 if ( nLen >= MAXSTRLEN )
2492 {
2493 SetError( errStringOverflow );
2494 nLen = MAXSTRLEN-1;
2495 }
2496 lcl_UnicodeStrNCpy( cSymbol, aSymbol.GetBuffer(), nLen );
2497 }
2498 else
2499 {
2500 nSrcPos = sal::static_int_cast<xub_StrLen>( pSrc - pStart );
2501 *pSym = 0;
2502 }
2503 if (mnRangeOpPosInSymbol >= 0 && mnRangeOpPosInSymbol == (pSym-1) - &cSymbol[0])
2504 {
2505 // This is a trailing range operator, which is nonsense. Will be caught
2506 // in next round.
2507 mnRangeOpPosInSymbol = -1;
2508 *--pSym = 0;
2509 --nSrcPos;
2510 }
2511 if ( bAutoCorrect )
2512 aCorrectedSymbol = cSymbol;
2513 if (bAutoIntersection && nSpaces > 1)
2514 --nSpaces; // replace '!!' with only one space
2515 return nSpaces;
2516 }
2517
2518 //---------------------------------------------------------------------------
2519 // Convert symbol to token
2520 //---------------------------------------------------------------------------
2521
IsOpCode(const String & rName,bool bInArray)2522 sal_Bool ScCompiler::IsOpCode( const String& rName, bool bInArray )
2523 {
2524 OpCodeHashMap::const_iterator iLook( mxSymbols->getHashMap()->find( rName));
2525 sal_Bool bFound = (iLook != mxSymbols->getHashMap()->end());
2526 if (bFound)
2527 {
2528 ScRawToken aToken;
2529 OpCode eOp = iLook->second;
2530 if (bInArray)
2531 {
2532 if (rName.Equals(mxSymbols->getSymbol(ocArrayColSep)))
2533 eOp = ocArrayColSep;
2534 else if (rName.Equals(mxSymbols->getSymbol(ocArrayRowSep)))
2535 eOp = ocArrayRowSep;
2536 }
2537 aToken.SetOpCode(eOp);
2538 pRawToken = aToken.Clone();
2539 }
2540 else if (mxSymbols->isODFF())
2541 {
2542 // ODFF names that are not written in the current mapping but to be
2543 // recognized. New names will be written in a future relase, then
2544 // exchange (!) with the names in
2545 // formula/source/core/resource/core_resource.src to be able to still
2546 // read the old names as well.
2547 struct FunctionName
2548 {
2549 const sal_Char* pName;
2550 OpCode eOp;
2551 };
2552 static const FunctionName aOdffAliases[] = {
2553 // Renamed old names:
2554 // XXX none yet.
2555 // Renamed new names:
2556 { "BINOM.DIST.RANGE", ocB }, // B -> BINOM.DIST.RANGE
2557 { "LEGACY.TDIST", ocTDist }, // TDIST -> LEGACY.TDIST
2558 { "ORG.OPENOFFICE.EASTERSUNDAY", ocEasterSunday } // EASTERSUNDAY -> ORG.OPENOFFICE.EASTERSUNDAY
2559 };
2560 static const size_t nOdffAliases = sizeof(aOdffAliases) / sizeof(aOdffAliases[0]);
2561 for (size_t i=0; i<nOdffAliases; ++i)
2562 {
2563 if (rName.EqualsIgnoreCaseAscii( aOdffAliases[i].pName))
2564 {
2565 ScRawToken aToken;
2566 aToken.SetOpCode( aOdffAliases[i].eOp);
2567 pRawToken = aToken.Clone();
2568 bFound = sal_True;
2569 break; // for
2570 }
2571 }
2572 }
2573 if (!bFound)
2574 {
2575 String aIntName;
2576 if (mxSymbols->hasExternals())
2577 {
2578 // If symbols are set by filters get mapping to exact name.
2579 ExternalHashMap::const_iterator iExt(
2580 mxSymbols->getExternalHashMap()->find( rName));
2581 if (iExt != mxSymbols->getExternalHashMap()->end())
2582 {
2583 if (ScGlobal::GetAddInCollection()->GetFuncData( (*iExt).second))
2584 aIntName = (*iExt).second;
2585 }
2586 if (!aIntName.Len())
2587 {
2588 // If that isn't found we might continue with rName lookup as a
2589 // last resort by just falling through to FindFunction(), but
2590 // it shouldn't happen if the map was setup correctly. Don't
2591 // waste time and bail out.
2592 return sal_False;
2593 }
2594 }
2595 if (!aIntName.Len())
2596 {
2597 // Old (deprecated) addins first for legacy.
2598 sal_uInt16 nIndex;
2599 bFound = ScGlobal::GetFuncCollection()->SearchFunc( cSymbol, nIndex);
2600 if (bFound)
2601 {
2602 ScRawToken aToken;
2603 aToken.SetExternal( cSymbol );
2604 pRawToken = aToken.Clone();
2605 }
2606 else
2607 // bLocalFirst=sal_False for (English) upper full original name
2608 // (service.function)
2609 aIntName = ScGlobal::GetAddInCollection()->FindFunction(
2610 rName, !mxSymbols->isEnglish());
2611 }
2612 if (aIntName.Len())
2613 {
2614 ScRawToken aToken;
2615 aToken.SetExternal( aIntName.GetBuffer() ); // international name
2616 pRawToken = aToken.Clone();
2617 bFound = sal_True;
2618 }
2619 }
2620 OpCode eOp;
2621 if (bFound && ((eOp = pRawToken->GetOpCode()) == ocSub || eOp == ocNegSub))
2622 {
2623 bool bShouldBeNegSub =
2624 (eLastOp == ocOpen || eLastOp == ocSep || eLastOp == ocNegSub ||
2625 (SC_OPCODE_START_BIN_OP <= eLastOp && eLastOp < SC_OPCODE_STOP_BIN_OP) ||
2626 eLastOp == ocArrayOpen ||
2627 eLastOp == ocArrayColSep || eLastOp == ocArrayRowSep);
2628 if (bShouldBeNegSub && eOp == ocSub)
2629 pRawToken->NewOpCode( ocNegSub );
2630 //! if ocNegSub had ForceArray we'd have to set it here
2631 else if (!bShouldBeNegSub && eOp == ocNegSub)
2632 pRawToken->NewOpCode( ocSub );
2633 }
2634 return bFound;
2635 }
2636
IsOpCode2(const String & rName)2637 sal_Bool ScCompiler::IsOpCode2( const String& rName )
2638 {
2639 sal_Bool bFound = sal_False;
2640 sal_uInt16 i;
2641
2642 for( i = ocInternalBegin; i <= ocInternalEnd && !bFound; i++ )
2643 bFound = rName.EqualsAscii( pInternal[ i-ocInternalBegin ] );
2644
2645 if (bFound)
2646 {
2647 ScRawToken aToken;
2648 aToken.SetOpCode( (OpCode) --i );
2649 pRawToken = aToken.Clone();
2650 }
2651 return bFound;
2652 }
2653
IsValue(const String & rSym)2654 sal_Bool ScCompiler::IsValue( const String& rSym )
2655 {
2656 double fVal;
2657 sal_uInt32 nIndex = ( mxSymbols->isEnglish() ?
2658 pDoc->GetFormatTable()->GetStandardIndex( LANGUAGE_ENGLISH_US ) : 0 );
2659 // sal_uLong nIndex = 0;
2660 //// sal_uLong nIndex = pDoc->GetFormatTable()->GetStandardIndex(ScGlobal::eLnge);
2661 if (pDoc->GetFormatTable()->IsNumberFormat( rSym, nIndex, fVal ) )
2662 {
2663 sal_uInt16 nType = pDoc->GetFormatTable()->GetType(nIndex);
2664
2665 // Don't accept 3:3 as time, it is a reference to entire row 3 instead.
2666 // Dates should never be entered directly and automatically converted
2667 // to serial, because the serial would be wrong if null-date changed.
2668 // Usually it wouldn't be accepted anyway because the date separator
2669 // clashed with other separators or operators.
2670 if (nType & (NUMBERFORMAT_TIME | NUMBERFORMAT_DATE))
2671 return sal_False;
2672
2673 if (nType == NUMBERFORMAT_LOGICAL)
2674 {
2675 const sal_Unicode* p = aFormula.GetBuffer() + nSrcPos;
2676 while( *p == ' ' )
2677 p++;
2678 if (*p == '(')
2679 return sal_False; // Boolean function instead.
2680 }
2681
2682 if( aFormula.GetChar(nSrcPos) == '.' )
2683 // numerical sheet name?
2684 return sal_False;
2685
2686 if( nType == NUMBERFORMAT_TEXT )
2687 // HACK: number too big!
2688 SetError( errIllegalArgument );
2689 ScRawToken aToken;
2690 aToken.SetDouble( fVal );
2691 pRawToken = aToken.Clone();
2692 return sal_True;
2693 }
2694 else
2695 return sal_False;
2696 }
2697
IsString()2698 sal_Bool ScCompiler::IsString()
2699 {
2700 const sal_Unicode* p = cSymbol;
2701 while ( *p )
2702 p++;
2703 xub_StrLen nLen = sal::static_int_cast<xub_StrLen>( p - cSymbol - 1 );
2704 sal_Bool bQuote = ((cSymbol[0] == '"') && (cSymbol[nLen] == '"'));
2705 if ((bQuote ? nLen-1 > MAXSTRLITLEN : nLen >= MAXSTRLEN-1))
2706 {
2707 SetError(errStringOverflow);
2708 return sal_False;
2709 }
2710 if ( bQuote )
2711 {
2712 cSymbol[nLen] = '\0';
2713 pRawToken = ScRawToken::NewString( cSymbol+1, nLen ? nLen-1 : 0 ); // lone quote: nLen is 0
2714 return sal_True;
2715 }
2716 return sal_False;
2717 }
2718
2719
IsPredetectedReference(const String & rName)2720 sal_Bool ScCompiler::IsPredetectedReference( const String& rName )
2721 {
2722 // Speedup documents with lots of broken references, e.g. sheet deleted.
2723 xub_StrLen nPos = rName.SearchAscii( "#REF!");
2724 if (nPos != STRING_NOTFOUND)
2725 {
2726 /* TODO: this may be enhanced by reusing scan information from
2727 * NextSymbol(), the positions of quotes and special characters found
2728 * there for $'sheet'.A1:... could be stored in a vector. We don't
2729 * fully rescan here whether found positions are within single quotes
2730 * for performance reasons. This code does not check for possible
2731 * occurrences of insane "valid" sheet names like
2732 * 'haha.#REF!1fooledyou' and will generate an error on such. */
2733 if (nPos == 0)
2734 return false; // #REF!.AB42 or #REF!42 or #REF!#REF!
2735 sal_Unicode c = rName.GetChar(nPos-1); // before #REF!
2736 if ('$' == c)
2737 {
2738 if (nPos == 1)
2739 return false; // $#REF!.AB42 or $#REF!42 or $#REF!#REF!
2740 c = rName.GetChar(nPos-2); // before $#REF!
2741 }
2742 sal_Unicode c2 = rName.GetChar(nPos+5); // after #REF!
2743 switch (c)
2744 {
2745 case '.':
2746 if ('$' == c2 || '#' == c2 || ('0' <= c2 && c2 <= '9'))
2747 return false; // sheet.#REF!42 or sheet.#REF!#REF!
2748 break;
2749 case ':':
2750 if (mnPredetectedReference > 1 &&
2751 ('.' == c2 || '$' == c2 || '#' == c2 ||
2752 ('0' <= c2 && c2 <= '9')))
2753 return false; // :#REF!.AB42 or :#REF!42 or :#REF!#REF!
2754 break;
2755 default:
2756 if ((('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) &&
2757 ((mnPredetectedReference > 1 && ':' == c2) || 0 == c2))
2758 return false; // AB#REF!: or AB#REF!
2759 }
2760 }
2761 switch (mnPredetectedReference)
2762 {
2763 case 1:
2764 return IsSingleReference( rName);
2765 case 2:
2766 return IsDoubleReference( rName);
2767 }
2768 return false;
2769 }
2770
2771
IsDoubleReference(const String & rName)2772 sal_Bool ScCompiler::IsDoubleReference( const String& rName )
2773 {
2774 ScRange aRange( aPos, aPos );
2775 const ScAddress::Details aDetails( pConv->meConv, aPos );
2776 ScAddress::ExternalInfo aExtInfo;
2777 sal_uInt16 nFlags = aRange.Parse( rName, pDoc, aDetails, &aExtInfo, &maExternalLinks );
2778 if( nFlags & SCA_VALID )
2779 {
2780 ScRawToken aToken;
2781 ScComplexRefData aRef;
2782 aRef.InitRange( aRange );
2783 aRef.Ref1.SetColRel( (nFlags & SCA_COL_ABSOLUTE) == 0 );
2784 aRef.Ref1.SetRowRel( (nFlags & SCA_ROW_ABSOLUTE) == 0 );
2785 aRef.Ref1.SetTabRel( (nFlags & SCA_TAB_ABSOLUTE) == 0 );
2786 if ( !(nFlags & SCA_VALID_TAB) )
2787 aRef.Ref1.SetTabDeleted( sal_True ); // #REF!
2788 aRef.Ref1.SetFlag3D( ( nFlags & SCA_TAB_3D ) != 0 );
2789 aRef.Ref2.SetColRel( (nFlags & SCA_COL2_ABSOLUTE) == 0 );
2790 aRef.Ref2.SetRowRel( (nFlags & SCA_ROW2_ABSOLUTE) == 0 );
2791 aRef.Ref2.SetTabRel( (nFlags & SCA_TAB2_ABSOLUTE) == 0 );
2792 if ( !(nFlags & SCA_VALID_TAB2) )
2793 aRef.Ref2.SetTabDeleted( sal_True ); // #REF!
2794 aRef.Ref2.SetFlag3D( ( nFlags & SCA_TAB2_3D ) != 0 );
2795 aRef.CalcRelFromAbs( aPos );
2796 if (aExtInfo.mbExternal)
2797 {
2798 ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
2799 const String* pRealTab = pRefMgr->getRealTableName(aExtInfo.mnFileId, aExtInfo.maTabName);
2800 aToken.SetExternalDoubleRef(
2801 aExtInfo.mnFileId, pRealTab ? *pRealTab : aExtInfo.maTabName, aRef);
2802 }
2803 else
2804 {
2805 aToken.SetDoubleReference(aRef);
2806 }
2807 pRawToken = aToken.Clone();
2808 }
2809
2810 return ( nFlags & SCA_VALID ) != 0;
2811 }
2812
2813
IsSingleReference(const String & rName)2814 sal_Bool ScCompiler::IsSingleReference( const String& rName )
2815 {
2816 ScAddress aAddr( aPos );
2817 const ScAddress::Details aDetails( pConv->meConv, aPos );
2818 ScAddress::ExternalInfo aExtInfo;
2819 sal_uInt16 nFlags = aAddr.Parse( rName, pDoc, aDetails, &aExtInfo, &maExternalLinks );
2820 // Something must be valid in order to recognize Sheet1.blah or blah.a1
2821 // as a (wrong) reference.
2822 if( nFlags & ( SCA_VALID_COL|SCA_VALID_ROW|SCA_VALID_TAB ) )
2823 {
2824 ScRawToken aToken;
2825 ScSingleRefData aRef;
2826 aRef.InitAddress( aAddr );
2827 aRef.SetColRel( (nFlags & SCA_COL_ABSOLUTE) == 0 );
2828 aRef.SetRowRel( (nFlags & SCA_ROW_ABSOLUTE) == 0 );
2829 aRef.SetTabRel( (nFlags & SCA_TAB_ABSOLUTE) == 0 );
2830 aRef.SetFlag3D( ( nFlags & SCA_TAB_3D ) != 0 );
2831 // the reference is really invalid
2832 if( !( nFlags & SCA_VALID ) )
2833 {
2834 if( !( nFlags & SCA_VALID_COL ) )
2835 aRef.nCol = MAXCOL+1;
2836 if( !( nFlags & SCA_VALID_ROW ) )
2837 aRef.nRow = MAXROW+1;
2838 if( !( nFlags & SCA_VALID_TAB ) )
2839 aRef.nTab = MAXTAB+3;
2840 nFlags |= SCA_VALID;
2841 }
2842 aRef.CalcRelFromAbs( aPos );
2843
2844 if (aExtInfo.mbExternal)
2845 {
2846 ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
2847 const String* pRealTab = pRefMgr->getRealTableName(aExtInfo.mnFileId, aExtInfo.maTabName);
2848 aToken.SetExternalSingleRef(
2849 aExtInfo.mnFileId, pRealTab ? *pRealTab : aExtInfo.maTabName, aRef);
2850 }
2851 else
2852 aToken.SetSingleReference(aRef);
2853 pRawToken = aToken.Clone();
2854 }
2855
2856 return ( nFlags & SCA_VALID ) != 0;
2857 }
2858
2859
IsReference(const String & rName)2860 sal_Bool ScCompiler::IsReference( const String& rName )
2861 {
2862 // Has to be called before IsValue
2863 sal_Unicode ch1 = rName.GetChar(0);
2864 sal_Unicode cDecSep = ( mxSymbols->isEnglish() ? '.' :
2865 ScGlobal::pLocaleData->getNumDecimalSep().GetChar(0) );
2866 if ( ch1 == cDecSep )
2867 return sal_False;
2868 // Who was that imbecile introducing '.' as the sheet name separator!?!
2869 if ( CharClass::isAsciiNumeric( ch1 ) )
2870 {
2871 // Numerical sheet name is valid.
2872 // But English 1.E2 or 1.E+2 is value 100, 1.E-2 is 0.01
2873 // Don't create a #REF! of values. But also do not bail out on
2874 // something like 3:3, meaning entire row 3.
2875 do
2876 {
2877 const xub_StrLen nPos = ScGlobal::FindUnquoted( rName, '.');
2878 if ( nPos == STRING_NOTFOUND )
2879 {
2880 if (ScGlobal::FindUnquoted( rName, ':') != STRING_NOTFOUND)
2881 break; // may be 3:3, continue as usual
2882 return sal_False;
2883 }
2884 sal_Unicode const * const pTabSep = rName.GetBuffer() + nPos;
2885 sal_Unicode ch2 = pTabSep[1]; // maybe a column identifier
2886 if ( !(ch2 == '$' || CharClass::isAsciiAlpha( ch2 )) )
2887 return sal_False;
2888 if ( cDecSep == '.' && (ch2 == 'E' || ch2 == 'e') // E + - digit
2889 && (GetCharTableFlags( pTabSep[2] ) & SC_COMPILER_C_VALUE_EXP) )
2890 { // #91053#
2891 // If it is an 1.E2 expression check if "1" is an existent sheet
2892 // name. If so, a desired value 1.E2 would have to be entered as
2893 // 1E2 or 1.0E2 or 1.E+2, sorry. Another possibility would be to
2894 // require numerical sheet names always being entered quoted, which
2895 // is not desirable (too many 1999, 2000, 2001 sheets in use).
2896 // Furthermore, XML files created with versions prior to SRC640e
2897 // wouldn't contain the quotes added by MakeTabStr()/CheckTabQuotes()
2898 // and would produce wrong formulas if the conditions here are met.
2899 // If you can live with these restrictions you may remove the
2900 // check and return an unconditional FALSE.
2901 String aTabName( rName.Copy( 0, nPos ) );
2902 SCTAB nTab;
2903 if ( !pDoc->GetTable( aTabName, nTab ) )
2904 return sal_False;
2905 // If sheet "1" exists and the expression is 1.E+2 continue as
2906 // usual, the ScRange/ScAddress parser will take care of it.
2907 }
2908 } while(0);
2909 }
2910
2911 if (IsSingleReference( rName))
2912 return true;
2913
2914 // Though the range operator is handled explicitly, when encountering
2915 // something like Sheet1.A:A we will have to treat it as one entity if it
2916 // doesn't pass as single cell reference.
2917 if (mnRangeOpPosInSymbol > 0) // ":foo" would be nonsense
2918 {
2919 if (IsDoubleReference( rName))
2920 return true;
2921 // Now try with a symbol up to the range operator, rewind source
2922 // position.
2923 sal_Int32 nLen = mnRangeOpPosInSymbol;
2924 while (cSymbol[++nLen])
2925 ;
2926 cSymbol[mnRangeOpPosInSymbol] = 0;
2927 nSrcPos -= static_cast<xub_StrLen>(nLen - mnRangeOpPosInSymbol);
2928 mnRangeOpPosInSymbol = -1;
2929 mbRewind = true;
2930 return true; // end all checks
2931 }
2932 else
2933 {
2934 // Special treatment for the 'E:\[doc]Sheet1:Sheet3'!D5 Excel sickness,
2935 // mnRangeOpPosInSymbol did not catch the range operator as it is
2936 // within a quoted name.
2937 switch (pConv->meConv)
2938 {
2939 case FormulaGrammar::CONV_XL_A1:
2940 case FormulaGrammar::CONV_XL_R1C1:
2941 case FormulaGrammar::CONV_XL_OOX:
2942 if (rName.GetChar(0) == '\'' && IsDoubleReference( rName))
2943 return true;
2944 break;
2945 default:
2946 ; // nothing
2947 }
2948 }
2949 return false;
2950 }
2951
IsMacro(const String & rName)2952 sal_Bool ScCompiler::IsMacro( const String& rName )
2953 {
2954 String aName( rName);
2955 StarBASIC* pObj = 0;
2956 SfxObjectShell* pDocSh = pDoc->GetDocumentShell();
2957
2958 SfxApplication* pSfxApp = SFX_APP();
2959
2960 if( pDocSh )//XXX
2961 pObj = pDocSh->GetBasic();
2962 else
2963 pObj = pSfxApp->GetBasic();
2964
2965 // ODFF recommends to store user-defined functions prefixed with "USER.",
2966 // use only unprefixed name if encountered. BASIC doesn't allow '.' in a
2967 // function name so a function "USER.FOO" could not exist, and macro check
2968 // is assigned the lowest priority in function name check.
2969 if (FormulaGrammar::isODFF( GetGrammar()) && aName.EqualsIgnoreCaseAscii( "USER.", 0, 5))
2970 aName.Erase( 0, 5);
2971
2972 SbxMethod* pMeth = (SbxMethod*) pObj->Find( aName, SbxCLASS_METHOD );
2973 if( !pMeth )
2974 {
2975 return sal_False;
2976 }
2977 // It really should be a BASIC function!
2978 if( pMeth->GetType() == SbxVOID
2979 || ( pMeth->IsFixed() && pMeth->GetType() == SbxEMPTY )
2980 || !pMeth->ISA(SbMethod) )
2981 {
2982 return sal_False;
2983 }
2984 ScRawToken aToken;
2985 aToken.SetExternal( aName.GetBuffer() );
2986 aToken.eOp = ocMacro;
2987 pRawToken = aToken.Clone();
2988 return sal_True;
2989 }
2990
IsNamedRange(const String & rUpperName)2991 sal_Bool ScCompiler::IsNamedRange( const String& rUpperName )
2992 {
2993 // IsNamedRange is called only from NextNewToken, with an upper-case string
2994
2995 sal_uInt16 n;
2996 ScRangeName* pRangeName = pDoc->GetRangeName();
2997 if (pRangeName->SearchNameUpper( rUpperName, n, aPos.Tab() ) )
2998 {
2999 ScRangeData* pData = (*pRangeName)[n];
3000 ScRawToken aToken;
3001 aToken.SetName( pData->GetIndex() );
3002 pRawToken = aToken.Clone();
3003 return sal_True;
3004 }
3005 if (pRangeName->SearchNameUpper( rUpperName, n ) )
3006 {
3007 ScRangeData* pData = (*pRangeName)[n];
3008 ScRawToken aToken;
3009 aToken.SetName( pData->GetIndex() );
3010 pRawToken = aToken.Clone();
3011 return sal_True;
3012 }
3013 else
3014 return sal_False;
3015 }
3016
IsExternalNamedRange(const String & rSymbol)3017 bool ScCompiler::IsExternalNamedRange( const String& rSymbol )
3018 {
3019 /* FIXME: This code currently (2008-12-02T15:41+0100 in CWS mooxlsc)
3020 * correctly parses external named references in OOo, as required per RFE
3021 * #i3740#, just that we can't store them in ODF yet. We will need an OASIS
3022 * spec first. Until then don't pretend to support external names that
3023 * wouldn't survive a save and reload cycle, return false instead. */
3024
3025 #if 0
3026 if (!pConv)
3027 return false;
3028
3029 String aFile, aName;
3030 if (!pConv->parseExternalName( rSymbol, aFile, aName, pDoc, &maExternalLinks))
3031 return false;
3032
3033 ScRawToken aToken;
3034 if (aFile.Len() > MAXSTRLEN || aName.Len() > MAXSTRLEN)
3035 return false;
3036
3037 ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
3038 pRefMgr->convertToAbsName(aFile);
3039 sal_uInt16 nFileId = pRefMgr->getExternalFileId(aFile);
3040 if (!pRefMgr->getRangeNameTokens(nFileId, aName).get())
3041 // range name doesn't exist in the source document.
3042 return false;
3043
3044 const String* pRealName = pRefMgr->getRealRangeName(nFileId, aName);
3045 aToken.SetExternalName(nFileId, pRealName ? *pRealName : aName);
3046 pRawToken = aToken.Clone();
3047 return true;
3048 #else
3049 (void)rSymbol;
3050 return false;
3051 #endif
3052 }
3053
IsDBRange(const String & rName)3054 sal_Bool ScCompiler::IsDBRange( const String& rName )
3055 {
3056 sal_uInt16 n;
3057 ScDBCollection* pDBColl = pDoc->GetDBCollection();
3058 if (pDBColl->SearchName( rName, n ) )
3059 {
3060 ScDBData* pData = (*pDBColl)[n];
3061 ScRawToken aToken;
3062 aToken.SetName( pData->GetIndex() );
3063 aToken.eOp = ocDBArea;
3064 pRawToken = aToken.Clone();
3065 return sal_True;
3066 }
3067 else
3068 return sal_False;
3069 }
3070
IsColRowName(const String & rName)3071 sal_Bool ScCompiler::IsColRowName( const String& rName )
3072 {
3073 sal_Bool bInList = sal_False;
3074 sal_Bool bFound = sal_False;
3075 ScSingleRefData aRef;
3076 String aName( rName );
3077 DeQuote( aName );
3078 SCTAB nThisTab = aPos.Tab();
3079 for ( short jThisTab = 1; jThisTab >= 0 && !bInList; jThisTab-- )
3080 { // #50300# first check ranges on this sheet, in case of duplicated names
3081 for ( short jRow=0; jRow<2 && !bInList; jRow++ )
3082 {
3083 ScRangePairList* pRL;
3084 if ( !jRow )
3085 pRL = pDoc->GetColNameRanges();
3086 else
3087 pRL = pDoc->GetRowNameRanges();
3088 for ( ScRangePair* pR = pRL->First(); pR && !bInList; pR = pRL->Next() )
3089 {
3090 const ScRange& rNameRange = pR->GetRange(0);
3091 if ( jThisTab && !(rNameRange.aStart.Tab() <= nThisTab &&
3092 nThisTab <= rNameRange.aEnd.Tab()) )
3093 continue; // for
3094 ScCellIterator aIter( pDoc, rNameRange );
3095 for ( ScBaseCell* pCell = aIter.GetFirst(); pCell && !bInList;
3096 pCell = aIter.GetNext() )
3097 {
3098 // Don't crash if cell (via CompileNameFormula) encounters
3099 // a formula cell without code and
3100 // HasStringData/Interpret/Compile is executed and all that
3101 // recursive..
3102 // Furthermore, *this* cell won't be touched, since no RPN exists yet.
3103 CellType eType = pCell->GetCellType();
3104 sal_Bool bOk = sal::static_int_cast<sal_Bool>( (eType == CELLTYPE_FORMULA ?
3105 ((ScFormulaCell*)pCell)->GetCode()->GetCodeLen() > 0
3106 && ((ScFormulaCell*)pCell)->aPos != aPos // noIter
3107 : sal_True ) );
3108 if ( bOk && pCell->HasStringData() )
3109 {
3110 String aStr;
3111 switch ( eType )
3112 {
3113 case CELLTYPE_STRING:
3114 ((ScStringCell*)pCell)->GetString( aStr );
3115 break;
3116 case CELLTYPE_FORMULA:
3117 ((ScFormulaCell*)pCell)->GetString( aStr );
3118 break;
3119 case CELLTYPE_EDIT:
3120 ((ScEditCell*)pCell)->GetString( aStr );
3121 break;
3122 case CELLTYPE_NONE:
3123 case CELLTYPE_VALUE:
3124 case CELLTYPE_NOTE:
3125 case CELLTYPE_SYMBOLS:
3126 #if DBG_UTIL
3127 case CELLTYPE_DESTROYED:
3128 #endif
3129 ; // nothing, prevent compiler warning
3130 break;
3131 }
3132 if ( ScGlobal::GetpTransliteration()->isEqual( aStr, aName ) )
3133 {
3134 aRef.InitFlags();
3135 aRef.nCol = aIter.GetCol();
3136 aRef.nRow = aIter.GetRow();
3137 aRef.nTab = aIter.GetTab();
3138 if ( !jRow )
3139 aRef.SetColRel( sal_True ); // ColName
3140 else
3141 aRef.SetRowRel( sal_True ); // RowName
3142 aRef.CalcRelFromAbs( aPos );
3143 bInList = bFound = sal_True;
3144 }
3145 }
3146 }
3147 }
3148 }
3149 }
3150 if ( !bInList && pDoc->GetDocOptions().IsLookUpColRowNames() )
3151 { // search in current sheet
3152 long nDistance = 0, nMax = 0;
3153 long nMyCol = (long) aPos.Col();
3154 long nMyRow = (long) aPos.Row();
3155 sal_Bool bTwo = sal_False;
3156 ScAddress aOne( 0, 0, aPos.Tab() );
3157 ScAddress aTwo( MAXCOL, MAXROW, aPos.Tab() );
3158
3159 ScAutoNameCache* pNameCache = pDoc->GetAutoNameCache();
3160 if ( pNameCache )
3161 {
3162 // #b6355215# use GetNameOccurences to collect all positions of aName on the sheet
3163 // (only once), similar to the outer part of the loop in the "else" branch.
3164
3165 const ScAutoNameAddresses& rAddresses = pNameCache->GetNameOccurences( aName, aPos.Tab() );
3166
3167 // Loop through the found positions, similar to the inner part of the loop in the "else" branch.
3168 // The order of addresses in the vector is the same as from ScCellIterator.
3169
3170 ScAutoNameAddresses::const_iterator aEnd(rAddresses.end());
3171 for ( ScAutoNameAddresses::const_iterator aAdrIter(rAddresses.begin()); aAdrIter != aEnd; ++aAdrIter )
3172 {
3173 ScAddress aAddress( *aAdrIter ); // cell address with an equal string
3174
3175 if ( bFound )
3176 { // stop if everything else is further away
3177 if ( nMax < (long)aAddress.Col() )
3178 break; // aIter
3179 }
3180 if ( aAddress != aPos )
3181 {
3182 // same treatment as in isEqual case below
3183
3184 SCCOL nCol = aAddress.Col();
3185 SCROW nRow = aAddress.Row();
3186 long nC = nMyCol - nCol;
3187 long nR = nMyRow - nRow;
3188 if ( bFound )
3189 {
3190 long nD = nC * nC + nR * nR;
3191 if ( nD < nDistance )
3192 {
3193 if ( nC < 0 || nR < 0 )
3194 { // right or below
3195 bTwo = sal_True;
3196 aTwo.Set( nCol, nRow, aAddress.Tab() );
3197 nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
3198 nDistance = nD;
3199 }
3200 else if ( !(nRow < aOne.Row() && nMyRow >= (long)aOne.Row()) )
3201 {
3202 // upper left, only if not further up than the
3203 // current entry and nMyRow is below (CellIter
3204 // runs column-wise)
3205 bTwo = sal_False;
3206 aOne.Set( nCol, nRow, aAddress.Tab() );
3207 nMax = Max( nMyCol + nC, nMyRow + nR );
3208 nDistance = nD;
3209 }
3210 }
3211 }
3212 else
3213 {
3214 aOne.Set( nCol, nRow, aAddress.Tab() );
3215 nDistance = nC * nC + nR * nR;
3216 nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
3217 }
3218 bFound = sal_True;
3219 }
3220 }
3221 }
3222 else
3223 {
3224 ScCellIterator aIter( pDoc, ScRange( aOne, aTwo ) );
3225 for ( ScBaseCell* pCell = aIter.GetFirst(); pCell; pCell = aIter.GetNext() )
3226 {
3227 if ( bFound )
3228 { // stop if everything else is further away
3229 if ( nMax < (long)aIter.GetCol() )
3230 break; // aIter
3231 }
3232 CellType eType = pCell->GetCellType();
3233 sal_Bool bOk = sal::static_int_cast<sal_Bool>( (eType == CELLTYPE_FORMULA ?
3234 ((ScFormulaCell*)pCell)->GetCode()->GetCodeLen() > 0
3235 && ((ScFormulaCell*)pCell)->aPos != aPos // noIter
3236 : sal_True ) );
3237 if ( bOk && pCell->HasStringData() )
3238 {
3239 String aStr;
3240 switch ( eType )
3241 {
3242 case CELLTYPE_STRING:
3243 ((ScStringCell*)pCell)->GetString( aStr );
3244 break;
3245 case CELLTYPE_FORMULA:
3246 ((ScFormulaCell*)pCell)->GetString( aStr );
3247 break;
3248 case CELLTYPE_EDIT:
3249 ((ScEditCell*)pCell)->GetString( aStr );
3250 break;
3251 case CELLTYPE_NONE:
3252 case CELLTYPE_VALUE:
3253 case CELLTYPE_NOTE:
3254 case CELLTYPE_SYMBOLS:
3255 #if DBG_UTIL
3256 case CELLTYPE_DESTROYED:
3257 #endif
3258 ; // nothing, prevent compiler warning
3259 break;
3260 }
3261 if ( ScGlobal::GetpTransliteration()->isEqual( aStr, aName ) )
3262 {
3263 SCCOL nCol = aIter.GetCol();
3264 SCROW nRow = aIter.GetRow();
3265 long nC = nMyCol - nCol;
3266 long nR = nMyRow - nRow;
3267 if ( bFound )
3268 {
3269 long nD = nC * nC + nR * nR;
3270 if ( nD < nDistance )
3271 {
3272 if ( nC < 0 || nR < 0 )
3273 { // right or below
3274 bTwo = sal_True;
3275 aTwo.Set( nCol, nRow, aIter.GetTab() );
3276 nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
3277 nDistance = nD;
3278 }
3279 else if ( !(nRow < aOne.Row() && nMyRow >= (long)aOne.Row()) )
3280 {
3281 // upper left, only if not further up than the
3282 // current entry and nMyRow is below (CellIter
3283 // runs column-wise)
3284 bTwo = sal_False;
3285 aOne.Set( nCol, nRow, aIter.GetTab() );
3286 nMax = Max( nMyCol + nC, nMyRow + nR );
3287 nDistance = nD;
3288 }
3289 }
3290 }
3291 else
3292 {
3293 aOne.Set( nCol, nRow, aIter.GetTab() );
3294 nDistance = nC * nC + nR * nR;
3295 nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
3296 }
3297 bFound = sal_True;
3298 }
3299 }
3300 }
3301 }
3302
3303 if ( bFound )
3304 {
3305 ScAddress aAdr;
3306 if ( bTwo )
3307 {
3308 if ( nMyCol >= (long)aOne.Col() && nMyRow >= (long)aOne.Row() )
3309 aAdr = aOne; // upper left takes precedence
3310 else
3311 {
3312 if ( nMyCol < (long)aOne.Col() )
3313 { // two to the right
3314 if ( nMyRow >= (long)aTwo.Row() )
3315 aAdr = aTwo; // directly right
3316 else
3317 aAdr = aOne;
3318 }
3319 else
3320 { // two below or below and right, take the nearest
3321 long nC1 = nMyCol - aOne.Col();
3322 long nR1 = nMyRow - aOne.Row();
3323 long nC2 = nMyCol - aTwo.Col();
3324 long nR2 = nMyRow - aTwo.Row();
3325 if ( nC1 * nC1 + nR1 * nR1 <= nC2 * nC2 + nR2 * nR2 )
3326 aAdr = aOne;
3327 else
3328 aAdr = aTwo;
3329 }
3330 }
3331 }
3332 else
3333 aAdr = aOne;
3334 aRef.InitAddress( aAdr );
3335 if ( (aRef.nRow != MAXROW && pDoc->HasStringData(
3336 aRef.nCol, aRef.nRow + 1, aRef.nTab ))
3337 || (aRef.nRow != 0 && pDoc->HasStringData(
3338 aRef.nCol, aRef.nRow - 1, aRef.nTab )) )
3339 aRef.SetRowRel( sal_True ); // RowName
3340 else
3341 aRef.SetColRel( sal_True ); // ColName
3342 aRef.CalcRelFromAbs( aPos );
3343 }
3344 }
3345 if ( bFound )
3346 {
3347 ScRawToken aToken;
3348 aToken.SetSingleReference( aRef );
3349 aToken.eOp = ocColRowName;
3350 pRawToken = aToken.Clone();
3351 return sal_True;
3352 }
3353 else
3354 return sal_False;
3355 }
3356
IsBoolean(const String & rName)3357 sal_Bool ScCompiler::IsBoolean( const String& rName )
3358 {
3359 OpCodeHashMap::const_iterator iLook( mxSymbols->getHashMap()->find( rName ) );
3360 if( iLook != mxSymbols->getHashMap()->end() &&
3361 ((*iLook).second == ocTrue ||
3362 (*iLook).second == ocFalse) )
3363 {
3364 ScRawToken aToken;
3365 aToken.SetOpCode( (*iLook).second );
3366 pRawToken = aToken.Clone();
3367 return sal_True;
3368 }
3369 else
3370 return sal_False;
3371 }
3372
3373 //---------------------------------------------------------------------------
3374
AutoCorrectParsedSymbol()3375 void ScCompiler::AutoCorrectParsedSymbol()
3376 {
3377 xub_StrLen nPos = aCorrectedSymbol.Len();
3378 if ( nPos )
3379 {
3380 nPos--;
3381 const sal_Unicode cQuote = '\"';
3382 const sal_Unicode cx = 'x';
3383 const sal_Unicode cX = 'X';
3384 sal_Unicode c1 = aCorrectedSymbol.GetChar( 0 );
3385 sal_Unicode c2 = aCorrectedSymbol.GetChar( nPos );
3386 if ( c1 == cQuote && c2 != cQuote )
3387 { // "...
3388 // What's not a word doesn't belong to it.
3389 // Don't be pedantic: c < 128 should be sufficient here.
3390 while ( nPos && ((aCorrectedSymbol.GetChar(nPos) < 128) &&
3391 ((GetCharTableFlags( aCorrectedSymbol.GetChar(nPos) ) &
3392 (SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_DONTCARE)) == 0)) )
3393 nPos--;
3394 if ( nPos == MAXSYMLEN - 2 )
3395 aCorrectedSymbol.SetChar( nPos, cQuote ); // '"' the last character
3396 else
3397 aCorrectedSymbol.Insert( cQuote, nPos + 1 );
3398 bCorrected = sal_True;
3399 }
3400 else if ( c1 != cQuote && c2 == cQuote )
3401 { // ..."
3402 aCorrectedSymbol.Insert( cQuote, 0 );
3403 bCorrected = sal_True;
3404 }
3405 else if ( nPos == 0 && (c1 == cx || c1 == cX) )
3406 { // x => *
3407 aCorrectedSymbol = mxSymbols->getSymbol(ocMul);
3408 bCorrected = sal_True;
3409 }
3410 else if ( (GetCharTableFlags( c1 ) & SC_COMPILER_C_CHAR_VALUE)
3411 && (GetCharTableFlags( c2 ) & SC_COMPILER_C_CHAR_VALUE) )
3412 {
3413 xub_StrLen nXcount;
3414 if ( (nXcount = aCorrectedSymbol.GetTokenCount( cx )) > 1 )
3415 { // x => *
3416 xub_StrLen nIndex = 0;
3417 sal_Unicode c = mxSymbols->getSymbol(ocMul).GetChar(0);
3418 while ( (nIndex = aCorrectedSymbol.SearchAndReplace(
3419 cx, c, nIndex )) != STRING_NOTFOUND )
3420 nIndex++;
3421 bCorrected = sal_True;
3422 }
3423 if ( (nXcount = aCorrectedSymbol.GetTokenCount( cX )) > 1 )
3424 { // X => *
3425 xub_StrLen nIndex = 0;
3426 sal_Unicode c = mxSymbols->getSymbol(ocMul).GetChar(0);
3427 while ( (nIndex = aCorrectedSymbol.SearchAndReplace(
3428 cX, c, nIndex )) != STRING_NOTFOUND )
3429 nIndex++;
3430 bCorrected = sal_True;
3431 }
3432 }
3433 else
3434 {
3435 String aSymbol( aCorrectedSymbol );
3436 String aDoc;
3437 xub_StrLen nPosition;
3438 if ( aSymbol.GetChar(0) == '\''
3439 && ((nPosition = aSymbol.SearchAscii( "'#" )) != STRING_NOTFOUND) )
3440 { // Split off 'Doc'#, may be d:\... or whatever
3441 aDoc = aSymbol.Copy( 0, nPosition + 2 );
3442 aSymbol.Erase( 0, nPosition + 2 );
3443 }
3444 xub_StrLen nRefs = aSymbol.GetTokenCount( ':' );
3445 sal_Bool bColons;
3446 if ( nRefs > 2 )
3447 { // duplicated or too many ':'? B:2::C10 => B2:C10
3448 bColons = sal_True;
3449 xub_StrLen nIndex = 0;
3450 String aTmp1( aSymbol.GetToken( 0, ':', nIndex ) );
3451 xub_StrLen nLen1 = aTmp1.Len();
3452 String aSym, aTmp2;
3453 sal_Bool bLastAlp, bNextNum;
3454 bLastAlp = bNextNum = sal_True;
3455 xub_StrLen nStrip = 0;
3456 xub_StrLen nCount = nRefs;
3457 for ( xub_StrLen j=1; j<nCount; j++ )
3458 {
3459 aTmp2 = aSymbol.GetToken( 0, ':', nIndex );
3460 xub_StrLen nLen2 = aTmp2.Len();
3461 if ( nLen1 || nLen2 )
3462 {
3463 if ( nLen1 )
3464 {
3465 aSym += aTmp1;
3466 bLastAlp = CharClass::isAsciiAlpha( aTmp1 );
3467 }
3468 if ( nLen2 )
3469 {
3470 bNextNum = CharClass::isAsciiNumeric( aTmp2 );
3471 if ( bLastAlp == bNextNum && nStrip < 1 )
3472 {
3473 // Must be alternating number/string, only
3474 // strip within a reference.
3475 nRefs--;
3476 nStrip++;
3477 }
3478 else
3479 {
3480 xub_StrLen nSymLen = aSym.Len();
3481 if ( nSymLen
3482 && (aSym.GetChar( nSymLen - 1 ) != ':') )
3483 aSym += ':';
3484 nStrip = 0;
3485 }
3486 bLastAlp = !bNextNum;
3487 }
3488 else
3489 { // ::
3490 nRefs--;
3491 if ( nLen1 )
3492 { // B10::C10 ? append ':' on next round
3493 if ( !bLastAlp && !CharClass::isAsciiNumeric( aTmp1 ) )
3494 nStrip++;
3495 }
3496 bNextNum = !bLastAlp;
3497 }
3498 aTmp1 = aTmp2;
3499 nLen1 = nLen2;
3500 }
3501 else
3502 nRefs--;
3503 }
3504 aSymbol = aSym;
3505 aSymbol += aTmp1;
3506 }
3507 else
3508 bColons = sal_False;
3509 if ( nRefs && nRefs <= 2 )
3510 { // reference twisted? 4A => A4 etc.
3511 String aTab[2], aRef[2];
3512 const ScAddress::Details aDetails( pConv->meConv, aPos );
3513 if ( nRefs == 2 )
3514 {
3515 aRef[0] = aSymbol.GetToken( 0, ':' );
3516 aRef[1] = aSymbol.GetToken( 1, ':' );
3517 }
3518 else
3519 aRef[0] = aSymbol;
3520
3521 sal_Bool bChanged = sal_False;
3522 sal_Bool bOk = sal_True;
3523 sal_uInt16 nMask = SCA_VALID | SCA_VALID_COL | SCA_VALID_ROW;
3524 for ( int j=0; j<nRefs; j++ )
3525 {
3526 xub_StrLen nTmp = 0;
3527 xub_StrLen nDotPos = STRING_NOTFOUND;
3528 while ( (nTmp = aRef[j].Search( '.', nTmp )) != STRING_NOTFOUND )
3529 nDotPos = nTmp++; // the last one counts
3530 if ( nDotPos != STRING_NOTFOUND )
3531 {
3532 aTab[j] = aRef[j].Copy( 0, nDotPos + 1 ); // with '.'
3533 aRef[j].Erase( 0, nDotPos + 1 );
3534 }
3535 String aOld( aRef[j] );
3536 String aStr2;
3537 const sal_Unicode* p = aRef[j].GetBuffer();
3538 while ( *p && CharClass::isAsciiNumeric( *p ) )
3539 aStr2 += *p++;
3540 aRef[j] = String( p );
3541 aRef[j] += aStr2;
3542 if ( bColons || aRef[j] != aOld )
3543 {
3544 bChanged = sal_True;
3545 ScAddress aAdr;
3546 bOk &= ((aAdr.Parse( aRef[j], pDoc, aDetails ) & nMask) == nMask);
3547 }
3548 }
3549 if ( bChanged && bOk )
3550 {
3551 aCorrectedSymbol = aDoc;
3552 aCorrectedSymbol += aTab[0];
3553 aCorrectedSymbol += aRef[0];
3554 if ( nRefs == 2 )
3555 {
3556 aCorrectedSymbol += ':';
3557 aCorrectedSymbol += aTab[1];
3558 aCorrectedSymbol += aRef[1];
3559 }
3560 bCorrected = sal_True;
3561 }
3562 }
3563 }
3564 }
3565 }
3566
lcl_UpperAsciiOrI18n(String & rUpper,const String & rOrg,FormulaGrammar::Grammar eGrammar)3567 inline bool lcl_UpperAsciiOrI18n( String& rUpper, const String& rOrg, FormulaGrammar::Grammar eGrammar )
3568 {
3569 if (FormulaGrammar::isODFF( eGrammar ))
3570 {
3571 // ODFF has a defined set of English function names, avoid i18n
3572 // overhead.
3573 rUpper = rOrg;
3574 rUpper.ToUpperAscii();
3575 return true;
3576 }
3577 else
3578 {
3579 rUpper = ScGlobal::pCharClass->upper( rOrg );
3580 return false;
3581 }
3582 }
3583
NextNewToken(bool bInArray)3584 sal_Bool ScCompiler::NextNewToken( bool bInArray )
3585 {
3586 bool bAllowBooleans = bInArray;
3587 xub_StrLen nSpaces = NextSymbol(bInArray);
3588
3589 #if 0
3590 fprintf( stderr, "NextNewToken '%s' (spaces = %d)\n",
3591 rtl::OUStringToOString( cSymbol, RTL_TEXTENCODING_UTF8 ).getStr(), nSpaces );
3592 #endif
3593
3594 if (!cSymbol[0])
3595 return false;
3596
3597 if( nSpaces )
3598 {
3599 ScRawToken aToken;
3600 aToken.SetOpCode( ocSpaces );
3601 aToken.sbyte.cByte = (sal_uInt8) ( nSpaces > 255 ? 255 : nSpaces );
3602 if( !static_cast<ScTokenArray*>(pArr)->AddRawToken( aToken ) )
3603 {
3604 SetError(errCodeOverflow);
3605 return false;
3606 }
3607 }
3608
3609 // Short cut for references when reading ODF to speedup things.
3610 if (mnPredetectedReference)
3611 {
3612 String aStr( cSymbol);
3613 if (aStr.EqualsAscii( "#REF!"))
3614 {
3615 // [#REF!], what ODF writes for a broken reference, is a deleted reference
3616 ScSingleRefData aRef;
3617 aRef.InitMembers();
3618 aRef.InitAddress( MAXCOL+1, MAXROW+1, MAXTAB+3); // out of range, as for an invalid reference
3619 aRef.SetColRel( sal_True);
3620 aRef.SetRowRel( sal_True);
3621 aRef.SetColDeleted( sal_True);
3622 aRef.SetRowDeleted( sal_True);
3623 aRef.SetTabDeleted( sal_True);
3624 aRef.CalcRelFromAbs( aPos);
3625 ScRawToken aToken;
3626 aToken.SetSingleReference( aRef);
3627 pRawToken = aToken.Clone();
3628 return true;
3629 }
3630 if (!IsPredetectedReference( aStr) && !IsExternalNamedRange( aStr))
3631 {
3632 /* TODO: it would be nice to generate a #REF! error here, which
3633 * would need an ocBad token with additional error value.
3634 * FormulaErrorToken wouldn't do because we want to preserve the
3635 * original string containing partial valid address
3636 * information. */
3637 ScRawToken aToken;
3638 aToken.SetString( aStr.GetBuffer() );
3639 aToken.NewOpCode( ocBad );
3640 pRawToken = aToken.Clone();
3641 }
3642 return true;
3643 }
3644
3645 if ( (cSymbol[0] == '#' || cSymbol[0] == '$') && cSymbol[1] == 0 &&
3646 !bAutoCorrect )
3647 { // #101100# special case to speed up broken [$]#REF documents
3648 /* FIXME: ISERROR(#REF!) would be valid and sal_True and the formula to
3649 * be processed as usual. That would need some special treatment,
3650 * also in NextSymbol() because of possible combinations of
3651 * #REF!.#REF!#REF! parts. In case of reading ODF that is all
3652 * handled by IsPredetectedReference(), this case here remains for
3653 * manual/API input. */
3654 String aBad( aFormula.Copy( nSrcPos-1 ) );
3655 eLastOp = pArr->AddBad( aBad )->GetOpCode();
3656 return false;
3657 }
3658
3659 if( IsString() )
3660 return true;
3661
3662 bool bMayBeFuncName;
3663 bool bAsciiNonAlnum; // operators, separators, ...
3664 if ( cSymbol[0] < 128 )
3665 {
3666 bMayBeFuncName = CharClass::isAsciiAlpha( cSymbol[0] );
3667 bAsciiNonAlnum = !bMayBeFuncName && !CharClass::isAsciiDigit( cSymbol[0] );
3668 }
3669 else
3670 {
3671 String aTmpStr( cSymbol[0] );
3672 bMayBeFuncName = ScGlobal::pCharClass->isLetter( aTmpStr, 0 );
3673 bAsciiNonAlnum = false;
3674 }
3675 if ( bMayBeFuncName )
3676 {
3677 // a function name must be followed by a parenthesis
3678 const sal_Unicode* p = aFormula.GetBuffer() + nSrcPos;
3679 while( *p == ' ' )
3680 p++;
3681 bMayBeFuncName = ( *p == '(' );
3682 }
3683
3684 #if 0
3685 fprintf( stderr, "Token '%s'\n",
3686 rtl::OUStringToOString( aUpper, RTL_TEXTENCODING_UTF8 ).getStr() );
3687 #endif
3688
3689 // #42016# Italian ARCTAN.2 resulted in #REF! => IsOpcode() before
3690 // IsReference().
3691
3692 String aUpper;
3693
3694 do
3695 {
3696 mbRewind = false;
3697 const String aOrg( cSymbol );
3698
3699 if (bAsciiNonAlnum && IsOpCode( aOrg, bInArray ))
3700 return true;
3701
3702 aUpper.Erase();
3703 bool bAsciiUpper = false;
3704 if (bMayBeFuncName)
3705 {
3706 bAsciiUpper = lcl_UpperAsciiOrI18n( aUpper, aOrg, meGrammar);
3707 if (IsOpCode( aUpper, bInArray ))
3708 return true;
3709 }
3710
3711 // Column 'DM' ("Deutsche Mark", German currency) couldn't be
3712 // referred => IsReference() before IsValue().
3713 // Preserve case of file names in external references.
3714 if (IsReference( aOrg ))
3715 {
3716 if (mbRewind) // Range operator, but no direct reference.
3717 continue; // do; up to range operator.
3718 return true;
3719 }
3720
3721 if (!aUpper.Len())
3722 bAsciiUpper = lcl_UpperAsciiOrI18n( aUpper, aOrg, meGrammar);
3723
3724 // IsBoolean() before IsValue() to catch inline bools without the kludge
3725 // for inline arrays.
3726 if (bAllowBooleans && IsBoolean( aUpper ))
3727 return true;
3728
3729 if (IsValue( aUpper ))
3730 return true;
3731
3732 // User defined names and such do need i18n upper also in ODF.
3733 if (bAsciiUpper)
3734 aUpper = ScGlobal::pCharClass->upper( aOrg );
3735
3736 if (IsNamedRange( aUpper ))
3737 return true;
3738 // Preserve case of file names in external references.
3739 if (IsExternalNamedRange( aOrg ))
3740 return true;
3741 if (IsDBRange( aUpper ))
3742 return true;
3743 if (IsColRowName( aUpper ))
3744 return true;
3745 if (bMayBeFuncName && IsMacro( aUpper ))
3746 return true;
3747 if (bMayBeFuncName && IsOpCode2( aUpper ))
3748 return true;
3749
3750 } while (mbRewind);
3751
3752 if ( mbExtendedErrorDetection )
3753 {
3754 // set an error and end compilation
3755 SetError( errNoName );
3756 return false;
3757 }
3758
3759 // Provide single token information and continue. Do not set an error, that
3760 // would prematurely end compilation. Simple unknown names are handled by
3761 // the interpreter.
3762 ScGlobal::pCharClass->toLower( aUpper );
3763 ScRawToken aToken;
3764 aToken.SetString( aUpper.GetBuffer() );
3765 aToken.NewOpCode( ocBad );
3766 pRawToken = aToken.Clone();
3767 if ( bAutoCorrect )
3768 AutoCorrectParsedSymbol();
3769 return true;
3770 }
3771
CreateStringFromXMLTokenArray(String & rFormula,String & rFormulaNmsp)3772 void ScCompiler::CreateStringFromXMLTokenArray( String& rFormula, String& rFormulaNmsp )
3773 {
3774 bool bExternal = GetGrammar() == FormulaGrammar::GRAM_EXTERNAL;
3775 sal_uInt16 nExpectedCount = bExternal ? 2 : 1;
3776 DBG_ASSERT( pArr->GetLen() == nExpectedCount, "ScCompiler::CreateStringFromXMLTokenArray - wrong number of tokens" );
3777 if( pArr->GetLen() == nExpectedCount )
3778 {
3779 FormulaToken** ppTokens = pArr->GetArray();
3780 // string tokens expected, GetString() will assert if token type is wrong
3781 rFormula = ppTokens[ 0 ]->GetString();
3782 if( bExternal )
3783 rFormulaNmsp = ppTokens[ 1 ]->GetString();
3784 }
3785 }
3786
CompileString(const String & rFormula)3787 ScTokenArray* ScCompiler::CompileString( const String& rFormula )
3788 {
3789 #if 0
3790 fprintf( stderr, "CompileString '%s'\n",
3791 rtl::OUStringToOString( rFormula, RTL_TEXTENCODING_UTF8 ).getStr() );
3792 #endif
3793
3794 OSL_ENSURE( meGrammar != FormulaGrammar::GRAM_EXTERNAL, "ScCompiler::CompileString - unexpected grammar GRAM_EXTERNAL" );
3795 if( meGrammar == FormulaGrammar::GRAM_EXTERNAL )
3796 SetGrammar( FormulaGrammar::GRAM_PODF );
3797
3798 ScTokenArray aArr;
3799 pArr = &aArr;
3800 aFormula = rFormula;
3801
3802 aFormula.EraseLeadingChars();
3803 aFormula.EraseTrailingChars();
3804 nSrcPos = 0;
3805 bCorrected = sal_False;
3806 if ( bAutoCorrect )
3807 {
3808 aCorrectedFormula.Erase();
3809 aCorrectedSymbol.Erase();
3810 }
3811 sal_uInt8 nForced = 0; // ==formula forces recalc even if cell is not visible
3812 if( aFormula.GetChar(nSrcPos) == '=' )
3813 {
3814 nSrcPos++;
3815 nForced++;
3816 if ( bAutoCorrect )
3817 aCorrectedFormula += '=';
3818 }
3819 if( aFormula.GetChar(nSrcPos) == '=' )
3820 {
3821 nSrcPos++;
3822 nForced++;
3823 if ( bAutoCorrect )
3824 aCorrectedFormula += '=';
3825 }
3826 struct FunctionStack
3827 {
3828 OpCode eOp;
3829 short nPar;
3830 };
3831 // FunctionStack only used if PODF!
3832 bool bPODF = FormulaGrammar::isPODF( meGrammar);
3833 const size_t nAlloc = 512;
3834 FunctionStack aFuncs[ nAlloc ];
3835 FunctionStack* pFunctionStack = (bPODF && rFormula.Len() > nAlloc ?
3836 new FunctionStack[ rFormula.Len() ] : &aFuncs[0]);
3837 pFunctionStack[0].eOp = ocNone;
3838 pFunctionStack[0].nPar = 0;
3839 size_t nFunction = 0;
3840 short nBrackets = 0;
3841 bool bInArray = false;
3842 eLastOp = ocOpen;
3843 while( NextNewToken( bInArray ) )
3844 {
3845 const OpCode eOp = pRawToken->GetOpCode();
3846 switch (eOp)
3847 {
3848 case ocOpen:
3849 {
3850 ++nBrackets;
3851 if (bPODF)
3852 {
3853 ++nFunction;
3854 pFunctionStack[ nFunction ].eOp = eLastOp;
3855 pFunctionStack[ nFunction ].nPar = 0;
3856 }
3857 }
3858 break;
3859 case ocClose:
3860 {
3861 if( !nBrackets )
3862 {
3863 SetError( errPairExpected );
3864 if ( bAutoCorrect )
3865 {
3866 bCorrected = sal_True;
3867 aCorrectedSymbol.Erase();
3868 }
3869 }
3870 else
3871 nBrackets--;
3872 if (bPODF && nFunction)
3873 --nFunction;
3874 }
3875 break;
3876 case ocSep:
3877 {
3878 if (bPODF)
3879 ++pFunctionStack[ nFunction ].nPar;
3880 }
3881 break;
3882 case ocArrayOpen:
3883 {
3884 if( bInArray )
3885 SetError( errNestedArray );
3886 else
3887 bInArray = true;
3888 // Don't count following column separator as parameter separator.
3889 if (bPODF)
3890 {
3891 ++nFunction;
3892 pFunctionStack[ nFunction ].eOp = eOp;
3893 pFunctionStack[ nFunction ].nPar = 0;
3894 }
3895 }
3896 break;
3897 case ocArrayClose:
3898 {
3899 if( bInArray )
3900 {
3901 bInArray = false;
3902 }
3903 else
3904 {
3905 SetError( errPairExpected );
3906 if ( bAutoCorrect )
3907 {
3908 bCorrected = sal_True;
3909 aCorrectedSymbol.Erase();
3910 }
3911 }
3912 if (bPODF && nFunction)
3913 --nFunction;
3914 }
3915 default:
3916 break;
3917 }
3918 if( (eLastOp == ocSep ||
3919 eLastOp == ocArrayRowSep ||
3920 eLastOp == ocArrayColSep ||
3921 eLastOp == ocArrayOpen) &&
3922 (eOp == ocSep ||
3923 eOp == ocArrayRowSep ||
3924 eOp == ocArrayColSep ||
3925 eOp == ocArrayClose) )
3926 {
3927 // FIXME: should we check for known functions with optional empty
3928 // args so the correction dialog can do better?
3929 if ( !static_cast<ScTokenArray*>(pArr)->Add( new FormulaMissingToken ) )
3930 {
3931 SetError(errCodeOverflow); break;
3932 }
3933 }
3934 if (bPODF)
3935 {
3936 /* TODO: for now this is the only PODF adapter. If there were more,
3937 * factor this out. */
3938 // Insert ADDRESS() new empty parameter 4 if there is a 4th, now to be 5th.
3939 if (eOp == ocSep &&
3940 pFunctionStack[ nFunction ].eOp == ocAddress &&
3941 pFunctionStack[ nFunction ].nPar == 3)
3942 {
3943 if (!static_cast<ScTokenArray*>(pArr)->Add( new FormulaToken( svSep,ocSep)) ||
3944 !static_cast<ScTokenArray*>(pArr)->Add( new FormulaDoubleToken( 1.0)))
3945 {
3946 SetError(errCodeOverflow); break;
3947 }
3948 ++pFunctionStack[ nFunction ].nPar;
3949 }
3950 }
3951 FormulaToken* pNewToken = static_cast<ScTokenArray*>(pArr)->Add( pRawToken->CreateToken());
3952 if (!pNewToken)
3953 {
3954 SetError(errCodeOverflow); break;
3955 }
3956 else if (eLastOp == ocRange && pNewToken->GetOpCode() == ocPush &&
3957 pNewToken->GetType() == svSingleRef)
3958 static_cast<ScTokenArray*>(pArr)->MergeRangeReference( aPos);
3959 eLastOp = pRawToken->GetOpCode();
3960 if ( bAutoCorrect )
3961 aCorrectedFormula += aCorrectedSymbol;
3962 }
3963 if ( mbCloseBrackets )
3964 {
3965 if( bInArray )
3966 {
3967 FormulaByteToken aToken( ocArrayClose );
3968 if( !pArr->AddToken( aToken ) )
3969 {
3970 SetError(errCodeOverflow);
3971 }
3972 else if ( bAutoCorrect )
3973 aCorrectedFormula += mxSymbols->getSymbol(ocArrayClose);
3974 }
3975
3976 FormulaByteToken aToken( ocClose );
3977 while( nBrackets-- )
3978 {
3979 if( !pArr->AddToken( aToken ) )
3980 {
3981 SetError(errCodeOverflow); break;
3982 }
3983 if ( bAutoCorrect )
3984 aCorrectedFormula += mxSymbols->getSymbol(ocClose);
3985 }
3986 }
3987 if ( aArr.GetLen() >= MAXCODE )
3988 {
3989 // keep the whole text, the tokens that fit would be written back as a shorter formula
3990 aArr.Clear();
3991 aArr.AddBad( aFormula.Copy( nForced ) );
3992 aArr.SetCodeError( errCodeOverflow );
3993 bCorrected = sal_False; // the corrected text stops where the tokens did
3994 }
3995 if ( nForced >= 2 )
3996 pArr->SetRecalcModeForced();
3997
3998 if (pFunctionStack != &aFuncs[0])
3999 delete [] pFunctionStack;
4000
4001 // remember pArr, in case a subsequent CompileTokenArray() is executed.
4002 ScTokenArray* pNew = new ScTokenArray( aArr );
4003 pArr = pNew;
4004 return pNew;
4005 }
4006
4007
CompileString(const String & rFormula,const String & rFormulaNmsp)4008 ScTokenArray* ScCompiler::CompileString( const String& rFormula, const String& rFormulaNmsp )
4009 {
4010 DBG_ASSERT( (GetGrammar() == FormulaGrammar::GRAM_EXTERNAL) || (rFormulaNmsp.Len() == 0),
4011 "ScCompiler::CompileString - unexpected formula namespace for internal grammar" );
4012 if( GetGrammar() == FormulaGrammar::GRAM_EXTERNAL ) try
4013 {
4014 ScFormulaParserPool& rParserPool = pDoc->GetFormulaParserPool();
4015 uno::Reference< sheet::XFormulaParser > xParser( rParserPool.getFormulaParser( rFormulaNmsp ), uno::UNO_SET_THROW );
4016 table::CellAddress aReferencePos;
4017 ScUnoConversion::FillApiAddress( aReferencePos, aPos );
4018 uno::Sequence< sheet::FormulaToken > aTokenSeq = xParser->parseFormula( rFormula, aReferencePos );
4019 ScTokenArray aTokenArray;
4020 if( ScTokenConversion::ConvertToTokenArray( *pDoc, aTokenArray, aTokenSeq ) )
4021 {
4022 // remember pArr, in case a subsequent CompileTokenArray() is executed.
4023 ScTokenArray* pNew = new ScTokenArray( aTokenArray );
4024 pArr = pNew;
4025 return pNew;
4026 }
4027 }
4028 catch( uno::Exception& )
4029 {
4030 }
4031 // no success - fallback to some internal grammar and hope the best
4032 return CompileString( rFormula );
4033 }
4034
4035
HandleRange()4036 sal_Bool ScCompiler::HandleRange()
4037 {
4038 ScRangeData* pRangeData = pDoc->GetRangeName()->FindIndex( pToken->GetIndex() );
4039 if (pRangeData)
4040 {
4041 sal_uInt16 nErr = pRangeData->GetErrCode();
4042 if( nErr )
4043 SetError( errNoName );
4044 else if ( !bCompileForFAP )
4045 {
4046 ScTokenArray* pNew;
4047 // #35168# put named formula into parentheses.
4048 // #37680# But only if there aren't any yet, parenthetical
4049 // ocSep doesn't work, e.g. SUM((...;...))
4050 // or if not directly between ocSep/parenthesis,
4051 // e.g. SUM(...;(...;...)) no, SUM(...;(...)*3) yes,
4052 // in short: if it isn't a self-contained expression.
4053 FormulaToken* p1 = pArr->PeekPrevNoSpaces();
4054 FormulaToken* p2 = pArr->PeekNextNoSpaces();
4055 OpCode eOp1 = (p1 ? p1->GetOpCode() : static_cast<OpCode>( ocSep ) );
4056 OpCode eOp2 = (p2 ? p2->GetOpCode() : static_cast<OpCode>( ocSep ) );
4057 sal_Bool bBorder1 = (eOp1 == ocSep || eOp1 == ocOpen);
4058 sal_Bool bBorder2 = (eOp2 == ocSep || eOp2 == ocClose);
4059 sal_Bool bAddPair = !(bBorder1 && bBorder2);
4060 if ( bAddPair )
4061 {
4062 pNew = new ScTokenArray();
4063 pNew->AddOpCode( ocClose );
4064 PushTokenArray( pNew, sal_True );
4065 pNew->Reset();
4066 }
4067 pNew = pRangeData->GetCode()->Clone();
4068 PushTokenArray( pNew, sal_True );
4069 if( pRangeData->HasReferences() )
4070 {
4071 SetRelNameReference();
4072 MoveRelWrap(pRangeData->GetMaxCol(), pRangeData->GetMaxRow());
4073 }
4074 pNew->Reset();
4075 if ( bAddPair )
4076 {
4077 pNew = new ScTokenArray();
4078 pNew->AddOpCode( ocOpen );
4079 PushTokenArray( pNew, sal_True );
4080 pNew->Reset();
4081 }
4082 return GetToken();
4083 }
4084 }
4085 else
4086 SetError(errNoName);
4087 return sal_True;
4088 }
4089 // -----------------------------------------------------------------------------
HandleExternalReference(const FormulaToken & _aToken)4090 sal_Bool ScCompiler::HandleExternalReference(const FormulaToken& _aToken)
4091 {
4092 // Handle external range names.
4093 switch (_aToken.GetType())
4094 {
4095 case svExternalSingleRef:
4096 case svExternalDoubleRef:
4097 pArr->IncrementRefs();
4098 break;
4099 case svExternalName:
4100 {
4101 ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
4102 const String* pFile = pRefMgr->getExternalFileName(_aToken.GetIndex());
4103 if (!pFile)
4104 {
4105 SetError(errNoName);
4106 return true;
4107 }
4108
4109 const String& rName = _aToken.GetString();
4110 ScExternalRefCache::TokenArrayRef xNew = pRefMgr->getRangeNameTokens(
4111 _aToken.GetIndex(), rName, &aPos);
4112
4113 if (!xNew)
4114 {
4115 SetError(errNoName);
4116 return true;
4117 }
4118
4119 ScTokenArray* pNew = xNew->Clone();
4120 PushTokenArray( pNew, true);
4121 if (pNew->GetNextReference() != NULL)
4122 {
4123 SetRelNameReference();
4124 MoveRelWrap(MAXCOL, MAXROW);
4125 }
4126 pNew->Reset();
4127 return GetToken();
4128 }
4129 default:
4130 DBG_ERROR("Wrong type for external reference!");
4131 return sal_False;
4132 }
4133 return sal_True;
4134 }
4135
4136
4137 //---------------------------------------------------------------------------
4138
4139
4140 //---------------------------------------------------------------------------
4141 // Append token to RPN code
4142 //---------------------------------------------------------------------------
4143
4144
4145 //-----------------------------------------------------------------------------
4146
4147 //---------------------------------------------------------------------------
4148 // RPN creation by recursion
4149 //---------------------------------------------------------------------------
4150
4151
4152
4153 //-----------------------------------------------------------------------------
4154
HasModifiedRange()4155 sal_Bool ScCompiler::HasModifiedRange()
4156 {
4157 pArr->Reset();
4158 for ( FormulaToken* t = pArr->Next(); t; t = pArr->Next() )
4159 {
4160 OpCode eOpCode = t->GetOpCode();
4161 if ( eOpCode == ocName )
4162 {
4163 ScRangeData* pRangeData = pDoc->GetRangeName()->FindIndex(t->GetIndex());
4164
4165 if (pRangeData && pRangeData->IsModified())
4166 return sal_True;
4167 }
4168 else if ( eOpCode == ocDBArea )
4169 {
4170 ScDBData* pDBData = pDoc->GetDBCollection()->FindIndex(t->GetIndex());
4171
4172 if (pDBData && pDBData->IsModified())
4173 return sal_True;
4174 }
4175 }
4176 return sal_False;
4177 }
4178
4179
4180 //---------------------------------------------------------------------------
4181
4182 template< typename T, typename S >
lcl_adjval(S & n,T pos,T max,sal_Bool bRel)4183 S lcl_adjval( S& n, T pos, T max, sal_Bool bRel )
4184 {
4185 max++;
4186 if( bRel )
4187 n = sal::static_int_cast<S>( n + pos );
4188 if( n < 0 )
4189 n = sal::static_int_cast<S>( n + max );
4190 else if( n >= max )
4191 n = sal::static_int_cast<S>( n - max );
4192 if( bRel )
4193 n = sal::static_int_cast<S>( n - pos );
4194 return n;
4195 }
4196
4197 // reference of named range with relative references
4198
SetRelNameReference()4199 void ScCompiler::SetRelNameReference()
4200 {
4201 pArr->Reset();
4202 for( ScToken* t = static_cast<ScToken*>(pArr->GetNextReference()); t;
4203 t = static_cast<ScToken*>(pArr->GetNextReference()) )
4204 {
4205 ScSingleRefData& rRef1 = t->GetSingleRef();
4206 if ( rRef1.IsColRel() || rRef1.IsRowRel() || rRef1.IsTabRel() )
4207 rRef1.SetRelName( sal_True );
4208 if ( t->GetType() == svDoubleRef )
4209 {
4210 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4211 if ( rRef2.IsColRel() || rRef2.IsRowRel() || rRef2.IsTabRel() )
4212 rRef2.SetRelName( sal_True );
4213 }
4214 }
4215 }
4216
4217 // Wrap-adjust relative references of a RangeName to current position,
4218 // don't call for other token arrays!
MoveRelWrap(SCCOL nMaxCol,SCROW nMaxRow)4219 void ScCompiler::MoveRelWrap( SCCOL nMaxCol, SCROW nMaxRow )
4220 {
4221 pArr->Reset();
4222 for( ScToken* t = static_cast<ScToken*>(pArr->GetNextReference()); t;
4223 t = static_cast<ScToken*>(pArr->GetNextReference()) )
4224 {
4225 if ( t->GetType() == svSingleRef || t->GetType() == svExternalSingleRef )
4226 ScRefUpdate::MoveRelWrap( pDoc, aPos, nMaxCol, nMaxRow, SingleDoubleRefModifier( t->GetSingleRef() ).Ref() );
4227 else
4228 ScRefUpdate::MoveRelWrap( pDoc, aPos, nMaxCol, nMaxRow, t->GetDoubleRef() );
4229 }
4230 }
4231
4232 // static
4233 // Wrap-adjust relative references of a RangeName to current position,
4234 // don't call for other token arrays!
MoveRelWrap(ScTokenArray & rArr,ScDocument * pDoc,const ScAddress & rPos,SCCOL nMaxCol,SCROW nMaxRow)4235 void ScCompiler::MoveRelWrap( ScTokenArray& rArr, ScDocument* pDoc, const ScAddress& rPos,
4236 SCCOL nMaxCol, SCROW nMaxRow )
4237 {
4238 rArr.Reset();
4239 for( ScToken* t = static_cast<ScToken*>(rArr.GetNextReference()); t;
4240 t = static_cast<ScToken*>(rArr.GetNextReference()) )
4241 {
4242 if ( t->GetType() == svSingleRef || t->GetType() == svExternalSingleRef )
4243 ScRefUpdate::MoveRelWrap( pDoc, rPos, nMaxCol, nMaxRow, SingleDoubleRefModifier( t->GetSingleRef() ).Ref() );
4244 else
4245 ScRefUpdate::MoveRelWrap( pDoc, rPos, nMaxCol, nMaxRow, t->GetDoubleRef() );
4246 }
4247 }
4248
UpdateReference(UpdateRefMode eUpdateRefMode,const ScAddress & rOldPos,const ScRange & r,SCsCOL nDx,SCsROW nDy,SCsTAB nDz,sal_Bool & rChanged,sal_Bool & rRefSizeChanged)4249 ScRangeData* ScCompiler::UpdateReference(UpdateRefMode eUpdateRefMode,
4250 const ScAddress& rOldPos, const ScRange& r,
4251 SCsCOL nDx, SCsROW nDy, SCsTAB nDz,
4252 sal_Bool& rChanged, sal_Bool& rRefSizeChanged )
4253 {
4254 rChanged = rRefSizeChanged = sal_False;
4255 if ( eUpdateRefMode == URM_COPY )
4256 { // Normally nothing has to be done here since RelRefs are used, also
4257 // SharedFormulas don't need any special handling, except if they
4258 // wrapped around sheet borders.
4259 // #67383# But ColRowName tokens pointing to a ColRow header which was
4260 // copied along with this formula need to be updated to point to the
4261 // copied header instead of the old position's new intersection.
4262 ScToken* t;
4263 pArr->Reset();
4264 while( (t = static_cast<ScToken*>(pArr->GetNextColRowName())) != NULL )
4265 {
4266 ScSingleRefData& rRef = t->GetSingleRef();
4267 rRef.CalcAbsIfRel( rOldPos );
4268 ScAddress aNewRef( rRef.nCol + nDx, rRef.nRow + nDy, rRef.nTab + nDz );
4269 if ( r.In( aNewRef ) )
4270 { // yes, this is URM_MOVE
4271 if ( ScRefUpdate::Update( pDoc, URM_MOVE, aPos,
4272 r, nDx, nDy, nDz,
4273 SingleDoubleRefModifier( rRef ).Ref() )
4274 != UR_NOTHING
4275 )
4276 rChanged = sal_True;
4277 }
4278 }
4279 // Check for SharedFormulas.
4280 ScRangeData* pRangeData = NULL;
4281 pArr->Reset();
4282 for( FormulaToken* j = pArr->GetNextName(); j && !pRangeData;
4283 j = pArr->GetNextName() )
4284 {
4285 if( j->GetOpCode() == ocName )
4286 {
4287 ScRangeData* pName = pDoc->GetRangeName()->FindIndex( j->GetIndex() );
4288 if (pName && pName->HasType(RT_SHARED))
4289 pRangeData = pName;
4290 }
4291 }
4292 // Check SharedFormulas for wraps.
4293 if (pRangeData)
4294 {
4295 ScRangeData* pName = pRangeData;
4296 pRangeData = NULL;
4297 pArr->Reset();
4298 for( t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()); t && !pRangeData;
4299 t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()) )
4300 {
4301 sal_Bool bRelName = (t->GetType() == svSingleRef ?
4302 t->GetSingleRef().IsRelName() :
4303 (t->GetDoubleRef().Ref1.IsRelName() ||
4304 t->GetDoubleRef().Ref2.IsRelName()));
4305 if (bRelName)
4306 {
4307 t->CalcAbsIfRel( rOldPos);
4308 sal_Bool bValid = (t->GetType() == svSingleRef ?
4309 t->GetSingleRef().Valid() :
4310 t->GetDoubleRef().Valid());
4311 // If the reference isn't valid, copying the formula
4312 // wrapped it. Replace SharedFormula.
4313 if (!bValid)
4314 {
4315 pRangeData = pName;
4316 rChanged = sal_True;
4317 }
4318 }
4319 }
4320 }
4321 return pRangeData;
4322 }
4323 else
4324 {
4325 /*
4326 * Set SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE to 1 if we wanted to preserve as
4327 * many shared formulas as possible instead of replacing them with direct code.
4328 * Note that this may produce shared formula usage Excel doesn't understand,
4329 * which would have to be adapted for in the export filter. Advisable as a long
4330 * term goal, since it could decrease memory footprint.
4331 */
4332 #define SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE 0
4333 ScRangeData* pRangeData = NULL;
4334 ScToken* t;
4335 pArr->Reset();
4336 while( (t = static_cast<ScToken*>(pArr->GetNextReferenceOrName())) != NULL )
4337 {
4338 if( t->GetOpCode() == ocName )
4339 {
4340 ScRangeData* pName = pDoc->GetRangeName()->FindIndex( t->GetIndex() );
4341 if (pName && pName->HasType(RT_SHAREDMOD))
4342 {
4343 pRangeData = pName; // maybe need a replacement of shared with own code
4344 #if ! SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4345 rChanged = sal_True;
4346 #endif
4347 }
4348 }
4349 else if( t->GetType() != svIndex ) // it may be a DB area!!!
4350 {
4351 t->CalcAbsIfRel( rOldPos );
4352 switch (t->GetType())
4353 {
4354 case svExternalSingleRef:
4355 case svExternalDoubleRef:
4356 // External references never change their positioning
4357 // nor point to parts that will be removed or expanded.
4358 // In fact, calling ScRefUpdate::Update() for URM_MOVE
4359 // may have negative side effects. Simply adapt
4360 // relative references to the new position.
4361 t->CalcRelFromAbs( aPos);
4362 break;
4363 case svSingleRef:
4364 {
4365 if ( ScRefUpdate::Update( pDoc, eUpdateRefMode,
4366 aPos, r, nDx, nDy, nDz,
4367 SingleDoubleRefModifier(
4368 t->GetSingleRef()).Ref())
4369 != UR_NOTHING)
4370 rChanged = sal_True;
4371 }
4372 break;
4373 default:
4374 {
4375 ScComplexRefData& rRef = t->GetDoubleRef();
4376 SCCOL nCols = rRef.Ref2.nCol - rRef.Ref1.nCol;
4377 SCROW nRows = rRef.Ref2.nRow - rRef.Ref1.nRow;
4378 SCTAB nTabs = rRef.Ref2.nTab - rRef.Ref1.nTab;
4379 if ( ScRefUpdate::Update( pDoc, eUpdateRefMode,
4380 aPos, r, nDx, nDy, nDz,
4381 t->GetDoubleRef()) != UR_NOTHING)
4382 {
4383 rChanged = sal_True;
4384 if (rRef.Ref2.nCol - rRef.Ref1.nCol != nCols ||
4385 rRef.Ref2.nRow - rRef.Ref1.nRow != nRows ||
4386 rRef.Ref2.nTab - rRef.Ref1.nTab != nTabs)
4387 rRefSizeChanged = sal_True;
4388 }
4389 }
4390 }
4391 }
4392 }
4393 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4394 sal_Bool bEasyShared, bPosInRange;
4395 if ( !pRangeData )
4396 bEasyShared = bPosInRange = sal_False;
4397 else
4398 {
4399 bEasyShared = sal_True;
4400 bPosInRange = r.In( eUpdateRefMode == URM_MOVE ? aPos : rOldPos );
4401 }
4402 #endif
4403 pArr->Reset();
4404 while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
4405 {
4406 if ( t->GetRef() != 1 )
4407 {
4408 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4409 bEasyShared = sal_False;
4410 #endif
4411 }
4412 else
4413 { // if nRefCnt>1 it's already updated in token code
4414 if ( t->GetType() == svSingleRef )
4415 {
4416 ScSingleRefData& rRef = t->GetSingleRef();
4417 SingleDoubleRefModifier aMod( rRef );
4418 if ( rRef.IsRelName() )
4419 {
4420 ScRefUpdate::MoveRelWrap( pDoc, aPos, MAXCOL, MAXROW, aMod.Ref() );
4421 rChanged = sal_True;
4422 }
4423 else
4424 {
4425 aMod.Ref().CalcAbsIfRel( rOldPos );
4426 if ( ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
4427 r, nDx, nDy, nDz, aMod.Ref() )
4428 != UR_NOTHING
4429 )
4430 rChanged = sal_True;
4431 }
4432 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4433 if ( bEasyShared )
4434 {
4435 const ScSingleRefData& rSRD = aMod.Ref().Ref1;
4436 ScAddress aRef( rSRD.nCol, rSRD.nRow, rSRD.nTab );
4437 if ( r.In( aRef ) != bPosInRange )
4438 bEasyShared = sal_False;
4439 }
4440 #endif
4441 }
4442 else
4443 {
4444 ScComplexRefData& rRef = t->GetDoubleRef();
4445 SCCOL nCols = rRef.Ref2.nCol - rRef.Ref1.nCol;
4446 SCROW nRows = rRef.Ref2.nRow - rRef.Ref1.nRow;
4447 SCTAB nTabs = rRef.Ref2.nTab - rRef.Ref1.nTab;
4448 if ( rRef.Ref1.IsRelName() || rRef.Ref2.IsRelName() )
4449 {
4450 ScRefUpdate::MoveRelWrap( pDoc, aPos, MAXCOL, MAXROW, rRef );
4451 rChanged = sal_True;
4452 }
4453 else
4454 {
4455 if ( ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
4456 r, nDx, nDy, nDz, rRef )
4457 != UR_NOTHING
4458 )
4459 {
4460 rChanged = sal_True;
4461 if (rRef.Ref2.nCol - rRef.Ref1.nCol != nCols ||
4462 rRef.Ref2.nRow - rRef.Ref1.nRow != nRows ||
4463 rRef.Ref2.nTab - rRef.Ref1.nTab != nTabs)
4464 {
4465 rRefSizeChanged = sal_True;
4466 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4467 bEasyShared = sal_False;
4468 #endif
4469 }
4470 }
4471 }
4472 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4473 if ( bEasyShared )
4474 {
4475 ScRange aRef( rRef.Ref1.nCol, rRef.Ref1.nRow,
4476 rRef.Ref1.nTab, rRef.Ref2.nCol, rRef.Ref2.nRow,
4477 rRef.Ref2.nTab );
4478 if ( r.In( aRef ) != bPosInRange )
4479 bEasyShared = sal_False;
4480 }
4481 #endif
4482 }
4483 }
4484 }
4485 #if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4486 if ( pRangeData )
4487 {
4488 if ( bEasyShared )
4489 pRangeData = 0;
4490 else
4491 rChanged = sal_True;
4492 }
4493 #endif
4494 #undef SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
4495 return pRangeData;
4496 }
4497 }
4498
UpdateNameReference(UpdateRefMode eUpdateRefMode,const ScRange & r,SCsCOL nDx,SCsROW nDy,SCsTAB nDz,sal_Bool & rChanged,sal_Bool bSharedFormula)4499 sal_Bool ScCompiler::UpdateNameReference(UpdateRefMode eUpdateRefMode,
4500 const ScRange& r,
4501 SCsCOL nDx, SCsROW nDy, SCsTAB nDz,
4502 sal_Bool& rChanged, sal_Bool bSharedFormula)
4503 {
4504 sal_Bool bRelRef = sal_False; // set if relative reference
4505 rChanged = sal_False;
4506 pArr->Reset();
4507 ScToken* t;
4508 while ( (t = static_cast<ScToken*>(pArr->GetNextReference())) != NULL )
4509 {
4510 SingleDoubleRefModifier aMod( *t );
4511 ScComplexRefData& rRef = aMod.Ref();
4512 bRelRef = rRef.Ref1.IsColRel() || rRef.Ref1.IsRowRel() ||
4513 rRef.Ref1.IsTabRel();
4514 if (!bRelRef && t->GetType() == svDoubleRef)
4515 bRelRef = rRef.Ref2.IsColRel() || rRef.Ref2.IsRowRel() ||
4516 rRef.Ref2.IsTabRel();
4517 bool bUpdate = !rRef.Ref1.IsColRel() || !rRef.Ref1.IsRowRel() ||
4518 !rRef.Ref1.IsTabRel();
4519 if (!bUpdate && t->GetType() == svDoubleRef)
4520 bUpdate = !rRef.Ref2.IsColRel() || !rRef.Ref2.IsRowRel() ||
4521 !rRef.Ref2.IsTabRel();
4522 if (!bSharedFormula)
4523 {
4524 // We cannot update names with sheet-relative references, they may
4525 // be used on other sheets as well and the resulting reference
4526 // would be wrong. This is a dilemma if col/row would need to be
4527 // updated for the current usage.
4528 // TODO: seems the only way out of this would be to not allow
4529 // relative sheet references and have sheet-local names that can be
4530 // copied along with sheets.
4531 bUpdate = bUpdate && !rRef.Ref1.IsTabRel() && !rRef.Ref2.IsTabRel();
4532 }
4533 if (bUpdate)
4534 {
4535 rRef.CalcAbsIfRel( aPos);
4536 if (ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos, r,
4537 nDx, nDy, nDz, rRef, ScRefUpdate::ABSOLUTE)
4538 != UR_NOTHING )
4539 rChanged = sal_True;
4540 }
4541 }
4542 return bRelRef;
4543 }
4544
4545
UpdateSharedFormulaReference(UpdateRefMode eUpdateRefMode,const ScAddress & rOldPos,const ScRange & r,SCsCOL nDx,SCsROW nDy,SCsTAB nDz)4546 void ScCompiler::UpdateSharedFormulaReference( UpdateRefMode eUpdateRefMode,
4547 const ScAddress& rOldPos, const ScRange& r,
4548 SCsCOL nDx, SCsROW nDy, SCsTAB nDz )
4549 {
4550 if ( eUpdateRefMode == URM_COPY )
4551 return ;
4552 else
4553 {
4554 ScToken* t;
4555 pArr->Reset();
4556 while ( (t = static_cast<ScToken*>(pArr->GetNextReference())) != NULL )
4557 {
4558 if( t->GetType() != svIndex ) // it may be a DB area!!!
4559 {
4560 t->CalcAbsIfRel( rOldPos );
4561 // Absolute references have been already adjusted in the named
4562 // shared formula itself prior to breaking the shared formula
4563 // and calling this function. Don't readjust them again.
4564 SingleDoubleRefModifier aMod( *t );
4565 ScComplexRefData& rRef = aMod.Ref();
4566 ScComplexRefData aBkp = rRef;
4567 ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
4568 r, nDx, nDy, nDz, rRef );
4569 // restore absolute parts
4570 if ( !aBkp.Ref1.IsColRel() )
4571 {
4572 rRef.Ref1.nCol = aBkp.Ref1.nCol;
4573 rRef.Ref1.nRelCol = aBkp.Ref1.nRelCol;
4574 rRef.Ref1.SetColDeleted( aBkp.Ref1.IsColDeleted() );
4575 }
4576 if ( !aBkp.Ref1.IsRowRel() )
4577 {
4578 rRef.Ref1.nRow = aBkp.Ref1.nRow;
4579 rRef.Ref1.nRelRow = aBkp.Ref1.nRelRow;
4580 rRef.Ref1.SetRowDeleted( aBkp.Ref1.IsRowDeleted() );
4581 }
4582 if ( !aBkp.Ref1.IsTabRel() )
4583 {
4584 rRef.Ref1.nTab = aBkp.Ref1.nTab;
4585 rRef.Ref1.nRelTab = aBkp.Ref1.nRelTab;
4586 rRef.Ref1.SetTabDeleted( aBkp.Ref1.IsTabDeleted() );
4587 }
4588 if ( t->GetType() == svDoubleRef )
4589 {
4590 if ( !aBkp.Ref2.IsColRel() )
4591 {
4592 rRef.Ref2.nCol = aBkp.Ref2.nCol;
4593 rRef.Ref2.nRelCol = aBkp.Ref2.nRelCol;
4594 rRef.Ref2.SetColDeleted( aBkp.Ref2.IsColDeleted() );
4595 }
4596 if ( !aBkp.Ref2.IsRowRel() )
4597 {
4598 rRef.Ref2.nRow = aBkp.Ref2.nRow;
4599 rRef.Ref2.nRelRow = aBkp.Ref2.nRelRow;
4600 rRef.Ref2.SetRowDeleted( aBkp.Ref2.IsRowDeleted() );
4601 }
4602 if ( !aBkp.Ref2.IsTabRel() )
4603 {
4604 rRef.Ref2.nTab = aBkp.Ref2.nTab;
4605 rRef.Ref2.nRelTab = aBkp.Ref2.nRelTab;
4606 rRef.Ref2.SetTabDeleted( aBkp.Ref2.IsTabDeleted() );
4607 }
4608 }
4609 }
4610 }
4611 }
4612 }
4613
4614
UpdateInsertTab(SCTAB nTable,sal_Bool bIsName)4615 ScRangeData* ScCompiler::UpdateInsertTab( SCTAB nTable, sal_Bool bIsName )
4616 {
4617 ScRangeData* pRangeData = NULL;
4618 SCTAB nPosTab = aPos.Tab(); // _after_ incremented!
4619 SCTAB nOldPosTab = ((nPosTab > nTable) ? (nPosTab - 1) : nPosTab);
4620 sal_Bool bIsRel = sal_False;
4621 ScToken* t;
4622 pArr->Reset();
4623 if (bIsName)
4624 t = static_cast<ScToken*>(pArr->GetNextReference());
4625 else
4626 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
4627 while( t )
4628 {
4629 if( t->GetOpCode() == ocName )
4630 {
4631 if (!bIsName)
4632 {
4633 ScRangeData* pName = pDoc->GetRangeName()->FindIndex(t->GetIndex());
4634 if (pName && pName->HasType(RT_SHAREDMOD))
4635 pRangeData = pName;
4636 }
4637 }
4638 else if( t->GetType() != svIndex ) // it may be a DB area!!!
4639 {
4640 if ( !(bIsName && t->GetSingleRef().IsTabRel()) )
4641 { // of names only adjust absolute references
4642 ScSingleRefData& rRef = t->GetSingleRef();
4643 if ( rRef.IsTabRel() )
4644 {
4645 rRef.nTab = rRef.nRelTab + nOldPosTab;
4646 if ( rRef.nTab < 0 )
4647 rRef.nTab = sal::static_int_cast<SCsTAB>( rRef.nTab + pDoc->GetTableCount() ); // was a wrap
4648 }
4649 if (nTable <= rRef.nTab)
4650 ++rRef.nTab;
4651 rRef.nRelTab = rRef.nTab - nPosTab;
4652 }
4653 else
4654 bIsRel = sal_True;
4655 if ( t->GetType() == svDoubleRef )
4656 {
4657 if ( !(bIsName && t->GetDoubleRef().Ref2.IsTabRel()) )
4658 { // of names only adjust absolute references
4659 ScSingleRefData& rRef = t->GetDoubleRef().Ref2;
4660 if ( rRef.IsTabRel() )
4661 {
4662 rRef.nTab = rRef.nRelTab + nOldPosTab;
4663 if ( rRef.nTab < 0 )
4664 rRef.nTab = sal::static_int_cast<SCsTAB>( rRef.nTab + pDoc->GetTableCount() ); // was a wrap
4665 }
4666 if (nTable <= rRef.nTab)
4667 ++rRef.nTab;
4668 rRef.nRelTab = rRef.nTab - nPosTab;
4669 }
4670 else
4671 bIsRel = sal_True;
4672 }
4673 if ( bIsName && bIsRel )
4674 pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
4675 }
4676 if (bIsName)
4677 t = static_cast<ScToken*>(pArr->GetNextReference());
4678 else
4679 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
4680 }
4681 if ( !bIsName )
4682 {
4683 pArr->Reset();
4684 while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
4685 {
4686 if ( t->GetRef() == 1 )
4687 {
4688 ScSingleRefData& rRef1 = t->GetSingleRef();
4689 if ( !(rRef1.IsRelName() && rRef1.IsTabRel()) )
4690 { // of names only adjust absolute references
4691 if ( rRef1.IsTabRel() )
4692 {
4693 rRef1.nTab = rRef1.nRelTab + nOldPosTab;
4694 if ( rRef1.nTab < 0 )
4695 rRef1.nTab = sal::static_int_cast<SCsTAB>( rRef1.nTab + pDoc->GetTableCount() ); // was a wrap
4696 }
4697 if (nTable <= rRef1.nTab)
4698 ++rRef1.nTab;
4699 rRef1.nRelTab = rRef1.nTab - nPosTab;
4700 }
4701 if ( t->GetType() == svDoubleRef )
4702 {
4703 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4704 if ( !(rRef2.IsRelName() && rRef2.IsTabRel()) )
4705 { // of names only adjust absolute references
4706 if ( rRef2.IsTabRel() )
4707 {
4708 rRef2.nTab = rRef2.nRelTab + nOldPosTab;
4709 if ( rRef2.nTab < 0 )
4710 rRef2.nTab = sal::static_int_cast<SCsTAB>( rRef2.nTab + pDoc->GetTableCount() ); // was a wrap
4711 }
4712 if (nTable <= rRef2.nTab)
4713 ++rRef2.nTab;
4714 rRef2.nRelTab = rRef2.nTab - nPosTab;
4715 }
4716 }
4717 }
4718 }
4719 }
4720 return pRangeData;
4721 }
4722
UpdateDeleteTab(SCTAB nTable,sal_Bool,sal_Bool bIsName,sal_Bool & rChanged)4723 ScRangeData* ScCompiler::UpdateDeleteTab(SCTAB nTable, sal_Bool /* bIsMove */, sal_Bool bIsName,
4724 sal_Bool& rChanged)
4725 {
4726 ScRangeData* pRangeData = NULL;
4727 SCTAB nTab, nTab2;
4728 SCTAB nPosTab = aPos.Tab(); // _after_ decremented!
4729 SCTAB nOldPosTab = ((nPosTab >= nTable) ? (nPosTab + 1) : nPosTab);
4730 rChanged = sal_False;
4731 sal_Bool bIsRel = sal_False;
4732 ScToken* t;
4733 pArr->Reset();
4734 if (bIsName)
4735 t = static_cast<ScToken*>(pArr->GetNextReference());
4736 else
4737 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
4738 while( t )
4739 {
4740 if( t->GetOpCode() == ocName )
4741 {
4742 if (!bIsName)
4743 {
4744 ScRangeData* pName = pDoc->GetRangeName()->FindIndex(t->GetIndex());
4745 if (pName && pName->HasType(RT_SHAREDMOD))
4746 pRangeData = pName;
4747 }
4748 rChanged = sal_True;
4749 }
4750 else if( t->GetType() != svIndex ) // it may be a DB area!!!
4751 {
4752 if ( !(bIsName && t->GetSingleRef().IsTabRel()) )
4753 { // of names only adjust absolute references
4754 ScSingleRefData& rRef = t->GetSingleRef();
4755 if ( rRef.IsTabRel() )
4756 nTab = rRef.nTab = rRef.nRelTab + nOldPosTab;
4757 else
4758 nTab = rRef.nTab;
4759 if ( nTable < nTab )
4760 {
4761 rRef.nTab = nTab - 1;
4762 rChanged = sal_True;
4763 }
4764 else if ( nTable == nTab )
4765 {
4766 if ( t->GetType() == svDoubleRef )
4767 {
4768 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4769 if ( rRef2.IsTabRel() )
4770 nTab2 = rRef2.nRelTab + nOldPosTab;
4771 else
4772 nTab2 = rRef2.nTab;
4773 if ( nTab == nTab2
4774 || (nTab+1) >= pDoc->GetTableCount() )
4775 {
4776 rRef.nTab = MAXTAB+1;
4777 rRef.SetTabDeleted( sal_True );
4778 }
4779 // else: nTab later points to what's nTable+1 now
4780 // => area shrunk
4781 }
4782 else
4783 {
4784 rRef.nTab = MAXTAB+1;
4785 rRef.SetTabDeleted( sal_True );
4786 }
4787 rChanged = sal_True;
4788 }
4789 rRef.nRelTab = rRef.nTab - nPosTab;
4790 }
4791 else
4792 bIsRel = sal_True;
4793 if ( t->GetType() == svDoubleRef )
4794 {
4795 if ( !(bIsName && t->GetDoubleRef().Ref2.IsTabRel()) )
4796 { // of names only adjust absolute references
4797 ScSingleRefData& rRef = t->GetDoubleRef().Ref2;
4798 if ( rRef.IsTabRel() )
4799 nTab = rRef.nTab = rRef.nRelTab + nOldPosTab;
4800 else
4801 nTab = rRef.nTab;
4802 if ( nTable < nTab )
4803 {
4804 rRef.nTab = nTab - 1;
4805 rChanged = sal_True;
4806 }
4807 else if ( nTable == nTab )
4808 {
4809 if ( !t->GetDoubleRef().Ref1.IsTabDeleted() )
4810 rRef.nTab = nTab - 1; // shrink area
4811 else
4812 {
4813 rRef.nTab = MAXTAB+1;
4814 rRef.SetTabDeleted( sal_True );
4815 }
4816 rChanged = sal_True;
4817 }
4818 rRef.nRelTab = rRef.nTab - nPosTab;
4819 }
4820 else
4821 bIsRel = sal_True;
4822 }
4823 if ( bIsName && bIsRel )
4824 pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
4825 }
4826 if (bIsName)
4827 t = static_cast<ScToken*>(pArr->GetNextReference());
4828 else
4829 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
4830 }
4831 if ( !bIsName )
4832 {
4833 pArr->Reset();
4834 while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
4835 {
4836 if ( t->GetRef() == 1 )
4837 {
4838 ScSingleRefData& rRef1 = t->GetSingleRef();
4839 if ( !(rRef1.IsRelName() && rRef1.IsTabRel()) )
4840 { // of names only adjust absolute references
4841 if ( rRef1.IsTabRel() )
4842 nTab = rRef1.nTab = rRef1.nRelTab + nOldPosTab;
4843 else
4844 nTab = rRef1.nTab;
4845 if ( nTable < nTab )
4846 {
4847 rRef1.nTab = nTab - 1;
4848 rChanged = sal_True;
4849 }
4850 else if ( nTable == nTab )
4851 {
4852 if ( t->GetType() == svDoubleRef )
4853 {
4854 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4855 if ( rRef2.IsTabRel() )
4856 nTab2 = rRef2.nRelTab + nOldPosTab;
4857 else
4858 nTab2 = rRef2.nTab;
4859 if ( nTab == nTab2
4860 || (nTab+1) >= pDoc->GetTableCount() )
4861 {
4862 rRef1.nTab = MAXTAB+1;
4863 rRef1.SetTabDeleted( sal_True );
4864 }
4865 // else: nTab later points to what's nTable+1 now
4866 // => area shrunk
4867 }
4868 else
4869 {
4870 rRef1.nTab = MAXTAB+1;
4871 rRef1.SetTabDeleted( sal_True );
4872 }
4873 rChanged = sal_True;
4874 }
4875 rRef1.nRelTab = rRef1.nTab - nPosTab;
4876 }
4877 if ( t->GetType() == svDoubleRef )
4878 {
4879 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4880 if ( !(rRef2.IsRelName() && rRef2.IsTabRel()) )
4881 { // of names only adjust absolute references
4882 if ( rRef2.IsTabRel() )
4883 nTab = rRef2.nTab = rRef2.nRelTab + nOldPosTab;
4884 else
4885 nTab = rRef2.nTab;
4886 if ( nTable < nTab )
4887 {
4888 rRef2.nTab = nTab - 1;
4889 rChanged = sal_True;
4890 }
4891 else if ( nTable == nTab )
4892 {
4893 if ( !rRef1.IsTabDeleted() )
4894 rRef2.nTab = nTab - 1; // shrink area
4895 else
4896 {
4897 rRef2.nTab = MAXTAB+1;
4898 rRef2.SetTabDeleted( sal_True );
4899 }
4900 rChanged = sal_True;
4901 }
4902 rRef2.nRelTab = rRef2.nTab - nPosTab;
4903 }
4904 }
4905 }
4906 }
4907 }
4908 return pRangeData;
4909 }
4910
4911 // aPos.Tab() must be already adjusted!
UpdateMoveTab(SCTAB nOldTab,SCTAB nNewTab,bool bIsName,bool bOnlyUpdateOwnTab)4912 ScRangeData* ScCompiler::UpdateMoveTab( SCTAB nOldTab, SCTAB nNewTab,
4913 bool bIsName, bool bOnlyUpdateOwnTab /*= FALSE*/)
4914 {
4915 ScRangeData* pRangeData = NULL;
4916 SCsTAB nTab;
4917
4918 SCTAB nStart, nEnd;
4919 short nDir; // direction in which others move
4920 if ( nOldTab < nNewTab )
4921 {
4922 nDir = -1;
4923 nStart = nOldTab;
4924 nEnd = nNewTab;
4925 }
4926 else
4927 {
4928 nDir = 1;
4929 nStart = nNewTab;
4930 nEnd = nOldTab;
4931 }
4932 SCTAB nPosTab = aPos.Tab(); // current sheet
4933 SCTAB nOldPosTab; // previously it was this one
4934 if ( nPosTab == nNewTab )
4935 nOldPosTab = nOldTab; // look, it's me!
4936 else if ( nPosTab < nStart || nEnd < nPosTab )
4937 nOldPosTab = nPosTab; // wasn't moved
4938 else
4939 nOldPosTab = nPosTab - nDir; // moved by one
4940
4941 sal_Bool bIsRel = sal_False;
4942 ScToken* t;
4943 pArr->Reset();
4944 if (bIsName)
4945 t = static_cast<ScToken*>(pArr->GetNextReference());
4946 else
4947 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
4948 while( t )
4949 {
4950 if( t->GetOpCode() == ocName )
4951 {
4952 if (!bIsName)
4953 {
4954 ScRangeData* pName = pDoc->GetRangeName()->FindIndex(t->GetIndex());
4955 if (pName && pName->HasType(RT_SHAREDMOD))
4956 pRangeData = pName;
4957 }
4958 }
4959 else if( t->GetType() != svIndex ) // it may be a DB area!!!
4960 {
4961 ScSingleRefData& rRef1 = t->GetSingleRef();
4962 if ( !(bIsName && rRef1.IsTabRel()) )
4963 { // of names only adjust absolute references
4964 if ( rRef1.IsTabRel() )
4965 nTab = rRef1.nRelTab + nOldPosTab;
4966 else
4967 nTab = rRef1.nTab;
4968 if ( nTab == nOldTab )
4969 rRef1.nTab = nNewTab;
4970 else if ( nStart <= nTab && nTab <= nEnd && !bOnlyUpdateOwnTab)
4971 rRef1.nTab = nTab + nDir;
4972 rRef1.nRelTab = rRef1.nTab - nPosTab;
4973 }
4974 else
4975 bIsRel = sal_True;
4976 if ( t->GetType() == svDoubleRef )
4977 {
4978 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
4979 if ( !(bIsName && rRef2.IsTabRel()) )
4980 { // of names only adjust absolute references
4981 if ( rRef2.IsTabRel() )
4982 nTab = rRef2.nRelTab + nOldPosTab;
4983 else
4984 nTab = rRef2.nTab;
4985 if ( nTab == nOldTab )
4986 rRef2.nTab = nNewTab;
4987 else if ( nStart <= nTab && nTab <= nEnd && !bOnlyUpdateOwnTab)
4988 rRef2.nTab = nTab + nDir;
4989 rRef2.nRelTab = rRef2.nTab - nPosTab;
4990 }
4991 else
4992 bIsRel = sal_True;
4993 SCsTAB nTab1, nTab2;
4994 if ( rRef1.IsTabRel() )
4995 nTab1 = rRef1.nRelTab + nPosTab;
4996 else
4997 nTab1 = rRef1.nTab;
4998 if ( rRef2.IsTabRel() )
4999 nTab2 = rRef2.nRelTab + nPosTab;
5000 else
5001 nTab2 = rRef1.nTab;
5002 if ( nTab2 < nTab1 )
5003 { // PutInOrder
5004 rRef1.nTab = nTab2;
5005 rRef2.nTab = nTab1;
5006 rRef1.nRelTab = rRef1.nTab - nPosTab;
5007 rRef2.nRelTab = rRef2.nTab - nPosTab;
5008 }
5009 }
5010 if ( bIsName && bIsRel )
5011 pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
5012 }
5013 if (bIsName)
5014 t = static_cast<ScToken*>(pArr->GetNextReference());
5015 else
5016 t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
5017 }
5018 if ( !bIsName )
5019 {
5020 SCsTAB nMaxTabMod = (SCsTAB) pDoc->GetTableCount();
5021 pArr->Reset();
5022 while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
5023 {
5024 if ( t->GetRef() == 1 )
5025 {
5026 ScSingleRefData& rRef1 = t->GetSingleRef();
5027 if ( rRef1.IsRelName() && rRef1.IsTabRel() )
5028 { // possibly wrap RelName, like lcl_MoveItWrap in refupdat.cxx
5029 nTab = rRef1.nRelTab + nPosTab;
5030 if ( nTab < 0 )
5031 nTab = sal::static_int_cast<SCsTAB>( nTab + nMaxTabMod );
5032 else if ( nTab > nMaxTab )
5033 nTab = sal::static_int_cast<SCsTAB>( nTab - nMaxTabMod );
5034 rRef1.nRelTab = nTab - nPosTab;
5035 }
5036 else
5037 {
5038 if ( rRef1.IsTabRel() )
5039 nTab = rRef1.nRelTab + nOldPosTab;
5040 else
5041 nTab = rRef1.nTab;
5042 if ( nTab == nOldTab )
5043 rRef1.nTab = nNewTab;
5044 else if ( nStart <= nTab && nTab <= nEnd )
5045 rRef1.nTab = nTab + nDir;
5046 rRef1.nRelTab = rRef1.nTab - nPosTab;
5047 }
5048 if( t->GetType() == svDoubleRef )
5049 {
5050 ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
5051 if ( rRef2.IsRelName() && rRef2.IsTabRel() )
5052 { // possibly wrap RelName, like lcl_MoveItWrap in refupdat.cxx
5053 nTab = rRef2.nRelTab + nPosTab;
5054 if ( nTab < 0 )
5055 nTab = sal::static_int_cast<SCsTAB>( nTab + nMaxTabMod );
5056 else if ( nTab > nMaxTab )
5057 nTab = sal::static_int_cast<SCsTAB>( nTab - nMaxTabMod );
5058 rRef2.nRelTab = nTab - nPosTab;
5059 }
5060 else
5061 {
5062 if ( rRef2.IsTabRel() )
5063 nTab = rRef2.nRelTab + nOldPosTab;
5064 else
5065 nTab = rRef2.nTab;
5066 if ( nTab == nOldTab )
5067 rRef2.nTab = nNewTab;
5068 else if ( nStart <= nTab && nTab <= nEnd )
5069 rRef2.nTab = nTab + nDir;
5070 rRef2.nRelTab = rRef2.nTab - nPosTab;
5071 }
5072 SCsTAB nTab1, nTab2;
5073 if ( rRef1.IsTabRel() )
5074 nTab1 = rRef1.nRelTab + nPosTab;
5075 else
5076 nTab1 = rRef1.nTab;
5077 if ( rRef2.IsTabRel() )
5078 nTab2 = rRef2.nRelTab + nPosTab;
5079 else
5080 nTab2 = rRef1.nTab;
5081 if ( nTab2 < nTab1 )
5082 { // PutInOrder
5083 rRef1.nTab = nTab2;
5084 rRef2.nTab = nTab1;
5085 rRef1.nRelTab = rRef1.nTab - nPosTab;
5086 rRef2.nRelTab = rRef2.nTab - nPosTab;
5087 }
5088 }
5089 }
5090 }
5091 }
5092 return pRangeData;
5093 }
5094
5095
CreateStringFromExternal(rtl::OUStringBuffer & rBuffer,FormulaToken * pTokenP)5096 void ScCompiler::CreateStringFromExternal(rtl::OUStringBuffer& rBuffer, FormulaToken* pTokenP)
5097 {
5098 FormulaToken* t = pTokenP;
5099 ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
5100 switch (t->GetType())
5101 {
5102 case svExternalName:
5103 {
5104 const String *pStr = pRefMgr->getExternalFileName(t->GetIndex());
5105 String aFileName = pStr ? *pStr : ScGlobal::GetRscString(STR_NO_NAME_REF);
5106 rBuffer.append(pConv->makeExternalNameStr( aFileName, t->GetString()));
5107 }
5108 break;
5109 case svExternalSingleRef:
5110 pConv->makeExternalRefStr(
5111 rBuffer, *this, t->GetIndex(), t->GetString(), static_cast<ScToken*>(t)->GetSingleRef(), pRefMgr);
5112 break;
5113 case svExternalDoubleRef:
5114 pConv->makeExternalRefStr(
5115 rBuffer, *this, t->GetIndex(), t->GetString(), static_cast<ScToken*>(t)->GetDoubleRef(), pRefMgr);
5116 break;
5117 default:
5118 // warning, not error, otherwise we may end up with a never
5119 // ending message box loop if this was the cursor cell to be redrawn.
5120 DBG_WARNING("ScCompiler::CreateStringFromToken: unknown type of ocExternalRef");
5121 }
5122 }
5123
CreateStringFromMatrix(rtl::OUStringBuffer & rBuffer,FormulaToken * pTokenP)5124 void ScCompiler::CreateStringFromMatrix( rtl::OUStringBuffer& rBuffer,
5125 FormulaToken* pTokenP)
5126 {
5127 const ScMatrix* pMatrix = static_cast<ScToken*>(pTokenP)->GetMatrix();
5128 SCSIZE nC, nMaxC, nR, nMaxR;
5129
5130 pMatrix->GetDimensions( nMaxC, nMaxR);
5131
5132 rBuffer.append( mxSymbols->getSymbol(ocArrayOpen) );
5133 for( nR = 0 ; nR < nMaxR ; nR++)
5134 {
5135 if( nR > 0)
5136 {
5137 rBuffer.append( mxSymbols->getSymbol(ocArrayRowSep) );
5138 }
5139
5140 for( nC = 0 ; nC < nMaxC ; nC++)
5141 {
5142 if( nC > 0)
5143 {
5144 rBuffer.append( mxSymbols->getSymbol(ocArrayColSep) );
5145 }
5146
5147 if( pMatrix->IsValue( nC, nR ) )
5148 {
5149 ScMatValType nType;
5150 const ScMatrixValue* pVal = pMatrix->Get( nC, nR, nType);
5151
5152 if( nType == SC_MATVAL_BOOLEAN )
5153 AppendBoolean( rBuffer, pVal->GetBoolean() );
5154 else
5155 {
5156 sal_uInt16 nErr = pVal->GetError();
5157 if( nErr )
5158 rBuffer.append( ScGlobal::GetErrorString( nErr ) );
5159 else
5160 AppendDouble( rBuffer, pVal->fVal );
5161 }
5162 }
5163 else if( pMatrix->IsEmpty( nC, nR ) )
5164 ;
5165 else if( pMatrix->IsString( nC, nR ) )
5166 AppendString( rBuffer, pMatrix->GetString( nC, nR ) );
5167 }
5168 }
5169 rBuffer.append( mxSymbols->getSymbol(ocArrayClose) );
5170 }
5171
CreateStringFromSingleRef(rtl::OUStringBuffer & rBuffer,FormulaToken * _pTokenP)5172 void ScCompiler::CreateStringFromSingleRef(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
5173 {
5174 const OpCode eOp = _pTokenP->GetOpCode();
5175 ScSingleRefData& rRef = static_cast<ScToken*>(_pTokenP)->GetSingleRef();
5176 ScComplexRefData aRef;
5177 aRef.Ref1 = aRef.Ref2 = rRef;
5178 if ( eOp == ocColRowName )
5179 {
5180 rRef.CalcAbsIfRel( aPos );
5181 if ( pDoc->HasStringData( rRef.nCol, rRef.nRow, rRef.nTab ) )
5182 {
5183 String aStr;
5184 pDoc->GetString( rRef.nCol, rRef.nRow, rRef.nTab, aStr );
5185 EnQuote( aStr );
5186 rBuffer.append(aStr);
5187 }
5188 else
5189 {
5190 rBuffer.append(ScGlobal::GetRscString(STR_NO_NAME_REF));
5191 pConv->MakeRefStr (rBuffer, *this, aRef, sal_True );
5192 }
5193 }
5194 else
5195 pConv->MakeRefStr( rBuffer, *this, aRef, sal_True );
5196 }
5197 // -----------------------------------------------------------------------------
CreateStringFromDoubleRef(rtl::OUStringBuffer & rBuffer,FormulaToken * _pTokenP)5198 void ScCompiler::CreateStringFromDoubleRef(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
5199 {
5200 pConv->MakeRefStr( rBuffer, *this, static_cast<ScToken*>(_pTokenP)->GetDoubleRef(), sal_False );
5201 }
5202 // -----------------------------------------------------------------------------
CreateStringFromIndex(rtl::OUStringBuffer & rBuffer,FormulaToken * _pTokenP)5203 void ScCompiler::CreateStringFromIndex(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
5204 {
5205 const OpCode eOp = _pTokenP->GetOpCode();
5206 rtl::OUStringBuffer aBuffer;
5207 switch ( eOp )
5208 {
5209 case ocName:
5210 {
5211 ScRangeData* pData = pDoc->GetRangeName()->FindIndex(_pTokenP->GetIndex());
5212 if (pData)
5213 {
5214 if (pData->HasType(RT_SHARED))
5215 pData->UpdateSymbol( aBuffer, aPos, GetGrammar());
5216 else
5217 aBuffer.append(pData->GetName());
5218 }
5219 }
5220 break;
5221 case ocDBArea:
5222 {
5223 ScDBData* pDBData = pDoc->GetDBCollection()->FindIndex(_pTokenP->GetIndex());
5224 if (pDBData)
5225 aBuffer.append(pDBData->GetName());
5226 }
5227 break;
5228 default:
5229 ; // nothing
5230 }
5231 if ( aBuffer.getLength() )
5232 rBuffer.append(aBuffer);
5233 else
5234 rBuffer.append(ScGlobal::GetRscString(STR_NO_NAME_REF));
5235 }
5236 // -----------------------------------------------------------------------------
LocalizeString(String & rName)5237 void ScCompiler::LocalizeString( String& rName )
5238 {
5239 ScGlobal::GetAddInCollection()->LocalizeString( rName );
5240 }
5241 // -----------------------------------------------------------------------------
IsImportingXML() const5242 sal_Bool ScCompiler::IsImportingXML() const
5243 {
5244 return pDoc->IsImportingXML();
5245 }
5246
5247 // Put quotes around string if non-alphanumeric characters are contained,
5248 // quote characters contained within are escaped by '\\'.
EnQuote(String & rStr)5249 sal_Bool ScCompiler::EnQuote( String& rStr )
5250 {
5251 sal_Int32 nType = ScGlobal::pCharClass->getStringType( rStr, 0, rStr.Len() );
5252 if ( !CharClass::isNumericType( nType )
5253 && CharClass::isAlphaNumericType( nType ) )
5254 return sal_False;
5255
5256 xub_StrLen nPos = 0;
5257 while ( (nPos = rStr.Search( '\'', nPos)) != STRING_NOTFOUND )
5258 {
5259 rStr.Insert( '\\', nPos );
5260 nPos += 2;
5261 }
5262 rStr.Insert( '\'', 0 );
5263 rStr += '\'';
5264 return sal_True;
5265 }
5266
GetNativeAddressSymbol(Convention::SpecialSymbolType eType) const5267 sal_Unicode ScCompiler::GetNativeAddressSymbol( Convention::SpecialSymbolType eType ) const
5268 {
5269 return pConv->getSpecialSymbol(eType);
5270 }
5271
fillAddInToken(::std::vector<::com::sun::star::sheet::FormulaOpCodeMapEntry> & _rVec,bool _bIsEnglish) const5272 void ScCompiler::fillAddInToken(::std::vector< ::com::sun::star::sheet::FormulaOpCodeMapEntry >& _rVec,bool _bIsEnglish) const
5273 {
5274 // All known AddIn functions.
5275 sheet::FormulaOpCodeMapEntry aEntry;
5276 aEntry.Token.OpCode = ocExternal;
5277
5278 ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
5279 const long nCount = pColl->GetFuncCount();
5280 for (long i=0; i < nCount; ++i)
5281 {
5282 const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
5283 if (pFuncData)
5284 {
5285 if ( _bIsEnglish )
5286 {
5287 String aName;
5288 if (pFuncData->GetExcelName( LANGUAGE_ENGLISH_US, aName))
5289 aEntry.Name = aName;
5290 else
5291 aEntry.Name = pFuncData->GetUpperName();
5292 }
5293 else
5294 aEntry.Name = pFuncData->GetUpperLocal();
5295 aEntry.Token.Data <<= ::rtl::OUString( pFuncData->GetOriginalName());
5296 _rVec.push_back( aEntry);
5297 }
5298 }
5299 // FIXME: what about those old non-UNO AddIns?
5300 }
5301 // -----------------------------------------------------------------------------
HandleSingleRef()5302 sal_Bool ScCompiler::HandleSingleRef()
5303 {
5304 ScSingleRefData& rRef = static_cast<ScToken*>((FormulaToken*)pToken)->GetSingleRef();
5305 rRef.CalcAbsIfRel( aPos );
5306 if ( !rRef.Valid() )
5307 {
5308 SetError( errNoRef );
5309 return sal_True;
5310 }
5311 SCCOL nCol = rRef.nCol;
5312 SCROW nRow = rRef.nRow;
5313 SCTAB nTab = rRef.nTab;
5314 ScAddress aLook( nCol, nRow, nTab );
5315 sal_Bool bColName = rRef.IsColRel();
5316 SCCOL nMyCol = aPos.Col();
5317 SCROW nMyRow = aPos.Row();
5318 sal_Bool bInList = sal_False;
5319 sal_Bool bValidName = sal_False;
5320 ScRangePairList* pRL = (bColName ?
5321 pDoc->GetColNameRanges() : pDoc->GetRowNameRanges());
5322 ScRange aRange;
5323 for ( ScRangePair* pR = pRL->First(); pR; pR = pRL->Next() )
5324 {
5325 if ( pR->GetRange(0).In( aLook ) )
5326 {
5327 bInList = bValidName = sal_True;
5328 aRange = pR->GetRange(1);
5329 if ( bColName )
5330 {
5331 aRange.aStart.SetCol( nCol );
5332 aRange.aEnd.SetCol( nCol );
5333 }
5334 else
5335 {
5336 aRange.aStart.SetRow( nRow );
5337 aRange.aEnd.SetRow( nRow );
5338 }
5339 break; // for
5340 }
5341 }
5342 if ( !bInList && pDoc->GetDocOptions().IsLookUpColRowNames() )
5343 { // automagically or created by copying and NamePos isn't in list
5344 sal_Bool bString = pDoc->HasStringData( nCol, nRow, nTab );
5345 if ( !bString && !pDoc->GetCell( aLook ) )
5346 bString = sal_True; // empty cell is ok
5347 if ( bString )
5348 { //! corresponds with ScInterpreter::ScColRowNameAuto()
5349 bValidName = sal_True;
5350 if ( bColName )
5351 { // ColName
5352 SCROW nStartRow = nRow + 1;
5353 if ( nStartRow > MAXROW )
5354 nStartRow = MAXROW;
5355 SCROW nMaxRow = MAXROW;
5356 if ( nMyCol == nCol )
5357 { // formula cell in same column
5358 if ( nMyRow == nStartRow )
5359 { // take remainder under name cell
5360 nStartRow++;
5361 if ( nStartRow > MAXROW )
5362 nStartRow = MAXROW;
5363 }
5364 else if ( nMyRow > nStartRow )
5365 { // from name cell down to formula cell
5366 nMaxRow = nMyRow - 1;
5367 }
5368 }
5369 for ( ScRangePair* pR = pRL->First(); pR; pR = pRL->Next() )
5370 { // next defined ColNameRange below limits row
5371 const ScRange& rRange = pR->GetRange(1);
5372 if ( rRange.aStart.Col() <= nCol && nCol <= rRange.aEnd.Col() )
5373 { // identical column range
5374 SCROW nTmp = rRange.aStart.Row();
5375 if ( nStartRow < nTmp && nTmp <= nMaxRow )
5376 nMaxRow = nTmp - 1;
5377 }
5378 }
5379 aRange.aStart.Set( nCol, nStartRow, nTab );
5380 aRange.aEnd.Set( nCol, nMaxRow, nTab );
5381 }
5382 else
5383 { // RowName
5384 SCCOL nStartCol = nCol + 1;
5385 if ( nStartCol > MAXCOL )
5386 nStartCol = MAXCOL;
5387 SCCOL nMaxCol = MAXCOL;
5388 if ( nMyRow == nRow )
5389 { // formula cell in same row
5390 if ( nMyCol == nStartCol )
5391 { // take remainder right from name cell
5392 nStartCol++;
5393 if ( nStartCol > MAXCOL )
5394 nStartCol = MAXCOL;
5395 }
5396 else if ( nMyCol > nStartCol )
5397 { // from name cell right to formula cell
5398 nMaxCol = nMyCol - 1;
5399 }
5400 }
5401 for ( ScRangePair* pR = pRL->First(); pR; pR = pRL->Next() )
5402 { // next defined RowNameRange to the right limits column
5403 const ScRange& rRange = pR->GetRange(1);
5404 if ( rRange.aStart.Row() <= nRow && nRow <= rRange.aEnd.Row() )
5405 { // identical row range
5406 SCCOL nTmp = rRange.aStart.Col();
5407 if ( nStartCol < nTmp && nTmp <= nMaxCol )
5408 nMaxCol = nTmp - 1;
5409 }
5410 }
5411 aRange.aStart.Set( nStartCol, nRow, nTab );
5412 aRange.aEnd.Set( nMaxCol, nRow, nTab );
5413 }
5414 }
5415 }
5416 if ( bValidName )
5417 {
5418 // And now the magic to distinguish between a range and a single
5419 // cell thereof, which is picked position-dependent of the formula
5420 // cell. If a direct neighbor is a binary operator (ocAdd, ...) a
5421 // SingleRef matching the column/row of the formula cell is
5422 // generated. A ocColRowName or ocIntersect as a neighbor results
5423 // in a range. Special case: if label is valid for a single cell, a
5424 // position independent SingleRef is generated.
5425 sal_Bool bSingle = (aRange.aStart == aRange.aEnd);
5426 sal_Bool bFound;
5427 if ( bSingle )
5428 bFound = sal_True;
5429 else
5430 {
5431 FormulaToken* p1 = pArr->PeekPrevNoSpaces();
5432 FormulaToken* p2 = pArr->PeekNextNoSpaces();
5433 // begin/end of a formula => single
5434 OpCode eOp1 = p1 ? p1->GetOpCode() : static_cast<OpCode>( ocAdd );
5435 OpCode eOp2 = p2 ? p2->GetOpCode() : static_cast<OpCode>( ocAdd );
5436 if ( eOp1 != ocColRowName && eOp1 != ocIntersect
5437 && eOp2 != ocColRowName && eOp2 != ocIntersect )
5438 {
5439 if ( (SC_OPCODE_START_BIN_OP <= eOp1 && eOp1 < SC_OPCODE_STOP_BIN_OP) ||
5440 (SC_OPCODE_START_BIN_OP <= eOp2 && eOp2 < SC_OPCODE_STOP_BIN_OP))
5441 bSingle = sal_True;
5442 }
5443 if ( bSingle )
5444 { // column and/or row must match range
5445 if ( bColName )
5446 {
5447 bFound = (aRange.aStart.Row() <= nMyRow
5448 && nMyRow <= aRange.aEnd.Row());
5449 if ( bFound )
5450 aRange.aStart.SetRow( nMyRow );
5451 }
5452 else
5453 {
5454 bFound = (aRange.aStart.Col() <= nMyCol
5455 && nMyCol <= aRange.aEnd.Col());
5456 if ( bFound )
5457 aRange.aStart.SetCol( nMyCol );
5458 }
5459 }
5460 else
5461 bFound = sal_True;
5462 }
5463 if ( !bFound )
5464 SetError(errNoRef);
5465 else if ( !bCompileForFAP )
5466 {
5467 ScTokenArray* pNew = new ScTokenArray();
5468 if ( bSingle )
5469 {
5470 ScSingleRefData aRefData;
5471 aRefData.InitAddress( aRange.aStart );
5472 if ( bColName )
5473 aRefData.SetColRel( sal_True );
5474 else
5475 aRefData.SetRowRel( sal_True );
5476 aRefData.CalcRelFromAbs( aPos );
5477 pNew->AddSingleReference( aRefData );
5478 }
5479 else
5480 {
5481 ScComplexRefData aRefData;
5482 aRefData.InitRange( aRange );
5483 if ( bColName )
5484 {
5485 aRefData.Ref1.SetColRel( sal_True );
5486 aRefData.Ref2.SetColRel( sal_True );
5487 }
5488 else
5489 {
5490 aRefData.Ref1.SetRowRel( sal_True );
5491 aRefData.Ref2.SetRowRel( sal_True );
5492 }
5493 aRefData.CalcRelFromAbs( aPos );
5494 if ( bInList )
5495 pNew->AddDoubleReference( aRefData );
5496 else
5497 { // automagically
5498 pNew->Add( new ScDoubleRefToken( aRefData, ocColRowNameAuto ) );
5499 }
5500 }
5501 PushTokenArray( pNew, sal_True );
5502 pNew->Reset();
5503 return GetToken();
5504 }
5505 }
5506 else
5507 SetError(errNoName);
5508 return sal_True;
5509 }
5510 // -----------------------------------------------------------------------------
HandleDbData()5511 sal_Bool ScCompiler::HandleDbData()
5512 {
5513 ScDBData* pDBData = pDoc->GetDBCollection()->FindIndex( pToken->GetIndex() );
5514 if ( !pDBData )
5515 SetError(errNoName);
5516 else if ( !bCompileForFAP )
5517 {
5518 ScComplexRefData aRefData;
5519 aRefData.InitFlags();
5520 pDBData->GetArea( (SCTAB&) aRefData.Ref1.nTab,
5521 (SCCOL&) aRefData.Ref1.nCol,
5522 (SCROW&) aRefData.Ref1.nRow,
5523 (SCCOL&) aRefData.Ref2.nCol,
5524 (SCROW&) aRefData.Ref2.nRow);
5525 aRefData.Ref2.nTab = aRefData.Ref1.nTab;
5526 aRefData.CalcRelFromAbs( aPos );
5527 ScTokenArray* pNew = new ScTokenArray();
5528 pNew->AddDoubleReference( aRefData );
5529 PushTokenArray( pNew, sal_True );
5530 pNew->Reset();
5531 return GetToken();
5532 }
5533 return sal_True;
5534 }
5535
GetScCompilerNativeSymbol(OpCode eOp)5536 String GetScCompilerNativeSymbol( OpCode eOp )
5537 {
5538 return ScCompiler::GetNativeSymbol( eOp );
5539 }
5540 // -----------------------------------------------------------------------------
ExtendRangeReference(FormulaToken & rTok1,FormulaToken & rTok2,bool bReuseDoubleRef)5541 FormulaTokenRef ScCompiler::ExtendRangeReference( FormulaToken & rTok1, FormulaToken & rTok2, bool bReuseDoubleRef )
5542 {
5543 return ScToken::ExtendRangeReference( rTok1, rTok2, aPos,bReuseDoubleRef );
5544 }
5545