1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #ifndef TENSORFLOW_TENSORFLOW_LITE_SUPPORT_CODEGEN_CODE_GENERATOR_H_ 17 #define TENSORFLOW_TENSORFLOW_LITE_SUPPORT_CODEGEN_CODE_GENERATOR_H_ 18 19 #include <map> 20 #include <memory> 21 #include <sstream> 22 #include <string> 23 24 #include "tensorflow_lite_support/codegen/utils.h" 25 #include "tensorflow_lite_support/metadata/metadata_schema_generated.h" 26 27 namespace tflite { 28 namespace support { 29 namespace codegen { 30 31 struct GenerationResult { 32 struct File { 33 std::string path; 34 std::string content; 35 }; 36 std::vector<File> files; 37 }; 38 39 /// Defines language-independent codegen strategies, like class naming, .etc. 40 /// Should not be used directly. 41 class CodeGenerator { 42 public: 43 CodeGenerator(); 44 45 using TensorMetadataList = 46 typename flatbuffers::Vector<flatbuffers::Offset<TensorMetadata>>; 47 ~CodeGenerator()48 virtual ~CodeGenerator() {} 49 50 // Strategies. 51 /// Names all the IO tensors. It's useful when they don't have names, or the 52 /// names have conflicts. We have to name every tensor for code generation. 53 // TODO(b/141225157): Add reserved keywords check. 54 static std::pair<std::vector<std::string>, std::vector<std::string>> 55 NameInputsAndOutputs(const TensorMetadataList* inputs, 56 const TensorMetadataList* outputs); 57 58 /// Loads a metadata for code generation. 59 /// Returns false if the metadata is not good for generation. 60 static bool VerifyMetadata(const ModelMetadata* metadata, ErrorReporter* err); 61 62 protected: 63 /// Converts a name into a valid form. Rules: 64 /// - lower all letters. 65 /// - replace all non alphabet nor numeric characters with underscores. 66 /// - remove prefix underscores. 67 /// - add prefix if the leading character is a number. 68 /// Returns empty string if not possible. 69 static std::string ConvertToValidName(const std::string& name); 70 static std::string NameTensor(const TensorMetadata& tensor, 71 const std::string& default_name); 72 static void ResolveConflictedInputAndOutputNames( 73 std::vector<std::string>* input, std::vector<std::string>* output); 74 }; 75 76 } // namespace codegen 77 } // namespace support 78 } // namespace tflite 79 80 #endif // TENSORFLOW_TENSORFLOW_LITE_SUPPORT_CODEGEN_CODE_GENERATOR_H_ 81