xref: /llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.cpp (revision 11adbacac86a740724d3bfe8f7de6563bf71a617)
1 //===-- ResourceScriptParser.cpp --------------------------------*- C++-*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 //
10 // This implements the parser defined in ResourceScriptParser.h.
11 //
12 //===---------------------------------------------------------------------===//
13 
14 #include "ResourceScriptParser.h"
15 #include "llvm/Option/ArgList.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/Process.h"
19 
20 // Take an expression returning llvm::Error and forward the error if it exists.
21 #define RETURN_IF_ERROR(Expr)                                                  \
22   if (auto Err = (Expr))                                                       \
23     return std::move(Err);
24 
25 // Take an expression returning llvm::Expected<T> and assign it to Var or
26 // forward the error out of the function.
27 #define ASSIGN_OR_RETURN(Var, Expr)                                            \
28   auto Var = (Expr);                                                           \
29   if (!Var)                                                                    \
30     return Var.takeError();
31 
32 namespace llvm {
33 namespace rc {
34 
35 RCParser::ParserError::ParserError(const Twine &Expected, const LocIter CurLoc,
36                                    const LocIter End)
37     : ErrorLoc(CurLoc), FileEnd(End) {
38   CurMessage = "Error parsing file: expected " + Expected.str() + ", got " +
39                (CurLoc == End ? "<EOF>" : CurLoc->value()).str();
40 }
41 
42 char RCParser::ParserError::ID = 0;
43 
44 RCParser::RCParser(std::vector<RCToken> TokenList)
45     : Tokens(std::move(TokenList)), CurLoc(Tokens.begin()), End(Tokens.end()) {}
46 
47 bool RCParser::isEof() const { return CurLoc == End; }
48 
49 RCParser::ParseType RCParser::parseSingleResource() {
50   // The first thing we read is usually a resource's name. However, in some
51   // cases (LANGUAGE and STRINGTABLE) the resources don't have their names
52   // and the first token to be read is the type.
53   ASSIGN_OR_RETURN(NameToken, readTypeOrName());
54 
55   if (NameToken->equalsLower("LANGUAGE"))
56     return parseLanguageResource();
57   else if (NameToken->equalsLower("STRINGTABLE"))
58     return parseStringTableResource();
59 
60   // If it's not an unnamed resource, what we've just read is a name. Now,
61   // read resource type;
62   ASSIGN_OR_RETURN(TypeToken, readTypeOrName());
63 
64   ParseType Result = std::unique_ptr<RCResource>();
65   (void)!Result;
66 
67   if (TypeToken->equalsLower("ACCELERATORS"))
68     Result = parseAcceleratorsResource();
69   else if (TypeToken->equalsLower("BITMAP"))
70     Result = parseBitmapResource();
71   else if (TypeToken->equalsLower("CURSOR"))
72     Result = parseCursorResource();
73   else if (TypeToken->equalsLower("DIALOG"))
74     Result = parseDialogResource(false);
75   else if (TypeToken->equalsLower("DIALOGEX"))
76     Result = parseDialogResource(true);
77   else if (TypeToken->equalsLower("HTML"))
78     Result = parseHTMLResource();
79   else if (TypeToken->equalsLower("ICON"))
80     Result = parseIconResource();
81   else if (TypeToken->equalsLower("MENU"))
82     Result = parseMenuResource();
83   else if (TypeToken->equalsLower("RCDATA"))
84     Result = parseUserDefinedResource(RkRcData);
85   else if (TypeToken->equalsLower("VERSIONINFO"))
86     Result = parseVersionInfoResource();
87   else
88     Result = parseUserDefinedResource(*TypeToken);
89 
90   if (Result)
91     (*Result)->setName(*NameToken);
92 
93   return Result;
94 }
95 
96 bool RCParser::isNextTokenKind(Kind TokenKind) const {
97   return !isEof() && look().kind() == TokenKind;
98 }
99 
100 const RCToken &RCParser::look() const {
101   assert(!isEof());
102   return *CurLoc;
103 }
104 
105 const RCToken &RCParser::read() {
106   assert(!isEof());
107   return *CurLoc++;
108 }
109 
110 void RCParser::consume() {
111   assert(!isEof());
112   CurLoc++;
113 }
114 
115 // An integer description might consist of a single integer or
116 // an arithmetic expression evaluating to the integer. The expressions
117 // can contain the following tokens: <int> ( ) + - | & ~. Their meaning
118 // is the same as in C++.
119 // The operators in the original RC implementation have the following
120 // precedence:
121 //   1) Unary operators (- ~),
122 //   2) Binary operators (+ - & |), with no precedence.
123 //
124 // The following grammar is used to parse the expressions Exp1:
125 //   Exp1 ::= Exp2 || Exp1 + Exp2 || Exp1 - Exp2 || Exp1 | Exp2 || Exp1 & Exp2
126 //   Exp2 ::= -Exp2 || ~Exp2 || Int || (Exp1).
127 // (More conveniently, Exp1 is a non-empty sequence of Exp2 expressions,
128 // separated by binary operators.)
129 //
130 // Expressions of type Exp1 are read by parseIntExpr1(Inner) method, while Exp2
131 // is read by parseIntExpr2().
132 //
133 // The original Microsoft tool handles multiple unary operators incorrectly.
134 // For example, in 16-bit little-endian integers:
135 //    1 => 01 00, -1 => ff ff, --1 => ff ff, ---1 => 01 00;
136 //    1 => 01 00, ~1 => fe ff, ~~1 => fd ff, ~~~1 => fc ff.
137 // Our implementation differs from the original one and handles these
138 // operators correctly:
139 //    1 => 01 00, -1 => ff ff, --1 => 01 00, ---1 => ff ff;
140 //    1 => 01 00, ~1 => fe ff, ~~1 => 01 00, ~~~1 => fe ff.
141 
142 Expected<RCInt> RCParser::readInt() { return parseIntExpr1(); }
143 
144 Expected<RCInt> RCParser::parseIntExpr1() {
145   // Exp1 ::= Exp2 || Exp1 + Exp2 || Exp1 - Exp2 || Exp1 | Exp2 || Exp1 & Exp2.
146   ASSIGN_OR_RETURN(FirstResult, parseIntExpr2());
147   RCInt Result = *FirstResult;
148 
149   while (!isEof() && look().isBinaryOp()) {
150     auto OpToken = read();
151     ASSIGN_OR_RETURN(NextResult, parseIntExpr2());
152 
153     switch (OpToken.kind()) {
154     case Kind::Plus:
155       Result += *NextResult;
156       break;
157 
158     case Kind::Minus:
159       Result -= *NextResult;
160       break;
161 
162     case Kind::Pipe:
163       Result |= *NextResult;
164       break;
165 
166     case Kind::Amp:
167       Result &= *NextResult;
168       break;
169 
170     default:
171       llvm_unreachable("Already processed all binary ops.");
172     }
173   }
174 
175   return Result;
176 }
177 
178 Expected<RCInt> RCParser::parseIntExpr2() {
179   // Exp2 ::= -Exp2 || ~Exp2 || Int || (Exp1).
180   static const char ErrorMsg[] = "'-', '~', integer or '('";
181 
182   if (isEof())
183     return getExpectedError(ErrorMsg);
184 
185   switch (look().kind()) {
186   case Kind::Minus: {
187     consume();
188     ASSIGN_OR_RETURN(Result, parseIntExpr2());
189     return -(*Result);
190   }
191 
192   case Kind::Tilde: {
193     consume();
194     ASSIGN_OR_RETURN(Result, parseIntExpr2());
195     return ~(*Result);
196   }
197 
198   case Kind::Int:
199     return RCInt(read());
200 
201   case Kind::LeftParen: {
202     consume();
203     ASSIGN_OR_RETURN(Result, parseIntExpr1());
204     RETURN_IF_ERROR(consumeType(Kind::RightParen));
205     return *Result;
206   }
207 
208   default:
209     return getExpectedError(ErrorMsg);
210   }
211 }
212 
213 Expected<StringRef> RCParser::readString() {
214   if (!isNextTokenKind(Kind::String))
215     return getExpectedError("string");
216   return read().value();
217 }
218 
219 Expected<StringRef> RCParser::readFilename() {
220   if (!isNextTokenKind(Kind::String) && !isNextTokenKind(Kind::Identifier))
221     return getExpectedError("string");
222   return read().value();
223 }
224 
225 Expected<StringRef> RCParser::readIdentifier() {
226   if (!isNextTokenKind(Kind::Identifier))
227     return getExpectedError("identifier");
228   return read().value();
229 }
230 
231 Expected<IntOrString> RCParser::readIntOrString() {
232   if (!isNextTokenKind(Kind::Int) && !isNextTokenKind(Kind::String))
233     return getExpectedError("int or string");
234   return IntOrString(read());
235 }
236 
237 Expected<IntOrString> RCParser::readTypeOrName() {
238   // We suggest that the correct resource name or type should be either an
239   // identifier or an integer. The original RC tool is much more liberal.
240   if (!isNextTokenKind(Kind::Identifier) && !isNextTokenKind(Kind::Int))
241     return getExpectedError("int or identifier");
242   return IntOrString(read());
243 }
244 
245 Error RCParser::consumeType(Kind TokenKind) {
246   if (isNextTokenKind(TokenKind)) {
247     consume();
248     return Error::success();
249   }
250 
251   switch (TokenKind) {
252 #define TOKEN(TokenName)                                                       \
253   case Kind::TokenName:                                                        \
254     return getExpectedError(#TokenName);
255 #define SHORT_TOKEN(TokenName, TokenCh)                                        \
256   case Kind::TokenName:                                                        \
257     return getExpectedError(#TokenCh);
258 #include "ResourceScriptTokenList.def"
259   }
260 
261   llvm_unreachable("All case options exhausted.");
262 }
263 
264 bool RCParser::consumeOptionalType(Kind TokenKind) {
265   if (isNextTokenKind(TokenKind)) {
266     consume();
267     return true;
268   }
269 
270   return false;
271 }
272 
273 Expected<SmallVector<RCInt, 8>> RCParser::readIntsWithCommas(size_t MinCount,
274                                                              size_t MaxCount) {
275   assert(MinCount <= MaxCount);
276 
277   SmallVector<RCInt, 8> Result;
278 
279   auto FailureHandler =
280       [&](llvm::Error Err) -> Expected<SmallVector<RCInt, 8>> {
281     if (Result.size() < MinCount)
282       return std::move(Err);
283     consumeError(std::move(Err));
284     return Result;
285   };
286 
287   for (size_t i = 0; i < MaxCount; ++i) {
288     // Try to read a comma unless we read the first token.
289     // Sometimes RC tool requires them and sometimes not. We decide to
290     // always require them.
291     if (i >= 1) {
292       if (auto CommaError = consumeType(Kind::Comma))
293         return FailureHandler(std::move(CommaError));
294     }
295 
296     if (auto IntResult = readInt())
297       Result.push_back(*IntResult);
298     else
299       return FailureHandler(IntResult.takeError());
300   }
301 
302   return std::move(Result);
303 }
304 
305 Expected<uint32_t> RCParser::parseFlags(ArrayRef<StringRef> FlagDesc,
306                                         ArrayRef<uint32_t> FlagValues) {
307   assert(!FlagDesc.empty());
308   assert(FlagDesc.size() == FlagValues.size());
309 
310   uint32_t Result = 0;
311   while (isNextTokenKind(Kind::Comma)) {
312     consume();
313     ASSIGN_OR_RETURN(FlagResult, readIdentifier());
314     bool FoundFlag = false;
315 
316     for (size_t FlagId = 0; FlagId < FlagDesc.size(); ++FlagId) {
317       if (!FlagResult->equals_lower(FlagDesc[FlagId]))
318         continue;
319 
320       Result |= FlagValues[FlagId];
321       FoundFlag = true;
322       break;
323     }
324 
325     if (!FoundFlag)
326       return getExpectedError(join(FlagDesc, "/"), true);
327   }
328 
329   return Result;
330 }
331 
332 uint16_t RCParser::parseMemoryFlags(uint16_t Flags) {
333   while (!isEof()) {
334     const RCToken &Token = look();
335     if (Token.kind() != Kind::Identifier)
336       return Flags;
337     const StringRef Ident = Token.value();
338     if (Ident.equals_lower("PRELOAD"))
339       Flags |= MfPreload;
340     else if (Ident.equals_lower("LOADONCALL"))
341       Flags &= ~MfPreload;
342     else if (Ident.equals_lower("FIXED"))
343       Flags &= ~(MfMoveable | MfDiscardable);
344     else if (Ident.equals_lower("MOVEABLE"))
345       Flags |= MfMoveable;
346     else if (Ident.equals_lower("DISCARDABLE"))
347       Flags |= MfDiscardable | MfMoveable | MfPure;
348     else if (Ident.equals_lower("PURE"))
349       Flags |= MfPure;
350     else if (Ident.equals_lower("IMPURE"))
351       Flags &= ~(MfPure | MfDiscardable);
352     else if (Ident.equals_lower("SHARED"))
353       Flags |= MfPure;
354     else if (Ident.equals_lower("NONSHARED"))
355       Flags &= ~(MfPure | MfDiscardable);
356     else
357       return Flags;
358     consume();
359   }
360   return Flags;
361 }
362 
363 Expected<OptionalStmtList>
364 RCParser::parseOptionalStatements(OptStmtType StmtsType) {
365   OptionalStmtList Result;
366 
367   // The last statement is always followed by the start of the block.
368   while (!isNextTokenKind(Kind::BlockBegin)) {
369     ASSIGN_OR_RETURN(SingleParse, parseSingleOptionalStatement(StmtsType));
370     Result.addStmt(std::move(*SingleParse));
371   }
372 
373   return std::move(Result);
374 }
375 
376 Expected<std::unique_ptr<OptionalStmt>>
377 RCParser::parseSingleOptionalStatement(OptStmtType StmtsType) {
378   ASSIGN_OR_RETURN(TypeToken, readIdentifier());
379   if (TypeToken->equals_lower("CHARACTERISTICS"))
380     return parseCharacteristicsStmt();
381   if (TypeToken->equals_lower("LANGUAGE"))
382     return parseLanguageStmt();
383   if (TypeToken->equals_lower("VERSION"))
384     return parseVersionStmt();
385 
386   if (StmtsType != OptStmtType::BasicStmt) {
387     if (TypeToken->equals_lower("CAPTION"))
388       return parseCaptionStmt();
389     if (TypeToken->equals_lower("FONT"))
390       return parseFontStmt(StmtsType);
391     if (TypeToken->equals_lower("STYLE"))
392       return parseStyleStmt();
393   }
394 
395   return getExpectedError("optional statement type, BEGIN or '{'",
396                           /* IsAlreadyRead = */ true);
397 }
398 
399 RCParser::ParseType RCParser::parseLanguageResource() {
400   // Read LANGUAGE as an optional statement. If it's read correctly, we can
401   // upcast it to RCResource.
402   return parseLanguageStmt();
403 }
404 
405 RCParser::ParseType RCParser::parseAcceleratorsResource() {
406   uint16_t MemoryFlags =
407       parseMemoryFlags(AcceleratorsResource::getDefaultMemoryFlags());
408   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
409   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
410 
411   auto Accels = llvm::make_unique<AcceleratorsResource>(
412       std::move(*OptStatements), MemoryFlags);
413 
414   while (!consumeOptionalType(Kind::BlockEnd)) {
415     ASSIGN_OR_RETURN(EventResult, readIntOrString());
416     RETURN_IF_ERROR(consumeType(Kind::Comma));
417     ASSIGN_OR_RETURN(IDResult, readInt());
418     ASSIGN_OR_RETURN(
419         FlagsResult,
420         parseFlags(AcceleratorsResource::Accelerator::OptionsStr,
421                    AcceleratorsResource::Accelerator::OptionsFlags));
422     Accels->addAccelerator(*EventResult, *IDResult, *FlagsResult);
423   }
424 
425   return std::move(Accels);
426 }
427 
428 RCParser::ParseType RCParser::parseCursorResource() {
429   uint16_t MemoryFlags =
430       parseMemoryFlags(CursorResource::getDefaultMemoryFlags());
431   ASSIGN_OR_RETURN(Arg, readFilename());
432   return llvm::make_unique<CursorResource>(*Arg, MemoryFlags);
433 }
434 
435 RCParser::ParseType RCParser::parseDialogResource(bool IsExtended) {
436   uint16_t MemoryFlags =
437       parseMemoryFlags(DialogResource::getDefaultMemoryFlags());
438   // Dialog resources have the following format of the arguments:
439   //  DIALOG:   x, y, width, height [opt stmts...] {controls...}
440   //  DIALOGEX: x, y, width, height [, helpID] [opt stmts...] {controls...}
441   // These are very similar, so we parse them together.
442   ASSIGN_OR_RETURN(LocResult, readIntsWithCommas(4, 4));
443 
444   uint32_t HelpID = 0; // When HelpID is unset, it's assumed to be 0.
445   if (IsExtended && consumeOptionalType(Kind::Comma)) {
446     ASSIGN_OR_RETURN(HelpIDResult, readInt());
447     HelpID = *HelpIDResult;
448   }
449 
450   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements(
451                                       IsExtended ? OptStmtType::DialogExStmt
452                                                  : OptStmtType::DialogStmt));
453 
454   assert(isNextTokenKind(Kind::BlockBegin) &&
455          "parseOptionalStatements, when successful, halts on BlockBegin.");
456   consume();
457 
458   auto Dialog = llvm::make_unique<DialogResource>(
459       (*LocResult)[0], (*LocResult)[1], (*LocResult)[2], (*LocResult)[3],
460       HelpID, std::move(*OptStatements), IsExtended, MemoryFlags);
461 
462   while (!consumeOptionalType(Kind::BlockEnd)) {
463     ASSIGN_OR_RETURN(ControlDefResult, parseControl());
464     Dialog->addControl(std::move(*ControlDefResult));
465   }
466 
467   return std::move(Dialog);
468 }
469 
470 RCParser::ParseType RCParser::parseUserDefinedResource(IntOrString Type) {
471   uint16_t MemoryFlags =
472       parseMemoryFlags(UserDefinedResource::getDefaultMemoryFlags());
473   if (isEof())
474     return getExpectedError("filename, '{' or BEGIN");
475 
476   // Check if this is a file resource.
477   switch (look().kind()) {
478   case Kind::String:
479   case Kind::Identifier:
480     return llvm::make_unique<UserDefinedResource>(Type, read().value(),
481                                                   MemoryFlags);
482   default:
483     break;
484   }
485 
486   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
487   std::vector<IntOrString> Data;
488 
489   // Consume comma before each consecutive token except the first one.
490   bool ConsumeComma = false;
491   while (!consumeOptionalType(Kind::BlockEnd)) {
492     if (ConsumeComma)
493       RETURN_IF_ERROR(consumeType(Kind::Comma));
494     ConsumeComma = true;
495 
496     ASSIGN_OR_RETURN(Item, readIntOrString());
497     Data.push_back(*Item);
498   }
499 
500   return llvm::make_unique<UserDefinedResource>(Type, std::move(Data),
501                                                 MemoryFlags);
502 }
503 
504 RCParser::ParseType RCParser::parseVersionInfoResource() {
505   uint16_t MemoryFlags =
506       parseMemoryFlags(VersionInfoResource::getDefaultMemoryFlags());
507   ASSIGN_OR_RETURN(FixedResult, parseVersionInfoFixed());
508   ASSIGN_OR_RETURN(BlockResult, parseVersionInfoBlockContents(StringRef()));
509   return llvm::make_unique<VersionInfoResource>(
510       std::move(**BlockResult), std::move(*FixedResult), MemoryFlags);
511 }
512 
513 Expected<Control> RCParser::parseControl() {
514   // Each control definition (except CONTROL) follows one of the schemes below
515   // depending on the control class:
516   //  [class] text, id, x, y, width, height [, style] [, exstyle] [, helpID]
517   //  [class]       id, x, y, width, height [, style] [, exstyle] [, helpID]
518   // Note that control ids must be integers.
519   // Text might be either a string or an integer pointing to resource ID.
520   ASSIGN_OR_RETURN(ClassResult, readIdentifier());
521   std::string ClassUpper = ClassResult->upper();
522   auto CtlInfo = Control::SupportedCtls.find(ClassUpper);
523   if (CtlInfo == Control::SupportedCtls.end())
524     return getExpectedError("control type, END or '}'", true);
525 
526   // Read caption if necessary.
527   IntOrString Caption{StringRef()};
528   if (CtlInfo->getValue().HasTitle) {
529     ASSIGN_OR_RETURN(CaptionResult, readIntOrString());
530     RETURN_IF_ERROR(consumeType(Kind::Comma));
531     Caption = *CaptionResult;
532   }
533 
534   ASSIGN_OR_RETURN(ID, readInt());
535   RETURN_IF_ERROR(consumeType(Kind::Comma));
536 
537   IntOrString Class;
538   Optional<uint32_t> Style;
539   if (ClassUpper == "CONTROL") {
540     // CONTROL text, id, class, style, x, y, width, height [, exstyle] [, helpID]
541     ASSIGN_OR_RETURN(ClassStr, readString());
542     RETURN_IF_ERROR(consumeType(Kind::Comma));
543     Class = *ClassStr;
544     ASSIGN_OR_RETURN(StyleVal, readInt());
545     RETURN_IF_ERROR(consumeType(Kind::Comma));
546     Style = *StyleVal;
547   } else {
548     Class = CtlInfo->getValue().CtlClass;
549   }
550 
551   // x, y, width, height
552   ASSIGN_OR_RETURN(Args, readIntsWithCommas(4, 4));
553 
554   if (ClassUpper != "CONTROL") {
555     if (consumeOptionalType(Kind::Comma)) {
556       ASSIGN_OR_RETURN(Val, readInt());
557       Style = *Val;
558     }
559   }
560 
561   Optional<uint32_t> ExStyle;
562   if (consumeOptionalType(Kind::Comma)) {
563     ASSIGN_OR_RETURN(Val, readInt());
564     ExStyle = *Val;
565   }
566   Optional<uint32_t> HelpID;
567   if (consumeOptionalType(Kind::Comma)) {
568     ASSIGN_OR_RETURN(Val, readInt());
569     HelpID = *Val;
570   }
571 
572   return Control(*ClassResult, Caption, *ID, (*Args)[0], (*Args)[1],
573                  (*Args)[2], (*Args)[3], Style, ExStyle, HelpID, Class);
574 }
575 
576 RCParser::ParseType RCParser::parseBitmapResource() {
577   uint16_t MemoryFlags =
578       parseMemoryFlags(BitmapResource::getDefaultMemoryFlags());
579   ASSIGN_OR_RETURN(Arg, readFilename());
580   return llvm::make_unique<BitmapResource>(*Arg, MemoryFlags);
581 }
582 
583 RCParser::ParseType RCParser::parseIconResource() {
584   uint16_t MemoryFlags =
585       parseMemoryFlags(IconResource::getDefaultMemoryFlags());
586   ASSIGN_OR_RETURN(Arg, readFilename());
587   return llvm::make_unique<IconResource>(*Arg, MemoryFlags);
588 }
589 
590 RCParser::ParseType RCParser::parseHTMLResource() {
591   uint16_t MemoryFlags =
592       parseMemoryFlags(HTMLResource::getDefaultMemoryFlags());
593   ASSIGN_OR_RETURN(Arg, readFilename());
594   return llvm::make_unique<HTMLResource>(*Arg, MemoryFlags);
595 }
596 
597 RCParser::ParseType RCParser::parseMenuResource() {
598   uint16_t MemoryFlags =
599       parseMemoryFlags(MenuResource::getDefaultMemoryFlags());
600   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
601   ASSIGN_OR_RETURN(Items, parseMenuItemsList());
602   return llvm::make_unique<MenuResource>(std::move(*OptStatements),
603                                          std::move(*Items), MemoryFlags);
604 }
605 
606 Expected<MenuDefinitionList> RCParser::parseMenuItemsList() {
607   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
608 
609   MenuDefinitionList List;
610 
611   // Read a set of items. Each item is of one of three kinds:
612   //   MENUITEM SEPARATOR
613   //   MENUITEM caption:String, result:Int [, menu flags]...
614   //   POPUP caption:String [, menu flags]... { items... }
615   while (!consumeOptionalType(Kind::BlockEnd)) {
616     ASSIGN_OR_RETURN(ItemTypeResult, readIdentifier());
617 
618     bool IsMenuItem = ItemTypeResult->equals_lower("MENUITEM");
619     bool IsPopup = ItemTypeResult->equals_lower("POPUP");
620     if (!IsMenuItem && !IsPopup)
621       return getExpectedError("MENUITEM, POPUP, END or '}'", true);
622 
623     if (IsMenuItem && isNextTokenKind(Kind::Identifier)) {
624       // Now, expecting SEPARATOR.
625       ASSIGN_OR_RETURN(SeparatorResult, readIdentifier());
626       if (SeparatorResult->equals_lower("SEPARATOR")) {
627         List.addDefinition(llvm::make_unique<MenuSeparator>());
628         continue;
629       }
630 
631       return getExpectedError("SEPARATOR or string", true);
632     }
633 
634     // Not a separator. Read the caption.
635     ASSIGN_OR_RETURN(CaptionResult, readString());
636 
637     // If MENUITEM, expect also a comma and an integer.
638     uint32_t MenuResult = -1;
639 
640     if (IsMenuItem) {
641       RETURN_IF_ERROR(consumeType(Kind::Comma));
642       ASSIGN_OR_RETURN(IntResult, readInt());
643       MenuResult = *IntResult;
644     }
645 
646     ASSIGN_OR_RETURN(FlagsResult, parseFlags(MenuDefinition::OptionsStr,
647                                              MenuDefinition::OptionsFlags));
648 
649     if (IsPopup) {
650       // If POPUP, read submenu items recursively.
651       ASSIGN_OR_RETURN(SubMenuResult, parseMenuItemsList());
652       List.addDefinition(llvm::make_unique<PopupItem>(
653           *CaptionResult, *FlagsResult, std::move(*SubMenuResult)));
654       continue;
655     }
656 
657     assert(IsMenuItem);
658     List.addDefinition(
659         llvm::make_unique<MenuItem>(*CaptionResult, MenuResult, *FlagsResult));
660   }
661 
662   return std::move(List);
663 }
664 
665 RCParser::ParseType RCParser::parseStringTableResource() {
666   uint16_t MemoryFlags =
667       parseMemoryFlags(StringTableResource::getDefaultMemoryFlags());
668   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
669   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
670 
671   auto Table = llvm::make_unique<StringTableResource>(std::move(*OptStatements),
672                                                       MemoryFlags);
673 
674   // Read strings until we reach the end of the block.
675   while (!consumeOptionalType(Kind::BlockEnd)) {
676     // Each definition consists of string's ID (an integer) and a string.
677     // Some examples in documentation suggest that there might be a comma in
678     // between, however we strictly adhere to the single statement definition.
679     ASSIGN_OR_RETURN(IDResult, readInt());
680     consumeOptionalType(Kind::Comma);
681     ASSIGN_OR_RETURN(StrResult, readString());
682     Table->addString(*IDResult, *StrResult);
683   }
684 
685   return std::move(Table);
686 }
687 
688 Expected<std::unique_ptr<VersionInfoBlock>>
689 RCParser::parseVersionInfoBlockContents(StringRef BlockName) {
690   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
691 
692   auto Contents = llvm::make_unique<VersionInfoBlock>(BlockName);
693 
694   while (!isNextTokenKind(Kind::BlockEnd)) {
695     ASSIGN_OR_RETURN(Stmt, parseVersionInfoStmt());
696     Contents->addStmt(std::move(*Stmt));
697   }
698 
699   consume(); // Consume BlockEnd.
700 
701   return std::move(Contents);
702 }
703 
704 Expected<std::unique_ptr<VersionInfoStmt>> RCParser::parseVersionInfoStmt() {
705   // Expect either BLOCK or VALUE, then a name or a key (a string).
706   ASSIGN_OR_RETURN(TypeResult, readIdentifier());
707 
708   if (TypeResult->equals_lower("BLOCK")) {
709     ASSIGN_OR_RETURN(NameResult, readString());
710     return parseVersionInfoBlockContents(*NameResult);
711   }
712 
713   if (TypeResult->equals_lower("VALUE")) {
714     ASSIGN_OR_RETURN(KeyResult, readString());
715     // Read a non-empty list of strings and/or ints, each
716     // possibly preceded by a comma. Unfortunately, the tool behavior depends
717     // on them existing or not, so we need to memorize where we found them.
718     std::vector<IntOrString> Values;
719     std::vector<bool> PrecedingCommas;
720     RETURN_IF_ERROR(consumeType(Kind::Comma));
721     while (!isNextTokenKind(Kind::Identifier) &&
722            !isNextTokenKind(Kind::BlockEnd)) {
723       // Try to eat a comma if it's not the first statement.
724       bool HadComma = Values.size() > 0 && consumeOptionalType(Kind::Comma);
725       ASSIGN_OR_RETURN(ValueResult, readIntOrString());
726       Values.push_back(*ValueResult);
727       PrecedingCommas.push_back(HadComma);
728     }
729     return llvm::make_unique<VersionInfoValue>(*KeyResult, std::move(Values),
730                                                std::move(PrecedingCommas));
731   }
732 
733   return getExpectedError("BLOCK or VALUE", true);
734 }
735 
736 Expected<VersionInfoResource::VersionInfoFixed>
737 RCParser::parseVersionInfoFixed() {
738   using RetType = VersionInfoResource::VersionInfoFixed;
739   RetType Result;
740 
741   // Read until the beginning of the block.
742   while (!isNextTokenKind(Kind::BlockBegin)) {
743     ASSIGN_OR_RETURN(TypeResult, readIdentifier());
744     auto FixedType = RetType::getFixedType(*TypeResult);
745 
746     if (!RetType::isTypeSupported(FixedType))
747       return getExpectedError("fixed VERSIONINFO statement type", true);
748     if (Result.IsTypePresent[FixedType])
749       return getExpectedError("yet unread fixed VERSIONINFO statement type",
750                               true);
751 
752     // VERSION variations take multiple integers.
753     size_t NumInts = RetType::isVersionType(FixedType) ? 4 : 1;
754     ASSIGN_OR_RETURN(ArgsResult, readIntsWithCommas(NumInts, NumInts));
755     SmallVector<uint32_t, 4> ArgInts(ArgsResult->begin(), ArgsResult->end());
756     Result.setValue(FixedType, ArgInts);
757   }
758 
759   return Result;
760 }
761 
762 RCParser::ParseOptionType RCParser::parseLanguageStmt() {
763   ASSIGN_OR_RETURN(Args, readIntsWithCommas(/* min = */ 2, /* max = */ 2));
764   return llvm::make_unique<LanguageResource>((*Args)[0], (*Args)[1]);
765 }
766 
767 RCParser::ParseOptionType RCParser::parseCharacteristicsStmt() {
768   ASSIGN_OR_RETURN(Arg, readInt());
769   return llvm::make_unique<CharacteristicsStmt>(*Arg);
770 }
771 
772 RCParser::ParseOptionType RCParser::parseVersionStmt() {
773   ASSIGN_OR_RETURN(Arg, readInt());
774   return llvm::make_unique<VersionStmt>(*Arg);
775 }
776 
777 RCParser::ParseOptionType RCParser::parseCaptionStmt() {
778   ASSIGN_OR_RETURN(Arg, readString());
779   return llvm::make_unique<CaptionStmt>(*Arg);
780 }
781 
782 RCParser::ParseOptionType RCParser::parseFontStmt(OptStmtType DialogType) {
783   assert(DialogType != OptStmtType::BasicStmt);
784 
785   ASSIGN_OR_RETURN(SizeResult, readInt());
786   RETURN_IF_ERROR(consumeType(Kind::Comma));
787   ASSIGN_OR_RETURN(NameResult, readString());
788 
789   // Default values for the optional arguments.
790   uint32_t FontWeight = 0;
791   bool FontItalic = false;
792   uint32_t FontCharset = 1;
793   if (DialogType == OptStmtType::DialogExStmt) {
794     if (consumeOptionalType(Kind::Comma)) {
795       ASSIGN_OR_RETURN(Args, readIntsWithCommas(/* min = */ 0, /* max = */ 3));
796       if (Args->size() >= 1)
797         FontWeight = (*Args)[0];
798       if (Args->size() >= 2)
799         FontItalic = (*Args)[1] != 0;
800       if (Args->size() >= 3)
801         FontCharset = (*Args)[2];
802     }
803   }
804   return llvm::make_unique<FontStmt>(*SizeResult, *NameResult, FontWeight,
805                                      FontItalic, FontCharset);
806 }
807 
808 RCParser::ParseOptionType RCParser::parseStyleStmt() {
809   ASSIGN_OR_RETURN(Arg, readInt());
810   return llvm::make_unique<StyleStmt>(*Arg);
811 }
812 
813 Error RCParser::getExpectedError(const Twine &Message, bool IsAlreadyRead) {
814   return make_error<ParserError>(
815       Message, IsAlreadyRead ? std::prev(CurLoc) : CurLoc, End);
816 }
817 
818 } // namespace rc
819 } // namespace llvm
820