summaryrefslogtreecommitdiff
path: root/sc/source/core/tool/formulalogger.cxx
blob: af6c873a1ae7faa0bd2814fdfda36d329c77d89f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <formulalogger.hxx>
#include <formulacell.hxx>
#include <tokenarray.hxx>
#include <document.hxx>
#include <tokenstringcontext.hxx>
#include <address.hxx>
#include <interpre.hxx>

#include <osl/file.hxx>
#include <o3tl/make_unique.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfile.hxx>
#include <tools/urlobj.hxx>
#include <formula/vectortoken.hxx>
#include <rtl/ustrbuf.hxx>

#include <cstdlib>

namespace sc {

namespace {

std::unique_ptr<osl::File> initFile()
{
    const char* pPath = std::getenv("LIBO_FORMULA_LOG_FILE");
    if (!pPath)
        return nullptr;

    // Support both file:///... and system file path notations.
    OUString aPath = OUString::createFromAscii(pPath);
    INetURLObject aURL;
    aURL.SetSmartURL(aPath);
    aPath = aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE);

    return o3tl::make_unique<osl::File>(aPath);
}

ScRefFlags getRefFlags( const ScAddress& rCellPos, const ScAddress& rRefPos )
{
    ScRefFlags eFlags = ScRefFlags::VALID;
    if (rCellPos.Tab() != rRefPos.Tab())
        eFlags |= ScRefFlags::TAB_3D;
    return eFlags;
}

}

FormulaLogger& FormulaLogger::get()
{
    static FormulaLogger aLogger;
    return aLogger;
}

struct FormulaLogger::GroupScope::Impl
{
    FormulaLogger& mrLogger;
    const ScDocument& mrDoc;

    OUString const maPrefix;
    std::vector<OUString> maMessages;

    bool mbCalcComplete;
    bool const mbOutputEnabled;

    Impl( FormulaLogger& rLogger, const OUString& rPrefix, const ScDocument& rDoc,
        const ScFormulaCell& rCell, bool bOutputEnabled ) :
        mrLogger(rLogger), mrDoc(rDoc), maPrefix(rPrefix),
        mbCalcComplete(false), mbOutputEnabled(bOutputEnabled)
    {
        ++mrLogger.mnNestLevel;

        if (mbOutputEnabled)
        {
            sc::TokenStringContext aCxt(&rDoc, rDoc.GetGrammar());
            OUString aFormula = rCell.GetCode()->CreateString(aCxt, rCell.aPos);

            mrLogger.write(maPrefix);
            mrLogger.writeNestLevel();

            mrLogger.writeAscii("-- enter (formula='");
            mrLogger.write(aFormula);
            mrLogger.writeAscii("', size=");
            mrLogger.write(rCell.GetSharedLength());
            mrLogger.writeAscii(")\n");
        }
    }

    ~Impl()
    {
        if (mbOutputEnabled)
        {
            for (const OUString& rMsg : maMessages)
            {
                mrLogger.write(maPrefix);
                mrLogger.writeNestLevel();
                mrLogger.writeAscii("   * ");
                mrLogger.write(rMsg);
                mrLogger.writeAscii("\n");
            }

            mrLogger.write(maPrefix);
            mrLogger.writeNestLevel();
            mrLogger.writeAscii("-- exit (");
            if (mbCalcComplete)
                mrLogger.writeAscii("calculation complete");
            else
                mrLogger.writeAscii("without calculation");

            mrLogger.writeAscii(")\n");

            mrLogger.sync();
        }

        --mrLogger.mnNestLevel;
    }
};

FormulaLogger::GroupScope::GroupScope(
    FormulaLogger& rLogger, const OUString& rPrefix, const ScDocument& rDoc,
    const ScFormulaCell& rCell, bool bOutputEnabled ) :
    mpImpl(o3tl::make_unique<Impl>(rLogger, rPrefix, rDoc, rCell, bOutputEnabled)) {}

FormulaLogger::GroupScope::GroupScope( GroupScope&& r ) : mpImpl(std::move(r.mpImpl)) {}

FormulaLogger::GroupScope::~GroupScope() {}

void FormulaLogger::GroupScope::addMessage( const OUString& rMsg )
{
    mpImpl->maMessages.push_back(rMsg);
}

void FormulaLogger::GroupScope::addRefMessage(
    const ScAddress& rCellPos, const ScAddress& rRefPos, size_t nLen,
    const formula::VectorRefArray& rArray )
{
    OUStringBuffer aBuf;

    ScRange aRefRange(rRefPos);
    aRefRange.aEnd.IncRow(nLen-1);
    OUString aRangeStr = aRefRange.Format(getRefFlags(rCellPos, rRefPos), &mpImpl->mrDoc);
    aBuf.append(aRangeStr);
    aBuf.append(": ");

    if (rArray.mpNumericArray)
    {
        if (rArray.mpStringArray)
        {
            // mixture of numeric and string cells.
            aBuf.append("numeric and string");
        }
        else
        {
            // numeric cells only.
            aBuf.append("numeric only");
        }
    }
    else
    {
        if (rArray.mpStringArray)
        {
            // string cells only.
            aBuf.append("string only");
        }
        else
        {
            // empty cells.
            aBuf.append("empty");
        }
    }

    mpImpl->maMessages.push_back(aBuf.makeStringAndClear());
}

