Sun, 02 Feb 2014 18:07:06 +0200
- blargh. buffers weren't initialized properly
88 | 1 | /* |
2 | Copyright 2012-2014 Santeri Piippo | |
3 | All rights reserved. | |
4 | ||
5 | Redistribution and use in source and binary forms, with or without | |
6 | modification, are permitted provided that the following conditions | |
7 | are met: | |
8 | ||
9 | 1. Redistributions of source code must retain the above copyright | |
10 | notice, this list of conditions and the following disclaimer. | |
11 | 2. Redistributions in binary form must reproduce the above copyright | |
12 | notice, this list of conditions and the following disclaimer in the | |
13 | documentation and/or other materials provided with the distribution. | |
14 | 3. The name of the author may not be used to endorse or promote products | |
15 | derived from this software without specific prior written permission. | |
16 | ||
17 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR | |
18 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES | |
19 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. | |
20 | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, | |
21 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT | |
22 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
23 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
24 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
25 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |
26 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
27 | */ | |
28 | ||
29 | #include "Parser.h" | |
30 | #include "Events.h" | |
31 | #include "Commands.h" | |
32 | #include "StringTable.h" | |
33 | #include "Variables.h" | |
34 | #include "Containers.h" | |
35 | #include "Lexer.h" | |
36 | #include "DataBuffer.h" | |
37 | ||
38 | #define SCOPE(n) (mScopeStack[mScopeCursor - n]) | |
39 | ||
40 | // ============================================================================ | |
41 | // | |
42 | BotscriptParser::BotscriptParser() : | |
43 | mReadOnly (false), | |
44 | mLexer (new Lexer) {} | |
45 | ||
46 | // ============================================================================ | |
47 | // | |
48 | BotscriptParser::~BotscriptParser() | |
49 | { | |
50 | delete mLexer; | |
51 | } | |
52 | ||
53 | // ============================================================================ | |
54 | // | |
55 | void BotscriptParser::CheckToplevel() | |
56 | { | |
57 | if (mCurrentMode != ETopLevelMode) | |
58 | Error ("%1-statements may only be defined at top level!", GetTokenString()); | |
59 | } | |
60 | ||
61 | // ============================================================================ | |
62 | // | |
63 | void BotscriptParser::CheckNotToplevel() | |
64 | { | |
65 | if (mCurrentMode == ETopLevelMode) | |
66 | Error ("%1-statements must not be defined at top level!", GetTokenString()); | |
67 | } | |
68 | ||
69 | // ============================================================================ | |
70 | // Main Parser code. Begins read of the script file, checks the syntax of it | |
71 | // and writes the data to the object file via Objwriter - which also takes care | |
72 | // of necessary buffering so stuff is written in the correct order. | |
73 | void BotscriptParser::ParseBotscript (String fileName) | |
74 | { | |
75 | // Lex and preprocess the file | |
76 | mLexer->ProcessFile (fileName); | |
77 | ||
89
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
78 | mMainBuffer = new DataBuffer; |
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
79 | mOnEnterBuffer = new DataBuffer; |
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
80 | mMainLoopBuffer = new DataBuffer; |
88 | 81 | mCurrentMode = ETopLevelMode; |
82 | mNumStates = 0; | |
83 | mNumEvents = 0; | |
84 | mScopeCursor = 0; | |
85 | mStateSpawnDefined = false; | |
86 | mGotMainLoop = false; | |
87 | mIfExpression = null; | |
88 | mCanElse = false; | |
89 | ||
90 | // Zero the entire block stack first | |
91 | // TODO: this shouldn't be necessary | |
92 | for (int i = 0; i < MAX_SCOPE; i++) | |
93 | ZERO (mScopeStack[i]); | |
94 | ||
95 | while (mLexer->GetNext()) | |
96 | { | |
97 | // Check if else is potentically valid | |
98 | if (TokenIs (tkElse) && mCanElse == false) | |
99 | Error ("else without preceding if"); | |
100 | ||
101 | if (TokenIs (tkElse) == false) | |
102 | mCanElse = false; | |
103 | ||
104 | switch (mLexer->GetToken()->type) | |
105 | { | |
106 | case tkState: | |
107 | ParseStateBlock(); | |
108 | break; | |
109 | ||
110 | case tkEvent: | |
111 | ParseEventBlock(); | |
112 | break; | |
113 | ||
114 | case tkMainloop: | |
115 | ParseMainloop(); | |
116 | break; | |
117 | ||
118 | case tkOnenter: | |
119 | case tkOnexit: | |
120 | ParseOnEnterExit(); | |
121 | break; | |
122 | ||
123 | case tkInt: | |
124 | case tkStr: | |
125 | case tkVoid: | |
126 | ParseVariableDeclaration(); | |
127 | break; | |
128 | ||
129 | case tkGoto: | |
130 | ParseGoto(); | |
131 | break; | |
132 | ||
133 | case tkIf: | |
134 | ParseIf(); | |
135 | break; | |
136 | ||
137 | case tkElse: | |
138 | ParseElse(); | |
139 | break; | |
140 | ||
141 | case tkWhile: | |
142 | ParseWhileBlock(); | |
143 | break; | |
144 | ||
145 | case tkFor: | |
146 | ParseForBlock(); | |
147 | break; | |
148 | ||
149 | case tkDo: | |
150 | ParseDoBlock(); | |
151 | break; | |
152 | ||
153 | case tkSwitch: | |
154 | ParseSwitchBlock(); | |
155 | break; | |
156 | ||
157 | case tkCase: | |
158 | ParseSwitchCase(); | |
159 | break; | |
160 | ||
161 | case tkDefault: | |
162 | ParseSwitchDefault(); | |
163 | break; | |
164 | ||
165 | case tkBreak: | |
166 | ParseBreak(); | |
167 | break; | |
168 | ||
169 | case tkContinue: | |
170 | ParseContinue(); | |
171 | break; | |
172 | ||
173 | case tkBraceEnd: | |
174 | ParseBlockEnd(); | |
175 | break; | |
176 | ||
177 | case tkConst: | |
178 | ParseConst(); | |
179 | break; | |
180 | ||
181 | case tkEventdef: | |
182 | ParseEventdef(); | |
183 | break; | |
184 | ||
185 | case tkFuncdef: | |
186 | ParseFuncdef(); | |
187 | break; | |
188 | ||
189 | default: | |
190 | { | |
191 | // Check for labels | |
192 | Lexer::Token next; | |
193 | ||
194 | if (TokenIs (tkSymbol) && | |
195 | mLexer->PeekNext (&next) && | |
196 | next.type == tkColon) | |
197 | { | |
198 | ParseLabel(); | |
199 | break; | |
200 | } | |
201 | ||
202 | // Check if it's a command | |
203 | CommandInfo* comm = FindCommandByName (GetTokenString()); | |
204 | ||
205 | if (comm) | |
206 | { | |
207 | buffer()->MergeAndDestroy (ParseCommand (comm)); | |
208 | mLexer->MustGetNext (tkSemicolon); | |
209 | continue; | |
210 | } | |
211 | ||
212 | // If nothing else, parse it as a statement | |
213 | DataBuffer* b = ParseStatement(); | |
214 | ||
215 | if (b == false) | |
216 | Error ("unknown token `%1`", GetTokenString()); | |
217 | ||
218 | buffer()->MergeAndDestroy (b); | |
219 | mLexer->MustGetNext (tkSemicolon); | |
220 | } | |
221 | break; | |
222 | } | |
223 | } | |
224 | ||
225 | // =============================================================================== | |
226 | // Script file ended. Do some last checks and write the last things to main buffer | |
227 | if (mCurrentMode != ETopLevelMode) | |
228 | Error ("script did not end at top level; a `}` is missing somewhere"); | |
229 | ||
230 | if (IsReadOnly() == false) | |
231 | { | |
232 | // stateSpawn must be defined! | |
233 | if (mStateSpawnDefined == false) | |
234 | Error ("script must have a state named `stateSpawn`!"); | |
235 | ||
236 | // Ensure no goto target is left undefined | |
237 | if (mUndefinedLabels.IsEmpty() == false) | |
238 | { | |
239 | StringList names; | |
240 | ||
241 | for (UndefinedLabel& undf : mUndefinedLabels) | |
242 | names << undf.name; | |
243 | ||
244 | Error ("labels `%1` are referenced via `goto` but are not defined\n", names); | |
245 | } | |
246 | ||
247 | // Dump the last state's onenter and mainloop | |
248 | writeMemberBuffers(); | |
249 | ||
250 | // String table | |
251 | WriteStringTable(); | |
252 | } | |
253 | } | |
254 | ||
255 | // ============================================================================ | |
256 | // | |
257 | void BotscriptParser::ParseStateBlock() | |
258 | { | |
259 | CheckToplevel(); | |
260 | mLexer->MustGetNext (tkString); | |
261 | String statename = GetTokenString(); | |
262 | ||
263 | // State name must be a word. | |
264 | if (statename.FirstIndexOf (" ") != -1) | |
265 | Error ("state name must be a single word, got `%1`", statename); | |
266 | ||
267 | // stateSpawn is special - it *must* be defined. If we | |
268 | // encountered it, then mark down that we have it. | |
269 | if (-statename == "statespawn") | |
270 | mStateSpawnDefined = true; | |
271 | ||
272 | // Must end in a colon | |
273 | mLexer->MustGetNext (tkColon); | |
274 | ||
275 | // write the previous state's onenter and | |
276 | // mainloop buffers to file now | |
277 | if (mCurrentState.IsEmpty() == false) | |
278 | writeMemberBuffers(); | |
279 | ||
280 | buffer()->WriteDWord (dhStateName); | |
281 | buffer()->WriteString (statename); | |
282 | buffer()->WriteDWord (dhStateIndex); | |
283 | buffer()->WriteDWord (mNumStates); | |
284 | ||
285 | mNumStates++; | |
286 | mCurrentState = statename; | |
287 | mGotMainLoop = false; | |
288 | } | |
289 | ||
290 | // ============================================================================ | |
291 | // | |
292 | void BotscriptParser::ParseEventBlock() | |
293 | { | |
294 | CheckToplevel(); | |
295 | mLexer->MustGetNext (tkString); | |
296 | ||
297 | EventDefinition* e = FindEventByName (GetTokenString()); | |
298 | ||
299 | if (e == null) | |
300 | Error ("bad event, got `%1`\n", GetTokenString()); | |
301 | ||
302 | mLexer->MustGetNext (tkBraceStart); | |
303 | mCurrentMode = EEventMode; | |
304 | buffer()->WriteDWord (dhEvent); | |
305 | buffer()->WriteDWord (e->number); | |
306 | mNumEvents++; | |
307 | } | |
308 | ||
309 | // ============================================================================ | |
310 | // | |
311 | void BotscriptParser::ParseMainloop() | |
312 | { | |
313 | CheckToplevel(); | |
314 | mLexer->MustGetNext (tkBraceStart); | |
315 | ||
316 | mCurrentMode = EMainLoopMode; | |
317 | mMainLoopBuffer->WriteDWord (dhMainLoop); | |
318 | } | |
319 | ||
320 | // ============================================================================ | |
321 | // | |
322 | void BotscriptParser::ParseOnEnterExit() | |
323 | { | |
324 | CheckToplevel(); | |
325 | bool onenter = (TokenIs (tkOnenter)); | |
326 | mLexer->MustGetNext (tkBraceStart); | |
327 | ||
328 | mCurrentMode = onenter ? EOnenterMode : EOnexitMode; | |
329 | buffer()->WriteDWord (onenter ? dhOnEnter : dhOnExit); | |
330 | } | |
331 | ||
332 | // ============================================================================ | |
333 | // | |
334 | void BotscriptParser::ParseVariableDeclaration() | |
335 | { | |
336 | // For now, only globals are supported | |
337 | if (mCurrentMode != ETopLevelMode || mCurrentState.IsEmpty() == false) | |
338 | Error ("variables must only be global for now"); | |
339 | ||
340 | EType type = (TokenIs (tkInt)) ? EIntType : | |
341 | (TokenIs (tkStr)) ? EStringType : | |
342 | EBoolType; | |
343 | ||
344 | mLexer->MustGetNext(); | |
345 | String varname = GetTokenString(); | |
346 | ||
347 | // Var name must not be a number | |
348 | if (varname.IsNumeric()) | |
349 | Error ("variable name must not be a number"); | |
350 | ||
351 | ScriptVariable* var = DeclareGlobalVariable (type, varname); | |
352 | (void) var; | |
353 | mLexer->MustGetNext (tkSemicolon); | |
354 | } | |
355 | ||
356 | // ============================================================================ | |
357 | // | |
358 | void BotscriptParser::ParseGoto() | |
359 | { | |
360 | CheckNotToplevel(); | |
361 | ||
362 | // Get the name of the label | |
363 | mLexer->MustGetNext(); | |
364 | ||
365 | // Find the mark this goto statement points to | |
366 | String target = GetTokenString(); | |
367 | ByteMark* mark = buffer()->FindMarkByName (target); | |
368 | ||
369 | // If not set, define it | |
370 | if (mark == null) | |
371 | { | |
372 | UndefinedLabel undf; | |
373 | undf.name = target; | |
374 | undf.target = buffer()->AddMark (target); | |
375 | mUndefinedLabels << undf; | |
376 | } | |
377 | ||
378 | // Add a reference to the mark. | |
379 | buffer()->WriteDWord (dhGoto); | |
380 | buffer()->AddReference (mark); | |
381 | mLexer->MustGetNext (tkSemicolon); | |
382 | } | |
383 | ||
384 | // ============================================================================ | |
385 | // | |
386 | void BotscriptParser::ParseIf() | |
387 | { | |
388 | CheckNotToplevel(); | |
389 | PushScope(); | |
390 | ||
391 | // Condition | |
392 | mLexer->MustGetNext (tkParenStart); | |
393 | ||
394 | // Read the expression and write it. | |
395 | mLexer->MustGetNext(); | |
396 | DataBuffer* c = ParseExpression (EIntType); | |
397 | buffer()->MergeAndDestroy (c); | |
398 | ||
399 | mLexer->MustGetNext (tkParenEnd); | |
400 | mLexer->MustGetNext (tkBraceStart); | |
401 | ||
402 | // Add a mark - to here temporarily - and add a reference to it. | |
403 | // Upon a closing brace, the mark will be adjusted. | |
404 | ByteMark* mark = buffer()->AddMark (""); | |
405 | ||
406 | // Use dhIfNotGoto - if the expression is not true, we goto the mark | |
407 | // we just defined - and this mark will be at the end of the scope block. | |
408 | buffer()->WriteDWord (dhIfNotGoto); | |
409 | buffer()->AddReference (mark); | |
410 | ||
411 | // Store it | |
412 | SCOPE (0).mark1 = mark; | |
413 | SCOPE (0).type = eIfScope; | |
414 | } | |
415 | ||
416 | // ============================================================================ | |
417 | // | |
418 | void BotscriptParser::ParseElse() | |
419 | { | |
420 | CheckNotToplevel(); | |
421 | mLexer->MustGetNext (tkBraceStart); | |
422 | ||
423 | // Don't use PushScope as it resets the scope | |
424 | mScopeCursor++; | |
425 | ||
426 | if (mScopeCursor >= MAX_SCOPE) | |
427 | Error ("too deep scope"); | |
428 | ||
429 | if (SCOPE (0).type != eIfScope) | |
430 | Error ("else without preceding if"); | |
431 | ||
432 | // write down to jump to the end of the else statement | |
433 | // Otherwise we have fall-throughs | |
434 | SCOPE (0).mark2 = buffer()->AddMark (""); | |
435 | ||
436 | // Instruction to jump to the end after if block is complete | |
437 | buffer()->WriteDWord (dhGoto); | |
438 | buffer()->AddReference (SCOPE (0).mark2); | |
439 | ||
440 | // Move the ifnot mark here and set type to else | |
441 | buffer()->AdjustMark (SCOPE (0).mark1); | |
442 | SCOPE (0).type = eElseScope; | |
443 | } | |
444 | ||
445 | // ============================================================================ | |
446 | // | |
447 | void BotscriptParser::ParseWhileBlock() | |
448 | { | |
449 | CheckNotToplevel(); | |
450 | PushScope(); | |
451 | ||
452 | // While loops need two marks - one at the start of the loop and one at the | |
453 | // end. The condition is checked at the very start of the loop, if it fails, | |
454 | // we use goto to skip to the end of the loop. At the end, we loop back to | |
455 | // the beginning with a go-to statement. | |
456 | ByteMark* mark1 = buffer()->AddMark (""); // start | |
457 | ByteMark* mark2 = buffer()->AddMark (""); // end | |
458 | ||
459 | // Condition | |
460 | mLexer->MustGetNext (tkParenStart); | |
461 | mLexer->MustGetNext(); | |
462 | DataBuffer* expr = ParseExpression (EIntType); | |
463 | mLexer->MustGetNext (tkParenEnd); | |
464 | mLexer->MustGetNext (tkBraceStart); | |
465 | ||
466 | // write condition | |
467 | buffer()->MergeAndDestroy (expr); | |
468 | ||
469 | // Instruction to go to the end if it fails | |
470 | buffer()->WriteDWord (dhIfNotGoto); | |
471 | buffer()->AddReference (mark2); | |
472 | ||
473 | // Store the needed stuff | |
474 | SCOPE (0).mark1 = mark1; | |
475 | SCOPE (0).mark2 = mark2; | |
476 | SCOPE (0).type = eWhileScope; | |
477 | } | |
478 | ||
479 | // ============================================================================ | |
480 | // | |
481 | void BotscriptParser::ParseForBlock() | |
482 | { | |
483 | CheckNotToplevel(); | |
484 | PushScope(); | |
485 | ||
486 | // Initializer | |
487 | mLexer->MustGetNext (tkParenStart); | |
488 | mLexer->MustGetNext(); | |
489 | DataBuffer* init = ParseStatement(); | |
490 | ||
491 | if (init == null) | |
492 | Error ("bad statement for initializer of for"); | |
493 | ||
494 | mLexer->MustGetNext (tkSemicolon); | |
495 | ||
496 | // Condition | |
497 | mLexer->MustGetNext(); | |
498 | DataBuffer* cond = ParseExpression (EIntType); | |
499 | ||
500 | if (cond == null) | |
501 | Error ("bad statement for condition of for"); | |
502 | ||
503 | mLexer->MustGetNext (tkSemicolon); | |
504 | ||
505 | // Incrementor | |
506 | mLexer->MustGetNext(); | |
507 | DataBuffer* incr = ParseStatement(); | |
508 | ||
509 | if (incr == null) | |
510 | Error ("bad statement for incrementor of for"); | |
511 | ||
512 | mLexer->MustGetNext (tkParenEnd); | |
513 | mLexer->MustGetNext (tkBraceStart); | |
514 | ||
515 | // First, write out the initializer | |
516 | buffer()->MergeAndDestroy (init); | |
517 | ||
518 | // Init two marks | |
519 | ByteMark* mark1 = buffer()->AddMark (""); | |
520 | ByteMark* mark2 = buffer()->AddMark (""); | |
521 | ||
522 | // Add the condition | |
523 | buffer()->MergeAndDestroy (cond); | |
524 | buffer()->WriteDWord (dhIfNotGoto); | |
525 | buffer()->AddReference (mark2); | |
526 | ||
527 | // Store the marks and incrementor | |
528 | SCOPE (0).mark1 = mark1; | |
529 | SCOPE (0).mark2 = mark2; | |
530 | SCOPE (0).buffer1 = incr; | |
531 | SCOPE (0).type = eForScope; | |
532 | } | |
533 | ||
534 | // ============================================================================ | |
535 | // | |
536 | void BotscriptParser::ParseDoBlock() | |
537 | { | |
538 | CheckNotToplevel(); | |
539 | PushScope(); | |
540 | mLexer->MustGetNext (tkBraceStart); | |
541 | SCOPE (0).mark1 = buffer()->AddMark (""); | |
542 | SCOPE (0).type = eDoScope; | |
543 | } | |
544 | ||
545 | // ============================================================================ | |
546 | // | |
547 | void BotscriptParser::ParseSwitchBlock() | |
548 | { | |
549 | // This gets a bit tricky. switch is structured in the | |
550 | // bytecode followingly: | |
551 | // | |
552 | // (expression) | |
553 | // case a: goto casemark1 | |
554 | // case b: goto casemark2 | |
555 | // case c: goto casemark3 | |
556 | // goto mark1 // jump to end if no matches | |
557 | // casemark1: ... | |
558 | // casemark2: ... | |
559 | // casemark3: ... | |
560 | // mark1: // end mark | |
561 | ||
562 | CheckNotToplevel(); | |
563 | PushScope(); | |
564 | mLexer->MustGetNext (tkParenStart); | |
565 | mLexer->MustGetNext(); | |
566 | buffer()->MergeAndDestroy (ParseExpression (EIntType)); | |
567 | mLexer->MustGetNext (tkParenEnd); | |
568 | mLexer->MustGetNext (tkBraceStart); | |
569 | SCOPE (0).type = eSwitchScope; | |
570 | SCOPE (0).mark1 = buffer()->AddMark (""); // end mark | |
571 | SCOPE (0).buffer1 = null; // default header | |
572 | } | |
573 | ||
574 | // ============================================================================ | |
575 | // | |
576 | void BotscriptParser::ParseSwitchCase() | |
577 | { | |
578 | // case is only allowed inside switch | |
579 | if (SCOPE (0).type != eSwitchScope) | |
580 | Error ("case label outside switch"); | |
581 | ||
582 | // Get the literal (Zandronum does not support expressions here) | |
583 | mLexer->MustGetNext (tkNumber); | |
584 | int num = mLexer->GetToken()->text.ToLong(); | |
585 | mLexer->MustGetNext (tkColon); | |
586 | ||
587 | for (int i = 0; i < MAX_CASE; i++) | |
588 | if (SCOPE (0).casenumbers[i] == num) | |
589 | Error ("multiple case %d labels in one switch", num); | |
590 | ||
591 | // Write down the expression and case-go-to. This builds | |
592 | // the case tree. The closing event will write the actual | |
593 | // blocks and move the marks appropriately. | |
594 | // | |
595 | // AddSwitchCase will add the reference to the mark | |
596 | // for the case block that this heralds, and takes care | |
597 | // of buffering setup and stuff like that. | |
598 | // | |
599 | // We null the switch buffer for the case-go-to statement as | |
600 | // we want it all under the switch, not into the case-buffers. | |
601 | mSwitchBuffer = null; | |
602 | buffer()->WriteDWord (dhCaseGoto); | |
603 | buffer()->WriteDWord (num); | |
604 | AddSwitchCase (null); | |
605 | SCOPE (0).casenumbers[SCOPE (0).casecursor] = num; | |
606 | } | |
607 | ||
608 | // ============================================================================ | |
609 | // | |
610 | void BotscriptParser::ParseSwitchDefault() | |
611 | { | |
612 | if (SCOPE (0).type != eSwitchScope) | |
613 | Error ("default label outside switch"); | |
614 | ||
615 | if (SCOPE (0).buffer1) | |
616 | Error ("multiple default labels in one switch"); | |
617 | ||
618 | mLexer->MustGetNext (tkColon); | |
619 | ||
620 | // The default header is buffered into buffer1, since | |
621 | // it has to be the last of the case headers | |
622 | // | |
623 | // Since the expression is pushed into the switch | |
624 | // and is only popped when case succeeds, we have | |
625 | // to pop it with dhDrop manually if we end up in | |
626 | // a default. | |
627 | DataBuffer* b = new DataBuffer; | |
628 | SCOPE (0).buffer1 = b; | |
629 | b->WriteDWord (dhDrop); | |
630 | b->WriteDWord (dhGoto); | |
631 | AddSwitchCase (b); | |
632 | } | |
633 | ||
634 | // ============================================================================ | |
635 | // | |
636 | void BotscriptParser::ParseBreak() | |
637 | { | |
638 | if (mScopeCursor == 0) | |
639 | Error ("unexpected `break`"); | |
640 | ||
641 | buffer()->WriteDWord (dhGoto); | |
642 | ||
643 | // switch and if use mark1 for the closing point, | |
644 | // for and while use mark2. | |
645 | switch (SCOPE (0).type) | |
646 | { | |
647 | case eIfScope: | |
648 | case eSwitchScope: | |
649 | { | |
650 | buffer()->AddReference (SCOPE (0).mark1); | |
651 | } break; | |
652 | ||
653 | case eForScope: | |
654 | case eWhileScope: | |
655 | { | |
656 | buffer()->AddReference (SCOPE (0).mark2); | |
657 | } break; | |
658 | ||
659 | default: | |
660 | { | |
661 | Error ("unexpected `break`"); | |
662 | } break; | |
663 | } | |
664 | ||
665 | mLexer->MustGetNext (tkSemicolon); | |
666 | } | |
667 | ||
668 | // ============================================================================ | |
669 | // | |
670 | void BotscriptParser::ParseContinue() | |
671 | { | |
672 | mLexer->MustGetNext (tkSemicolon); | |
673 | ||
674 | int curs; | |
675 | bool found = false; | |
676 | ||
677 | // Fall through the scope until we find a loop block | |
678 | for (curs = mScopeCursor; curs > 0 && !found; curs--) | |
679 | { | |
680 | switch (mScopeStack[curs].type) | |
681 | { | |
682 | case eForScope: | |
683 | case eWhileScope: | |
684 | case eDoScope: | |
685 | { | |
686 | buffer()->WriteDWord (dhGoto); | |
687 | buffer()->AddReference (mScopeStack[curs].mark1); | |
688 | found = true; | |
689 | } break; | |
690 | ||
691 | default: | |
692 | break; | |
693 | } | |
694 | } | |
695 | ||
696 | // No loop blocks | |
697 | if (found == false) | |
698 | Error ("`continue`-statement not inside a loop"); | |
699 | } | |
700 | ||
701 | // ============================================================================ | |
702 | // | |
703 | void BotscriptParser::ParseBlockEnd() | |
704 | { | |
705 | // Closing brace | |
706 | // If we're in the block stack, we're descending down from it now | |
707 | if (mScopeCursor > 0) | |
708 | { | |
709 | switch (SCOPE (0).type) | |
710 | { | |
711 | case eIfScope: | |
712 | // Adjust the closing mark. | |
713 | buffer()->AdjustMark (SCOPE (0).mark1); | |
714 | ||
715 | // We're returning from if, thus else can be next | |
716 | mCanElse = true; | |
717 | break; | |
718 | ||
719 | case eElseScope: | |
720 | // else instead uses mark1 for itself (so if expression | |
721 | // fails, jump to else), mark2 means end of else | |
722 | buffer()->AdjustMark (SCOPE (0).mark2); | |
723 | break; | |
724 | ||
725 | case eForScope: | |
726 | // write the incrementor at the end of the loop block | |
727 | buffer()->MergeAndDestroy (SCOPE (0).buffer1); | |
728 | case eWhileScope: | |
729 | // write down the instruction to go back to the start of the loop | |
730 | buffer()->WriteDWord (dhGoto); | |
731 | buffer()->AddReference (SCOPE (0).mark1); | |
732 | ||
733 | // Move the closing mark here since we're at the end of the while loop | |
734 | buffer()->AdjustMark (SCOPE (0).mark2); | |
735 | break; | |
736 | ||
737 | case eDoScope: | |
738 | { | |
739 | mLexer->MustGetNext (tkWhile); | |
740 | mLexer->MustGetNext (tkParenStart); | |
741 | mLexer->MustGetNext(); | |
742 | DataBuffer* expr = ParseExpression (EIntType); | |
743 | mLexer->MustGetNext (tkParenEnd); | |
744 | mLexer->MustGetNext (tkSemicolon); | |
745 | ||
746 | // If the condition runs true, go back to the start. | |
747 | buffer()->MergeAndDestroy (expr); | |
748 | buffer()->WriteDWord (dhIfGoto); | |
749 | buffer()->AddReference (SCOPE (0).mark1); | |
750 | break; | |
751 | } | |
752 | ||
753 | case eSwitchScope: | |
754 | { | |
755 | // Switch closes. Move down to the record buffer of | |
756 | // the lower block. | |
757 | if (SCOPE (1).casecursor != -1) | |
758 | mSwitchBuffer = SCOPE (1).casebuffers[SCOPE (1).casecursor]; | |
759 | else | |
760 | mSwitchBuffer = null; | |
761 | ||
762 | // If there was a default in the switch, write its header down now. | |
763 | // If not, write instruction to jump to the end of switch after | |
764 | // the headers (thus won't fall-through if no case matched) | |
765 | if (SCOPE (0).buffer1) | |
766 | buffer()->MergeAndDestroy (SCOPE (0).buffer1); | |
767 | else | |
768 | { | |
769 | buffer()->WriteDWord (dhDrop); | |
770 | buffer()->WriteDWord (dhGoto); | |
771 | buffer()->AddReference (SCOPE (0).mark1); | |
772 | } | |
773 | ||
774 | // Go through all of the buffers we | |
775 | // recorded down and write them. | |
776 | for (int u = 0; u < MAX_CASE; u++) | |
777 | { | |
778 | if (SCOPE (0).casebuffers[u] == null) | |
779 | continue; | |
780 | ||
781 | buffer()->AdjustMark (SCOPE (0).casemarks[u]); | |
782 | buffer()->MergeAndDestroy (SCOPE (0).casebuffers[u]); | |
783 | } | |
784 | ||
785 | // Move the closing mark here | |
786 | buffer()->AdjustMark (SCOPE (0).mark1); | |
787 | break; | |
788 | } | |
789 | ||
790 | case eUnknownScope: | |
791 | break; | |
792 | } | |
793 | ||
794 | // Descend down the stack | |
795 | mScopeCursor--; | |
796 | return; | |
797 | } | |
798 | ||
799 | int dataheader = (mCurrentMode == EEventMode) ? dhEndEvent : | |
800 | (mCurrentMode == EMainLoopMode) ? dhEndMainLoop : | |
801 | (mCurrentMode == EOnenterMode) ? dhEndOnEnter : | |
802 | (mCurrentMode == EOnexitMode) ? dhEndOnExit : -1; | |
803 | ||
804 | if (dataheader == -1) | |
805 | Error ("unexpected `}`"); | |
806 | ||
807 | // Data header must be written before mode is changed because | |
808 | // onenter and mainloop go into special buffers, and we want | |
809 | // the closing data headers into said buffers too. | |
810 | buffer()->WriteDWord (dataheader); | |
811 | mCurrentMode = ETopLevelMode; | |
812 | mLexer->GetNext (tkSemicolon); | |
813 | } | |
814 | ||
815 | // ============================================================================ | |
816 | // | |
817 | void BotscriptParser::ParseConst() | |
818 | { | |
819 | ConstantInfo info; | |
820 | ||
821 | // Get the type | |
822 | mLexer->MustGetNext(); | |
823 | String typestring = GetTokenString(); | |
824 | info.type = GetTypeByName (typestring); | |
825 | ||
826 | if (info.type == EUnknownType || info.type == EVoidType) | |
827 | Error ("unknown type `%1` for constant", typestring); | |
828 | ||
829 | mLexer->MustGetNext(); | |
830 | info.name = GetTokenString(); | |
831 | ||
832 | mLexer->MustGetNext (tkAssign); | |
833 | ||
834 | switch (info.type) | |
835 | { | |
836 | case EBoolType: | |
837 | case EIntType: | |
838 | { | |
839 | mLexer->MustGetNext (tkNumber); | |
840 | } break; | |
841 | ||
842 | case EStringType: | |
843 | { | |
844 | mLexer->MustGetNext (tkString); | |
845 | } break; | |
846 | ||
847 | case EUnknownType: | |
848 | case EVoidType: | |
849 | break; | |
850 | } | |
851 | ||
852 | info.val = mLexer->GetToken()->text; | |
853 | mConstants << info; | |
854 | ||
855 | mLexer->MustGetNext (tkSemicolon); | |
856 | } | |
857 | ||
858 | // ============================================================================ | |
859 | // | |
860 | void BotscriptParser::ParseLabel() | |
861 | { | |
862 | CheckNotToplevel(); | |
863 | String labelName = GetTokenString(); | |
864 | ByteMark* mark = null; | |
865 | ||
866 | // want no conflicts.. | |
867 | if (FindCommandByName (labelName)) | |
868 | Error ("label name `%1` conflicts with command name\n", labelName); | |
869 | ||
870 | if (FindGlobalVariable (labelName)) | |
871 | Error ("label name `%1` conflicts with variable\n", labelName); | |
872 | ||
873 | // See if a mark already exists for this label | |
89
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
874 | for (UndefinedLabel& label : mUndefinedLabels) |
88 | 875 | { |
89
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
876 | if (label.name != labelName) |
88 | 877 | continue; |
878 | ||
89
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
879 | mark = label.target; |
88 | 880 | buffer()->AdjustMark (mark); |
881 | ||
882 | // No longer undefined | |
89
029a330a9bef
- blargh. buffers weren't initialized properly
Teemu Piippo <crimsondusk64@gmail.com>
parents:
88
diff
changeset
|
883 | mUndefinedLabels.Remove (label); |
88 | 884 | break; |
885 | } | |
886 | ||
887 | // Not found in unmarked lists, define it now | |
888 | if (mark == null) | |
889 | buffer()->AddMark (labelName); | |
890 | ||
891 | mLexer->MustGetNext (tkColon); | |
892 | } | |
893 | ||
894 | // ============================================================================= | |
895 | // | |
896 | void BotscriptParser::ParseEventdef() | |
897 | { | |
898 | EventDefinition* e = new EventDefinition; | |
899 | ||
900 | mLexer->MustGetNext (tkNumber); | |
901 | e->number = GetTokenString().ToLong(); | |
902 | mLexer->MustGetNext (tkColon); | |
903 | mLexer->MustGetNext (tkSymbol); | |
904 | e->name = mLexer->GetToken()->text; | |
905 | mLexer->MustGetNext (tkParenStart); | |
906 | mLexer->MustGetNext (tkParenEnd); | |
907 | mLexer->MustGetNext (tkSemicolon); | |
908 | AddEvent (e); | |
909 | } | |
910 | ||
911 | // ============================================================================= | |
912 | // | |
913 | void BotscriptParser::ParseFuncdef() | |
914 | { | |
915 | CommandInfo* comm = new CommandInfo; | |
916 | ||
917 | // Number | |
918 | mLexer->MustGetNext (tkNumber); | |
919 | comm->number = mLexer->GetToken()->text.ToLong(); | |
920 | mLexer->MustGetNext (tkColon); | |
921 | ||
922 | // Name | |
923 | mLexer->MustGetNext (tkSymbol); | |
924 | comm->name = mLexer->GetToken()->text; | |
925 | mLexer->MustGetNext (tkColon); | |
926 | ||
927 | // Return value | |
928 | mLexer->MustGetAnyOf ({tkInt, tkVoid, tkBool, tkStr}); | |
929 | comm->returnvalue = GetTypeByName (mLexer->GetToken()->text); // TODO | |
930 | assert (comm->returnvalue != -1); | |
931 | mLexer->MustGetNext (tkColon); | |
932 | ||
933 | // Num args | |
934 | mLexer->MustGetNext (tkNumber); | |
935 | comm->numargs = mLexer->GetToken()->text.ToLong(); | |
936 | mLexer->MustGetNext (tkColon); | |
937 | ||
938 | // Max args | |
939 | mLexer->MustGetNext (tkNumber); | |
940 | comm->maxargs = mLexer->GetToken()->text.ToLong(); | |
941 | ||
942 | // Argument types | |
943 | int curarg = 0; | |
944 | ||
945 | while (curarg < comm->maxargs) | |
946 | { | |
947 | CommandArgument arg; | |
948 | mLexer->MustGetNext (tkColon); | |
949 | mLexer->MustGetAnyOf ({tkInt, tkBool, tkStr}); | |
950 | EType type = GetTypeByName (mLexer->GetToken()->text); | |
951 | assert (type != -1 && type != EVoidType); | |
952 | arg.type = type; | |
953 | ||
954 | mLexer->MustGetNext (tkParenStart); | |
955 | mLexer->MustGetNext (tkSymbol); | |
956 | arg.name = mLexer->GetToken()->text; | |
957 | ||
958 | // If this is an optional parameter, we need the default value. | |
959 | if (curarg >= comm->numargs) | |
960 | { | |
961 | mLexer->MustGetNext (tkAssign); | |
962 | ||
963 | switch (type) | |
964 | { | |
965 | case EIntType: | |
966 | case EBoolType: | |
967 | mLexer->MustGetNext (tkNumber); | |
968 | break; | |
969 | ||
970 | case EStringType: | |
971 | mLexer->MustGetNext (tkString); | |
972 | break; | |
973 | ||
974 | case EUnknownType: | |
975 | case EVoidType: | |
976 | break; | |
977 | } | |
978 | ||
979 | arg.defvalue = mLexer->GetToken()->text.ToLong(); | |
980 | } | |
981 | ||
982 | mLexer->MustGetNext (tkParenEnd); | |
983 | comm->args << arg; | |
984 | curarg++; | |
985 | } | |
986 | ||
987 | mLexer->MustGetNext (tkSemicolon); | |
988 | AddCommandDefinition (comm); | |
989 | } | |
990 | ||
991 | // ============================================================================ | |
992 | // Parses a command call | |
993 | DataBuffer* BotscriptParser::ParseCommand (CommandInfo* comm) | |
994 | { | |
995 | DataBuffer* r = new DataBuffer (64); | |
996 | ||
997 | if (mCurrentMode == ETopLevelMode) | |
998 | Error ("command call at top level"); | |
999 | ||
1000 | mLexer->MustGetNext (tkParenStart); | |
1001 | mLexer->MustGetNext(); | |
1002 | ||
1003 | int curarg = 0; | |
1004 | ||
1005 | while (1) | |
1006 | { | |
1007 | if (TokenIs (tkParenEnd)) | |
1008 | { | |
1009 | if (curarg < comm->numargs) | |
1010 | Error ("too few arguments passed to %1\n\tusage is: %2", | |
1011 | comm->name, comm->GetSignature()); | |
1012 | ||
1013 | break; | |
1014 | curarg++; | |
1015 | } | |
1016 | ||
1017 | if (curarg >= comm->maxargs) | |
1018 | Error ("too many arguments passed to %1\n\tusage is: %2", | |
1019 | comm->name, comm->GetSignature()); | |
1020 | ||
1021 | r->MergeAndDestroy (ParseExpression (comm->args[curarg].type)); | |
1022 | mLexer->MustGetNext(); | |
1023 | ||
1024 | if (curarg < comm->numargs - 1) | |
1025 | { | |
1026 | mLexer->TokenMustBe (tkComma); | |
1027 | mLexer->MustGetNext(); | |
1028 | } | |
1029 | else if (curarg < comm->maxargs - 1) | |
1030 | { | |
1031 | // Can continue, but can terminate as well. | |
1032 | if (TokenIs (tkParenEnd)) | |
1033 | { | |
1034 | curarg++; | |
1035 | break; | |
1036 | } | |
1037 | else | |
1038 | { | |
1039 | mLexer->TokenMustBe (tkComma); | |
1040 | mLexer->MustGetNext(); | |
1041 | } | |
1042 | } | |
1043 | ||
1044 | curarg++; | |
1045 | } | |
1046 | ||
1047 | // If the script skipped any optional arguments, fill in defaults. | |
1048 | while (curarg < comm->maxargs) | |
1049 | { | |
1050 | r->WriteDWord (dhPushNumber); | |
1051 | r->WriteDWord (comm->args[curarg].defvalue); | |
1052 | curarg++; | |
1053 | } | |
1054 | ||
1055 | r->WriteDWord (dhCommand); | |
1056 | r->WriteDWord (comm->number); | |
1057 | r->WriteDWord (comm->maxargs); | |
1058 | ||
1059 | return r; | |
1060 | } | |
1061 | ||
1062 | // ============================================================================ | |
1063 | // Is the given operator an assignment operator? | |
1064 | // | |
1065 | static bool IsAssignmentOperator (int oper) | |
1066 | { | |
1067 | switch (oper) | |
1068 | { | |
1069 | case OPER_ASSIGNADD: | |
1070 | case OPER_ASSIGNSUB: | |
1071 | case OPER_ASSIGNMUL: | |
1072 | case OPER_ASSIGNDIV: | |
1073 | case OPER_ASSIGNMOD: | |
1074 | case OPER_ASSIGNLEFTSHIFT: | |
1075 | case OPER_ASSIGNRIGHTSHIFT: | |
1076 | case OPER_ASSIGN: | |
1077 | return true; | |
1078 | } | |
1079 | ||
1080 | return false; | |
1081 | } | |
1082 | ||
1083 | // ============================================================================ | |
1084 | // Finds an operator's corresponding dataheader | |
1085 | // | |
1086 | static word GetDataHeaderByOperator (ScriptVariable* var, int oper) | |
1087 | { | |
1088 | if (IsAssignmentOperator (oper)) | |
1089 | { | |
1090 | if (var == null) | |
1091 | Error ("operator %d requires left operand to be a variable\n", oper); | |
1092 | ||
1093 | // TODO: At the moment, vars only are global | |
1094 | // OPER_ASSIGNLEFTSHIFT and OPER_ASSIGNRIGHTSHIFT do not | |
1095 | // have data headers, instead they are expanded out in | |
1096 | // the operator Parser | |
1097 | switch (oper) | |
1098 | { | |
1099 | case OPER_ASSIGNADD: return dhAddGlobalVar; | |
1100 | case OPER_ASSIGNSUB: return dhSubtractGlobalVar; | |
1101 | case OPER_ASSIGNMUL: return dhMultiplyGlobalVar; | |
1102 | case OPER_ASSIGNDIV: return dhDivideGlobalVar; | |
1103 | case OPER_ASSIGNMOD: return dhModGlobalVar; | |
1104 | case OPER_ASSIGN: return dhAssignGlobalVar; | |
1105 | ||
1106 | default: Error ("bad assignment operator!\n"); | |
1107 | } | |
1108 | } | |
1109 | ||
1110 | switch (oper) | |
1111 | { | |
1112 | case OPER_ADD: return dhAdd; | |
1113 | case OPER_SUBTRACT: return dhSubtract; | |
1114 | case OPER_MULTIPLY: return dhMultiply; | |
1115 | case OPER_DIVIDE: return dhDivide; | |
1116 | case OPER_MODULUS: return dhModulus; | |
1117 | case OPER_EQUALS: return dhEquals; | |
1118 | case OPER_NOTEQUALS: return dhNotEquals; | |
1119 | case OPER_LESSTHAN: return dhLessThan; | |
1120 | case OPER_GREATERTHAN: return dhGreaterThan; | |
1121 | case OPER_LESSTHANEQUALS: return dhAtMost; | |
1122 | case OPER_GREATERTHANEQUALS: return dhAtLeast; | |
1123 | case OPER_LEFTSHIFT: return dhLeftShift; | |
1124 | case OPER_RIGHTSHIFT: return dhRightShift; | |
1125 | case OPER_OR: return dhOrLogical; | |
1126 | case OPER_AND: return dhAndLogical; | |
1127 | case OPER_BITWISEOR: return dhOrBitwise; | |
1128 | case OPER_BITWISEEOR: return dhEorBitwise; | |
1129 | case OPER_BITWISEAND: return dhAndBitwise; | |
1130 | } | |
1131 | ||
1132 | Error ("DataHeaderByOperator: couldn't find dataheader for operator %d!\n", oper); | |
1133 | return 0; | |
1134 | } | |
1135 | ||
1136 | // ============================================================================ | |
1137 | // Parses an expression, potentially recursively | |
1138 | // | |
1139 | DataBuffer* BotscriptParser::ParseExpression (EType reqtype) | |
1140 | { | |
1141 | DataBuffer* retbuf = new DataBuffer (64); | |
1142 | ||
1143 | // Parse first operand | |
1144 | retbuf->MergeAndDestroy (ParseExprValue (reqtype)); | |
1145 | ||
1146 | // Parse any and all operators we get | |
1147 | int oper; | |
1148 | ||
1149 | while ( (oper = ParseOperator (true)) != -1) | |
1150 | { | |
1151 | // We peeked the operator, move forward now | |
1152 | mLexer->Skip(); | |
1153 | ||
1154 | // Can't be an assignement operator, those belong in assignments. | |
1155 | if (IsAssignmentOperator (oper)) | |
1156 | Error ("assignment operator inside expression"); | |
1157 | ||
1158 | // Parse the right operand. | |
1159 | mLexer->MustGetNext(); | |
1160 | DataBuffer* rb = ParseExprValue (reqtype); | |
1161 | ||
1162 | if (oper == OPER_TERNARY) | |
1163 | { | |
1164 | // Ternary operator requires - naturally - a third operand. | |
1165 | mLexer->MustGetNext (tkColon); | |
1166 | mLexer->MustGetNext(); | |
1167 | DataBuffer* tb = ParseExprValue (reqtype); | |
1168 | ||
1169 | // It also is handled differently: there isn't a dataheader for ternary | |
1170 | // operator. Instead, we abuse PUSHNUMBER and IFNOTGOTO for this. | |
1171 | // Behold, big block of writing madness! :P | |
1172 | ByteMark* mark1 = retbuf->AddMark (""); // start of "else" case | |
1173 | ByteMark* mark2 = retbuf->AddMark (""); // end of expression | |
1174 | retbuf->WriteDWord (dhIfNotGoto); // if the first operand (condition) | |
1175 | retbuf->AddReference (mark1); // didn't eval true, jump into mark1 | |
1176 | retbuf->MergeAndDestroy (rb); // otherwise, perform second operand (true case) | |
1177 | retbuf->WriteDWord (dhGoto); // afterwards, jump to the end, which is | |
1178 | retbuf->AddReference (mark2); // marked by mark2. | |
1179 | retbuf->AdjustMark (mark1); // move mark1 at the end of the true case | |
1180 | retbuf->MergeAndDestroy (tb); // perform third operand (false case) | |
1181 | retbuf->AdjustMark (mark2); // move the ending mark2 here | |
1182 | } | |
1183 | else | |
1184 | { | |
1185 | // write to buffer | |
1186 | retbuf->MergeAndDestroy (rb); | |
1187 | retbuf->WriteDWord (GetDataHeaderByOperator (null, oper)); | |
1188 | } | |
1189 | } | |
1190 | ||
1191 | return retbuf; | |
1192 | } | |
1193 | ||
1194 | // ============================================================================ | |
1195 | // Parses an operator string. Returns the operator number code. | |
1196 | // | |
1197 | #define ISNEXT(C) (mLexer->PeekNextString (peek ? 1 : 0) == C) | |
1198 | ||
1199 | int BotscriptParser::ParseOperator (bool peek) | |
1200 | { | |
1201 | String oper; | |
1202 | ||
1203 | if (peek) | |
1204 | oper += mLexer->PeekNextString(); | |
1205 | else | |
1206 | oper += GetTokenString(); | |
1207 | ||
1208 | if (-oper == "strlen") | |
1209 | return OPER_STRLEN; | |
1210 | ||
1211 | // Check one-char operators | |
1212 | bool equalsnext = ISNEXT ("="); | |
1213 | ||
1214 | int o = (oper == "=" && !equalsnext) ? OPER_ASSIGN : | |
1215 | (oper == ">" && !equalsnext && !ISNEXT (">")) ? OPER_GREATERTHAN : | |
1216 | (oper == "<" && !equalsnext && !ISNEXT ("<")) ? OPER_LESSTHAN : | |
1217 | (oper == "&" && !ISNEXT ("&")) ? OPER_BITWISEAND : | |
1218 | (oper == "|" && !ISNEXT ("|")) ? OPER_BITWISEOR : | |
1219 | (oper == "+" && !equalsnext) ? OPER_ADD : | |
1220 | (oper == "-" && !equalsnext) ? OPER_SUBTRACT : | |
1221 | (oper == "*" && !equalsnext) ? OPER_MULTIPLY : | |
1222 | (oper == "/" && !equalsnext) ? OPER_DIVIDE : | |
1223 | (oper == "%" && !equalsnext) ? OPER_MODULUS : | |
1224 | (oper == "^") ? OPER_BITWISEEOR : | |
1225 | (oper == "?") ? OPER_TERNARY : | |
1226 | -1; | |
1227 | ||
1228 | if (o != -1) | |
1229 | { | |
1230 | return o; | |
1231 | } | |
1232 | ||
1233 | // Two-char operators | |
1234 | oper += mLexer->PeekNextString (peek ? 1 : 0); | |
1235 | equalsnext = mLexer->PeekNextString (peek ? 2 : 1) == ("="); | |
1236 | ||
1237 | o = (oper == "+=") ? OPER_ASSIGNADD : | |
1238 | (oper == "-=") ? OPER_ASSIGNSUB : | |
1239 | (oper == "*=") ? OPER_ASSIGNMUL : | |
1240 | (oper == "/=") ? OPER_ASSIGNDIV : | |
1241 | (oper == "%=") ? OPER_ASSIGNMOD : | |
1242 | (oper == "==") ? OPER_EQUALS : | |
1243 | (oper == "!=") ? OPER_NOTEQUALS : | |
1244 | (oper == ">=") ? OPER_GREATERTHANEQUALS : | |
1245 | (oper == "<=") ? OPER_LESSTHANEQUALS : | |
1246 | (oper == "&&") ? OPER_AND : | |
1247 | (oper == "||") ? OPER_OR : | |
1248 | (oper == "<<" && !equalsnext) ? OPER_LEFTSHIFT : | |
1249 | (oper == ">>" && !equalsnext) ? OPER_RIGHTSHIFT : | |
1250 | -1; | |
1251 | ||
1252 | if (o != -1) | |
1253 | { | |
1254 | mLexer->MustGetNext(); | |
1255 | return o; | |
1256 | } | |
1257 | ||
1258 | // Three-char opers | |
1259 | oper += mLexer->PeekNextString (peek ? 2 : 1); | |
1260 | o = oper == "<<=" ? OPER_ASSIGNLEFTSHIFT : | |
1261 | oper == ">>=" ? OPER_ASSIGNRIGHTSHIFT : | |
1262 | -1; | |
1263 | ||
1264 | if (o != -1) | |
1265 | { | |
1266 | mLexer->MustGetNext(); | |
1267 | mLexer->MustGetNext(); | |
1268 | } | |
1269 | ||
1270 | return o; | |
1271 | } | |
1272 | ||
1273 | // ============================================================================ | |
1274 | // | |
1275 | String BotscriptParser::ParseFloat() | |
1276 | { | |
1277 | mLexer->TokenMustBe (tkNumber); | |
1278 | String floatstring = GetTokenString(); | |
1279 | Lexer::Token tok; | |
1280 | ||
1281 | // Go after the decimal point | |
1282 | if (mLexer->PeekNext (&tok) && tok.type == tkDot) | |
1283 | { | |
1284 | mLexer->Skip(); | |
1285 | mLexer->MustGetNext (tkNumber); | |
1286 | floatstring += "."; | |
1287 | floatstring += GetTokenString(); | |
1288 | } | |
1289 | ||
1290 | return floatstring; | |
1291 | } | |
1292 | ||
1293 | // ============================================================================ | |
1294 | // Parses a value in the expression and returns the data needed to push | |
1295 | // it, contained in a data buffer. A value can be either a variable, a command, | |
1296 | // a literal or an expression. | |
1297 | // | |
1298 | DataBuffer* BotscriptParser::ParseExprValue (EType reqtype) | |
1299 | { | |
1300 | DataBuffer* b = new DataBuffer (16); | |
1301 | ScriptVariable* g; | |
1302 | ||
1303 | // Prefixing "!" means negation. | |
1304 | bool negate = TokenIs (tkExclamationMark); | |
1305 | ||
1306 | if (negate) // Jump past the "!" | |
1307 | mLexer->Skip(); | |
1308 | ||
1309 | if (TokenIs (tkParenStart)) | |
1310 | { | |
1311 | // Expression | |
1312 | mLexer->MustGetNext(); | |
1313 | DataBuffer* c = ParseExpression (reqtype); | |
1314 | b->MergeAndDestroy (c); | |
1315 | mLexer->MustGetNext (tkParenEnd); | |
1316 | } | |
1317 | else if (CommandInfo* comm = FindCommandByName (GetTokenString())) | |
1318 | { | |
1319 | delete b; | |
1320 | ||
1321 | // Command | |
1322 | if (reqtype && comm->returnvalue != reqtype) | |
1323 | Error ("%1 returns an incompatible data type", comm->name); | |
1324 | ||
1325 | b = ParseCommand (comm); | |
1326 | } | |
1327 | else if (ConstantInfo* constant = FindConstant (GetTokenString())) | |
1328 | { | |
1329 | // Type check | |
1330 | if (reqtype != constant->type) | |
1331 | Error ("constant `%1` is %2, expression requires %3\n", | |
1332 | constant->name, GetTypeName (constant->type), | |
1333 | GetTypeName (reqtype)); | |
1334 | ||
1335 | switch (constant->type) | |
1336 | { | |
1337 | case EBoolType: | |
1338 | case EIntType: | |
1339 | { | |
1340 | b->WriteDWord (dhPushNumber); | |
1341 | b->WriteDWord (constant->val.ToLong()); | |
1342 | break; | |
1343 | } | |
1344 | ||
1345 | case EStringType: | |
1346 | { | |
1347 | b->WriteStringIndex (constant->val); | |
1348 | break; | |
1349 | } | |
1350 | ||
1351 | case EVoidType: | |
1352 | case EUnknownType: | |
1353 | break; | |
1354 | } | |
1355 | } | |
1356 | else if ((g = FindGlobalVariable (GetTokenString()))) | |
1357 | { | |
1358 | // Global variable | |
1359 | b->WriteDWord (dhPushGlobalVar); | |
1360 | b->WriteDWord (g->index); | |
1361 | } | |
1362 | else | |
1363 | { | |
1364 | // If nothing else, check for literal | |
1365 | switch (reqtype) | |
1366 | { | |
1367 | case EVoidType: | |
1368 | case EUnknownType: | |
1369 | { | |
1370 | Error ("unknown identifier `%1` (expected keyword, function or variable)", GetTokenString()); | |
1371 | break; | |
1372 | } | |
1373 | ||
1374 | case EBoolType: | |
1375 | case EIntType: | |
1376 | { | |
1377 | mLexer->TokenMustBe (tkNumber); | |
1378 | ||
1379 | // All values are written unsigned - thus we need to write the value's | |
1380 | // absolute value, followed by an unary minus for negatives. | |
1381 | b->WriteDWord (dhPushNumber); | |
1382 | ||
1383 | long v = GetTokenString().ToLong(); | |
1384 | b->WriteDWord (static_cast<word> (abs (v))); | |
1385 | ||
1386 | if (v < 0) | |
1387 | b->WriteDWord (dhUnaryMinus); | |
1388 | ||
1389 | break; | |
1390 | } | |
1391 | ||
1392 | case EStringType: | |
1393 | { | |
1394 | // PushToStringTable either returns the string index of the | |
1395 | // string if it finds it in the table, or writes it to the | |
1396 | // table and returns it index if it doesn't find it there. | |
1397 | mLexer->TokenMustBe (tkString); | |
1398 | b->WriteStringIndex (GetTokenString()); | |
1399 | break; | |
1400 | } | |
1401 | } | |
1402 | } | |
1403 | ||
1404 | // Negate it now if desired | |
1405 | if (negate) | |
1406 | b->WriteDWord (dhNegateLogical); | |
1407 | ||
1408 | return b; | |
1409 | } | |
1410 | ||
1411 | // ============================================================================ | |
1412 | // Parses an assignment. An assignment starts with a variable name, followed | |
1413 | // by an assignment operator, followed by an expression value. Expects current | |
1414 | // token to be the name of the variable, and expects the variable to be given. | |
1415 | // | |
1416 | DataBuffer* BotscriptParser::ParseAssignment (ScriptVariable* var) | |
1417 | { | |
1418 | // Get an operator | |
1419 | mLexer->MustGetNext(); | |
1420 | int oper = ParseOperator(); | |
1421 | ||
1422 | if (IsAssignmentOperator (oper) == false) | |
1423 | Error ("expected assignment operator"); | |
1424 | ||
1425 | if (mCurrentMode == ETopLevelMode) | |
1426 | Error ("can't alter variables at top level"); | |
1427 | ||
1428 | // Parse the right operand | |
1429 | mLexer->MustGetNext(); | |
1430 | DataBuffer* retbuf = new DataBuffer; | |
1431 | DataBuffer* expr = ParseExpression (var->type); | |
1432 | ||
1433 | // <<= and >>= do not have data headers. Solution: expand them. | |
1434 | // a <<= b -> a = a << b | |
1435 | // a >>= b -> a = a >> b | |
1436 | if (oper == OPER_ASSIGNLEFTSHIFT || oper == OPER_ASSIGNRIGHTSHIFT) | |
1437 | { | |
1438 | retbuf->WriteDWord (var->IsGlobal() ? dhPushGlobalVar : dhPushLocalVar); | |
1439 | retbuf->WriteDWord (var->index); | |
1440 | retbuf->MergeAndDestroy (expr); | |
1441 | retbuf->WriteDWord ((oper == OPER_ASSIGNLEFTSHIFT) ? dhLeftShift : dhRightShift); | |
1442 | retbuf->WriteDWord (var->IsGlobal() ? dhAssignGlobalVar : dhAssignLocalVar); | |
1443 | retbuf->WriteDWord (var->index); | |
1444 | } | |
1445 | else | |
1446 | { | |
1447 | retbuf->MergeAndDestroy (expr); | |
1448 | long dh = GetDataHeaderByOperator (var, oper); | |
1449 | retbuf->WriteDWord (dh); | |
1450 | retbuf->WriteDWord (var->index); | |
1451 | } | |
1452 | ||
1453 | return retbuf; | |
1454 | } | |
1455 | ||
1456 | // ============================================================================ | |
1457 | // | |
1458 | void BotscriptParser::PushScope() | |
1459 | { | |
1460 | mScopeCursor++; | |
1461 | ||
1462 | if (mScopeCursor >= MAX_SCOPE) | |
1463 | Error ("too deep scope"); | |
1464 | ||
1465 | ScopeInfo* info = &SCOPE (0); | |
1466 | info->type = eUnknownScope; | |
1467 | info->mark1 = null; | |
1468 | info->mark2 = null; | |
1469 | info->buffer1 = null; | |
1470 | info->casecursor = -1; | |
1471 | ||
1472 | for (int i = 0; i < MAX_CASE; i++) | |
1473 | { | |
1474 | info->casemarks[i] = null; | |
1475 | info->casebuffers[i] = null; | |
1476 | info->casenumbers[i] = -1; | |
1477 | } | |
1478 | } | |
1479 | ||
1480 | // ============================================================================ | |
1481 | // | |
1482 | DataBuffer* BotscriptParser::ParseStatement() | |
1483 | { | |
1484 | if (FindConstant (GetTokenString())) // There should not be constants here. | |
1485 | Error ("invalid use for constant\n"); | |
1486 | ||
1487 | // If it's a variable, expect assignment. | |
1488 | if (ScriptVariable* var = FindGlobalVariable (GetTokenString())) | |
1489 | return ParseAssignment (var); | |
1490 | ||
1491 | return null; | |
1492 | } | |
1493 | ||
1494 | // ============================================================================ | |
1495 | // | |
1496 | void BotscriptParser::AddSwitchCase (DataBuffer* b) | |
1497 | { | |
1498 | ScopeInfo* info = &SCOPE (0); | |
1499 | ||
1500 | info->casecursor++; | |
1501 | ||
1502 | if (info->casecursor >= MAX_CASE) | |
1503 | Error ("too many cases in one switch"); | |
1504 | ||
1505 | // Init a mark for the case buffer | |
1506 | ByteMark* casemark = buffer()->AddMark (""); | |
1507 | info->casemarks[info->casecursor] = casemark; | |
1508 | ||
1509 | // Add a reference to the mark. "case" and "default" both | |
1510 | // add the necessary bytecode before the reference. | |
1511 | if (b) | |
1512 | b->AddReference (casemark); | |
1513 | else | |
1514 | buffer()->AddReference (casemark); | |
1515 | ||
1516 | // Init a buffer for the case block and tell the object | |
1517 | // writer to record all written data to it. | |
1518 | info->casebuffers[info->casecursor] = mSwitchBuffer = new DataBuffer; | |
1519 | } | |
1520 | ||
1521 | // ============================================================================ | |
1522 | // | |
1523 | ConstantInfo* BotscriptParser::FindConstant (const String& tok) | |
1524 | { | |
1525 | for (int i = 0; i < mConstants.Size(); i++) | |
1526 | if (mConstants[i].name == tok) | |
1527 | return &mConstants[i]; | |
1528 | ||
1529 | return null; | |
1530 | } | |
1531 | ||
1532 | // ============================================================================ | |
1533 | // | |
1534 | bool BotscriptParser::TokenIs (EToken a) | |
1535 | { | |
1536 | return (mLexer->GetTokenType() == a); | |
1537 | } | |
1538 | ||
1539 | // ============================================================================ | |
1540 | // | |
1541 | String BotscriptParser::GetTokenString() | |
1542 | { | |
1543 | return mLexer->GetToken()->text; | |
1544 | } | |
1545 | ||
1546 | // ============================================================================ | |
1547 | // | |
1548 | String BotscriptParser::DescribePosition() const | |
1549 | { | |
1550 | Lexer::Token* tok = mLexer->GetToken(); | |
1551 | return tok->file + ":" + String (tok->line) + ":" + String (tok->column); | |
1552 | } | |
1553 | ||
1554 | // ============================================================================ | |
1555 | // | |
1556 | DataBuffer* BotscriptParser::buffer() | |
1557 | { | |
1558 | if (mSwitchBuffer != null) | |
1559 | return mSwitchBuffer; | |
1560 | ||
1561 | if (mCurrentMode == EMainLoopMode) | |
1562 | return mMainLoopBuffer; | |
1563 | ||
1564 | if (mCurrentMode == EOnenterMode) | |
1565 | return mOnEnterBuffer; | |
1566 | ||
1567 | return mMainBuffer; | |
1568 | } | |
1569 | ||
1570 | // ============================================================================ | |
1571 | // | |
1572 | void BotscriptParser::writeMemberBuffers() | |
1573 | { | |
1574 | // If there was no mainloop defined, write a dummy one now. | |
1575 | if (mGotMainLoop == false) | |
1576 | { | |
1577 | mMainLoopBuffer->WriteDWord (dhMainLoop); | |
1578 | mMainLoopBuffer->WriteDWord (dhEndMainLoop); | |
1579 | } | |
1580 | ||
1581 | // Write the onenter and mainloop buffers, in that order in particular. | |
1582 | for (DataBuffer** bufp : List<DataBuffer**> ({&mOnEnterBuffer, &mMainLoopBuffer})) | |
1583 | { | |
1584 | buffer()->MergeAndDestroy (*bufp); | |
1585 | ||
1586 | // Clear the buffer afterwards for potential next state | |
1587 | *bufp = new DataBuffer; | |
1588 | } | |
1589 | ||
1590 | // Next state definitely has no mainloop yet | |
1591 | mGotMainLoop = false; | |
1592 | } | |
1593 | ||
1594 | // ============================================================================ | |
1595 | // | |
1596 | // Write string table | |
1597 | // | |
1598 | void BotscriptParser::WriteStringTable() | |
1599 | { | |
1600 | int stringcount = CountStringsInTable(); | |
1601 | ||
1602 | if (stringcount == 0) | |
1603 | return; | |
1604 | ||
1605 | // Write header | |
1606 | mMainBuffer->WriteDWord (dhStringList); | |
1607 | mMainBuffer->WriteDWord (stringcount); | |
1608 | ||
1609 | // Write all strings | |
1610 | for (int i = 0; i < stringcount; i++) | |
1611 | mMainBuffer->WriteString (GetStringTable()[i]); | |
1612 | } | |
1613 | ||
1614 | // ============================================================================ | |
1615 | // | |
1616 | // Write the compiled bytecode to a file | |
1617 | // | |
1618 | void BotscriptParser::WriteToFile (String outfile) | |
1619 | { | |
1620 | FILE* fp = fopen (outfile, "w"); | |
1621 | ||
1622 | if (fp == null) | |
1623 | Error ("couldn't open %1 for writing: %2", outfile, strerror (errno)); | |
1624 | ||
1625 | // First, resolve references | |
1626 | for (MarkReference* ref : mMainBuffer->GetReferences()) | |
1627 | { | |
1628 | // Substitute the placeholder with the mark position | |
1629 | for (int v = 0; v < 4; v++) | |
1630 | mMainBuffer->GetBuffer()[ref->pos + v] = ((ref->target->pos) << (8 * v)) & 0xFF; | |
1631 | ||
1632 | Print ("reference at %1 resolved to mark at %2\n", ref->pos, ref->target->pos); | |
1633 | } | |
1634 | ||
1635 | // Then, dump the main buffer to the file | |
1636 | fwrite (mMainBuffer->GetBuffer(), 1, mMainBuffer->GetWrittenSize(), fp); | |
1637 | Print ("-- %1 byte%s1 written to %2\n", mMainBuffer->GetWrittenSize(), outfile); | |
1638 | fclose (fp); | |
1639 | } |