summaryrefslogtreecommitdiffstats
path: root/private/windbg/eecan/debparse.c
blob: 8c47d64d5c1a5e15108e504fc968624222410aa1 (plain) (blame)
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
/***    DEBPARSE.C - Main parser module for C expression evaluator
 *
 *       Operator precedence parser for parsing arbitrary (almost)
 *       C expressions.
 */


/*  The parser deals with nearly all C operators, with the exception of ?:
 *  operator.
 *
 *  The parser is an operator precedence parser; because of the large
 *  number of operators, an operator precedence function has been designed,
 *  and is used instead of the precedence matrix.  See "Compilers, principles,
 *  techniques, and tools" (the 'Dragon' book) by Aho, Sethi and Ullman,
 *  section 4.6.
 *
 *  Five operators (::, +, -, & and *) are ambiguous; they can be used in
 *  either the unary or binary sense.  Again, the main parsing loop cannot
 *  tell the difference; therefore, we keep track of the previous token:  if it
 *  is id, const, ) or ], an ambiguous token is interpreted as being binary;
 *  otherwise, it is unary.  Note that the lexer will always claim to have
 *  found the unary version of these three ops: '*' will always be returned
 *  as OP_fetch, and the parser will convert to OP_mult if necessary.
 */


//  Size of shift-reduce stack, below.

#define SRSTACKSIZE     30
#define SRSTACKGROW     10
#define FCNDEPTH         5


// Macros for pushes and pops from the shift-reduce stack.

#define SRPUSH(tok) (pSRStack[--SRsp] = (tok))
#define SRPOP()     (pSRStack[SRsp++])
#define SRCUR()     (pSRStack[SRsp])
#define SRPREV()    (pSRStack[SRsp+1])



// Precedence function arrays.

#ifdef WIN32
uchar F_level[COPS_EXPR] =
#else
uchar _based(_segname("_CODE")) F_level[COPS_EXPR] =
#endif
{
#define OPCNT(name, val)
#define OPCDAT(opc)
#define OPDAT(op, opfprec, opgprec, opclass, opbind, opeval, opwalk) opfprec,
#include "debops.h"
#undef OPDAT
#undef OPCDAT
#undef OPCNT
};

#ifdef WIN32
uchar G_level[COPS_EXPR] =
#else
uchar _based(_segname("_CODE")) G_level[COPS_EXPR] =
#endif
{
#define OPCNT(name, val)
#define OPCDAT(opc)
#define OPDAT(op, opfprec, opgprec, opclass, opbind, opeval, opwalk) opgprec,
#include "debops.h"
#undef OPDAT
#undef OPCDAT
#undef OPCNT
};

typedef enum PTN_flag {
    PTN_error,          // error encountered
    PTN_nottype,        // not a type
    PTN_typestr,        // type string (type...)
    PTN_typefcn,        // (type)(....
    PTN_formal          // ...type, or ...type)
} PTN_flag;

HDEP        hSRStack = 0;
ushort      maxSRsp = SRSTACKSIZE;
token_t *pSRStack;
ushort      SRsp;
ushort      argcnt[FCNDEPTH];
short       fdepth;

LOCAL   ushort      CvtOp (ptoken_t, ptoken_t, ushort);
LOCAL   ushort      CheckErr (op_t, op_t, ushort);
LOCAL   bool_t      GrowSR (void);
LOCAL   EESTATUS    FParseExpr (uint radix);
LOCAL   PTN_flag    ParseTypeName (ptoken_t, char *, uint, EESTATUS *);
LOCAL   void        ParseContext (ptoken_t, EESTATUS *);




/**     Parse - parse expression string to abstract syntax tree
 *
 *      ushort Parse (szExpr, radix, fCase, phTM);
 *
 *      Entry   szExpr = pointer to expression string
 *              radix = default number radix for conversions
 *              fCase = case sensitive search if TRUE
 *              phTM = pointer to handle of expression state structure
 *              pEnd = pointer to ushort for index of char that ended parse
 *
 *      Exit    *phTM = handle of expression state structure if allocated
 *              *phTM = 0 if expression state structure could not be allocated
 *              *pEnd = index of character that terminated parse
 *
 *      Returns EENOERROR if no error in parse
 *              EECATASTROPHIC if unable to initialize
 *              error number if error
 */