void FormulaLogger::GroupScope::addRefMessage(
    const ScAddress& rCellPos, const ScAddress& rRefPos, size_t nLen,
    const std::vector<formula::VectorRefArray>& rArrays )
{
    ScAddress aPos(rRefPos); // copy
    for (const formula::VectorRefArray& rArray : rArrays)
    {
        addRefMessage(rCellPos, aPos, nLen, rArray);
        aPos.IncCol();
    }
}

void FormulaLogger::GroupScope::addRefMessage(
    const ScAddress& rCellPos, const ScAddress& rRefPos,
    const formula::FormulaToken& rToken )
{
    OUStringBuffer aBuf;
    OUString aPosStr = rRefPos.Format(getRefFlags(rCellPos, rRefPos), &mpImpl->mrDoc);
    aBuf.append(aPosStr);
    aBuf.append(": ");

    switch (rToken.GetType())
    {
        case formula::svDouble:
            aBuf.append("numeric value");
            break;
        case formula::svString:
            aBuf.append("string value");
            break;
        default:
            aBuf.append("unknown value");
    }

    mpImpl->maMessages.push_back(aBuf.makeStringAndClear());
}

void FormulaLogger::GroupScope::addGroupSizeThresholdMessage( const ScFormulaCell& rCell )
{
    OUStringBuffer aBuf;
    aBuf.append("group length below minimum threshold (");
    aBuf.append(rCell.GetWeight());
    aBuf.append(" < ");
    aBuf.append(ScInterpreter::GetGlobalConfig().mnOpenCLMinimumFormulaGroupSize);
    aBuf.append(")");
    mpImpl->maMessages.push_back(aBuf.makeStringAndClear());
}

void FormulaLogger::GroupScope::setCalcComplete()
{
    mpImpl->mbCalcComplete = true;
    addMessage("calculation performed");
}

FormulaLogger::FormulaLogger()
{
    mpLogFile = initFile();

    if (!mpLogFile)
        return;

    osl::FileBase::RC eRC = mpLogFile->open(osl_File_OpenFlag_Write | osl_File_OpenFlag_Create);

    if (eRC == osl::FileBase::E_EXIST)
    {
        eRC = mpLogFile->open(osl_File_OpenFlag_Write);

        if (eRC != osl::FileBase::E_None)
        {
            // Failed to open an existing log file.
            mpLogFile.reset();
            return;
        }

        if (mpLogFile->setPos(osl_Pos_End, 0) != osl::FileBase::E_None)
        {
            // Failed to set the position to the end of the file.
            mpLogFile.reset();
            return;
        }
    }
    else if (eRC != osl::FileBase::E_None)
    {
        // Failed to create a new file.
        mpLogFile.reset();
        return;
    }

    // Output the header information.
    writeAscii("---\n");
    writeAscii("OpenCL: ");
    writeAscii(ScCalcConfig::isOpenCLEnabled() ? "enabled\n" : "disabled\n");
    writeAscii("---\n");

    sync();
}

FormulaLogger::~FormulaLogger()
{
    if (mpLogFile)
        mpLogFile->close();
}

void FormulaLogger::writeAscii( const char* s )
{
    if (!mpLogFile)
        return;

    sal_uInt64 nBytes;
    mpLogFile->write(s, strlen(s), nBytes);
}

void FormulaLogger::writeAscii( const char* s, size_t n )
{
    if (!mpLogFile)
        return;

    sal_uInt64 nBytes;
    mpLogFile->write(s, n, nBytes);
}

void FormulaLogger::write( const OUString& ou )
{
    OString s = rtl::OUStringToOString(ou, RTL_TEXTENCODING_UTF8).getStr();
    writeAscii(s.getStr(), s.getLength());
}

void FormulaLogger::write( sal_Int32 n )
{
    OString s = OString::number(n);
    writeAscii(s.getStr(), s.getLength());
}

void FormulaLogger::sync()
{
    if (!mpLogFile)
        return;

    mpLogFile->sync();
}

void FormulaLogger::writeNestLevel()
{
    // Write the nest level, but keep it only 1-character length to avoid
    // messing up the spacing.
    if (mnNestLevel < 10)
        write(mnNestLevel);
    else
        writeAscii("!");

    writeAscii(": ");
    for (sal_Int32 i = 1; i < mnNestLevel; ++i)
        writeAscii("   ");
}

FormulaLogger::GroupScope FormulaLogger::enterGroup(
    const ScDocument& rDoc, const ScFormulaCell& rCell )
{
    // Get the file name if available.
    const SfxObjectShell* pShell = rDoc.GetDocumentShell();
    const SfxMedium* pMedium = pShell ? pShell->GetMedium() : nullptr;
    OUString aName;
    if (pMedium)
        aName = pMedium->GetURLObject().GetLastName();
    if (aName.isEmpty())
        aName = "-"; // unsaved document.

    OUString aGroupPrefix = aName;

    aGroupPrefix += ": formula-group: ";
    aGroupPrefix += rCell.aPos.Format(ScRefFlags::VALID | ScRefFlags::TAB_3D, &rDoc, rDoc.GetAddressConvention());
    aGroupPrefix += ": ";

    bool bOutputEnabled = mpLastGroup != rCell.GetCellGroup().get();
    mpLastGroup = rCell.GetCellGroup().get();

    return GroupScope(*this, aGroupPrefix, rDoc, rCell, bOutputEnabled);
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */