• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <stdio.h>
18 #include <cctype>
19 #include <cstdlib>
20 #include <fstream>
21 #include <functional>
22 #include <iostream>
23 #include <memory>
24 #include <sstream>
25 #include <strings.h>
26 
27 #include "Generator.h"
28 #include "Scanner.h"
29 #include "Specification.h"
30 #include "Utilities.h"
31 
32 using namespace std;
33 
34 // API level when RenderScript was added.
35 const unsigned int MIN_API_LEVEL = 9;
36 
37 const NumericalType TYPES[] = {
38             {"f16", "FLOAT_16", "half", "short", FLOATING_POINT, 11, 5},
39             {"f32", "FLOAT_32", "float", "float", FLOATING_POINT, 24, 8},
40             {"f64", "FLOAT_64", "double", "double", FLOATING_POINT, 53, 11},
41             {"i8", "SIGNED_8", "char", "byte", SIGNED_INTEGER, 7, 0},
42             {"u8", "UNSIGNED_8", "uchar", "byte", UNSIGNED_INTEGER, 8, 0},
43             {"i16", "SIGNED_16", "short", "short", SIGNED_INTEGER, 15, 0},
44             {"u16", "UNSIGNED_16", "ushort", "short", UNSIGNED_INTEGER, 16, 0},
45             {"i32", "SIGNED_32", "int", "int", SIGNED_INTEGER, 31, 0},
46             {"u32", "UNSIGNED_32", "uint", "int", UNSIGNED_INTEGER, 32, 0},
47             {"i64", "SIGNED_64", "long", "long", SIGNED_INTEGER, 63, 0},
48             {"u64", "UNSIGNED_64", "ulong", "long", UNSIGNED_INTEGER, 64, 0},
49 };
50 
51 const int NUM_TYPES = sizeof(TYPES) / sizeof(TYPES[0]);
52 
53 static const char kTagUnreleased[] = "UNRELEASED";
54 
55 // Patterns that get substituted with C type or RS Data type names in function
56 // names, arguments, return types, and inlines.
57 static const string kCTypePatterns[] = {"#1", "#2", "#3", "#4"};
58 static const string kRSTypePatterns[] = {"#RST_1", "#RST_2", "#RST_3", "#RST_4"};
59 
60 // The singleton of the collected information of all the spec files.
61 SystemSpecification systemSpecification;
62 
63 // Returns the index in TYPES for the provided cType
findCType(const string & cType)64 static int findCType(const string& cType) {
65     for (int i = 0; i < NUM_TYPES; i++) {
66         if (cType == TYPES[i].cType) {
67             return i;
68         }
69     }
70     return -1;
71 }
72 
73 /* Converts a string like "u8, u16" to a vector of "ushort", "uint".
74  * For non-numerical types, we don't need to convert the abbreviation.
75  */
convertToTypeVector(const string & input)76 static vector<string> convertToTypeVector(const string& input) {
77     // First convert the string to an array of strings.
78     vector<string> entries;
79     stringstream stream(input);
80     string entry;
81     while (getline(stream, entry, ',')) {
82         trimSpaces(&entry);
83         entries.push_back(entry);
84     }
85 
86     /* Second, we look for present numerical types. We do it this way
87      * so the order of numerical types is always the same, no matter
88      * how specified in the spec file.
89      */
90     vector<string> result;
91     for (auto t : TYPES) {
92         for (auto i = entries.begin(); i != entries.end(); ++i) {
93             if (*i == t.specType) {
94                 result.push_back(t.cType);
95                 entries.erase(i);
96                 break;
97             }
98         }
99     }
100 
101     // Add the remaining; they are not numerical types.
102     for (auto s : entries) {
103         result.push_back(s);
104     }
105 
106     return result;
107 }
108 
109 // Returns true if each entry in typeVector is an RS numerical type
isRSTValid(const vector<string> & typeVector)110 static bool isRSTValid(const vector<string> &typeVector) {
111     for (auto type: typeVector) {
112         if (findCType(type) == -1)
113             return false;
114     }
115     return true;
116 }
117 
getVectorSizeAndBaseType(const string & type,string & vectorSize,string & baseType)118 void getVectorSizeAndBaseType(const string& type, string& vectorSize, string& baseType) {
119     vectorSize = "1";
120     baseType = type;
121 
122     /* If it's a vector type, we need to split the base type from the size.
123      * We know that's it's a vector type if the last character is a digit and
124      * the rest is an actual base type.   We used to only verify the first part,
125      * which created a problem with rs_matrix2x2.
126      */
127     const int last = type.size() - 1;
128     const char lastChar = type[last];
129     if (lastChar >= '0' && lastChar <= '9') {
130         const string trimmed = type.substr(0, last);
131         int i = findCType(trimmed);
132         if (i >= 0) {
133             baseType = trimmed;
134             vectorSize = lastChar;
135         }
136     }
137 }
138 
parseParameterDefinition(const string & type,const string & name,const string & testOption,int lineNumber,bool isReturn,Scanner * scanner)139 void ParameterDefinition::parseParameterDefinition(const string& type, const string& name,
140                                                    const string& testOption, int lineNumber,
141                                                    bool isReturn, Scanner* scanner) {
142     rsType = type;
143     specName = name;
144 
145     // Determine if this is an output.
146     isOutParameter = isReturn || charRemoved('*', &rsType);
147 
148     getVectorSizeAndBaseType(rsType, mVectorSize, rsBaseType);
149     typeIndex = findCType(rsBaseType);
150 
151     if (mVectorSize == "3") {
152         vectorWidth = "4";
153     } else {
154         vectorWidth = mVectorSize;
155     }
156 
157     /* Create variable names to be used in the java and .rs files.  Because x and
158      * y are reserved in .rs files, we prefix variable names with "in" or "out".
159      */
160     if (isOutParameter) {
161         variableName = "out";
162         if (!specName.empty()) {
163             variableName += capitalize(specName);
164         } else if (!isReturn) {
165             scanner->error(lineNumber) << "Should have a name.\n";
166         }
167         doubleVariableName = variableName + "Double";
168     } else {
169         variableName = "in";
170         if (specName.empty()) {
171             scanner->error(lineNumber) << "Should have a name.\n";
172         }
173         variableName += capitalize(specName);
174         doubleVariableName = variableName + "Double";
175     }
176     rsAllocName = "gAlloc" + capitalize(variableName);
177     javaAllocName = variableName;
178     javaArrayName = "array" + capitalize(javaAllocName);
179 
180     // Process the option.
181     undefinedIfOutIsNan = false;
182     compatibleTypeIndex = -1;
183     if (!testOption.empty()) {
184         if (testOption.compare(0, 6, "range(") == 0) {
185             size_t pComma = testOption.find(',');
186             size_t pParen = testOption.find(')');
187             if (pComma == string::npos || pParen == string::npos) {
188                 scanner->error(lineNumber) << "Incorrect range " << testOption << "\n";
189             } else {
190                 minValue = testOption.substr(6, pComma - 6);
191                 maxValue = testOption.substr(pComma + 1, pParen - pComma - 1);
192             }
193         } else if (testOption.compare(0, 6, "above(") == 0) {
194             size_t pParen = testOption.find(')');
195             if (pParen == string::npos) {
196                 scanner->error(lineNumber) << "Incorrect testOption " << testOption << "\n";
197             } else {
198                 smallerParameter = testOption.substr(6, pParen - 6);
199             }
200         } else if (testOption.compare(0, 11, "compatible(") == 0) {
201             size_t pParen = testOption.find(')');
202             if (pParen == string::npos) {
203                 scanner->error(lineNumber) << "Incorrect testOption " << testOption << "\n";
204             } else {
205                 compatibleTypeIndex = findCType(testOption.substr(11, pParen - 11));
206             }
207         } else if (testOption.compare(0, 11, "conditional") == 0) {
208             undefinedIfOutIsNan = true;
209         } else {
210             scanner->error(lineNumber) << "Unrecognized testOption " << testOption << "\n";
211         }
212     }
213 
214     isFloatType = false;
215     if (typeIndex >= 0) {
216         javaBaseType = TYPES[typeIndex].javaType;
217         specType = TYPES[typeIndex].specType;
218         isFloatType = TYPES[typeIndex].exponentBits > 0;
219     }
220     if (!minValue.empty()) {
221         if (typeIndex < 0 || TYPES[typeIndex].kind != FLOATING_POINT) {
222             scanner->error(lineNumber) << "range(,) is only supported for floating point\n";
223         }
224     }
225 }
226 
scan(Scanner * scanner,unsigned int maxApiLevel)227 bool VersionInfo::scan(Scanner* scanner, unsigned int maxApiLevel) {
228     if (scanner->findOptionalTag("version:")) {
229         const string s = scanner->getValue();
230         if (s.compare(0, sizeof(kTagUnreleased), kTagUnreleased) == 0) {
231             // The API is still under development and does not have
232             // an official version number.
233             minVersion = maxVersion = kUnreleasedVersion;
234         } else {
235             sscanf(s.c_str(), "%u %u", &minVersion, &maxVersion);
236             if (minVersion && minVersion < MIN_API_LEVEL) {
237                 scanner->error() << "Minimum version must >= 9\n";
238             }
239             if (minVersion == MIN_API_LEVEL) {
240                 minVersion = 0;
241             }
242             if (maxVersion && maxVersion < MIN_API_LEVEL) {
243                 scanner->error() << "Maximum version must >= 9\n";
244             }
245         }
246     }
247     if (scanner->findOptionalTag("size:")) {
248         sscanf(scanner->getValue().c_str(), "%i", &intSize);
249     }
250 
251     if (maxVersion > maxApiLevel) {
252         maxVersion = maxApiLevel;
253     }
254 
255     return minVersion == 0 || minVersion <= maxApiLevel;
256 }
257 
Definition(const std::string & name)258 Definition::Definition(const std::string& name)
259     : mName(name), mDeprecatedApiLevel(0), mHidden(false), mFinalVersion(-1) {
260 }
261 
updateFinalVersion(const VersionInfo & info)262 void Definition::updateFinalVersion(const VersionInfo& info) {
263     /* We set it if:
264      * - We have never set mFinalVersion before, or
265      * - The max version is 0, which means we have not expired this API, or
266      * - We have a max that's later than what we currently have.
267      */
268     if (mFinalVersion < 0 || info.maxVersion == 0 ||
269         (mFinalVersion > 0 && info.maxVersion > mFinalVersion)) {
270         mFinalVersion = info.maxVersion;
271     }
272 }
273 
scanDocumentationTags(Scanner * scanner,bool firstOccurence,const SpecFile * specFile)274 void Definition::scanDocumentationTags(Scanner* scanner, bool firstOccurence,
275                                        const SpecFile* specFile) {
276     if (scanner->findOptionalTag("hidden:")) {
277         scanner->checkNoValue();
278         mHidden = true;
279     }
280     if (scanner->findOptionalTag("deprecated:")) {
281         string value = scanner->getValue();
282         size_t pComma = value.find(", ");
283         if (pComma != string::npos) {
284             mDeprecatedMessage = value.substr(pComma + 2);
285             value.erase(pComma);
286         }
287         sscanf(value.c_str(), "%i", &mDeprecatedApiLevel);
288         if (mDeprecatedApiLevel <= 0) {
289             scanner->error() << "deprecated entries should have a level > 0\n";
290         }
291     }
292     if (firstOccurence) {
293         if (scanner->findTag("summary:")) {
294             mSummary = scanner->getValue();
295         }
296         if (scanner->findTag("description:")) {
297             scanner->checkNoValue();
298             while (scanner->findOptionalTag("")) {
299                 mDescription.push_back(scanner->getValue());
300             }
301         }
302         mUrl = specFile->getDetailedDocumentationUrl() + "#android_rs:" + mName;
303     } else if (scanner->findOptionalTag("summary:")) {
304         scanner->error() << "Only the first specification should have a summary.\n";
305     }
306 }
307 
~Constant()308 Constant::~Constant() {
309     for (auto i : mSpecifications) {
310         delete i;
311     }
312 }
313 
~Type()314 Type::~Type() {
315     for (auto i : mSpecifications) {
316         delete i;
317     }
318 }
319 
Function(const string & name)320 Function::Function(const string& name) : Definition(name) {
321     mCapitalizedName = capitalize(mName);
322 }
323 
~Function()324 Function::~Function() {
325     for (auto i : mSpecifications) {
326         delete i;
327     }
328 }
329 
someParametersAreDocumented() const330 bool Function::someParametersAreDocumented() const {
331     for (auto p : mParameters) {
332         if (!p->documentation.empty()) {
333             return true;
334         }
335     }
336     return false;
337 }
338 
addParameter(ParameterEntry * entry,Scanner * scanner)339 void Function::addParameter(ParameterEntry* entry, Scanner* scanner) {
340     for (auto i : mParameters) {
341         if (i->name == entry->name) {
342             // It's a duplicate.
343             if (!entry->documentation.empty()) {
344                 scanner->error(entry->lineNumber)
345                             << "Only the first occurence of an arg should have the "
346                                "documentation.\n";
347             }
348             return;
349         }
350     }
351     mParameters.push_back(entry);
352 }
353 
addReturn(ParameterEntry * entry,Scanner * scanner)354 void Function::addReturn(ParameterEntry* entry, Scanner* scanner) {
355     if (entry->documentation.empty()) {
356         return;
357     }
358     if (!mReturnDocumentation.empty()) {
359         scanner->error() << "ret: should be documented only for the first variant\n";
360     }
361     mReturnDocumentation = entry->documentation;
362 }
363 
scanConstantSpecification(Scanner * scanner,SpecFile * specFile,unsigned int maxApiLevel)364 void ConstantSpecification::scanConstantSpecification(Scanner* scanner, SpecFile* specFile,
365                                                       unsigned int maxApiLevel) {
366     string name = scanner->getValue();
367     VersionInfo info;
368     if (!info.scan(scanner, maxApiLevel)) {
369         cout << "Skipping some " << name << " definitions.\n";
370         scanner->skipUntilTag("end:");
371         return;
372     }
373 
374     bool created = false;
375     Constant* constant = systemSpecification.findOrCreateConstant(name, &created);
376     ConstantSpecification* spec = new ConstantSpecification(constant);
377     constant->addSpecification(spec);
378     constant->updateFinalVersion(info);
379     specFile->addConstantSpecification(spec, created);
380     spec->mVersionInfo = info;
381 
382     if (scanner->findTag("value:")) {
383         spec->mValue = scanner->getValue();
384     }
385     constant->scanDocumentationTags(scanner, created, specFile);
386 
387     scanner->findTag("end:");
388 }
389 
scanTypeSpecification(Scanner * scanner,SpecFile * specFile,unsigned int maxApiLevel)390 void TypeSpecification::scanTypeSpecification(Scanner* scanner, SpecFile* specFile,
391                                               unsigned int maxApiLevel) {
392     string name = scanner->getValue();
393     VersionInfo info;
394     if (!info.scan(scanner, maxApiLevel)) {
395         cout << "Skipping some " << name << " definitions.\n";
396         scanner->skipUntilTag("end:");
397         return;
398     }
399 
400     bool created = false;
401     Type* type = systemSpecification.findOrCreateType(name, &created);
402     TypeSpecification* spec = new TypeSpecification(type);
403     type->addSpecification(spec);
404     type->updateFinalVersion(info);
405     specFile->addTypeSpecification(spec, created);
406     spec->mVersionInfo = info;
407 
408     if (scanner->findOptionalTag("simple:")) {
409         spec->mKind = SIMPLE;
410         spec->mSimpleType = scanner->getValue();
411     }
412     if (scanner->findOptionalTag("rs_object:")) {
413         spec->mKind = RS_OBJECT;
414     }
415     if (scanner->findOptionalTag("struct:")) {
416         spec->mKind = STRUCT;
417         spec->mStructName = scanner->getValue();
418         while (scanner->findOptionalTag("field:")) {
419             string s = scanner->getValue();
420             string comment;
421             scanner->parseDocumentation(&s, &comment);
422             spec->mFields.push_back(s);
423             spec->mFieldComments.push_back(comment);
424         }
425     }
426     if (scanner->findOptionalTag("enum:")) {
427         spec->mKind = ENUM;
428         spec->mEnumName = scanner->getValue();
429         while (scanner->findOptionalTag("value:")) {
430             string s = scanner->getValue();
431             string comment;
432             scanner->parseDocumentation(&s, &comment);
433             spec->mValues.push_back(s);
434             spec->mValueComments.push_back(comment);
435         }
436     }
437     if (scanner->findOptionalTag("attrib:")) {
438         spec->mAttribute = scanner->getValue();
439     }
440     type->scanDocumentationTags(scanner, created, specFile);
441 
442     scanner->findTag("end:");
443 }
444 
~FunctionSpecification()445 FunctionSpecification::~FunctionSpecification() {
446     for (auto i : mParameters) {
447         delete i;
448     }
449     delete mReturn;
450     for (auto i : mPermutations) {
451         delete i;
452     }
453 }
454 
expandRSTypeInString(const string & s,const string & pattern,const string & cTypeStr) const455 string FunctionSpecification::expandRSTypeInString(const string &s,
456                                                    const string &pattern,
457                                                    const string &cTypeStr) const {
458     // Find index of numerical type corresponding to cTypeStr.  The case where
459     // pattern is found in s but cTypeStr is not a numerical type is checked in
460     // checkRSTPatternValidity.
461     int typeIdx = findCType(cTypeStr);
462     if (typeIdx == -1) {
463         return s;
464     }
465     // If index exists, perform replacement.
466     return stringReplace(s, pattern, TYPES[typeIdx].rsDataType);
467 }
468 
expandString(string s,int replacementIndexes[MAX_REPLACEABLES]) const469 string FunctionSpecification::expandString(string s,
470                                            int replacementIndexes[MAX_REPLACEABLES]) const {
471 
472 
473     for (unsigned idx = 0; idx < mReplaceables.size(); idx ++) {
474         string toString = mReplaceables[idx][replacementIndexes[idx]];
475 
476         // replace #RST_i patterns with RS datatype corresponding to toString
477         s = expandRSTypeInString(s, kRSTypePatterns[idx], toString);
478 
479         // replace #i patterns with C type from mReplaceables
480         s = stringReplace(s, kCTypePatterns[idx], toString);
481     }
482 
483     return s;
484 }
485 
expandStringVector(const vector<string> & in,int replacementIndexes[MAX_REPLACEABLES],vector<string> * out) const486 void FunctionSpecification::expandStringVector(const vector<string>& in,
487                                                int replacementIndexes[MAX_REPLACEABLES],
488                                                vector<string>* out) const {
489     out->clear();
490     for (vector<string>::const_iterator iter = in.begin(); iter != in.end(); iter++) {
491         out->push_back(expandString(*iter, replacementIndexes));
492     }
493 }
494 
createPermutations(Function * function,Scanner * scanner)495 void FunctionSpecification::createPermutations(Function* function, Scanner* scanner) {
496     int start[MAX_REPLACEABLES];
497     int end[MAX_REPLACEABLES];
498     for (int i = 0; i < MAX_REPLACEABLES; i++) {
499         if (i < (int)mReplaceables.size()) {
500             start[i] = 0;
501             end[i] = mReplaceables[i].size();
502         } else {
503             start[i] = -1;
504             end[i] = 0;
505         }
506     }
507     int replacementIndexes[MAX_REPLACEABLES];
508     // TODO: These loops assume that MAX_REPLACEABLES is 4.
509     for (replacementIndexes[3] = start[3]; replacementIndexes[3] < end[3];
510          replacementIndexes[3]++) {
511         for (replacementIndexes[2] = start[2]; replacementIndexes[2] < end[2];
512              replacementIndexes[2]++) {
513             for (replacementIndexes[1] = start[1]; replacementIndexes[1] < end[1];
514                  replacementIndexes[1]++) {
515                 for (replacementIndexes[0] = start[0]; replacementIndexes[0] < end[0];
516                      replacementIndexes[0]++) {
517                     auto p = new FunctionPermutation(function, this, replacementIndexes, scanner);
518                     mPermutations.push_back(p);
519                 }
520             }
521         }
522     }
523 }
524 
getName(int replacementIndexes[MAX_REPLACEABLES]) const525 string FunctionSpecification::getName(int replacementIndexes[MAX_REPLACEABLES]) const {
526     return expandString(mUnexpandedName, replacementIndexes);
527 }
528 
getReturn(int replacementIndexes[MAX_REPLACEABLES],std::string * retType,int * lineNumber) const529 void FunctionSpecification::getReturn(int replacementIndexes[MAX_REPLACEABLES],
530                                       std::string* retType, int* lineNumber) const {
531     *retType = expandString(mReturn->type, replacementIndexes);
532     *lineNumber = mReturn->lineNumber;
533 }
534 
getParam(size_t index,int replacementIndexes[MAX_REPLACEABLES],std::string * type,std::string * name,std::string * testOption,int * lineNumber) const535 void FunctionSpecification::getParam(size_t index, int replacementIndexes[MAX_REPLACEABLES],
536                                      std::string* type, std::string* name, std::string* testOption,
537                                      int* lineNumber) const {
538     ParameterEntry* p = mParameters[index];
539     *type = expandString(p->type, replacementIndexes);
540     *name = p->name;
541     *testOption = expandString(p->testOption, replacementIndexes);
542     *lineNumber = p->lineNumber;
543 }
544 
getInlines(int replacementIndexes[MAX_REPLACEABLES],std::vector<std::string> * inlines) const545 void FunctionSpecification::getInlines(int replacementIndexes[MAX_REPLACEABLES],
546                                        std::vector<std::string>* inlines) const {
547     expandStringVector(mInline, replacementIndexes, inlines);
548 }
549 
parseTest(Scanner * scanner)550 void FunctionSpecification::parseTest(Scanner* scanner) {
551     const string value = scanner->getValue();
552     if (value == "scalar" || value == "vector" || value == "noverify" || value == "custom" ||
553         value == "none") {
554         mTest = value;
555     } else if (value.compare(0, 7, "limited") == 0) {
556         mTest = "limited";
557         if (value.compare(7, 1, "(") == 0) {
558             size_t pParen = value.find(')');
559             if (pParen == string::npos) {
560                 scanner->error() << "Incorrect test: \"" << value << "\"\n";
561             } else {
562                 mPrecisionLimit = value.substr(8, pParen - 8);
563             }
564         }
565     } else {
566         scanner->error() << "Unrecognized test option: \"" << value << "\"\n";
567     }
568 }
569 
hasTests(unsigned int versionOfTestFiles) const570 bool FunctionSpecification::hasTests(unsigned int versionOfTestFiles) const {
571     if (mVersionInfo.maxVersion != 0 && mVersionInfo.maxVersion < versionOfTestFiles) {
572         return false;
573     }
574     if (mTest == "none") {
575         return false;
576     }
577     return true;
578 }
579 
checkRSTPatternValidity(const string & inlineStr,bool allow,Scanner * scanner)580 void FunctionSpecification::checkRSTPatternValidity(const string &inlineStr,  bool allow,
581                                                     Scanner *scanner) {
582     for (int i = 0; i < MAX_REPLACEABLES; i ++) {
583         bool patternFound = inlineStr.find(kRSTypePatterns[i]) != string::npos;
584 
585         if (patternFound) {
586             if (!allow) {
587                 scanner->error() << "RST_i pattern not allowed here\n";
588             }
589             else if (mIsRSTAllowed[i] == false) {
590                 scanner->error() << "Found pattern \"" << kRSTypePatterns[i]
591                     << "\" in spec.  But some entry in the corresponding"
592                     << " parameter list cannot be translated to an RS type\n";
593             }
594         }
595     }
596 }
597 
scanFunctionSpecification(Scanner * scanner,SpecFile * specFile,unsigned int maxApiLevel)598 void FunctionSpecification::scanFunctionSpecification(Scanner* scanner, SpecFile* specFile,
599                                                       unsigned int maxApiLevel) {
600     // Some functions like convert have # part of the name.  Truncate at that point.
601     const string& unexpandedName = scanner->getValue();
602     string name = unexpandedName;
603     size_t p = name.find('#');
604     if (p != string::npos) {
605         if (p > 0 && name[p - 1] == '_') {
606             p--;
607         }
608         name.erase(p);
609     }
610     VersionInfo info;
611     if (!info.scan(scanner, maxApiLevel)) {
612         cout << "Skipping some " << name << " definitions.\n";
613         scanner->skipUntilTag("end:");
614         return;
615     }
616 
617     bool created = false;
618     Function* function = systemSpecification.findOrCreateFunction(name, &created);
619     FunctionSpecification* spec = new FunctionSpecification(function);
620     function->addSpecification(spec);
621     function->updateFinalVersion(info);
622     specFile->addFunctionSpecification(spec, created);
623 
624     spec->mUnexpandedName = unexpandedName;
625     spec->mTest = "scalar";  // default
626     spec->mVersionInfo = info;
627 
628     if (scanner->findOptionalTag("internal:")) {
629         spec->mInternal = (scanner->getValue() == "true");
630     }
631     if (scanner->findOptionalTag("intrinsic:")) {
632         spec->mIntrinsic = (scanner->getValue() == "true");
633     }
634     if (scanner->findOptionalTag("attrib:")) {
635         spec->mAttribute = scanner->getValue();
636     }
637     if (scanner->findOptionalTag("w:")) {
638         vector<string> t;
639         if (scanner->getValue().find("1") != string::npos) {
640             t.push_back("");
641         }
642         if (scanner->getValue().find("2") != string::npos) {
643             t.push_back("2");
644         }
645         if (scanner->getValue().find("3") != string::npos) {
646             t.push_back("3");
647         }
648         if (scanner->getValue().find("4") != string::npos) {
649             t.push_back("4");
650         }
651         spec->mReplaceables.push_back(t);
652         // RST_i pattern not applicable for width.
653         spec->mIsRSTAllowed.push_back(false);
654     }
655 
656     while (scanner->findOptionalTag("t:")) {
657         spec->mReplaceables.push_back(convertToTypeVector(scanner->getValue()));
658         spec->mIsRSTAllowed.push_back(isRSTValid(spec->mReplaceables.back()));
659     }
660 
661     // Disallow RST_* pattern in function name
662     // FIXME the line number for this error would be wrong
663     spec->checkRSTPatternValidity(unexpandedName, false, scanner);
664 
665     if (scanner->findTag("ret:")) {
666         ParameterEntry* p = scanner->parseArgString(true);
667         function->addReturn(p, scanner);
668         spec->mReturn = p;
669 
670         // Disallow RST_* pattern in return type
671         spec->checkRSTPatternValidity(p->type, false, scanner);
672     }
673     while (scanner->findOptionalTag("arg:")) {
674         ParameterEntry* p = scanner->parseArgString(false);
675         function->addParameter(p, scanner);
676         spec->mParameters.push_back(p);
677 
678         // Disallow RST_* pattern in parameter type or testOption
679         spec->checkRSTPatternValidity(p->type, false, scanner);
680         spec->checkRSTPatternValidity(p->testOption, false, scanner);
681     }
682 
683     function->scanDocumentationTags(scanner, created, specFile);
684 
685     if (scanner->findOptionalTag("inline:")) {
686         scanner->checkNoValue();
687         while (scanner->findOptionalTag("")) {
688             spec->mInline.push_back(scanner->getValue());
689 
690             // Allow RST_* pattern in inline definitions
691             spec->checkRSTPatternValidity(spec->mInline.back(), true, scanner);
692         }
693     }
694     if (scanner->findOptionalTag("test:")) {
695         spec->parseTest(scanner);
696     }
697 
698     scanner->findTag("end:");
699 
700     spec->createPermutations(function, scanner);
701 }
702 
FunctionPermutation(Function * func,FunctionSpecification * spec,int replacementIndexes[MAX_REPLACEABLES],Scanner * scanner)703 FunctionPermutation::FunctionPermutation(Function* func, FunctionSpecification* spec,
704                                          int replacementIndexes[MAX_REPLACEABLES], Scanner* scanner)
705     : mReturn(nullptr), mInputCount(0), mOutputCount(0) {
706     // We expand the strings now to make capitalization easier.  The previous code preserved
707     // the #n
708     // markers just before emitting, which made capitalization difficult.
709     mName = spec->getName(replacementIndexes);
710     mNameTrunk = func->getName();
711     mTest = spec->getTest();
712     mPrecisionLimit = spec->getPrecisionLimit();
713     spec->getInlines(replacementIndexes, &mInline);
714 
715     mHasFloatAnswers = false;
716     for (size_t i = 0; i < spec->getNumberOfParams(); i++) {
717         string type, name, testOption;
718         int lineNumber = 0;
719         spec->getParam(i, replacementIndexes, &type, &name, &testOption, &lineNumber);
720         ParameterDefinition* def = new ParameterDefinition();
721         def->parseParameterDefinition(type, name, testOption, lineNumber, false, scanner);
722         if (def->isOutParameter) {
723             mOutputCount++;
724         } else {
725             mInputCount++;
726         }
727 
728         if (def->typeIndex < 0 && mTest != "none") {
729             scanner->error(lineNumber)
730                         << "Could not find " << def->rsBaseType
731                         << " while generating automated tests.  Use test: none if not needed.\n";
732         }
733         if (def->isOutParameter && def->isFloatType) {
734             mHasFloatAnswers = true;
735         }
736         mParams.push_back(def);
737     }
738 
739     string retType;
740     int lineNumber = 0;
741     spec->getReturn(replacementIndexes, &retType, &lineNumber);
742     if (!retType.empty()) {
743         mReturn = new ParameterDefinition();
744         mReturn->parseParameterDefinition(retType, "", "", lineNumber, true, scanner);
745         if (mReturn->isFloatType) {
746             mHasFloatAnswers = true;
747         }
748         mOutputCount++;
749     }
750 }
751 
~FunctionPermutation()752 FunctionPermutation::~FunctionPermutation() {
753     for (auto i : mParams) {
754         delete i;
755     }
756     delete mReturn;
757 }
758 
SpecFile(const string & specFileName)759 SpecFile::SpecFile(const string& specFileName) : mSpecFileName(specFileName) {
760     string core = mSpecFileName;
761     // Remove .spec
762     size_t l = core.length();
763     const char SPEC[] = ".spec";
764     const int SPEC_SIZE = sizeof(SPEC) - 1;
765     const int start = l - SPEC_SIZE;
766     if (start >= 0 && core.compare(start, SPEC_SIZE, SPEC) == 0) {
767         core.erase(start);
768     }
769 
770     // The header file name should have the same base but with a ".rsh" extension.
771     mHeaderFileName = core + ".rsh";
772     mDetailedDocumentationUrl = core + ".html";
773 }
774 
addConstantSpecification(ConstantSpecification * spec,bool hasDocumentation)775 void SpecFile::addConstantSpecification(ConstantSpecification* spec, bool hasDocumentation) {
776     mConstantSpecificationsList.push_back(spec);
777     if (hasDocumentation) {
778         Constant* constant = spec->getConstant();
779         mDocumentedConstants.insert(pair<string, Constant*>(constant->getName(), constant));
780     }
781 }
782 
addTypeSpecification(TypeSpecification * spec,bool hasDocumentation)783 void SpecFile::addTypeSpecification(TypeSpecification* spec, bool hasDocumentation) {
784     mTypeSpecificationsList.push_back(spec);
785     if (hasDocumentation) {
786         Type* type = spec->getType();
787         mDocumentedTypes.insert(pair<string, Type*>(type->getName(), type));
788     }
789 }
790 
addFunctionSpecification(FunctionSpecification * spec,bool hasDocumentation)791 void SpecFile::addFunctionSpecification(FunctionSpecification* spec, bool hasDocumentation) {
792     mFunctionSpecificationsList.push_back(spec);
793     if (hasDocumentation) {
794         Function* function = spec->getFunction();
795         mDocumentedFunctions.insert(pair<string, Function*>(function->getName(), function));
796     }
797 }
798 
799 // Read the specification, adding the definitions to the global functions map.
readSpecFile(unsigned int maxApiLevel)800 bool SpecFile::readSpecFile(unsigned int maxApiLevel) {
801     FILE* specFile = fopen(mSpecFileName.c_str(), "rt");
802     if (!specFile) {
803         cerr << "Error opening input file: " << mSpecFileName << "\n";
804         return false;
805     }
806 
807     Scanner scanner(mSpecFileName, specFile);
808 
809     // Scan the header that should start the file.
810     scanner.skipBlankEntries();
811     if (scanner.findTag("header:")) {
812         if (scanner.findTag("summary:")) {
813             mBriefDescription = scanner.getValue();
814         }
815         if (scanner.findTag("description:")) {
816             scanner.checkNoValue();
817             while (scanner.findOptionalTag("")) {
818                 mFullDescription.push_back(scanner.getValue());
819             }
820         }
821         if (scanner.findOptionalTag("include:")) {
822             scanner.checkNoValue();
823             while (scanner.findOptionalTag("")) {
824                 mVerbatimInclude.push_back(scanner.getValue());
825             }
826         }
827         scanner.findTag("end:");
828     }
829 
830     while (1) {
831         scanner.skipBlankEntries();
832         if (scanner.atEnd()) {
833             break;
834         }
835         const string tag = scanner.getNextTag();
836         if (tag == "function:") {
837             FunctionSpecification::scanFunctionSpecification(&scanner, this, maxApiLevel);
838         } else if (tag == "type:") {
839             TypeSpecification::scanTypeSpecification(&scanner, this, maxApiLevel);
840         } else if (tag == "constant:") {
841             ConstantSpecification::scanConstantSpecification(&scanner, this, maxApiLevel);
842         } else {
843             scanner.error() << "Expected function:, type:, or constant:.  Found: " << tag << "\n";
844             return false;
845         }
846     }
847 
848     fclose(specFile);
849     return scanner.getErrorCount() == 0;
850 }
851 
~SystemSpecification()852 SystemSpecification::~SystemSpecification() {
853     for (auto i : mConstants) {
854         delete i.second;
855     }
856     for (auto i : mTypes) {
857         delete i.second;
858     }
859     for (auto i : mFunctions) {
860         delete i.second;
861     }
862     for (auto i : mSpecFiles) {
863         delete i;
864     }
865 }
866 
867 // Returns the named entry in the map.  Creates it if it's not there.
868 template <class T>
findOrCreate(const string & name,map<string,T * > * map,bool * created)869 T* findOrCreate(const string& name, map<string, T*>* map, bool* created) {
870     auto iter = map->find(name);
871     if (iter != map->end()) {
872         *created = false;
873         return iter->second;
874     }
875     *created = true;
876     T* f = new T(name);
877     map->insert(pair<string, T*>(name, f));
878     return f;
879 }
880 
findOrCreateConstant(const string & name,bool * created)881 Constant* SystemSpecification::findOrCreateConstant(const string& name, bool* created) {
882     return findOrCreate<Constant>(name, &mConstants, created);
883 }
884 
findOrCreateType(const string & name,bool * created)885 Type* SystemSpecification::findOrCreateType(const string& name, bool* created) {
886     return findOrCreate<Type>(name, &mTypes, created);
887 }
888 
findOrCreateFunction(const string & name,bool * created)889 Function* SystemSpecification::findOrCreateFunction(const string& name, bool* created) {
890     return findOrCreate<Function>(name, &mFunctions, created);
891 }
892 
readSpecFile(const string & fileName,unsigned int maxApiLevel)893 bool SystemSpecification::readSpecFile(const string& fileName, unsigned int maxApiLevel) {
894     SpecFile* spec = new SpecFile(fileName);
895     if (!spec->readSpecFile(maxApiLevel)) {
896         cerr << fileName << ": Failed to parse.\n";
897         return false;
898     }
899     mSpecFiles.push_back(spec);
900     return true;
901 }
902 
903 
updateMaxApiLevel(const VersionInfo & info,unsigned int * maxApiLevel)904 static void updateMaxApiLevel(const VersionInfo& info, unsigned int* maxApiLevel) {
905     if (info.minVersion == VersionInfo::kUnreleasedVersion) {
906         // Ignore development API level in consideration of max API level.
907         return;
908     }
909     *maxApiLevel = max(*maxApiLevel, max(info.minVersion, info.maxVersion));
910 }
911 
getMaximumApiLevel()912 unsigned int SystemSpecification::getMaximumApiLevel() {
913     unsigned int maxApiLevel = 0;
914     for (auto i : mConstants) {
915         for (auto j: i.second->getSpecifications()) {
916             updateMaxApiLevel(j->getVersionInfo(), &maxApiLevel);
917         }
918     }
919     for (auto i : mTypes) {
920         for (auto j: i.second->getSpecifications()) {
921             updateMaxApiLevel(j->getVersionInfo(), &maxApiLevel);
922         }
923     }
924     for (auto i : mFunctions) {
925         for (auto j: i.second->getSpecifications()) {
926             updateMaxApiLevel(j->getVersionInfo(), &maxApiLevel);
927         }
928     }
929     return maxApiLevel;
930 }
931 
generateFiles(bool forVerification,unsigned int maxApiLevel) const932 bool SystemSpecification::generateFiles(bool forVerification, unsigned int maxApiLevel) const {
933     bool success = generateHeaderFiles("scriptc") &&
934                    generateDocumentation("docs", forVerification) &&
935                    generateTestFiles("test", maxApiLevel) &&
936                    generateStubsWhiteList("slangtest", maxApiLevel);
937     if (success) {
938         cout << "Successfully processed " << mTypes.size() << " types, " << mConstants.size()
939              << " constants, and " << mFunctions.size() << " functions.\n";
940     }
941     return success;
942 }
943 
getHtmlAnchor(const string & name) const944 string SystemSpecification::getHtmlAnchor(const string& name) const {
945     Definition* d = nullptr;
946     auto c = mConstants.find(name);
947     if (c != mConstants.end()) {
948         d = c->second;
949     } else {
950         auto t = mTypes.find(name);
951         if (t != mTypes.end()) {
952             d = t->second;
953         } else {
954             auto f = mFunctions.find(name);
955             if (f != mFunctions.end()) {
956                 d = f->second;
957             } else {
958                 return string();
959             }
960         }
961     }
962     ostringstream stream;
963     stream << "<a href='" << d->getUrl() << "'>" << name << "</a>";
964     return stream.str();
965 }
966