EESTATUS
Parse (
    char *szExpr,
    uint radix,
    SHFLAG fCase,
    PHTM phTM,
    uint *pEnd
    )
{
    ushort      len = 0;
    uchar   *p = (uchar *)szExpr;

    if ((*phTM = MHMemAllocate (sizeof (struct exstate_t))) == 0) {
        return (EECATASTROPHIC);
    }

    // lock expression state structure, clear and allocate components

    DASSERT(pExState == NULL);
    pExState = (pexstate_t)MHMemLock (*phTM);
    memset (pExState, 0, sizeof (exstate_t));

    // allocate buffer for input string and copy

    for (; *p != 0; p++) {
        if (*p == 0xff) {
            p += sizeof (HSYM);
        }
    }
    pExState->ExLen = (ushort)(p - szExpr);
    if ((pExState->hExStr = MHMemAllocate (pExState->ExLen + 1)) == 0) {
        // clean up after error in allocation of input string buffer
        MHMemUnLock (*phTM);
        pExState = NULL;
        EEFreeTM (phTM);
        return (EECATASTROPHIC);
    }
    memcpy (MHMemLock (pExState->hExStr), szExpr, pExState->ExLen + 1);
    MHMemUnLock (pExState->hExStr);
    pExState = NULL;
    MHMemUnLock (*phTM);
    return (DoParse (phTM, radix, fCase, pEnd));
}


/***    DoParse - parse expression
 *
 *      error = DoParse (phTM, radix, fCase, pEnd)
 *
 *      Entry   phTM = pointer to handle to TM
 *              radix = numberic radix for conversions
 *              fCase = case sensitive search if TRUE
 *              pEnd = pointer to ushort for index of char that ended parse
 *
 *      Exit    expression parsed
 *              pExState->hExStr = handle of expression string
 *              pExState->ExLen = length of expression string
 *              *pEnd = index of character that terminated parse
 *
 *      Returns EENOERROR if expression parsed without error
 *              EECATASTROPHIC if parser was unable to initialize
 *              EEGENERAL if syntax error in expression
 */


EESTATUS
DoParse (
    PHTM phTM,
    uint radix,
    bool_t fCase,
    uint *pEnd
    )
{
    EESTATUS    error;
    uint        len;

    DASSERT(pExState == NULL);

    pExState = (pexstate_t)MHMemLock (*phTM);
    pExState->radix = radix;
    pExState->state.fCase = fCase;
    len = sizeof (stree_t) + NODE_DEFAULT + NSTACK_MAX * sizeof (bnode_t);
    if ((pExState->hSTree = MHMemAllocate (len)) == 0) {
        // clean up if error in allocation of syntax tree buffer
        MHMemUnLock (*phTM);
        pExState = NULL;
        EEFreeTM (phTM);
        return (EECATASTROPHIC);
    }
    else {
        memset ((pTree = MHMemLock (pExState->hSTree)), 0, len);
        pTree->size = len;
        pTree->stack_base = sizeof (stree_t) + NODE_DEFAULT;
        // note that stack_next is zero from memset above
        pTree->node_next = pTree->start_node = offsetof (stree_t, nodebase[0]);
    }

    // call the parser
    // note that the expression state structure and the abstract syntax tree
    // buffers are locked.

    if ((error = FParseExpr (radix)) == EECATASTROPHIC) {
        // clean up if parser unable to initialize
        MHMemUnLock (pExState->hSTree);
        pExState = NULL;
        MHMemUnLock (*phTM);
        EEFreeTM (phTM);
    }

    //  compute the correct size of the abstract syntax tree buffer and
    //  reallocate the buffer to that size

    len = pTree->node_next;
    pTree->size = len;
    MHMemUnLock (pExState->hSTree);
    pExState->hSTree = MHMemReAlloc (pExState->hSTree, len);
    *pEnd = pExState->strIndex;
    MHMemUnLock (*phTM);
    pExState = NULL;
    return (error);
}




/***    FParseExpr - Parse a C expression
 *
 *      fSuccess = FParseExpr (radix);
 *
 *      Entry   radix = default numeric radix
 *
 *      Exit    expression state structure updated
 *
 *      Returns EENOERROR if expression was successfully parsed
 *              EENOMEMORY if out of memory
 *              EEGENERAL if parse error
 *
 *      Description
 *              Lexes and parses the expression string into an abstract
 *              syntax tree.
 *
 */

