-
Notifications
You must be signed in to change notification settings - Fork 532
/
StringParser.cpp
1997 lines (1820 loc) · 49.7 KB
/
StringParser.cpp
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
/*
* StringParser.cpp
*
* Created on: 6 Feb 2015
* Author: David
*/
//*************************************************************************************
#include "StringParser.h"
#include "GCodeBuffer.h"
#include "ExpressionParser.h"
#include <GCodes/GCodes.h>
#include <Platform/Platform.h>
#include <Platform/RepRap.h>
#include <Networking/NetworkDefs.h>
// Replace the default definition of THROW_INTERNAL_ERROR by one that gives line information
#undef THROW_INTERNAL_ERROR
#define THROW_INTERNAL_ERROR throw ConstructParseException("internal error at file " __FILE__ "(%d)", __LINE__)
#if HAS_MASS_STORAGE
static constexpr char eofString[] = EOF_STRING; // What's at the end of an HTML file?
#endif
StringParser::StringParser(GCodeBuffer& gcodeBuffer) noexcept
: gb(gcodeBuffer), fileBeingWritten(nullptr), writingFileSize(0), indentToSkipTo(NoIndentSkip), eofStringCounter(0),
hasCommandNumber(false), commandLetter('Q'), checksumRequired(false), crcRequired(false), binaryWriting(false)
{
StartNewFile();
Init();
}
void StringParser::Init() noexcept
{
gcodeLineEnd = 0;
commandStart = commandLength = 0; // set both to zero so that calls to GetFilePosition don't return negative values
readPointer = -1;
hadLineNumber = hadChecksum = overflowed = seenExpression = false;
computedChecksum = 0;
gb.bufferState = GCodeBufferState::parseNotStarted;
commandIndent = 0;
if (!seenMetaCommand)
{
seenLeadingSpace = seenLeadingTab = false;
}
}
inline void StringParser::AddToChecksum(char c) noexcept
{
// As computing the CRC takes several cycles, we only do it if we had a line number
if (hadLineNumber)
{
computedChecksum ^= (uint8_t)c;
crc16.Update(c);
}
}
inline void StringParser::StoreAndAddToChecksum(char c) noexcept
{
AddToChecksum(c);
if (gcodeLineEnd + 1 < ARRAY_SIZE(gb.buffer)) // if there is space for this character and a trailing null
{
gb.buffer[gcodeLineEnd++] = c;
}
else if (gb.bufferState != GCodeBufferState::parsingComment) // we don't care if comment lines overflow
{
overflowed = true;
}
}
// Add a byte to the code being assembled. If false is returned, the code is
// not yet complete. If true, it is complete and ready to be acted upon and 'indent'
// is the number of leading white space characters..
bool StringParser::Put(char c) noexcept
{
if (c != 0)
{
++commandLength;
}
if (c == 0 || c == '\n' || c == '\r')
{
return LineFinished();
}
if (c == 0x7F && gb.bufferState != GCodeBufferState::discarding)
{
// The UART receiver stores 0x7F in the buffer if an overrun or framing errors occurs. So discard the command and resync on the next newline.
gcodeLineEnd = 0;
gb.bufferState = GCodeBufferState::discarding;
}
// Process the incoming character in a state machine
bool again;
do
{
again = false;
switch (gb.bufferState)
{
case GCodeBufferState::parseNotStarted: // we haven't started parsing yet
braceCount = 0;
switch (c)
{
case 'N':
case 'n':
hadLineNumber = true;
crc16.Reset(0);
AddToChecksum(c);
gb.bufferState = GCodeBufferState::parsingLineNumber;
receivedLineNumber = 0;
break;
case ' ':
AddToChecksum(c);
++commandIndent;
seenLeadingSpace = true;
break;
case '\t':
AddToChecksum(c);
commandIndent = (commandIndent + 4) & ~3; // move on at least 1 to next multiple of 4
seenLeadingTab = true;
break;
default:
gb.bufferState = GCodeBufferState::parsingGCode;
commandStart = 0;
again = true;
break;
}
break;
case GCodeBufferState::parsingLineNumber: // we saw N at the start and we are parsing the line number
if (isDigit(c))
{
AddToChecksum(c);
receivedLineNumber = (10 * receivedLineNumber) + (c - '0');
break;
}
else
{
gb.bufferState = GCodeBufferState::parsingWhitespace;
again = true;
}
break;
case GCodeBufferState::parsingWhitespace:
switch (c)
{
case ' ':
case '\t':
AddToChecksum(c);
break;
default:
gb.bufferState = GCodeBufferState::parsingGCode;
commandStart = 0;
again = true;
break;
}
break;
case GCodeBufferState::parsingGCode: // parsing GCode words
switch (c)
{
case '*':
if (hadLineNumber && braceCount == 0)
{
declaredChecksum = 0;
checksumCharsReceived = 0;
hadChecksum = true;
gb.bufferState = GCodeBufferState::parsingChecksum;
}
else
{
StoreAndAddToChecksum(c);
}
break;
case ';':
if (commandIndent == 0 && gcodeLineEnd == 0)
{
StoreAndAddToChecksum(c);
gb.bufferState = GCodeBufferState::parsingComment;
}
else
{
gb.bufferState = GCodeBufferState::discarding;
}
break;
case '(':
if (braceCount == 0 && reprap.GetGCodes().GetMachineType() == MachineType::cnc)
{
AddToChecksum(c);
gb.bufferState = GCodeBufferState::parsingBracketedComment;
}
else
{
StoreAndAddToChecksum(c);
}
break;
case '"':
StoreAndAddToChecksum(c);
gb.bufferState = GCodeBufferState::parsingQuotedString;
break;
case '{':
++braceCount;
seenExpression = true;
StoreAndAddToChecksum(c);
break;
case '}':
if (braceCount != 0)
{
--braceCount;
}
StoreAndAddToChecksum(c);
break;
default:
StoreAndAddToChecksum(c);
}
break;
case GCodeBufferState::parsingComment:
// We are parsing a whole-line comment, which may possibly be of interest
// For now we assume that a '*' character is not the start of a checksum
StoreAndAddToChecksum(c);
break;
case GCodeBufferState::parsingBracketedComment: // inside a (...) comment
AddToChecksum(c);
if (c == ')')
{
gb.bufferState = GCodeBufferState::parsingGCode;
}
break;
case GCodeBufferState::parsingQuotedString: // inside a double-quoted string
StoreAndAddToChecksum(c);
if (c == '"')
{
gb.bufferState = GCodeBufferState::parsingGCode;
}
break;
case GCodeBufferState::parsingChecksum: // parsing the checksum after '*'
if (isDigit(c))
{
declaredChecksum = (10 * declaredChecksum) + (c - '0');
++checksumCharsReceived;
}
else
{
gb.bufferState = GCodeBufferState::discarding;
again = true;
}
break;
case GCodeBufferState::discarding: // discarding characters after the checksum or an end-of-line comment
default:
// throw the character away
break;
}
} while (again);
return false;
}
// This is called when we are fed a null, CR or LF character.
// Return true if there is a completed command ready to be executed.
bool StringParser::LineFinished() noexcept
{
if (hadLineNumber)
{
gb.CurrentFileMachineState().lineNumber = receivedLineNumber;
}
else
{
++gb.CurrentFileMachineState().lineNumber;
}
if (gcodeLineEnd == 0)
{
// Empty line
Init();
return false;
}
gb.buffer[gcodeLineEnd] = 0;
if (gb.bufferState != GCodeBufferState::parsingComment) // we don't checksum or echo comment lines, but we still need to process them
{
bool badChecksum, missingChecksum;
if (hadChecksum)
{
missingChecksum = false;
switch (checksumCharsReceived)
{
case 1:
case 2:
case 3:
// If a CRC is required then the only command we allow without a CRC is M409
badChecksum = (crcRequired || computedChecksum != declaredChecksum);
break;
case 5:
badChecksum = (crc16.Get() != declaredChecksum);
break;
default:
badChecksum = true;
break;
}
}
else
{
badChecksum = false;
missingChecksum = ((checksumRequired || crcRequired) && gb.LatestMachineState().GetPrevious() == nullptr);
}
if (reprap.GetDebugFlags(moduleGcodes).IsBitSet(gb.GetChannel().ToBaseType()) && fileBeingWritten == nullptr)
{
debugPrintf("%s%s: %s\n", gb.GetChannel().ToString(), ((badChecksum) ? "(bad-csum)" : (missingChecksum) ? "(no-csum)" : ""), gb.buffer);
}
if (badChecksum || missingChecksum)
{
Init();
return false;
}
}
commandStart = 0;
return true;
}
// Check whether the current command is a meta command, or we are skipping commands in a block
// Return true if the current line no longer needs to be processed
bool StringParser::CheckMetaCommand(const StringRef& reply) THROWS(GCodeException)
{
if (overflowed)
{
throw GCodeException(gb.GetLineNumber(), ARRAY_SIZE(gb.buffer) + commandIndent - 1, "GCode command too long");
}
const bool doingFile = gb.IsDoingFile();
BlockType skippedBlockType = BlockType::plain;
if (doingFile)
{
// Deal with warning about mixed spaces and tabs
if (commandIndent == 0)
{
seenLeadingSpace = seenLeadingTab = false; // it's OK if the previous block used only space and the following one uses only tab, or v.v.
}
else
{
CheckForMixedSpacesAndTabs();
}
// Deal with skipping blocks
if (indentToSkipTo != NoIndentSkip)
{
if (indentToSkipTo < commandIndent)
{
Init();
return true; // continue skipping this block
}
else
{
// Finished skipping the nested block
if (indentToSkipTo == commandIndent)
{
skippedBlockType = gb.GetBlockState().GetType(); // save the type of the block we skipped in case the command is 'else' or 'elif'
gb.GetBlockState().SetPlainBlock(); // we've ended the loop or if-block
}
indentToSkipTo = NoIndentSkip; // no longer skipping
}
}
while (commandIndent < gb.GetBlockIndent())
{
gb.CurrentFileMachineState().EndBlock();
if (gb.GetBlockState().GetType() == BlockType::loop)
{
// Go back to the start of the loop and re-evaluate the while-part
gb.CurrentFileMachineState().lineNumber = gb.GetBlockState().GetLineNumber();
gb.RestartFrom(gb.GetBlockState().GetFilePosition());
Init();
return true;
}
}
if (commandIndent > gb.GetBlockIndent())
{
// Indentation has increased so start new block(s)
if (!gb.CurrentFileMachineState().CreateBlock(commandIndent))
{
throw ConstructParseException("blocks nested too deeply");
}
}
}
// Save and clear the command letter in case ProcessConditionalGCode throws an exception, so that the error message won't include the previous command
const char savedCommandLetter = commandLetter;
commandLetter = 'E'; // we use this to flag a meta command, see GCodeException::GetMessage
const bool b = ProcessConditionalGCode(reply, skippedBlockType, doingFile); // this may throw a GCodeException
if (b)
{
seenMetaCommand = true;
commandEnd = gcodeLineEnd; // there are no more commands on this line
if (doingFile)
{
CheckForMixedSpacesAndTabs();
}
Init();
}
else
{
commandLetter = savedCommandLetter; // restore this so that we can handle Fanuc-style GCode
}
return b;
}
void StringParser::CheckForMixedSpacesAndTabs() noexcept
{
if (seenMetaCommand && !warnedAboutMixedSpacesAndTabs && seenLeadingSpace && seenLeadingTab)
{
reprap.GetPlatform().MessageF(AddWarning(gb.GetResponseMessageType()),
"both space and tab characters used to indent blocks at/before line %" PRIu32 "\n", gb.GetLineNumber());
warnedAboutMixedSpacesAndTabs = true;
}
}
// Check for and process a conditional GCode language command returning true if we found one, false if it's a regular line of GCode that we need to process
// If we just finished skipping an if- or elif-block when the condition was false then 'skippedBlockType' is the type of that block, else it is BlockType::plain
bool StringParser::ProcessConditionalGCode(const StringRef& reply, BlockType skippedBlockType, bool doingFile) THROWS(GCodeException)
{
// First count the number of lowercase characters.
unsigned int i = 0;
while (gb.buffer[i] >= 'a' && gb.buffer[i] <= 'z')
{
++i;
if (i == 9)
{
break; // all command words are less than 9 characters long
}
}
if (i >= 2 && i < 9
&& (gb.buffer[i] == 0 || gb.buffer[i] == ' ' || gb.buffer[i] == '\t' || gb.buffer[i] == '{' || gb.buffer[i] == '"' || gb.buffer[i] == '(') // if the command word is properly terminated
)
{
readPointer = i;
const char * const command = gb.buffer;
switch (i)
{
case 2:
if (doingFile && StringStartsWith(command, "if"))
{
ProcessIfCommand();
return true;
}
break;
case 3:
if (StringStartsWith(command, "var"))
{
ProcessVarOrGlobalCommand(false);
return true;
}
if (StringStartsWith(command, "set"))
{
ProcessSetCommand();
return true;
}
break;
case 4:
if (StringStartsWith(command, "echo"))
{
ProcessEchoCommand(reply);
return true;
}
if (StringStartsWith(command, "skip"))
{
return true;
}
if (doingFile)
{
if (StringStartsWith(command, "else"))
{
ProcessElseCommand(skippedBlockType);
return true;
}
if (StringStartsWith(command, "elif"))
{
ProcessElifCommand(skippedBlockType);
return true;
}
}
break;
case 5:
if (doingFile)
{
if (StringStartsWith(command, "while"))
{
ProcessWhileCommand();
return true;
}
if (StringStartsWith(command, "break"))
{
ProcessBreakCommand();
return true;
}
if (StringStartsWith(command, "abort"))
{
ProcessAbortCommand(reply);
return true;
}
}
break;
case 6:
if (StringStartsWith(command, "global"))
{
ProcessVarOrGlobalCommand(true);
return true;
}
break;
case 8:
if (doingFile && StringStartsWith(command, "continue"))
{
ProcessContinueCommand();
return true;
}
break;
default:
break;
}
}
readPointer = -1;
return false;
}
void StringParser::ProcessIfCommand() THROWS(GCodeException)
{
if (EvaluateCondition())
{
gb.GetBlockState().SetIfTrueBlock();
}
else
{
gb.GetBlockState().SetIfFalseNoneTrueBlock();
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the block
}
}
void StringParser::ProcessElseCommand(BlockType skippedBlockType) THROWS(GCodeException)
{
if (skippedBlockType == BlockType::ifFalseNoneTrue)
{
gb.GetBlockState().SetPlainBlock(); // execute the else-block, treating it like a plain block
}
else if (skippedBlockType == BlockType::ifFalseHadTrue || gb.GetBlockState().GetType() == BlockType::ifTrue)
{
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the if-block
gb.GetBlockState().SetPlainBlock(); // so that we get an error if there is another 'else' part
}
else
{
throw ConstructParseException("'else' did not follow 'if'");
}
}
void StringParser::ProcessElifCommand(BlockType skippedBlockType) THROWS(GCodeException)
{
if (skippedBlockType == BlockType::ifFalseNoneTrue)
{
if (EvaluateCondition())
{
gb.GetBlockState().SetIfTrueBlock();
}
else
{
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the elif-block
gb.GetBlockState().SetIfFalseNoneTrueBlock();
}
}
else if (skippedBlockType == BlockType::ifFalseHadTrue || gb.GetBlockState().GetType() == BlockType::ifTrue)
{
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the if-block
gb.GetBlockState().SetIfFalseHadTrueBlock();
}
else
{
throw ConstructParseException("'elif' did not follow 'if");
}
}
void StringParser::ProcessWhileCommand() THROWS(GCodeException)
{
// Set the current block as a loop block first so that we may use 'iterations' in the condition
if (gb.GetBlockState().GetType() == BlockType::loop)
{
gb.GetBlockState().IncrementIterations(); // starting another iteration
}
else
{
gb.GetBlockState().SetLoopBlock(GetFilePosition(), gb.GetLineNumber());
}
if (!EvaluateCondition())
{
gb.GetBlockState().SetPlainBlock();
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the block
}
}
void StringParser::ProcessBreakCommand() THROWS(GCodeException)
{
do
{
if (gb.GetBlockIndent() == 0)
{
throw ConstructParseException("'break' was not inside a loop");
}
gb.CurrentFileMachineState().EndBlock();
} while (gb.GetBlockState().GetType() != BlockType::loop);
gb.GetBlockState().SetPlainBlock();
indentToSkipTo = gb.GetBlockIndent(); // skip forwards to the end of the loop
}
void StringParser::ProcessContinueCommand() THROWS(GCodeException)
{
do
{
if (gb.GetBlockIndent() == 0)
{
throw ConstructParseException("'continue' was not inside a loop");
}
gb.CurrentFileMachineState().EndBlock();
} while (gb.GetBlockState().GetType() != BlockType::loop);
// Go back to the start of the loop and re-evaluate the while-part
gb.CurrentFileMachineState().lineNumber = gb.GetBlockState().GetLineNumber();
gb.RestartFrom(gb.GetBlockState().GetFilePosition());
}
void StringParser::ProcessVarOrGlobalCommand(bool isGlobal) THROWS(GCodeException)
{
SkipWhiteSpace();
// Get the identifier
char c = gb.buffer[readPointer];
if (!isalpha(c))
{
throw ConstructParseException("expected a new variable name");
}
String<MaxVariableNameLength> varName;
do
{
varName.cat(c);
++readPointer;
c = gb.buffer[readPointer];
} while (isalpha(c) || isdigit(c) || c == '_' );
// Expect '='
SkipWhiteSpace();
if (gb.buffer[readPointer] != '=')
{
throw ConstructParseException("expected '='");
}
++readPointer;
// Check whether the identifier already exists
WriteLockedPointer<VariableSet> vset = (isGlobal)
? reprap.GetGlobalVariablesForWriting()
: WriteLockedPointer<VariableSet>(nullptr, &gb.GetVariables());
Variable * const v = vset->Lookup(varName.c_str());
if (v != nullptr)
{
// For now we don't allow an existing variable to be reassigned using a 'var' or 'global' statement. We may need to allow it for 'global' statements.
throw ConstructParseException("variable '%s' already exists", varName.c_str());
}
SkipWhiteSpace();
ExpressionParser parser(gb, gb.buffer + readPointer, gb.buffer + ARRAY_SIZE(gb.buffer), commandIndent + readPointer);
ExpressionValue ev = parser.Parse();
vset->InsertNew(varName.c_str(), ev, (isGlobal) ? 0 : gb.CurrentFileMachineState().GetBlockNesting());
if (isGlobal)
{
reprap.GlobalUpdated();
}
}
void StringParser::ProcessSetCommand() THROWS(GCodeException)
{
// Skip the "var." or "global." prefix
SkipWhiteSpace();
const bool isGlobal = StringStartsWith(gb.buffer + readPointer, "global.");
WriteLockedPointer<VariableSet> vset = (isGlobal)
? (readPointer += strlen("global."), reprap.GetGlobalVariablesForWriting())
: (StringStartsWith(gb.buffer + readPointer, "var."))
? (readPointer += strlen("var."), WriteLockedPointer<VariableSet>(nullptr, &gb.GetVariables()))
: throw ConstructParseException("expected a global or local variable");
// Get the identifier
char c = gb.buffer[readPointer];
if (!isalpha(c))
{
throw ConstructParseException("expected a new variable name");
}
String<MaxVariableNameLength> varName;
do
{
varName.cat(c);
++readPointer;
c = gb.buffer[readPointer];
} while (isalpha(c) || isdigit(c) || c == '_' );
// Expect '='
SkipWhiteSpace();
if (gb.buffer[readPointer] != '=')
{
throw ConstructParseException("expected '='");
}
++readPointer;
// Look up the identifier
Variable * const var = vset->Lookup(varName.c_str());
if (var == nullptr)
{
throw ConstructParseException("unknown variable '%s'", varName.c_str());
}
SkipWhiteSpace();
ExpressionParser parser(gb, gb.buffer + readPointer, gb.buffer + ARRAY_SIZE(gb.buffer), commandIndent + readPointer);
ExpressionValue ev = parser.Parse();
var->Assign(ev);
if (isGlobal)
{
reprap.GlobalUpdated();
}
}
void StringParser::ProcessAbortCommand(const StringRef& reply) noexcept
{
SkipWhiteSpace();
if (gb.buffer[readPointer] != 0)
{
// If we fail to parse the expression, we want to abort anyway
try
{
ExpressionParser parser(gb, gb.buffer + readPointer, gb.buffer + ARRAY_SIZE(gb.buffer), commandIndent + readPointer);
const ExpressionValue val = parser.Parse();
readPointer = parser.GetEndptr() - gb.buffer;
val.AppendAsString(reply);
}
catch (const GCodeException& e)
{
e.GetMessage(reply, &gb);
reply.Insert(0, "invalid expression after 'abort': ");
}
}
else
{
reply.copy("'abort' command executed");
}
reprap.GetGCodes().AbortPrint(gb);
}
void StringParser::ProcessEchoCommand(const StringRef& reply) THROWS(GCodeException)
{
SkipWhiteSpace();
#if HAS_MASS_STORAGE || HAS_SBC_INTERFACE
FileData outputFile;
#endif
if (gb.buffer[readPointer] == '>')
{
#if HAS_MASS_STORAGE || HAS_SBC_INTERFACE
// Redirect the line to file
++readPointer;
OpenMode openMode;
if (gb.buffer[readPointer] == '>')
{
openMode = OpenMode::append;
++readPointer;
}
else
{
openMode = OpenMode::write;
}
String<MaxFilenameLength> filename;
GetQuotedString(filename.GetRef(), false);
FileStore * const f = reprap.GetPlatform().OpenSysFile(filename.c_str(), openMode);
if (f == nullptr)
{
throw GCodeException(gb.GetLineNumber(), readPointer + commandIndent, "Failed to create or open file");
}
outputFile.Set(f);
#else
throw GCodeException(gb.GetLineNumber(), readPointer + commandIndent, "Can't write to this file system");
#endif
}
while (true)
{
SkipWhiteSpace();
if (gb.buffer[readPointer] == 0)
{
break;
}
ExpressionParser parser(gb, gb.buffer + readPointer, gb.buffer + ARRAY_SIZE(gb.buffer), commandIndent + readPointer);
const ExpressionValue val = parser.Parse();
readPointer = parser.GetEndptr() - gb.buffer;
if (!reply.IsEmpty())
{
reply.cat(' ');
}
val.AppendAsString(reply);
SkipWhiteSpace();
if (gb.buffer[readPointer] == ',')
{
++readPointer;
}
else if (gb.buffer[readPointer] != 0)
{
throw ConstructParseException("expected ','");
}
}
#if HAS_MASS_STORAGE || HAS_SBC_INTERFACE
if (outputFile.IsLive())
{
reply.cat('\n');
const bool ok = outputFile.Write(reply.c_str());
outputFile.Close();
reply.Clear();
if (!ok)
{
throw GCodeException(gb.GetLineNumber(), -1, "Failed to write to redirect file");
}
}
#endif
}
// Evaluate the condition that should follow 'if' or 'while'
bool StringParser::EvaluateCondition() THROWS(GCodeException)
{
ExpressionParser parser(gb, gb.buffer + readPointer, gb.buffer + ARRAY_SIZE(gb.buffer), commandIndent + readPointer);
const bool b = parser.ParseBoolean();
parser.CheckForExtraCharacters();
return b;
}
// Decode this command and find the start of the next one on the same line.
// On entry, 'commandStart' has already been set to the address the start of where the command should be
// and 'commandIndent' is the number of leading whitespace characters at the start of the current line.
// On return, the state must be set to 'ready' to indicate that a command is available and we should stop adding characters.
void StringParser::DecodeCommand() noexcept
{
// Check for a valid command letter at the start
char cl = gb.buffer[commandStart];
if (cl == '\'') // check for a lowercase axis letter in Fanuc mode
{
++commandStart;
cl = tolower(gb.buffer[commandStart]);
}
else
{
cl = toupper(cl);
}
commandFraction = -1;
if (cl == 'G' || cl == 'M' || cl == 'T')
{
commandLetter = cl;
hasCommandNumber = false;
commandNumber = -1;
if (cl == 'T' && gb.buffer[commandStart + 1] == '{')
{
// It's a T command with an expression for the tool number. This will be treated as if it's "T T{...}.
parameterStart = commandStart; // so that 'Seen('T')' will return true
}
else
{
parameterStart = commandStart + 1;
const bool negative = (gb.buffer[parameterStart] == '-');
if (negative)
{
++parameterStart;
}
if (isdigit(gb.buffer[parameterStart]))
{
hasCommandNumber = true;
// Read the number after the command letter
commandNumber = 0;
do
{
commandNumber = (10 * commandNumber) + (gb.buffer[parameterStart] - '0');
++parameterStart;
}
while (isdigit(gb.buffer[parameterStart]));
if (negative)
{
commandNumber = -commandNumber;
}
// Read the fractional digit, if any
if (gb.buffer[parameterStart] == '.')
{
++parameterStart;
if (isdigit(gb.buffer[parameterStart]))
{
commandFraction = gb.buffer[parameterStart] - '0';
++parameterStart;
}
}
}
}
// Skip any whitespace after the command letter/number. This speeds up searching for parameters and is assumed by GetUnprecedentedString.
while (parameterStart < gcodeLineEnd && (gb.buffer[parameterStart] == ' ' || gb.buffer[parameterStart] == '\t'))
{
++parameterStart;
}
FindParameters();
}
else if (cl == ';')
{
// It's a whole line comment without indentation. Turn it into an internal Q0 command.
overflowed = false; // we can get very long comment lines and we don't mind if they are truncated
commandLetter = 'Q';
commandNumber = 0;
hasCommandNumber = true;
parameterStart = 1; // there is a single unquoted string parameter, which is the remainder of the line
commandEnd = gcodeLineEnd;
}
else if ( hasCommandNumber
&& commandLetter == 'G'
&& commandNumber <= 1
&& strchr(reprap.GetGCodes().GetAxisLetters(), cl) != nullptr
&& ( reprap.GetGCodes().GetMachineType() == MachineType::cnc // Fanuc style CNC
|| reprap.GetGCodes().GetMachineType() == MachineType::laser // LaserWeb style
)
&& !isalpha(gb.buffer[commandStart + 1]) // make sure it isn't an if-command or other meta command
)
{
// Fanuc or LaserWeb-style GCode, repeat the existing G0/G1 command with the new parameters
parameterStart = commandStart;
FindParameters();
}
else
{
// Bad command
commandLetter = cl;
hasCommandNumber = false;
commandNumber = -1;
commandFraction = -1;
parameterStart = commandStart;
commandEnd = gcodeLineEnd;
}
gb.bufferState = GCodeBufferState::ready;
}
// Find where the end of the command is. We assume that a G or M not inside quotes or { } and not preceded by ' is the start of a new command.
// This isn't true if the command has an unquoted string argument, but we deal with that later.
void StringParser::FindParameters() noexcept
{
bool inQuotes = false;
bool escaped = false;
unsigned int localBraceCount = 0;
parametersPresent.Clear();
for (commandEnd = parameterStart; commandEnd < gcodeLineEnd; ++commandEnd)
{
const char c = gb.buffer[commandEnd];
if (c == '\'')
{
escaped = !inQuotes;
}
else
{
if (c == '"')
{