1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 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 #include "codegen/code_generator.h" 17 #include "metadata/metadata_builder.h" 18 #include "metadata/metadata_dumper.h" 19 #include "metadata/metadata_reader.h" 20 #include "metadata/metadata_serializer.h" 21 #include "parser/parser.h" 22 #include "util/logger.h" 23 #include "util/options.h" 24 25 using namespace OHOS::Idl; 26 27 static const char* TAG = "idl"; 28 main(int argc,char ** argv)29 int main(int argc, char** argv) 30 { 31 Options options(argc, argv); 32 33 if (options.DoShowUsage()) { 34 options.ShowUsage(); 35 return 0; 36 } 37 38 if (options.DoShowVersion()) { 39 options.ShowVersion(); 40 return 0; 41 } 42 43 if (options.HasErrors()) { 44 options.ShowErrors(); 45 return 0; 46 } 47 48 std::shared_ptr<MetaComponent> metadata; 49 50 if (options.DoCompile()) { 51 Parser parser(options); 52 if (!parser.Parse(options.GetSourceFile())) { 53 Logger::E(TAG, "Parsing .idl failed."); 54 return -1; 55 } 56 57 MetadataBuilder builder(parser.GetModule()); 58 metadata = builder.Build(); 59 if (metadata == nullptr) { 60 Logger::E(TAG, "Generate metadata failed."); 61 return -1; 62 } 63 } 64 65 if (options.DoDumpMetadata()) { 66 MetadataDumper dumper(metadata.get()); 67 dumper.Dump(""); 68 } 69 70 if (options.DoSaveMetadata()) { 71 File metadataFile(options.GetMetadataFile(), File::WRITE); 72 if (!metadataFile.IsValid()) { 73 Logger::E(TAG, "Create metadata file failed."); 74 return -1; 75 } 76 77 MetadataSerializer serializer(metadata.get()); 78 serializer.Serialize(); 79 uintptr_t data = serializer.GetData(); 80 int size = serializer.GetDataSize(); 81 82 metadataFile.WriteData(reinterpret_cast<void*>(data), size); 83 metadataFile.Flush(); 84 metadataFile.Close(); 85 } 86 87 if (options.DoGenerateCode()) { 88 if (metadata == nullptr) { 89 String metadataFile = options.GetMetadataFile(); 90 metadata = MetadataReader::ReadMetadataFromFile(metadataFile); 91 if (metadata == nullptr) { 92 Logger::E(TAG, "Get metadata from \"%s\" failed.", metadataFile.string()); 93 return -1; 94 } 95 } 96 97 CodeGenerator codeGen(metadata.get(), options.GetTargetLanguage(), 98 options.GetGenerationDirectory()); 99 if (!codeGen.Generate()) { 100 Logger::E(TAG, "Generate \"%s\" codes failed.", options.GetTargetLanguage().string()); 101 return -1; 102 } 103 } 104 105 return 0; 106 } 107