LOCAL EESTATUS FParseExpr (uint radix)
{
    EESTATUS    error = EENOERROR;
    ERRNUM      lexerr = ERR_NONE;
    token_t     tokOld;
    token_t     tokNext;
    token_t     tokT;
    short       pdepth = 0;
    char   *szStart;
    char   *szExpr;

    // allocate memory for shift-reduce stack if not already allocated

    if (hSRStack == 0) {
        if ((hSRStack = MHMemAllocate (maxSRsp * sizeof (token_t))) == 0) {
            // unable to allocate space for shift reduce stack
            return (EECATASTROPHIC);
        }
    }
    pSRStack = (token_t *)MHMemLock (hSRStack);
    SRsp = maxSRsp;

    // lock the expression buffer.  Note that all exits from this
    // routine must unlock the expression buffer and unlock
    // the shift-reduce stack

    szStart = MHMemLock (pExState->hExStr);
    szExpr = szStart;
    fdepth = 0;
    pExState->strIndex = 0;

    // push the lowest-precedence terminal token on the shift-reduce stack

    tokOld.opTok = OP_lowprec;
    SRPUSH (tokOld);

    // Fetch first token

    while ((*szExpr == ' ') || (*szExpr == '\t')) {
        szExpr++;
    }
    if (*szExpr == 0) {
        lexerr = ERR_SYNTAX;
        tokNext.opTok = OP_badtok;
    }
    else if ((lexerr = GetDBToken ((uchar *)szExpr, &tokNext, radix,
      SRCUR().opTok)) == ERR_NONE) {
        // compute the index of the start of the first token from
        // the beginning of the input
        tokNext.iTokStart = (ushort)(tokNext.pbTok - szStart);
    }

    // process tokens from the input string until either a bad token is
    // encountered, an illegal combination of operators and operators occurrs
    // or the end of string is found.

    for (;;) {
kludge:
        if (tokNext.opTok == OP_badtok) {
            if (lexerr != ERR_NONE) {
                pExState->err_num = lexerr;
            }
            else {
                pExState->err_num = ERR_SYNTAX;
            }
            error = EEGENERAL;
            break;
        }
        if (error != EENOERROR) {
            if (pExState->err_num == ERR_NONE) {
                pExState->err_num = ERR_SYNTAX;
            }
            break;
        }
        if (SRsp == 0) {
            // shift/reduce stack overflow
            if (!GrowSR ()) {
                pExState->err_num = ERR_TOOCOMPLEX;
                error = EEGENERAL;
                break;
            }
        }

        // Change increment and decrement operators to pre or post form.
        // process opening parenthesis that is beginning of a function,
        // cast expression or sizeof expression

        if (tokNext.opTok == OP_incr) {
            if (F_level[SRCUR().opTok] <= G_level[OP_incr]) {
                tokNext.opTok = OP_preinc;
            }
            else {
                tokNext.opTok = OP_postinc;
            }
        }
        else if (tokNext.opTok == OP_decr) {
            if (F_level[SRCUR().opTok] <= G_level[OP_decr]) {
                tokNext.opTok = OP_predec;
            }
            else {
                tokNext.opTok = OP_postdec;
            }
        }
        else if (tokNext.opTok == OP_lcurly) {
            ParseContext (&tokNext, &error);
        }
        else if ((tokNext.opTok == OP_lparen) &&
          ((SRCUR().opTok == OP_ident) ||
          (tokOld.opTok == OP_rparen))) {

            // If the next token is a left parenthesis and the
            // shift/reduce top is an identifier or the previous
            // token was a right paren "(*pfcn)(...)

            tokNext.opTok = OP_function;
        }
        else if ((tokNext.opTok == OP_lparen) ||
          ((tokNext.opTok == OP_ident) &&
            (SRCUR().opTok == OP_arg) && (fdepth > 0))) {
            // we possibly have either a type string of the form (type) or an
            // identifier which is the first token of an argument

            switch (ParseTypeName (&tokNext, szExpr, radix, &error)) {
                case PTN_nottype:
                case PTN_error:
                    break;

                case PTN_typestr:
                    if (SRCUR().opTok == OP_sizeof) {
                        // sizeof (type string)
                        tokNext.opTok = OP_typestr;
                    }
                    else {
                        // OP_cast is a unary op.  However, we will treat it as
                        // a binary op and put the type string onto the tree
                        // and change the current token to an OP_cast

                        tokT = tokNext;
                        tokT.opTok = OP_typestr;
                        if ((error = PushToken (&tokT)) != 0) {
                            break;
                        }
                        tokNext.opTok = OP_cast;
                    }
                    break;

                case PTN_typefcn:
                    if (SRCUR().opTok == OP_sizeof) {
                        // sizeof (type string)(.... is an error
                        pExState->err_num = ERR_NOOPERAND;
                        error = EEGENERAL;
                    }
                    else {
                        // we have something of the form (type string)(....
                        // which is a cast.  We will treat this as in the
                        // case above.

                        tokT = tokNext;
                        tokT.opTok = OP_typestr;
                        if ((error = PushToken (&tokT)) != 0)
                            break;
                        tokNext.opTok = OP_cast;
                    }
                    break;

                case PTN_formal:
                    // let parser push as an argument
                    break;

                default:
                    DASSERT (FALSE);
                    pExState->err_num = ERR_INTERNAL;
                    error = EEGENERAL;
                    break;
            }
        }
        if (error != 0) {
            break;
        }
        if ((tokOld.opTok == OP_function) || (tokOld.opTok == OP_lparen)) {
            // increment paren depth to detect proper nesting
            pdepth++;
        }
        if (tokOld.opTok == OP_function) {
            // increment function depth to allow comma terminated typestring
            // arguments.  Also initialize function argument counter
            argcnt[fdepth++] = 0;
            if (fdepth == FCNDEPTH) {
                error = EEGENERAL;
                lexerr = ERR_FCNTOODEEP;
            }
            if (tokNext.opTok != OP_rparen) {
                // insert token for first argument onto stack
                tokOld.opTok = OP_arg;
                SRPUSH(tokOld);
                argcnt[fdepth - 1]++;
                // this allows foo(const class &... and similar forms
                goto kludge;
            }
        }

        // Convert unary op to binary if necessary

        if ((pExState->err_num =
          CvtOp (&tokOld, &tokNext, pdepth)) != ERR_NONE) {
            error = EEGENERAL;
            break;
        }

        if (tokNext.opTok == OP_execontext) {
            // there is an identifier on top of the stack
            // discard the indentifier and keep the string in this token.
            DASSERT(SRCUR().opTok == OP_ident);

            tokNext.pbTok = SRCUR().pbTok;
            tokNext.iTokStart = SRCUR().iTokStart;
            tokNext.cbTok = tokNext.pbEnd - tokNext.pbTok;
            szExpr = szStart + tokNext.iTokStart;

            (void)SRPOP();
        }

        // check for scan termination

        if (((SRCUR().opTok == OP_lowprec) && (tokNext.opTok == OP_lowprec))) {
            if ((pTree->stack_next != 1) || (SRsp != (ushort)(maxSRsp - 1)) ||
              (pdepth != 0) || (fdepth != 0)) {
                // statement did not reduce to a single node
                pExState->err_num = ERR_SYNTAX;
                error = EEGENERAL;
            }
            else {
                pExState->strIndex = (ushort)(szExpr - szStart);
                pExState->state.parse_ok = TRUE;
            }
            break;
        }

        // process ) as either end of function or end of grouping

        if (tokNext.opTok == OP_rparen) {
            if ((SRCUR().opTok == OP_function) &&
              (argcnt[fdepth - 1] == 0)) {
                // For a function with no arguments, shift the end of
                // arguments token onto the stack and convert the right
                // parenthesis into the end of function token

                tokOld.opTok = OP_endofargs;
                SRPUSH(tokOld);
                tokNext.opTok = OP_fcnend;
                fdepth--;
            }
            else if (((SRCUR().opTok != OP_lparen) && (SRCUR().opTok != OP_arg))
               && (SRPREV().opTok == OP_arg)) {

                // For a function with one or more arguments, pop the last
                // argument, shift the end of arguments token onto the stack
                // and then convert the right parenthesis into the end of function

                tokT = SRPOP();
                if (tokT.opTok != OP_grouped) {
                    if ((error = PushToken (&tokT)) != 0) {
                        break;
                    }
                }
                tokOld.opTok = OP_endofargs;
                SRPUSH(tokOld);
                tokNext.opTok = OP_fcnend;
                fdepth--;
            }
            else if ((SRPREV().opTok == OP_function) &&
              (SRCUR().opTok == OP_arg)) {
                tokOld.opTok = OP_endofargs;
                SRPUSH(tokOld);
                tokNext.opTok = OP_fcnend;
                fdepth--;
            }
        }
        if ((pExState->err_num =
          CheckErr (SRCUR().opTok, tokNext.opTok, pdepth)) != ERR_NONE) {
            error = EEGENERAL;
            break;
        }

        if (F_level[SRCUR().opTok] <= G_level[tokNext.opTok]) {
            // Shift next token onto stack since it has higher precedence
            // than token on top of the stack.  Note that f values larger
            // than g values mean higher precedence

            if((SRCUR().opTok == OP_lparen) && (tokNext.opTok == OP_rparen)) {
                // change the left paren on the stack to a grouping operator
                // which will be discarded later.  This is to solve the problem
                // of (id)++ becoming a preincrement
                SRCUR().opTok = OP_grouped;
            }
            else {
                SRPUSH(tokNext);
            }
            if ((tokNext.opTok == OP_rparen) || (tokNext.opTok == OP_fcnend)) {
                if (pdepth-- < 0) {
                    pExState->err_num = ERR_MISSINGLP;
                    error = EEGENERAL;
                    break;
                }
            }
            // Skip token and trailing spaces in string
            szExpr += tokNext.cbTok;
            while ((*szExpr == ' ') || (*szExpr == '\t')) {
                ++szExpr;
            }

            // save contents of next token in old token for later

            tokOld = tokNext;
            if (*szExpr) {
                // If not at end of input
                if ((lexerr = GetDBToken ((uchar *)szExpr, &tokNext, radix, SRCUR().opTok)) == ERR_NONE) {
                    tokNext.iTokStart = (ushort) (tokNext.pbTok - szStart);
                }
            }
            else {
                tokNext.opTok = OP_lowprec;
                tokNext.cbTok = 0;
            }
        }
        else {
            // Reduce ...
            // This loop pops tokens off the stack while the token removed has
            // lower precedence than the token remaining on the top of the stack.
            // This has the effect of throwing away the right parenthesis of
            // () and the right bracket of [] and pushing only the left paren or
            // left bracket;

            do {
                // Pop off stack (struct copy)
                tokT = SRPOP();
            }
            while (F_level[SRCUR().opTok] >= G_level[tokT.opTok]);

            // Push onto RPN stack or whatever
            if (tokT.opTok != OP_grouped) {
                if ((error = PushToken (&tokT)) != 0) {
                    break;
                }
            }
        }
    }

    //  unlock and free the shift-reduce stack and unlock the
    //  input string

    MHMemUnLock (hSRStack);
    MHMemUnLock (pExState->hExStr);
    return (error);
}




