-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.c
1734 lines (1534 loc) · 54.6 KB
/
parser.c
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
//
// parser.c
// logo
//
// Created by ben on 18/01/2015.
// Copyright (c) 2015 ben. All rights reserved.
//
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
typedef enum operator {
opPlus = '+',
opMinus = '-',
opMultiply = '*',
opDivide = '/',
} operator;
typedef struct stack {
int itemsInStack;
float * array;
} stack;
typedef struct parser {
char ** progArray;
int numberOfTokens, atToken;
float * varValues;
symbolList * symList;
stack * polishCalcStack;
char ** errorList;
int numberOfErrors;
} parser;
//symbol parsers
int parseMAIN(parser * p);
int parseINSTRCTLST(parser * p);
int parseINSTRUCTION(parser * p);
int parseFD(parser * p);
int parseRT(parser * p);
int parseLT(parser * p);
int parseVARNUM(parser * p, float * result);
char parseVAR(parser * p);
int parseDO(parser * p);
int parseSET(parser * p);
int parseOP(parser * p, operator * op);
int parsePOLISH(parser * p, float * result);
//parserStruct functions
parser * initParser();
parser * getParser(parser * store);
void freeParser(parser * p);
int incrementAtToken(parser * p);
//parserStruct -> varValues funcs
float getVarValue(parser *p, char var);
int setVarValue(parser *p, char var, float newValue);
//parserStruct -> symbol list funcs
int addSymToList(parser * p, symbol sym, float value);
int printSymList(parser * p);
int printSymNode(symbolNode * node);
//parserStruct -> polish calc functions
int pushValue(parser *p, float value);
int popToOperator(parser * p, operator op);
void clearStack(stack * s);
//parserStruct -> error list functions
int addErrorToList(parser * p,char * errorString);
int displayErrors(parser * p);
int syntaxError(parser * p, const char * errorString);
int addWhatDoWeExpectStringToErrorList(parser * p, symbol context);
//parserStruct -> token array functions
char ** tokenise(const char * inputString, int * numberOfTokensPtr, const char * delimiter);
void testTokenArray(char ** tokenArray, int numberOfTokens);
void freeTokenArray(char **tokenArray,int numberOfTokens);
int isStringWhiteSpace(char * string);
//Unit tests
#pragma mark Unit Test Prototypes
void testTokenise();
void testInitParser();
void testIncrementToken();
void testParserErrors();
void testVarValueFunctions();
void testSymListFunctions();
void testPolishCalcFunctions();
void testParseVar();
void testParseVarnum();
void testParseOp();
void testParsePolish();
void testParseSet();
void testParseFd();
void testParseRt();
void testParseLt();
void testParseInstruction();
void testParseDo();
void testParseInstrctlst();
void testParseMain();
symbolList * parse(char * inputString)
{
unsigned long inputStringLength = strlen(inputString);
if(!inputStringLength)
{
printError("Parser recieved a empty string. Exiting.",__FILE__,__FUNCTION__,__LINE__);
return NULL;
}
parser * p = initParser();
p->progArray = tokenise(inputString, &p->numberOfTokens, " \n\r\t\v\f");
if(VERBOSE)
{
testTokenArray(p->progArray, p->numberOfTokens);
}
if(parseMAIN(p))
{
if(VERBOSE)
{
printf("\n\nProgram was validated successfully.\n");
printSymList(p);
}
}
else
{
printSymList(p);
displayErrors(p);
freeParser(p);
return NULL;
}
symbolList * symList = p->symList;
freeParser(p);
return symList;
}
#pragma mark symbol parsers
int parseMAIN(parser * p)
{
if(stringsMatch(p->progArray[p->atToken], "{"))
{
if(incrementAtToken(p))
{
return parseINSTRCTLST(p);
}
else
{
return 0;
}
}
else
{
syntaxError(p,"Expected to begin program with ""{"".");
return 0;
}
}
int parseINSTRCTLST(parser * p)
{
if(stringsMatch(p->progArray[p->atToken], "}"))
{
return 1;
}
else if(parseINSTRUCTION(p))
{
return parseINSTRCTLST(p);
}
else
{
syntaxError(p,"Expected to read an instruction or a ""}"".");
return 0;
}
}
int parseINSTRUCTION(parser * p)
{
if(parseFD(p))
{
return 1;
}
else if(parseLT(p))
{
return 1;
}
else if(parseRT(p))
{
return 1;
}
else if(parseDO(p))
{
return 1;
}
else if(parseSET(p))
{
return 1;
}
else
{
//error handled in parseINSTRCTLST()
return 0;
}
}
int parseFD(parser * p)
{
if(stringsMatch(p->progArray[p->atToken], "FD"))
{
if(incrementAtToken(p)==0) return 0;
else
{
float value;
if(parseVARNUM(p,&value)==0)
{
addWhatDoWeExpectStringToErrorList(p, symFD);
syntaxError(p,"FD could not read VARNUM.");
return 0;
}
if(value==0)
{
syntaxError(p,"FD 0 is a redundant instruction.");
return 1;
}
return addSymToList(p, symFD, value);
}
}
return 0;
}
int parseLT(parser * p)
{
if(stringsMatch(p->progArray[p->atToken], "LT"))
{
if(incrementAtToken(p)==0) return 0;
else
{
float value;
if(parseVARNUM(p,&value)==0)
{
addWhatDoWeExpectStringToErrorList(p, symLT);
syntaxError(p,"LT could not read VARNUM.");
return 0;
}
if(value==0)
{
syntaxError(p,"LT 0 is a redundant instruction.");
return 1;
}
return addSymToList(p, symLT, value);
}
}
else return 0;
}
int parseRT(parser * p)
{
if(!stringsMatch(p->progArray[p->atToken], "RT")) return 0;
else
{
if(incrementAtToken(p)==0) return 0;
else
{
float value;
if(parseVARNUM(p,&value)==0)
{
addWhatDoWeExpectStringToErrorList(p, symRT);
syntaxError(p,"RT could not read VARNUM.");
return 0;
}
if(value==0)
{
syntaxError(p,"RT 0 is a redundant instruction.");
return 1;
}
return addSymToList(p, symRT, value);
}
}
}
int parseVARNUM(parser * p, float * result)
{
float value;
if(strlen(p->progArray[p->atToken])<1)
{
printError("parseVARNUM recieved a empty string.",__FILE__,__FUNCTION__,__LINE__);
return 0;
}
if(isdigit(p->progArray[p->atToken][0]) )//if its a digit...
{
value = atof(p->progArray[p->atToken]);
if(incrementAtToken(p)==0) return 0;
*result = value;
return 1;
}
else if(isupper(p->progArray[p->atToken][0]))//if its a upper case letter...
{
char var = parseVAR(p);
if(var=='\0') return 0; //could not read a valid VAR. error sent in func
value = getVarValue(p,var);//retrieves the value of the specified variable
*result = value;
return 1;
}
else
{
return 0;
}
}
/**
Reads the token p->progArray[p->atToken], if it is a valid VAR i.e. a char 'A'-'Z'
then that charecter is return, other wise 0 is.
*/
char parseVAR(parser * p)
{
if(strlen(p->progArray[p->atToken])<1)
{
printError("parseVAR recieved a empty string. Exiting.",__FILE__,__FUNCTION__,__LINE__);
return '\0';
}
if(!isupper(p->progArray[p->atToken][0]))
{
return '\0';
}
else
{//increment token and if successful return the char
return incrementAtToken(p) ? p->progArray[p->atToken-1][0] : '\0';
}
}
/*
* <DO> ::= "DO" <VAR> "FROM" <VARNUM> "TO" <VARNUM> "{" <INSTRCTLST>
*
*/
int parseDO(parser * p)
{
//"DO"
if(!stringsMatch(p->progArray[p->atToken], "DO")) return 0;
else
{
if(incrementAtToken(p)==0) return 0;
//<VAR>
char var = parseVAR(p);
if(var=='\0')
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read ""VAR"".");
return 0;
}
// "FROM"
if(!stringsMatch(p->progArray[p->atToken], "FROM"))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read ""FROM"".");
return 0;
}
if(incrementAtToken(p)==0) return 0;
// <VARNUM> start
float fromVarNum;
if(!parseVARNUM(p,&fromVarNum))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read 1st <VARNUM>.");
return 0;
}
// "TO"
if(!stringsMatch(p->progArray[p->atToken], "TO"))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read ""TO"".");
return 0;
}
if(incrementAtToken(p)==0) return 0;
// <VARNUM> end
float toVarNum;
if(!parseVARNUM(p,&toVarNum))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read 2nd <VARNUM>.");
return 0;
}
// get "{"
if(!stringsMatch(p->progArray[p->atToken], "{"))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read ""{"".");
return 0;
}
if(incrementAtToken(p)==0) return 0;
//now loop:
int loopStartToken = p->atToken;
for(int iter = fromVarNum; iter<=toVarNum; ++iter)
{
p->varValues[(int)var]=iter;
if(parseINSTRCTLST(p)==0) return 0;
p->atToken = loopStartToken;
}
return 1;
}
}
/*
* <SET> ::= "SET" <VAR> ":=" <POLISH>
*/
int parseSET(parser * p)
{
// "SET"
if(!stringsMatch(p->progArray[p->atToken], "SET")) return 0;
else
{
if(incrementAtToken(p)==0) return 0;
char var = parseVAR(p);
if(var=='\0')
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read ""VAR"".");
return 0;
}
// ":="
if(!stringsMatch(p->progArray[p->atToken], ":="))
{
addWhatDoWeExpectStringToErrorList(p,symDO);
syntaxError(p,"Could not read "":="".");
return 0;
}
if(incrementAtToken(p)==0) return 0;
clearStack(p->polishCalcStack);
float setToValue;
if(parsePOLISH(p, &setToValue)==0) return 0;
if(setVarValue(p, var, setToValue)==0) return 0;
return 1;
}
}
/*
* <POLISH> ::= <OP> <POLISH> | <VARNUM> <POLISH> | ";"
*/
int parsePOLISH(parser * p, float * result)
{
if(stringsMatch(p->progArray[p->atToken], ";"))
{
if(p->polishCalcStack->itemsInStack!=1)
{
syntaxError(p,"polish expression incorrectly formatted.");
return 0;
}
if(incrementAtToken(p)==0) return 0;
*result = p->polishCalcStack->array[0];
return 1;
}
// <VARNUM> end
float varnumValue;
operator op;
if(parseVARNUM(p,&varnumValue))
{
pushValue(p, varnumValue);
return parsePOLISH(p, result);
}
if(parseOP(p,&op))
{
if(popToOperator(p, op)==0)
{
syntaxError(p,"polish expression incorrectly formatted.");
return 0;
}
return parsePOLISH(p, result);
}
addWhatDoWeExpectStringToErrorList(p, symPOLISH);
syntaxError(p,"could not read VARNUM or OP or ;.");
return 0;
}
/*
* <SET> ::= "SET" <VAR> ":=" <POLISH>
*/
int parseOP(parser * p, operator * op)
{
if(stringsMatch(p->progArray[p->atToken], "+"))
{
*op = opPlus;
}
else if(stringsMatch(p->progArray[p->atToken], "-"))
{
*op = opMinus;
}
else if(stringsMatch(p->progArray[p->atToken], "*"))
{
*op = opMultiply;
}
else if(stringsMatch(p->progArray[p->atToken], "/"))
{
*op = opDivide;
}
else return 0;
return incrementAtToken(p) ? 1 : 0;
}
#pragma mark parser obj functions
/**
builds and returns a * to parser struct.
*/
parser * initParser()
{
parser * p = malloc(sizeof(parser));
if(p==NULL)
{
printError("parser * p = malloc(sizeof(parser)) failed exiting.",__FILE__,__FUNCTION__,__LINE__);
exit(1);
}
p->progArray = NULL;
p->numberOfTokens = 0;
p->atToken=0;
p->varValues = calloc('Z'+1, sizeof(int));//over sized array, variables can be indexed by their ascii values
p->symList = malloc(sizeof(symbolList));
if(p->symList==NULL)
{
printError(" p->symList = malloc(sizeof(symbolList)) failed exiting.",__FILE__,__FUNCTION__,__LINE__);
exit(1);
}
p->symList->length=0;
p->symList->start=NULL;
p->symList->end=NULL;
p->polishCalcStack = malloc(sizeof(stack));
p->polishCalcStack->array = NULL;
p->polishCalcStack->itemsInStack=0;
p->errorList=NULL;
p->numberOfErrors=0;
return p;
}
/**
free's p except for p->symList since this is returned by parse()
*/
void freeParser(parser * p)
{
freeTokenArray(p->progArray, p->numberOfTokens);
//free error list:
for(int i=0; i<p->numberOfErrors; ++i)
{
free(p->errorList[i]);
}
free(p->errorList);
free(p->polishCalcStack->array);
free(p->polishCalcStack);
free(p);
//do not want to free symlist as this is returned.
}
/**
Increments p->atToken if possible and returns 1.
if there is not another token it returns 0.
*/
int incrementAtToken(parser * p)
{
if(p->atToken < p->numberOfTokens-1)
{
++p->atToken;
//if(VERBOSE) printf("moved to token %d [%s]\n",p->atToken, p->progArray[p->atToken]);
return 1;
}
else
{
addErrorToList(p,"ERROR: expected program to end with a ""}""\n");
return 0;
}
}
#pragma mark VAR value functions
/**
sets the value of var (should be 'A' to 'Z', if its not it sends an erro and returns 0) to newValue
and returns that value.
*/
int setVarValue(parser *p, char var, float newValue)
{
if(var>'Z' || var<'A')
{
char errStr[MAX_ERROR_STRING_SIZE];
sprintf(errStr, "setVarValue was passed the invalid variable charecter %c vars should be 'A' to 'Z' only.",var);
printError(errStr, __FILE__, __FUNCTION__, __LINE__);
return 0;
}
p->varValues[(int)var]=newValue;
return 1;
}
/**
Gets the value of var (should be 'A' to 'Z', if its not it sends an erro and returns 0)
and returns that value.
*/
float getVarValue(parser *p, char var)
{
if(var>'Z' || var<'A')
{
char errStr[MAX_ERROR_STRING_SIZE];
sprintf(errStr, "getVarValue was passed the invalid variable charecter %c vars should be 'A' to 'Z' only.",var);
printError(errStr, __FILE__, __FUNCTION__, __LINE__);
return 0;
}
return p->varValues[(int)var];
}
#pragma mark symbol list functions
/**
Creates a symbolNode for the input values and ands it to p->symList linked list
symList only needs to contain FD LT and RT instructions, all others can be expanded to these.
if this function is called with a sym other than these, it prints an error and returns 0.
otherwise it returns the new length of the list
*/
int addSymToList(parser * p, symbol sym, float value)
{
symbolNode * newNode = malloc(sizeof(symbolNode));
if(newNode==NULL)
{
printError("symbolNode * newNode = malloc(sizeof(symbolNode)) failed.", __FILE__, __FUNCTION__, __LINE__);
exit(1);
}
newNode->sym = sym;
newNode->value = value;
newNode->next = NULL;
if(sym!=symFD && sym!=symLT && sym!=symRT)
{
printError("addSymToList called a sym type that doesnt need to be placed on symList.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
if(p->symList->length==0)
{//if first node:
p->symList->start = newNode;
p->symList->end = newNode;
}
else
{
p->symList->end->next = newNode;
p->symList->end = newNode;
}
return (int)++p->symList->length;
}
/**
Prints each node of p->symList to stdout.
Returns 1 if completed succesfully, 0 if there is unexpected symbols in the list.
*/
int printSymList(parser * p)
{
symbolNode * current = p->symList->start;
printf("{\n");
while(current)
{
if(printSymNode(current)==0) return 0;
current=current->next;
}
printf("}\n");
return 1;
}
/**
Prints a line detailing the contents of node to stdout.
Returns 1 if completed succesfully, 0 if there is an unexpected symbols.
*/
int printSymNode(symbolNode * node)
{
switch (node->sym)
{
case symFD:
{
printf(" FD ");
break;
}
case symRT:
{
printf(" RT ");
break;
}
case symLT:
{
printf(" LT ");
break;
}
default:
{
printError("symList contained a unexpected symbol. Only FD, RT, and LT instructions are neccessary to be added to symList, others can be expanded to just these.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
}
printf("%f\n",node->value);
return 1;
}
#pragma mark polish calculator functions
/**
accesses p->polishCalcStack. pushes value onto the top of the stack.
returns the number of items now in the stack.
*/
int pushValue(parser *p, float value)
{
++p->polishCalcStack->itemsInStack;
float * tmp = realloc(p->polishCalcStack->array, p->polishCalcStack->itemsInStack*sizeof(int));
if(tmp==NULL)
{
printError(" float * tmp = realloc(p->polishCalcStack->array, p->polishCalcStack->itemsInStack*sizeof(int)) failed. Exiting.", __FILE__, __FUNCTION__, __LINE__);
exit(1);
}
p->polishCalcStack->array = tmp;
p->polishCalcStack->array[p->polishCalcStack->itemsInStack-1]=value;
return p->polishCalcStack->itemsInStack;
}
/**
accesses p->polishCalcStack poping the top two values off and combining them with
operator op. the top item goes to the rhs the 2nd top goes lhs. the result is pushed
back on to the stack.
returns 1 if successful 0 if not.
*/
int popToOperator(parser * p, operator op)
{
if(p->polishCalcStack->itemsInStack<2)
{
printError("popToOperator called when there is less than two items on stack. returning 0.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
float rhs = p->polishCalcStack->array[p->polishCalcStack->itemsInStack-1],
lhs = p->polishCalcStack->array[p->polishCalcStack->itemsInStack-2],
result;
switch (op)
{
case opPlus:
{
result = lhs + rhs;
break;
}
case opMinus:
{
result = lhs - rhs;
break;
}
case opMultiply:
{
result = lhs * rhs;
break;
}
case opDivide:
{
result = lhs / rhs;
break;
}
}
p->polishCalcStack->itemsInStack -= 2;
float * tmp = realloc(p->polishCalcStack->array, p->polishCalcStack->itemsInStack*sizeof(int));
if(!tmp)
{
printError("realloc failed. Exiting.", __FILE__, __FUNCTION__, __LINE__);
exit(1);
}
p->polishCalcStack->array = tmp;
return pushValue(p, result) ? 1 : 0;
}
/**
resets stack struct.
*/
void clearStack(stack * s)
{
if(s->array) free(s->array);
s->array=NULL;
s->itemsInStack=0;
}
#pragma mark error messaging functions
/**
Adds error string to the string array p->errorList.
@returns 1 if sucessful
*/
int addErrorToList(parser * p, char * errorString)
{
++p->numberOfErrors;
char ** tmp = realloc(p->errorList,p->numberOfErrors*sizeof(char*));
if(tmp==NULL)
{
printError("realloc failed exiting.",__FILE__,__FUNCTION__,__LINE__);
exit(1);
}
p->errorList = tmp;
p->errorList[p->numberOfErrors-1] = strdup(errorString);
return 1;
}
/**
Prints all of the strings int p->errorList array.
@returns 1
*/
int displayErrors(parser * p)
{
if(p->numberOfErrors==0) return 0;
printf("\n\nParsing Failed. There were %d errors:",p->numberOfErrors);
for(int i=0; i<p->numberOfErrors; ++i)
{
printf("\n%s \n",p->errorList[i]);
}
printf("\n");
return 1;
}
/**
Adds a syntax error to p->errorList array.
@returns 1 if successful. returns 0 and a Error message if unsuccessful.
*/
int syntaxError(parser * p, const char * errorString)
{
if(strlen(errorString)<1)
{
printError("Function was called with empty string.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
if(p->numberOfTokens<1)
{
printError("Syntax error called but there are no tokens yet.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
char * editableErrorString = strdup(errorString);
char stringStart[MAX_ERROR_STRING_SIZE]={'\0'};
if(p->atToken>=1)
{
sprintf(stringStart,"ERROR: invalid syntax at token %d ""%s"" previous token %d ""%s"". \n",
p->atToken, p->progArray[p->atToken],
p->atToken-1, p->progArray[p->atToken-1]);
}
strcat(stringStart,editableErrorString);
free(editableErrorString);
return addErrorToList(p,stringStart);
}
/**
Adds a line explaing the expected syntax of a symbol context to p->errorList array.
@returns 1 if successful. returns 0 and a Error message if unsuccessful.
*/
int addWhatDoWeExpectStringToErrorList(parser * p, symbol context)
{
char outputString[MAX_ERROR_STRING_SIZE];
switch(context)
{
case symMAIN:
sprintf(outputString,"Expected: <MAIN> ::= ""{"" <INSTRCTLST>");
break;
case symINSTRCTLST:
sprintf(outputString,"Expected: <INSTRCTLST> ::= <INSTRUCTION><INSTRCTLST> | ""}"" ");
break;
case symINSTRUCTION:
sprintf(outputString,"Expected: <INSTRUCTION> ::= <FD> | <LT> | <RT> | <DO> | <SET>");
break;
case symFD:
sprintf(outputString, "Expected: <FD> ::= ""FD"" <VARNUM>");
break;
case symLT:
sprintf(outputString, "Expected: <LT> ::= ""LT"" <VARNUM>");
break;
case symRT:
sprintf(outputString, "Expected: <RT> ::= ""RT"" <VARNUM>");
break;
case symDO:
sprintf(outputString, "Expected: <DO> ::= ""DO"" <VAR> ""FROM"" <VARNUM> ""TO"" <VARNUM> ""{"" <INSTRCTLST>");
break;
case symVAR:
sprintf(outputString, "Expected: <VAR> ::= [A-Z]");
break;
case symVARNUM:
sprintf(outputString, "Expected: <VARNUM> ::= number | <VAR>");
break;
case symSET:
sprintf(outputString,"Expected: <SET> ::= ""SET"" <VAR> "":="" <POLISH>");
break;
case symPOLISH:
sprintf(outputString,"Expected: <POLISH> ::= <OP> <POLISH> | <VARNUM> <POLISH> | "";"" ");
break;
case symOP:
sprintf(outputString, "Expected: <OP> ::= ""+"" | ""-"" | ""*"" | ""/"" ");
break;
default:
printError("read an invalid symbol context.", __FILE__, __FUNCTION__, __LINE__);
return 0;
}
int successfullyAdded = addErrorToList(p,outputString);
return successfullyAdded ? 1 : 0;
}
#pragma mark tokenArray
/*
* Takes the input string and breaks into separate words where ever it finds a charecter contained in the delimeter string each of these words is stored in the returned array which is an array of strings. the number of strings is stored in numberOfTokensPtr.
*/
char ** tokenise(const char * inputString, int * numberOfTokensPtr, const char * delimiter)
{
static int calls=1;
char *stringToken, //holds the chunks on the input string as we break it up
*inputStringDuplicate = strdup(inputString),//duplicate input string for editting
**tokenArray = NULL; //this will be an array to hold each of the chunk strings
int numberOfTokens=0;
//using http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
stringToken = strtok(inputStringDuplicate, delimiter); // gets the first chunk (up to the first space)
// walk through rest of string
while( stringToken != NULL )
{
if(isStringWhiteSpace(stringToken))
{
//discard this token, do nothing
}
else
{
++numberOfTokens;
char ** tmp = (char **)realloc(tokenArray,numberOfTokens*sizeof(char*));//array of strings
if(!tmp)
{
printError("realloc failed, exiting.",__FILE__,__FUNCTION__,__LINE__);
exit(1);
}
tokenArray = tmp;
tokenArray[numberOfTokens-1]=(char *)malloc((size_t)(strlen(stringToken)*sizeof(char)+1));
if(!tokenArray[numberOfTokens-1])
{
printError("malloc failed, exiting.",__FILE__,__FUNCTION__,__LINE__);
exit(1);
}
strcpy(tokenArray[numberOfTokens-1],stringToken);
}
stringToken = strtok(NULL, delimiter);
}
free(inputStringDuplicate);//frees the malloc made in strdup()
//$(numberOfChunks) strings now stored in the commandArray
*numberOfTokensPtr=numberOfTokens;
++calls;
return tokenArray;
}
/**
Returns 1 if string is entirly whitespace ( \t\r\v\f\n)
*/
int isStringWhiteSpace(char * string)
{
for(int i=0;string[i];++i)
{
if(!isspace(string[i])) return 0;
}
return 1;
}
/*
* frees the memory allocated to a tokenArray in tokenise func
*/
void freeTokenArray(char **tokenArray,int numberOfTokens)
{
for(int i=0; i<numberOfTokens; ++i)
{
free(tokenArray[i]);
}
free(tokenArray);
}
#pragma mark developement tests
/*
* Test function for developement. Prints contents of a tokenArray
*/
void testTokenArray(char ** tokenArray, int numberOfTokens)
{
printf("\ntestTokenArray:\n");
for(int i=0; i<numberOfTokens; ++i)
{
printf("%d:[%s] ",i,tokenArray[i]);
}
printf("\n\n");
}
/******************************************************************************/
//Unit Tests
#pragma mark Parser Unit Test Functions