Add -Lformat option to format .hal files

Formats .hal files.

Bug: 137553653
Test: hidl-gen -Lformat <IFACE>
Test: aosp/1051701
Test: hidl-gen -Lformat (google-interfaces) & hidl-gen -Lcheck
(google-interfaces)
Change-Id: I5aa554d99fd4977acb7939d8c793081680a3f598
diff --git a/Scope.cpp b/Scope.cpp
index d4953aa..cfe004d 100644
--- a/Scope.cpp
+++ b/Scope.cpp
@@ -122,6 +122,16 @@
     return ret;
 }
 
+std::vector<const NamedType*> Scope::getSortedDefinedTypes() const {
+    std::vector<const NamedType*> ret;
+    ret.insert(ret.end(), mTypes.begin(), mTypes.end());
+
+    std::sort(ret.begin(), ret.end(), [](const NamedType* lhs, const NamedType* rhs) -> bool {
+        return lhs->location() < rhs->location();
+    });
+    return ret;
+}
+
 std::vector<const ConstantExpression*> Scope::getConstantExpressions() const {
     std::vector<const ConstantExpression*> ret;
     for (const auto* annotation : mAnnotations) {
@@ -146,6 +156,12 @@
     }
 }
 
+void Scope::emitHidlDefinition(Formatter& out) const {
+    const std::vector<const NamedType*>& definedTypes = getSortedDefinedTypes();
+    out.join(definedTypes.begin(), definedTypes.end(), "\n",
+             [&](auto t) { t->emitHidlDefinition(out); });
+}
+
 void Scope::emitTypeDeclarations(Formatter& out) const {
     if (mTypes.empty()) return;