LOCAL bool_t GrowSR ()
{
    ushort  oldSRsp = maxSRsp;

    MHMemUnLock (hSRStack);
    if ((hSRStack = MHMemReAlloc (hSRStack, (maxSRsp + SRSTACKGROW) * sizeof (token_t))) == 0) {
        pSRStack = MHMemLock (hSRStack);
        return (FALSE);
    }
    maxSRsp += SRSTACKGROW;
    pSRStack = MHMemLock (hSRStack);
    memmove (((char *)pSRStack) + SRSTACKGROW * sizeof (token_t),
      pSRStack, oldSRsp * sizeof (token_t));
    SRsp += SRSTACKGROW;
    return (TRUE);
}




/***    CvtOp - Convert a token from unary to binary if necessary
 *
 *      error = CvtOp (ptokPrev, ptokNext, pdepth)
 *
 *
 *      Entry   ptokPrev = pointer to previously fetched token
 *              ptokNext = pointer to token just fetched
 *              pdepth = parenthesis depth
 *
 *      Exit    ptokNext->opTok = binary form of operator if necessary
 *
 *      Returns 0 if no error
 *              error index if error
 *
 *      Because operator precedence parsing can't deal with ambiguous
 *      operators (such as '-': is it unary or binary?), this routine
 *      looks at the previous token to determine whether the operator
 *      is unary or binary.
 *
 *      Note that ALL tokens come through here; this routine ignores
 *      tokens that have no ambiguity.  The lexer will always return
 *      the unary form of the operator; thus, OP_fetch instead of
 *      OP_mult for '*'.
 */


