xref: /llvm-project/llvm/tools/llvm-rc/ResourceScriptParser.cpp (revision 7bc3c5822e408d3387f1d383ee50b2ed389ca949)
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 Expected<OptionalStmtList>
333 RCParser::parseOptionalStatements(OptStmtType StmtsType) {
334   OptionalStmtList Result;
335 
336   // The last statement is always followed by the start of the block.
337   while (!isNextTokenKind(Kind::BlockBegin)) {
338     ASSIGN_OR_RETURN(SingleParse, parseSingleOptionalStatement(StmtsType));
339     Result.addStmt(std::move(*SingleParse));
340   }
341 
342   return std::move(Result);
343 }
344 
345 Expected<std::unique_ptr<OptionalStmt>>
346 RCParser::parseSingleOptionalStatement(OptStmtType StmtsType) {
347   ASSIGN_OR_RETURN(TypeToken, readIdentifier());
348   if (TypeToken->equals_lower("CHARACTERISTICS"))
349     return parseCharacteristicsStmt();
350   if (TypeToken->equals_lower("LANGUAGE"))
351     return parseLanguageStmt();
352   if (TypeToken->equals_lower("VERSION"))
353     return parseVersionStmt();
354 
355   if (StmtsType != OptStmtType::BasicStmt) {
356     if (TypeToken->equals_lower("CAPTION"))
357       return parseCaptionStmt();
358     if (TypeToken->equals_lower("FONT"))
359       return parseFontStmt(StmtsType);
360     if (TypeToken->equals_lower("STYLE"))
361       return parseStyleStmt();
362   }
363 
364   return getExpectedError("optional statement type, BEGIN or '{'",
365                           /* IsAlreadyRead = */ true);
366 }
367 
368 RCParser::ParseType RCParser::parseLanguageResource() {
369   // Read LANGUAGE as an optional statement. If it's read correctly, we can
370   // upcast it to RCResource.
371   return parseLanguageStmt();
372 }
373 
374 RCParser::ParseType RCParser::parseAcceleratorsResource() {
375   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
376   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
377 
378   auto Accels =
379       llvm::make_unique<AcceleratorsResource>(std::move(*OptStatements));
380 
381   while (!consumeOptionalType(Kind::BlockEnd)) {
382     ASSIGN_OR_RETURN(EventResult, readIntOrString());
383     RETURN_IF_ERROR(consumeType(Kind::Comma));
384     ASSIGN_OR_RETURN(IDResult, readInt());
385     ASSIGN_OR_RETURN(
386         FlagsResult,
387         parseFlags(AcceleratorsResource::Accelerator::OptionsStr,
388                    AcceleratorsResource::Accelerator::OptionsFlags));
389     Accels->addAccelerator(*EventResult, *IDResult, *FlagsResult);
390   }
391 
392   return std::move(Accels);
393 }
394 
395 RCParser::ParseType RCParser::parseCursorResource() {
396   ASSIGN_OR_RETURN(Arg, readFilename());
397   return llvm::make_unique<CursorResource>(*Arg);
398 }
399 
400 RCParser::ParseType RCParser::parseDialogResource(bool IsExtended) {
401   // Dialog resources have the following format of the arguments:
402   //  DIALOG:   x, y, width, height [opt stmts...] {controls...}
403   //  DIALOGEX: x, y, width, height [, helpID] [opt stmts...] {controls...}
404   // These are very similar, so we parse them together.
405   ASSIGN_OR_RETURN(LocResult, readIntsWithCommas(4, 4));
406 
407   uint32_t HelpID = 0; // When HelpID is unset, it's assumed to be 0.
408   if (IsExtended && consumeOptionalType(Kind::Comma)) {
409     ASSIGN_OR_RETURN(HelpIDResult, readInt());
410     HelpID = *HelpIDResult;
411   }
412 
413   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements(
414                                       IsExtended ? OptStmtType::DialogExStmt
415                                                  : OptStmtType::DialogStmt));
416 
417   assert(isNextTokenKind(Kind::BlockBegin) &&
418          "parseOptionalStatements, when successful, halts on BlockBegin.");
419   consume();
420 
421   auto Dialog = llvm::make_unique<DialogResource>(
422       (*LocResult)[0], (*LocResult)[1], (*LocResult)[2], (*LocResult)[3],
423       HelpID, std::move(*OptStatements), IsExtended);
424 
425   while (!consumeOptionalType(Kind::BlockEnd)) {
426     ASSIGN_OR_RETURN(ControlDefResult, parseControl());
427     Dialog->addControl(std::move(*ControlDefResult));
428   }
429 
430   return std::move(Dialog);
431 }
432 
433 RCParser::ParseType RCParser::parseUserDefinedResource(IntOrString Type) {
434   if (isEof())
435     return getExpectedError("filename, '{' or BEGIN");
436 
437   // Check if this is a file resource.
438   switch (look().kind()) {
439   case Kind::String:
440   case Kind::Identifier:
441     return llvm::make_unique<UserDefinedResource>(Type, read().value());
442   default:
443     break;
444   }
445 
446   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
447   std::vector<IntOrString> Data;
448 
449   // Consume comma before each consecutive token except the first one.
450   bool ConsumeComma = false;
451   while (!consumeOptionalType(Kind::BlockEnd)) {
452     if (ConsumeComma)
453       RETURN_IF_ERROR(consumeType(Kind::Comma));
454     ConsumeComma = true;
455 
456     ASSIGN_OR_RETURN(Item, readIntOrString());
457     Data.push_back(*Item);
458   }
459 
460   return llvm::make_unique<UserDefinedResource>(Type, std::move(Data));
461 }
462 
463 RCParser::ParseType RCParser::parseVersionInfoResource() {
464   ASSIGN_OR_RETURN(FixedResult, parseVersionInfoFixed());
465   ASSIGN_OR_RETURN(BlockResult, parseVersionInfoBlockContents(StringRef()));
466   return llvm::make_unique<VersionInfoResource>(std::move(**BlockResult),
467                                                 std::move(*FixedResult));
468 }
469 
470 Expected<Control> RCParser::parseControl() {
471   // Each control definition (except CONTROL) follows one of the schemes below
472   // depending on the control class:
473   //  [class] text, id, x, y, width, height [, style] [, exstyle] [, helpID]
474   //  [class]       id, x, y, width, height [, style] [, exstyle] [, helpID]
475   // Note that control ids must be integers.
476   // Text might be either a string or an integer pointing to resource ID.
477   ASSIGN_OR_RETURN(ClassResult, readIdentifier());
478   std::string ClassUpper = ClassResult->upper();
479   auto CtlInfo = Control::SupportedCtls.find(ClassUpper);
480   if (CtlInfo == Control::SupportedCtls.end())
481     return getExpectedError("control type, END or '}'", true);
482 
483   // Read caption if necessary.
484   IntOrString Caption{StringRef()};
485   if (CtlInfo->getValue().HasTitle) {
486     ASSIGN_OR_RETURN(CaptionResult, readIntOrString());
487     RETURN_IF_ERROR(consumeType(Kind::Comma));
488     Caption = *CaptionResult;
489   }
490 
491   ASSIGN_OR_RETURN(ID, readInt());
492   RETURN_IF_ERROR(consumeType(Kind::Comma));
493 
494   IntOrString Class;
495   Optional<uint32_t> Style;
496   if (ClassUpper == "CONTROL") {
497     // CONTROL text, id, class, style, x, y, width, height [, exstyle] [, helpID]
498     ASSIGN_OR_RETURN(ClassStr, readString());
499     RETURN_IF_ERROR(consumeType(Kind::Comma));
500     Class = *ClassStr;
501     ASSIGN_OR_RETURN(StyleVal, readInt());
502     RETURN_IF_ERROR(consumeType(Kind::Comma));
503     Style = *StyleVal;
504   } else {
505     Class = CtlInfo->getValue().CtlClass;
506   }
507 
508   // x, y, width, height
509   ASSIGN_OR_RETURN(Args, readIntsWithCommas(4, 4));
510 
511   if (ClassUpper != "CONTROL") {
512     if (consumeOptionalType(Kind::Comma)) {
513       ASSIGN_OR_RETURN(Val, readInt());
514       Style = *Val;
515     }
516   }
517 
518   Optional<uint32_t> ExStyle;
519   if (consumeOptionalType(Kind::Comma)) {
520     ASSIGN_OR_RETURN(Val, readInt());
521     ExStyle = *Val;
522   }
523   Optional<uint32_t> HelpID;
524   if (consumeOptionalType(Kind::Comma)) {
525     ASSIGN_OR_RETURN(Val, readInt());
526     HelpID = *Val;
527   }
528 
529   return Control(*ClassResult, Caption, *ID, (*Args)[0], (*Args)[1],
530                  (*Args)[2], (*Args)[3], Style, ExStyle, HelpID, Class);
531 }
532 
533 RCParser::ParseType RCParser::parseBitmapResource() {
534   ASSIGN_OR_RETURN(Arg, readFilename());
535   return llvm::make_unique<BitmapResource>(*Arg);
536 }
537 
538 RCParser::ParseType RCParser::parseIconResource() {
539   ASSIGN_OR_RETURN(Arg, readFilename());
540   return llvm::make_unique<IconResource>(*Arg);
541 }
542 
543 RCParser::ParseType RCParser::parseHTMLResource() {
544   ASSIGN_OR_RETURN(Arg, readFilename());
545   return llvm::make_unique<HTMLResource>(*Arg);
546 }
547 
548 RCParser::ParseType RCParser::parseMenuResource() {
549   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
550   ASSIGN_OR_RETURN(Items, parseMenuItemsList());
551   return llvm::make_unique<MenuResource>(std::move(*OptStatements),
552                                          std::move(*Items));
553 }
554 
555 Expected<MenuDefinitionList> RCParser::parseMenuItemsList() {
556   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
557 
558   MenuDefinitionList List;
559 
560   // Read a set of items. Each item is of one of three kinds:
561   //   MENUITEM SEPARATOR
562   //   MENUITEM caption:String, result:Int [, menu flags]...
563   //   POPUP caption:String [, menu flags]... { items... }
564   while (!consumeOptionalType(Kind::BlockEnd)) {
565     ASSIGN_OR_RETURN(ItemTypeResult, readIdentifier());
566 
567     bool IsMenuItem = ItemTypeResult->equals_lower("MENUITEM");
568     bool IsPopup = ItemTypeResult->equals_lower("POPUP");
569     if (!IsMenuItem && !IsPopup)
570       return getExpectedError("MENUITEM, POPUP, END or '}'", true);
571 
572     if (IsMenuItem && isNextTokenKind(Kind::Identifier)) {
573       // Now, expecting SEPARATOR.
574       ASSIGN_OR_RETURN(SeparatorResult, readIdentifier());
575       if (SeparatorResult->equals_lower("SEPARATOR")) {
576         List.addDefinition(llvm::make_unique<MenuSeparator>());
577         continue;
578       }
579 
580       return getExpectedError("SEPARATOR or string", true);
581     }
582 
583     // Not a separator. Read the caption.
584     ASSIGN_OR_RETURN(CaptionResult, readString());
585 
586     // If MENUITEM, expect also a comma and an integer.
587     uint32_t MenuResult = -1;
588 
589     if (IsMenuItem) {
590       RETURN_IF_ERROR(consumeType(Kind::Comma));
591       ASSIGN_OR_RETURN(IntResult, readInt());
592       MenuResult = *IntResult;
593     }
594 
595     ASSIGN_OR_RETURN(FlagsResult, parseFlags(MenuDefinition::OptionsStr,
596                                              MenuDefinition::OptionsFlags));
597 
598     if (IsPopup) {
599       // If POPUP, read submenu items recursively.
600       ASSIGN_OR_RETURN(SubMenuResult, parseMenuItemsList());
601       List.addDefinition(llvm::make_unique<PopupItem>(
602           *CaptionResult, *FlagsResult, std::move(*SubMenuResult)));
603       continue;
604     }
605 
606     assert(IsMenuItem);
607     List.addDefinition(
608         llvm::make_unique<MenuItem>(*CaptionResult, MenuResult, *FlagsResult));
609   }
610 
611   return std::move(List);
612 }
613 
614 RCParser::ParseType RCParser::parseStringTableResource() {
615   ASSIGN_OR_RETURN(OptStatements, parseOptionalStatements());
616   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
617 
618   auto Table =
619       llvm::make_unique<StringTableResource>(std::move(*OptStatements));
620 
621   // Read strings until we reach the end of the block.
622   while (!consumeOptionalType(Kind::BlockEnd)) {
623     // Each definition consists of string's ID (an integer) and a string.
624     // Some examples in documentation suggest that there might be a comma in
625     // between, however we strictly adhere to the single statement definition.
626     ASSIGN_OR_RETURN(IDResult, readInt());
627     consumeOptionalType(Kind::Comma);
628     ASSIGN_OR_RETURN(StrResult, readString());
629     Table->addString(*IDResult, *StrResult);
630   }
631 
632   return std::move(Table);
633 }
634 
635 Expected<std::unique_ptr<VersionInfoBlock>>
636 RCParser::parseVersionInfoBlockContents(StringRef BlockName) {
637   RETURN_IF_ERROR(consumeType(Kind::BlockBegin));
638 
639   auto Contents = llvm::make_unique<VersionInfoBlock>(BlockName);
640 
641   while (!isNextTokenKind(Kind::BlockEnd)) {
642     ASSIGN_OR_RETURN(Stmt, parseVersionInfoStmt());
643     Contents->addStmt(std::move(*Stmt));
644   }
645 
646   consume(); // Consume BlockEnd.
647 
648   return std::move(Contents);
649 }
650 
651 Expected<std::unique_ptr<VersionInfoStmt>> RCParser::parseVersionInfoStmt() {
652   // Expect either BLOCK or VALUE, then a name or a key (a string).
653   ASSIGN_OR_RETURN(TypeResult, readIdentifier());
654 
655   if (TypeResult->equals_lower("BLOCK")) {
656     ASSIGN_OR_RETURN(NameResult, readString());
657     return parseVersionInfoBlockContents(*NameResult);
658   }
659 
660   if (TypeResult->equals_lower("VALUE")) {
661     ASSIGN_OR_RETURN(KeyResult, readString());
662     // Read a non-empty list of strings and/or ints, each
663     // possibly preceded by a comma. Unfortunately, the tool behavior depends
664     // on them existing or not, so we need to memorize where we found them.
665     std::vector<IntOrString> Values;
666     std::vector<bool> PrecedingCommas;
667     RETURN_IF_ERROR(consumeType(Kind::Comma));
668     while (!isNextTokenKind(Kind::Identifier) &&
669            !isNextTokenKind(Kind::BlockEnd)) {
670       // Try to eat a comma if it's not the first statement.
671       bool HadComma = Values.size() > 0 && consumeOptionalType(Kind::Comma);
672       ASSIGN_OR_RETURN(ValueResult, readIntOrString());
673       Values.push_back(*ValueResult);
674       PrecedingCommas.push_back(HadComma);
675     }
676     return llvm::make_unique<VersionInfoValue>(*KeyResult, std::move(Values),
677                                                std::move(PrecedingCommas));
678   }
679 
680   return getExpectedError("BLOCK or VALUE", true);
681 }
682 
683 Expected<VersionInfoResource::VersionInfoFixed>
684 RCParser::parseVersionInfoFixed() {
685   using RetType = VersionInfoResource::VersionInfoFixed;
686   RetType Result;
687 
688   // Read until the beginning of the block.
689   while (!isNextTokenKind(Kind::BlockBegin)) {
690     ASSIGN_OR_RETURN(TypeResult, readIdentifier());
691     auto FixedType = RetType::getFixedType(*TypeResult);
692 
693     if (!RetType::isTypeSupported(FixedType))
694       return getExpectedError("fixed VERSIONINFO statement type", true);
695     if (Result.IsTypePresent[FixedType])
696       return getExpectedError("yet unread fixed VERSIONINFO statement type",
697                               true);
698 
699     // VERSION variations take multiple integers.
700     size_t NumInts = RetType::isVersionType(FixedType) ? 4 : 1;
701     ASSIGN_OR_RETURN(ArgsResult, readIntsWithCommas(NumInts, NumInts));
702     SmallVector<uint32_t, 4> ArgInts(ArgsResult->begin(), ArgsResult->end());
703     Result.setValue(FixedType, ArgInts);
704   }
705 
706   return Result;
707 }
708 
709 RCParser::ParseOptionType RCParser::parseLanguageStmt() {
710   ASSIGN_OR_RETURN(Args, readIntsWithCommas(/* min = */ 2, /* max = */ 2));
711   return llvm::make_unique<LanguageResource>((*Args)[0], (*Args)[1]);
712 }
713 
714 RCParser::ParseOptionType RCParser::parseCharacteristicsStmt() {
715   ASSIGN_OR_RETURN(Arg, readInt());
716   return llvm::make_unique<CharacteristicsStmt>(*Arg);
717 }
718 
719 RCParser::ParseOptionType RCParser::parseVersionStmt() {
720   ASSIGN_OR_RETURN(Arg, readInt());
721   return llvm::make_unique<VersionStmt>(*Arg);
722 }
723 
724 RCParser::ParseOptionType RCParser::parseCaptionStmt() {
725   ASSIGN_OR_RETURN(Arg, readString());
726   return llvm::make_unique<CaptionStmt>(*Arg);
727 }
728 
729 RCParser::ParseOptionType RCParser::parseFontStmt(OptStmtType DialogType) {
730   assert(DialogType != OptStmtType::BasicStmt);
731 
732   ASSIGN_OR_RETURN(SizeResult, readInt());
733   RETURN_IF_ERROR(consumeType(Kind::Comma));
734   ASSIGN_OR_RETURN(NameResult, readString());
735 
736   // Default values for the optional arguments.
737   uint32_t FontWeight = 0;
738   bool FontItalic = false;
739   uint32_t FontCharset = 1;
740   if (DialogType == OptStmtType::DialogExStmt) {
741     if (consumeOptionalType(Kind::Comma)) {
742       ASSIGN_OR_RETURN(Args, readIntsWithCommas(/* min = */ 0, /* max = */ 3));
743       if (Args->size() >= 1)
744         FontWeight = (*Args)[0];
745       if (Args->size() >= 2)
746         FontItalic = (*Args)[1] != 0;
747       if (Args->size() >= 3)
748         FontCharset = (*Args)[2];
749     }
750   }
751   return llvm::make_unique<FontStmt>(*SizeResult, *NameResult, FontWeight,
752                                      FontItalic, FontCharset);
753 }
754 
755 RCParser::ParseOptionType RCParser::parseStyleStmt() {
756   ASSIGN_OR_RETURN(Arg, readInt());
757   return llvm::make_unique<StyleStmt>(*Arg);
758 }
759 
760 Error RCParser::getExpectedError(const Twine &Message, bool IsAlreadyRead) {
761   return make_error<ParserError>(
762       Message, IsAlreadyRead ? std::prev(CurLoc) : CurLoc, End);
763 }
764 
765 } // namespace rc
766 } // namespace llvm
767