summaryrefslogtreecommitdiffstats
path: root/kformula/fsparser.cc
blob: 3d425a169fbbb191bbe874a6305ebe0c250fed0a (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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/* This file is part of the KDE project
   Copyright (C) 2002 Ulrich Kuettler <[email protected]>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include <tqptrlist.h>

#include <kdebug.h>
#include <klocale.h>

#include <kformuladefs.h>
#include <kformuladocument.h>
#include <symboltable.h>

#include "fsparser.h"


using namespace std;

class ParserNode {
public:
    ParserNode() { debugCount++; }
    virtual ~ParserNode() { debugCount--; }
    //virtual void output( ostream& ) = 0;
    virtual void buildXML( TQDomDocument& doc, TQDomElement element ) = 0;
    virtual bool isSimple() { return false; }

    static int debugCount;
};

int ParserNode::debugCount = 0;

class PrimaryNode : public ParserNode {
public:
    PrimaryNode( TQString primary ) : m_primary( primary ), m_functionName( false ) {}
    //virtual void output( ostream& stream ) { stream << "PrimaryNode {" << m_primary << "}" << endl; }
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
    virtual bool isSimple() { return true; }
    void setUnicode( TQChar tqunicode ) { m_tqunicode = tqunicode; }
    void setFunctionName( bool functionName ) { m_functionName = functionName; }
    TQString primary() const { return m_primary; }
private:
    TQString m_primary;
    TQChar m_tqunicode;
    bool m_functionName;
};

void PrimaryNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    if ( m_tqunicode != TQChar::null ) {
        TQDomElement de = doc.createElement( "TEXT" );
        de.setAttribute( "CHAR", TQString( m_tqunicode ) );
        de.setAttribute( "SYMBOL", "3" );
        element.appendChild( de );
    }
    else {
        if ( m_functionName ) {
            TQDomElement namesequence = doc.createElement( "NAMESEQUENCE" );
            element.appendChild( namesequence );
            element = namesequence;
        }
        for ( uint i = 0; i < m_primary.length(); i++ ) {
            TQDomElement de = doc.createElement( "TEXT" );
            de.setAttribute( "CHAR", TQString( m_primary[i] ) );
            element.appendChild( de );
        }
    }
}

class UnaryMinus : public ParserNode {
public:
    UnaryMinus( ParserNode* primary ) : m_primary( primary ) {}
    ~UnaryMinus() { delete m_primary; }
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
private:
    ParserNode* m_primary;
};

void UnaryMinus::buildXML( TQDomDocument& doc, TQDomElement element )
{
    TQDomElement de = doc.createElement( "TEXT" );
    de.setAttribute( "CHAR", "-" );
    element.appendChild( de );
    m_primary->buildXML( doc, element );
}

class OperatorNode : public ParserNode {
public:
    OperatorNode( TQString type, ParserNode* lhs, ParserNode* rhs )
        : m_type( type ), m_lhs( lhs ), m_rhs( rhs ) {}
    ~OperatorNode() { delete m_rhs; delete m_lhs; }
//     virtual void output( ostream& stream ) {
//         stream << "OperatorNode {";
//         m_lhs->output( stream ); stream << m_type; m_rhs->output( stream );
//         stream << "}" << endl; }
protected:
    TQString m_type;
    ParserNode* m_lhs;
    ParserNode* m_rhs;
};

class AssignNode : public OperatorNode {
public:
    AssignNode( TQString type, ParserNode* lhs, ParserNode* rhs ) : OperatorNode( type, lhs, rhs ) {}
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
};

void AssignNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    m_lhs->buildXML( doc, element );
    TQDomElement de = doc.createElement( "TEXT" );
    de.setAttribute( "CHAR", TQString( m_type ) );
    element.appendChild( de );
    m_rhs->buildXML( doc, element );
}

class ExprNode : public OperatorNode {
public:
    ExprNode( TQString type, ParserNode* lhs, ParserNode* rhs ) : OperatorNode( type, lhs, rhs ) {}
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
};

void ExprNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    m_lhs->buildXML( doc, element );
    TQDomElement de = doc.createElement( "TEXT" );
    de.setAttribute( "CHAR", TQString( m_type ) );
    element.appendChild( de );
    m_rhs->buildXML( doc, element );
}

class TermNode : public OperatorNode {
public:
    TermNode( TQString type, ParserNode* lhs, ParserNode* rhs ) : OperatorNode( type, lhs, rhs ) {}
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
};

void TermNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    if ( m_type == "*" ) {
        m_lhs->buildXML( doc, element );
        TQDomElement de = doc.createElement( "TEXT" );
        de.setAttribute( "CHAR", TQString( m_type ) );
        element.appendChild( de );
        m_rhs->buildXML( doc, element );
    }
    else {
        TQDomElement fraction = doc.createElement( "FRACTION" );
        TQDomElement numerator = doc.createElement( "NUMERATOR" );
        TQDomElement sequence = doc.createElement( "SEQUENCE" );
        m_lhs->buildXML( doc, sequence );
        numerator.appendChild( sequence );
        fraction.appendChild( numerator );
        TQDomElement denominator = doc.createElement( "DENOMINATOR" );
        sequence = doc.createElement( "SEQUENCE" );
        m_rhs->buildXML( doc, sequence );
        denominator.appendChild( sequence );
        fraction.appendChild( denominator );
        element.appendChild( fraction );
    }
}


class PowerNode : public OperatorNode {
public:
    PowerNode( TQString type, ParserNode* lhs, ParserNode* rhs ) : OperatorNode( type, lhs, rhs ) {}
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
};

void PowerNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    TQDomElement index = doc.createElement( "INDEX" );
    TQDomElement content = doc.createElement( "CONTENT" );
    TQDomElement sequence = doc.createElement( "SEQUENCE" );
    content.appendChild( sequence );
    index.appendChild( content );

    if ( !m_lhs->isSimple() ) {
        TQDomElement bracket = doc.createElement( "BRACKET" );
        bracket.setAttribute( "LEFT", '(' );
        bracket.setAttribute( "RIGHT", ')' );
        sequence.appendChild( bracket );

        content = doc.createElement( "CONTENT" );
        bracket.appendChild( content );

        sequence = doc.createElement( "SEQUENCE" );
        content.appendChild( sequence );
    }
    m_lhs->buildXML( doc, sequence );
    if ( m_type == "_" ) {
        TQDomElement lowerRight = doc.createElement( "LOWERRIGHT" );
        sequence = doc.createElement( "SEQUENCE" );
        m_rhs->buildXML( doc, sequence );
        lowerRight.appendChild( sequence );
        index.appendChild( lowerRight );
    }
    else {
        TQDomElement upperRight = doc.createElement( "UPPERRIGHT" );
        sequence = doc.createElement( "SEQUENCE" );
        m_rhs->buildXML( doc, sequence );
        upperRight.appendChild( sequence );
        index.appendChild( upperRight );
    }
    element.appendChild( index );
}


class FunctionNode : public ParserNode {
public:
    FunctionNode( PrimaryNode* name, TQPtrList<ParserNode>& args ) : m_name( name ), m_args( args ) {
        m_args.setAutoDelete( true );
    }
    ~FunctionNode() { delete m_name; }
    //virtual void output( ostream& stream );
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
private:
    void buildSymbolXML( TQDomDocument& doc, TQDomElement element, KFormula::SymbolType type );
    PrimaryNode* m_name;
    TQPtrList<ParserNode> m_args;
};

void FunctionNode::buildSymbolXML( TQDomDocument& doc, TQDomElement element, KFormula::SymbolType type )
{
    TQDomElement symbol = doc.createElement( "SYMBOL" );
    symbol.setAttribute( "TYPE", type );
    TQDomElement content = doc.createElement( "CONTENT" );
    TQDomElement sequence = doc.createElement( "SEQUENCE" );
    m_args.at( 0 )->buildXML( doc, sequence );
    content.appendChild( sequence );
    symbol.appendChild( content );
    if ( m_args.count() > 2 ) {
        ParserNode* lowerLimit = m_args.at( m_args.count()-2 );
        ParserNode* upperLimit = m_args.at( m_args.count()-1 );

        TQDomElement lower = doc.createElement( "LOWER" );
        sequence = doc.createElement( "SEQUENCE" );
        lowerLimit->buildXML( doc, sequence );
        lower.appendChild( sequence );
        symbol.appendChild( lower );

        TQDomElement upper = doc.createElement( "UPPER" );
        sequence = doc.createElement( "SEQUENCE" );
        upperLimit->buildXML( doc, sequence );
        upper.appendChild( sequence );
        symbol.appendChild( upper );
    }
    element.appendChild( symbol );
}

void FunctionNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    if ( ( m_name->primary() == "sqrt" ) && ( m_args.count() == 1 ) ) {
        TQDomElement root = doc.createElement( "ROOT" );
        TQDomElement content = doc.createElement( "CONTENT" );
        TQDomElement sequence = doc.createElement( "SEQUENCE" );
        m_args.at( 0 )->buildXML( doc, sequence );
        content.appendChild( sequence );
        root.appendChild( content );
        element.appendChild( root );
    }
    else if ( ( m_name->primary() == "pow" ) && ( m_args.count() == 2 ) ) {
        TQDomElement index = doc.createElement( "INDEX" );
        TQDomElement content = doc.createElement( "CONTENT" );
        TQDomElement sequence = doc.createElement( "SEQUENCE" );
        m_args.at( 0 )->buildXML( doc, sequence );
        content.appendChild( sequence );
        index.appendChild( content );
        TQDomElement upperRight = doc.createElement( "UPPERRIGHT" );
        sequence = doc.createElement( "SEQUENCE" );
        m_args.at( 1 )->buildXML( doc, sequence );
        upperRight.appendChild( sequence );
        index.appendChild( upperRight );
        element.appendChild( index );
    }
    else if ( ( m_name->primary() == "sum" ) && ( m_args.count() > 0 ) ) {
        buildSymbolXML( doc, element, KFormula::Sum );
    }
    else if ( ( m_name->primary() == "prod" ) && ( m_args.count() > 0 ) ) {
        buildSymbolXML( doc, element, KFormula::Product );
    }
    else if ( ( ( m_name->primary() == "int" ) ||
                ( m_name->primary() == "integrate" ) ||
                ( m_name->primary() == "quad" ) )
              && ( m_args.count() > 0 ) ) {
        buildSymbolXML( doc, element, KFormula::Integral );
    }
    else {
        m_name->buildXML( doc, element );
        TQDomElement bracket = doc.createElement( "BRACKET" );
        bracket.setAttribute( "LEFT", '(' );
        bracket.setAttribute( "RIGHT", ')' );
        TQDomElement content = doc.createElement( "CONTENT" );
        TQDomElement sequence = doc.createElement( "SEQUENCE" );

        for ( uint i = 0; i < m_args.count(); i++ ) {
            m_args.at( i )->buildXML( doc, sequence );
            if ( i < m_args.count()-1 ) {
                TQDomElement de = doc.createElement( "TEXT" );
                de.setAttribute( "CHAR", "," );
                sequence.appendChild( de );
            }
        }

        content.appendChild( sequence );
        bracket.appendChild( content );
        element.appendChild( bracket );
    }
}

// void FunctionNode::output( ostream& stream )
// {
//     m_name->output( stream );
//     for ( uint i = 0; i < m_args.count(); i++ ) {
//         m_args.at( i )->output( stream );
//     }
// }

class RowNode : public ParserNode {
public:
    RowNode( TQPtrList<ParserNode> row ) : m_row( row ) { m_row.setAutoDelete( true ); }
    //virtual void output( ostream& stream );
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
    uint columns() const { return m_row.count(); }
    void setRequiredColumns( uint requiredColumns ) { m_requiredColumns = requiredColumns; }
private:
    TQPtrList<ParserNode> m_row;
    uint m_requiredColumns;
};

void RowNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    for ( uint i = 0; i < m_requiredColumns; i++ ) {
        TQDomElement sequence = doc.createElement( "SEQUENCE" );
        if ( i < m_row.count() ) {
            m_row.at( i )->buildXML( doc, sequence );
        }
        else {
            TQDomElement de = doc.createElement( "TEXT" );
            de.setAttribute( "CHAR", "0" );
            sequence.appendChild( de );
        }
        element.appendChild( sequence );
    }
}

// void RowNode::output( ostream& stream )
// {
//     stream << "[";
//     for ( uint i = 0; i < m_row.count(); i++ ) {
//         m_row.at( i )->output( stream );
//         if ( i < m_row.count()-1 ) {
//             stream << ", ";
//         }
//     }
//     stream << "]";
// }

class MatrixNode : public ParserNode {
public:
    MatrixNode( TQPtrList<RowNode> rows ) : m_rows( rows ) { m_rows.setAutoDelete( true ); }
    //virtual void output( ostream& stream );
    virtual void buildXML( TQDomDocument& doc, TQDomElement element );
    virtual bool isSimple() { return true; }
    uint columns();
    uint rows() { return m_rows.count(); }
private:
    TQPtrList<RowNode> m_rows;
};

uint MatrixNode::columns()
{
    uint columns = 0;
    for ( uint i = 0; i < m_rows.count(); i++ ) {
        columns = TQMAX( columns, m_rows.at( i )->columns() );
    }
    return columns;
}

void MatrixNode::buildXML( TQDomDocument& doc, TQDomElement element )
{
    TQDomElement bracket = doc.createElement( "BRACKET" );
    bracket.setAttribute( "LEFT", '(' );
    bracket.setAttribute( "RIGHT", ')' );
    TQDomElement content = doc.createElement( "CONTENT" );
    TQDomElement sequence = doc.createElement( "SEQUENCE" );

    uint cols = columns();
    TQDomElement matrix = doc.createElement( "MATRIX" );
    matrix.setAttribute( "ROWS", m_rows.count() );
    matrix.setAttribute( "COLUMNS", cols );
    for ( uint i = 0; i < m_rows.count(); i++ ) {
        m_rows.at( i )->setRequiredColumns( cols );
        m_rows.at( i )->buildXML( doc, matrix );
        matrix.appendChild( doc.createComment( "end of row" ) );
    }
    sequence.appendChild( matrix );
    content.appendChild( sequence );
    bracket.appendChild( content );
    element.appendChild( bracket );
}

// void MatrixNode::output( ostream& stream )
// {
//     stream << "[";
//     for ( uint i = 0; i < m_rows.count(); i++ ) {
//         m_rows.at( i )->output( stream );
//         if ( i < m_rows.count()-1 ) {
//             stream << ", ";
//         }
//     }
//     stream << "]";
// }


FormulaStringParser::FormulaStringParser( const KFormula::SymbolTable& symbolTable, TQString formula )
    : m_symbolTable( symbolTable ), m_formula( formula ),
      pos( 0 ), line( 1 ), column( 1 ), m_newlineIsSpace( true )
{
}

FormulaStringParser::~FormulaStringParser()
{
    delete head;
    if ( ParserNode::debugCount != 0 ) {
        kdDebug( KFormula::DEBUGID ) << "ParserNode::debugCount = " << ParserNode::debugCount << endl;
    }
}

TQDomDocument FormulaStringParser::parse()
{
    nextToken();
    head = parseAssign();
    //head->output( cout );
    if ( !eol() ) {
        error( TQString( i18n( "Aborted parsing at %1:%2" ) ).tqarg( line ).tqarg( column ) );
    }

    TQDomDocument doc = KFormula::Document::createDomDocument();
    TQDomElement root = doc.documentElement();
    TQDomElement de = doc.createElement( "FORMULA" );
    // here comes the current version of FormulaElement
    //de.setAttribute( "VERSION", "4" );
    head->buildXML( doc, de );
    root.appendChild(de);

    kdDebug( 39001 ) << doc.toString() << endl;
    return doc;
}

ParserNode* FormulaStringParser::parseAssign()
{
    ParserNode* lhs = parseExpr();
    for ( ;; ) {
        switch ( currentType ) {
        case ASSIGN: {
            TQString c = current;
            nextToken();
            lhs = new AssignNode( c, lhs, parseExpr() );
            break;
        }
        default:
            return lhs;
        }
    }
}

ParserNode* FormulaStringParser::parseExpr()
{
    ParserNode* lhs = parseTerm();
    for ( ;; ) {
        switch ( currentType ) {
        case PLUS:
        case SUB: {
            TQString c = current;
            nextToken();
            lhs = new ExprNode( c, lhs, parseTerm() );
            break;
        }
        default:
            return lhs;
        }
    }
}

ParserNode* FormulaStringParser::parseTerm()
{
    ParserNode* lhs = parsePower();
    for ( ;; ) {
        switch ( currentType ) {
        case MUL:
        case DIV: {
            TQString c = current;
            nextToken();
            lhs = new TermNode( c, lhs, parsePower() );
            break;
        }
        default:
            return lhs;
        }
    }
}

ParserNode* FormulaStringParser::parsePower()
{
    ParserNode* lhs = parsePrimary();
    for ( ;; ) {
        switch ( currentType ) {
        case INDEX:
        case POW: {
            TQString c = current;
            nextToken();
            lhs = new PowerNode( c, lhs, parsePrimary() );
            break;
        }
        default:
            return lhs;
        }
    }
}

ParserNode* FormulaStringParser::parsePrimary()
{
    switch ( currentType ) {
    case NUMBER: {
        PrimaryNode* node = new PrimaryNode( current );
        nextToken();
        return node;
    }
    case NAME: {
        PrimaryNode* node = new PrimaryNode( current );
        node->setUnicode( m_symbolTable.tqunicode( current ) );
        nextToken();
        if ( currentType == LP ) {
            nextToken();
            TQPtrList<ParserNode> args;
            args.setAutoDelete( false );
            while ( ( currentType != EOL ) && ( currentType != RP ) ) {
                ParserNode* node = parseExpr();
                args.append( node );
                if ( currentType == COMMA ) {
                    nextToken();
                }
            }
            expect( RP, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( ")" ) );
            node->setFunctionName( true );
            return new FunctionNode( node, args );
        }
        return node;
    }
    case SUB: {
        nextToken();
        //ParserNode* node = new UnaryMinus( parsePrimary() );
        ParserNode* node = new UnaryMinus( parseTerm() );
        return node;
    }
    case LP: {
        nextToken();
        ParserNode* node = parseExpr();
        expect( RP, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( ")" ) );
        return node;
    }
    case LB: {
        nextToken();
        TQPtrList<RowNode> rows;
        rows.setAutoDelete( false );
        bool innerBrackets = currentType == LB;
        m_newlineIsSpace = innerBrackets;
        while ( ( currentType != EOL ) && ( currentType != RB ) ) {
            if ( innerBrackets ) {
                expect( LB, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( "[" ) );
            }
            TQPtrList<ParserNode> row;
            row.setAutoDelete( false );
            while ( ( currentType != EOL ) && ( currentType != RB ) &&
                    ( innerBrackets || ( currentType != SEMIC && currentType != NEWLINE ) ) ) {
                row.append( parseExpr() );
                if ( currentType == COMMA ) {
                    nextToken();
                }
            }
            if ( innerBrackets ) {
                expect( RB, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( "]" ) );
                if ( currentType == COMMA ) {
                    nextToken();
                }
            }
            else {
                if ( currentType != RB ) {
                    if ( currentType == NEWLINE ) {
                        nextToken();
                    }
                    else {
                        expect( SEMIC, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( ";" ) );
                    }
                }
            }
            rows.append( new RowNode( row ) );
        }
        m_newlineIsSpace = true;
        expect( RB, TQString( i18n( "'%3' expected at %1:%2" ) ).tqarg( line ).tqarg( column ).tqarg( "]" ) );
        MatrixNode* node = new MatrixNode( rows );
        if ( node->columns() == 0 ) {
            error( TQString( i18n( "Null columns in Matrix at %1:%2" ) ).tqarg( line ).tqarg( column ) );
        }
        if ( node->rows() == 0 ) {
            error( TQString( i18n( "Null rows in Matrix at %1:%2" ) ).tqarg( line ).tqarg( column ) );
        }
        return node;
    }
    case OTHER: {
        ParserNode* node = new PrimaryNode( current );
        nextToken();
        return node;
    }
    default:
        error( TQString( i18n( "Unexpected token at %1:%2" ) ).tqarg( line ).tqarg( column ) );
        return new PrimaryNode( "?" );
    }
}

void FormulaStringParser::expect( TokenType type, TQString msg )
{
    if ( currentType == type ) {
        nextToken();
    }
    else {
        error( msg );
    }
}

TQString FormulaStringParser::nextToken()
{
    // We skip any ' or " so that we can parse string literals.
    while ( !eol() && ( m_formula[pos].isSpace() ||
                        ( m_formula[pos] == '"' ) ||
                        ( m_formula[pos] == '\'' ) ) ) {
        if ( m_formula[pos] == '\n' ) {
            line++;
            if ( m_newlineIsSpace ) {
                column = 0;
            }
            else {
                pos++;
                column = 1;
                currentType = NEWLINE;
                return current = "\n";
            }
        }
        pos++; column++;
    }
    if ( eol() ) {
        currentType = EOL;
        return TQString();
    }
    if ( m_formula[pos].isDigit() || m_formula[pos] == '.' ) {
        uint begin = pos;
        readNumber();
        currentType = NUMBER;
        current = m_formula.mid( begin, pos-begin );
        if ( current[0] == '.' ) {
            current = "0" + current;
        }
        if ( current[current.length()-1] == '.' ) {
            current = current + "0";
        }
        return current;
    }
    else if ( m_formula[pos].isLetter() ) {
        uint begin = pos;
        pos++; column++;
        while ( !eol() && m_formula[pos].isLetter() ) {
            pos++; column++;
        }
        currentType = NAME;
        return current = m_formula.mid( begin, pos-begin );
    }
    else {
        switch ( m_formula[pos].latin1() ) {
        case '+':
            pos++; column++;
            currentType = PLUS;
            return current = "+";
        case '-':
            pos++; column++;
            currentType = SUB;
            return current = "-";
        case '*':
            pos++; column++;
            if ( !eol() && m_formula[pos] == '*' ) {
                pos++; column++;
                currentType = POW;
                return current = "**";
            }
            currentType = MUL;
            return current = "*";
        case '/':
            pos++; column++;
            currentType = DIV;
            return current = "/";
        case '^':
            pos++; column++;
            currentType = POW;
            return current = "**";
        case '_':
            pos++; column++;
            currentType = INDEX;
            return current = "_";
        case '(':
            pos++; column++;
            currentType = LP;
            return current = "(";
        case ')':
            pos++; column++;
            currentType = RP;
            return current = ")";
        case '[':
            pos++; column++;
            currentType = LB;
            return current = "[";
        case ']':
            pos++; column++;
            currentType = RB;
            return current = "]";
        case ',':
            pos++; column++;
            currentType = COMMA;
            return current = ",";
        case ';':
            pos++; column++;
            currentType = SEMIC;
            return current = ";";
        case '=':
            pos++; column++;
            currentType = ASSIGN;
            return current = "=";
        default:
            pos++; column++;
            currentType = OTHER;
            return current = m_formula.mid( pos-1, 1 );
        }
    }
}

void FormulaStringParser::readNumber()
{
    bool digitsBeforeDot = m_formula[pos] != '.';

    readDigits();
    if ( pos < m_formula.length()-1 ) {
        TQChar ch = m_formula[pos];

        // Look for a dot.
        if ( ch == '.' ) {
            pos++;
            column++;
            ch = m_formula[pos];
            if ( ch.isDigit() ) {
                readDigits();
            }
            else if ( !digitsBeforeDot ) {
                error( TQString( i18n( "A single '.' is not a number at %1:%2" ) ).tqarg( line ).tqarg( column ) );
                return;
            }
        }

        // there might as well be an exponent
        if ( pos < m_formula.length()-1 ) {
            ch = m_formula[pos];
            if ( ( ch == 'E' ) || ( ch == 'e' ) ) {
                pos++;
                column++;
                ch = m_formula[pos];

                // signs are allowed after the exponent
                if ( ( ( ch == '+' ) || ( ch == '-' ) ) &&
                     ( pos < m_formula.length()-1 ) ) {
                    pos++;
                    column++;
                    ch = m_formula[pos];
                    if ( ch.isDigit() ) {
                        readDigits();
                    }
                    else {
                        pos -= 2;
                        column -= 2;
                        return;
                    }
                }
                else if ( ch.isDigit() ) {
                    readDigits();
                }
                else {
                    pos--;
                    column--;
                }
            }
        }
    }
}


void FormulaStringParser::readDigits()
{
    while ( !eol() && m_formula[pos].isDigit() ) {
        pos++;
        column++;
    }
}

void FormulaStringParser::error( TQString err )
{
    kdDebug( KFormula::DEBUGID ) << err << " (" << currentType << "; " << current << ")" << endl;
    m_errorList.push_back( err );
}