LOCAL ushort
CvtOp (
    ptoken_t ptokOld,
    ptoken_t ptokNext,
    ushort pdepth
    )
{
    if (ptokNext->opTok == OP_comma) {
        if (pdepth == 0) {
            ptokNext->opTok = OP_lowprec;
        } else if (ptokOld->opTok == OP_arg) {
            // error if OP_arg followed immediately by a comma
            pExState->err_num = ERR_SYNTAX;
            return (EEGENERAL);
        } else {
            ptokNext->opTok = OP_arg;
            argcnt[pdepth - 1]++;
        }
    }

    switch (ptokOld->opTok) {
        case OP_ident:
        case OP_hsym:
        case OP_const:
        case OP_rparen:
        case OP_fcnend:
        case OP_rbrack:
        case OP_postinc:
        case OP_postdec:
        case OP_typestr:

            // If the previous token was an identifier, a constant, or
            // a right parenthesis or bracket, and the token is ambiguous,
            // it is taken to be of the binary form.

            switch (ptokNext->opTok) {
                case OP_fetch:
                    ptokNext->opTok = OP_mult;
                    break;

                case OP_uplus:
                    ptokNext->opTok = OP_plus;
                    break;

                case OP_negate:
                    ptokNext->opTok = OP_minus;
                    break;

                case OP_addrof:
                    ptokNext->opTok = OP_and;
                    break;

                case OP_uscope:
                    ptokNext->opTok = OP_bscope;
                    break;

                case OP_bang:
                    if (ptokOld->opTok == OP_ident) {
                        ptokNext->opTok = OP_execontext;
                    }
                    break;
            }
            break;

        default:
            break;
    }
    return (ERR_NONE);
}




/***    CheckErr - Check for syntax errors which parser won't find
 *
 *      err = CheckErr (op1, op2, pdepth)
 *
 *      Entry   op1 = (OP_...) token at top of shift-reduce stack
 *              op2 = (OP_...) token at head of input string
 *              pdepth = parenthesis nesting depth
 *
 *      Returns error index
 *
 * DESCRIPTION
 *       Checks for errors which the parser is incapable of finding
 *       (since we use precedence functions rather than a matrix).
 *       Simple code, could probably be optimized.
 */


LOCAL ushort CheckErr (op_t op1, op_t op2, ushort pdepth)
{
    switch (op1) {
        // Top token on shift-reduce stack
        case OP_ident:
        case OP_const:
            if ((op2 == OP_ident) || (op2 == OP_const)) {
                return (ERR_NOOPERATOR);
            }
            if ((op2 == OP_bang) || (op2 == OP_tilde)) {
                return (ERR_SYNTAX);
            }
            break;

        case OP_lparen:
            if (op2 == OP_rbrack) {
                return (ERR_SYNTAX);
            }
            else if (op2 == OP_lowprec) {
                return (ERR_MISSINGRP);
            }
            break;

        case OP_rparen:
            if ((op2 == OP_bang) || (op2 == OP_tilde)) {
                return (ERR_SYNTAX);
            }
            break;

        case OP_lbrack:
            if (op2 == OP_rparen) {
                return (ERR_SYNTAX);
            }
            else if (op2 == OP_lowprec) {
                return (ERR_MISSINGRB);
            }
            break;

        case OP_rbrack:
            if ((op2 == OP_ident) || (op2 == OP_lparen)) {
                return (ERR_NOOPERATOR);
            }
            if ((op2 == OP_bang) || (op2 == OP_tilde)) {
                return (ERR_SYNTAX);
            }
            break;

        case OP_lowprec:
            if (op2 == OP_rparen) {
                return (ERR_MISSINGLP);
            }
            else if (op2 == OP_rbrack) {
                return (ERR_MISSINGLB);
            }
            else if (op2 == OP_rcurly) {
                return (ERR_MISSINGLC);
            }
            else if ((op2 == OP_lowprec) && (pdepth != 0)) {
                return (ERR_SYNTAX);
            }
            break;
    }
    return (ERR_NONE);
}



/**     ParseTypeName - Parse a type name  (e.g., "(int)")
 *
 *      value = ParseTypeName (pn, szExpr, radix, perror)
 *
 *      Entry   pn = pointer to initial token
 *              szExpr = pointer to expression
 *              radix = radix for numeric constants
 *              perror = pointer to error return
 *
 *      Exit    pExState->err-num = ERR_MISSINGRP if end of string encountered
 *              *perror = EEGENERAL if end of string encountered
 *              token pointers in pn updated if valid type name
 *
 *      Returns PTN_error if error
 *              PTN_nottype if not a type string
 *              PTN_typefcn if (type string)(......
 *              PTN_typestr if (type string){ident | constant | op}
 *              PTN_formal  if ...typestring, or ...typestring)
 *
 * DESCRIPTION
 *      Examines string for possible type strings
 *      Note that the actual type flags are not set in the node.
 *      This is left to the bind phase.
 */


LOCAL PTN_flag ParseTypeName (ptoken_t ptokEntry, char *szExpr,
  uint radix, EESTATUS *perror)
{
    enum {
        PT_S0,
        PT_S1,
        PT_S2,
        PT_S3,
        PT_S4,
        PT_S5
    };
    token_t     tokNext;
    char   *pParen;
    bool_t      ParenReq;
    ushort      state = PT_S0;
    op_t        tokTerm;

    // Save entry token for later update if this is a type string


    tokNext = *ptokEntry;

    // if the initial character is a ( then the termination must be a )

    ParenReq =  (*szExpr == '(')? TRUE: FALSE;

    //  check tokens up to next right parenthesis or comma.  There are the
    //  following cases:
    //
    //  1.  (token)
    //      token can be either an identifier or a type name.
    //      If opprev is OP_sizeof, call it an identifier and let the
    //      binder detect that is a type string.  If the token after the
    //      ')' is a constant, identifier or '(' then '(token)' must be a
    //      cast.
    //
    //  2.  (token op token)
    //      This can only be an expression
    //
    //  3.  (token token...)
    //      This can only be a type.  Let the binder evaluate it to a type
    //
    //  4.  (token op)
    //      if op is * or & then it is a type.  Otherwise, it is an expression
    //
    //  5.  (op token)
    //      This can only be an expression

    for (;;) {
        // Skip token and trailing spaces in string

        if ((state != PT_S0) || (ParenReq == TRUE)) {
           // skip the previous token or skip the initial paren if
           // this is the first time through the loop
           szExpr += tokNext.cbTok;
           while ((*szExpr == ' ') || (*szExpr == '\t')) {
               szExpr++;
           }
           if (*szExpr != 0) {
               if ((GetDBToken ((uchar *)szExpr, &tokNext, radix, OP_lowprec) != ERR_NONE) ||
                 (tokNext.opTok == OP_badtok)) {
                   pExState->err_num = ERR_SYNTAX;
                   *perror = EEGENERAL;
                   return (PTN_error);
               }
           }
           else {
               // flag end of statement
               tokNext.opTok = OP_lowprec;
           }
        }
        switch (state) {
            case PT_S0:
                // state 0 looks at the first token and and if it is an
                // identifier, continues the scan

                switch (tokNext.opTok) {
                    case OP_ident:
                    case OP_hsym:
                        // 'token' can be either type or expression
                        state = PT_S1;
                        break;

                    default:
                        // let parser handle everything else
                        return (PTN_nottype);
                }
                break;

            case PT_S1:
                // state 1 looks at the token after the initial identifier
                switch (tokNext.opTok) {
                    case OP_rparen:
                        if (ParenReq) {
                            // go to state that will examine token after ')'
                            // to see if (token) is a cast or expression.
                            // save location of ')'

                            pParen = szExpr;
                            state = PT_S3;
                        }
                        else {
                            // we have ...token) which must be an argument
                            return (PTN_nottype);
                        }
                        break;

                    case OP_comma:
                        if (ParenReq) {
                            // if the opening character was a '(', then
                            // a ',' is an error
                            return (PTN_error);
                        }
                        else  {
                            // if we have "...token," then it must be an expression
                            return (PTN_nottype);
                        }
                        break;

                    case OP_ident:
                    case OP_hsym:
                        // '(token token...' must be a type string
                        // enter the state that is looking for the terminating
                        // ')' or ','

                        state = PT_S4;
                        break;

                    case OP_fetch:
                    case OP_addrof:
                        // '(token *' or '(token &' can be expression or type
                        // go to state where we are looking for ident, ')'
                        // or ','

                        state = PT_S2;
                        break;

                    default:
                        // '(token op' must be an expression
                        return (PTN_nottype);
                }
                break;

            case PT_S2:
                // state 2 looks at the token after an ambiguous operator
                // if the token is '*' or '&', then the string is a type string

                switch (tokNext.opTok) {
                    case OP_rparen:

                        // '...token *)' or '...token &)' is a type string

                        pParen = tokNext.pbTok;
                        tokTerm = tokNext.opTok;
                        state = PT_S5;
                        break;

                    case OP_comma:
                        if (ParenReq) {
                            // an string of the form '(token *,' is an error
                            // because the function processing has already
                            // processed the opening paren
                            return (PTN_error);
                        }

                        // 'token *,' or 'token &,' is a type string

                        ptokEntry->pbEnd = szExpr;
                        ptokEntry->cbTok = (uchar)(ptokEntry->pbEnd - ptokEntry->pbTok);
                        return (PTN_formal);

                    default:
                        // '(token * ...' or '(token & ...' must be an expr
                        return (PTN_nottype);
                }
                break;

            case PT_S3:
                // we have found  '(token)...'  We now look at the next
                // token to determine if we have type string or the parenthesized
                // name of a function call or pointer to function
                switch (tokNext.opTok) {
                    case OP_const:
                    case OP_ident:
                    case OP_hsym:
                    case OP_lparen:
                    case OP_sizeof:
                    case OP_bang:
                    case OP_tilde:
                    case OP_uscope:
                    case OP_context:
                        // reset parse to ')' at end of type string
                        ptokEntry->pbEnd = ++pParen;
                        ptokEntry->cbTok = (uchar)(ptokEntry->pbEnd - ptokEntry->pbTok);
                        if (tokNext.opTok == OP_lparen) {
                            return (PTN_typefcn);
                        }
                        else {
                            return (PTN_typestr);
                        }

                    default:
                        // '(token) op ...' is an expression not a type
                        // note that we for the operators + - * &
                        // we assume the binary forms.  If the user wants
                        // to cast these then the operand must be in (...)
                        // for example (type)(+var)

                        return (PTN_nottype);
                }
                break;


            case PT_S4:
                // state 4 looks for the terminating ')' or ',' at the end
                // of a type string

                switch (tokNext.opTok) {
                    case OP_lowprec:
                        // end of statement without ')' or ','
                        pExState->err_num = ERR_MISSINGRP;
                        *perror = EEGENERAL;
                        return (PTN_error);

                    case OP_rparen:
                        // save location of ')' and set state to look
                        // the next token
                        pParen = szExpr;
                        tokTerm = tokNext.opTok;
                        state = PT_S5;
                        break;

                    case OP_comma:
                        ptokEntry->pbEnd = szExpr;
                        ptokEntry->cbTok = (uchar)(ptokEntry->pbEnd - ptokEntry->pbTok);
                        return (PTN_formal);


                    default:
                        // loop to closing )
                        break;
                }
                break;

            case PT_S5:
                // we know we have a type string.  Set the end of string
                // to the closing ).  If the next token is ( then the type
                // string is functional style, i.e. (type)(....).  Otherwise,
                // it is a normal typestring '(type)token.....' or '(token)\0'

                if (ParenReq) {
                    ptokEntry->pbEnd = ++pParen;
                }
                else {
                    ptokEntry->pbEnd = pParen;
                }
                ptokEntry->cbTok = (uchar)(ptokEntry->pbEnd - ptokEntry->pbTok);

                switch (tokNext.opTok) {
                    case OP_lparen:
                        // (typestr)(...
                        return (PTN_typefcn);

                    default:
                        if (ParenReq) {
                            return (PTN_typestr);
                        }
                        else {
                            return (PTN_formal);
                        }
                }
                break;
        }
    }
}




/**     ParseContext - Parse a context description {...}
 *
 *      flag = ParseContext (pn, perror)
 *
 *      Entry   pn = Pointer to token containing {
 *
 *      Exit    perror = ERR_BADCONTEXT if end of string encountered
 *              token pointers in pn updated if valid context
 *
 *      Returns none
 *
 * DESCRIPTION
 *      Examines type string for primitive types such as "int", "long",
 *      etc.    Also checks for "struct" keyword.  Note that the actual type
 *      flags are not set in the node.  This is left to the evaluation phase.
 *
 * NOTES
 */


LOCAL void ParseContext (ptoken_t ptokNext, EESTATUS *perror)
{
    char    *pb;
    char    *pbSave;
    char    *pbCurly;

    // Initialization.

    pb = pbSave = ptokNext->pbTok + 1 - ptokNext->cbTok;

    while (isspace(*pb))
        ++pb;

    DASSERT (*pb == '{');

    // Save position and skip '{'

    pbCurly = pb++;

    //  skip to closing }

    while ((*pb != 0) && (*pb != '}')) {
        // M00KLUDGE need to check for } in quoted long file name
#ifdef DBCS
        pb = CharNext(pb);
#else
        pb++;
#endif
    }

    ptokNext->cbTok = (uchar)(pb - pbCurly + 1);
    ptokNext->opTok = OP_context;

    if (*pb != '}') {
        pExState->err_num = ERR_BADCONTEXT;
        *perror = EEGENERAL;
    }
}