首页 > 解决方案 > 如何在 Ada 中读取 yaml 文件

问题描述

我试图了解如何使用 Ada 和 AdaYaml 库(https://github.com/yaml/AdaYaml/)。我有几个 yaml 文件,我需要将它们转换为 Ada 记录以进行进一步处理。

在玩了几个小时的库后,我不知道如何使用 Accessor 访问 yaml 数据。

我最小的工作代码是

with Ada.Text_IO;
with Ada.Command_Line;

with Yaml.Source.File;
with Yaml.Source.Text_IO;
with Yaml.Dom.Loading;
with Yaml.Dom.Node;
with Yaml; use Yaml;
with Text; use Text;

procedure Load_Dom is
   Input : Source.Pointer;
begin
   
   if Ada.Command_Line.Argument_Count = 0 then
      Input := Yaml.Source.Text_IO.As_Source (Ada.Text_IO.Standard_Input);
   else
      Input := Yaml.Source.File.As_Source (Ada.Command_Line.Argument (1));
   end if;
   
   declare
      
      Document : Yaml.Dom.Document_Reference :=
        Yaml.Dom.Loading.From_Source (Input);
     
   begin
      Ada.Text_IO.Put_Line ("Root node is a " & Yaml.Dom.Node.Instance'(Document.Root.Value).Kind'Img);
      Ada.Text_IO.Put_Line ("Root node is a " & Yaml.Dom.Node.Instance'(Document.Root.Value).Tag);
      Ada.Text_IO.Put_Line ("Root node is a " & Yaml.Dom.Node.Instance'(Document.Root.Value).Mapping_Style'Img);
   end;
end Load_Dom;

我认为显式转换Yaml.Dom.Node.Instance'(Document.Root.Value)是不正确的,我必须遗漏一些东西。

任何想法或代码示例如何以正确的方式读取 yaml 文件?

标签: yamlada

解决方案


我是 AdaYaml 的作者。

返回的AccessorwhichDocument.Root.Value定义如下:

type Accessor (Data : not null access Node.Instance) is limited private
     with Implicit_Dereference => Data;

与任何具有判别式的类型一样,您可以Node.Instance通过其名称访问Data. 所以这个显式表达式检索根节点的种类:

Document.Root.Value.Data.all.Kind

现在 Ada 允许我们使指针取消引用隐式,删除.all

Document.Root.Value.Data.Kind

Implicit_Dereference属性允许Accessor我们删除.Data

Document.Root.Value.Kind

所以你想做的是

declare
   Document : Yaml.Dom.Document_Reference :=
      Yaml.Dom.Loading.From_Source (Input);
   Root : Yaml.Dom.Accessor := Document.Root.Value; 
begin
   Ada.Text_IO.Put_Line ("Root node is a " & Root.Kind'Img);
   Ada.Text_IO.Put_Line ("Root node is a " & Root.Tag);
   Ada.Text_IO.Put_Line ("Root node is a " & Root.Mapping_Style'Img);
end;

这在文档中简要显示,但未解释。为了进一步阅读,这颗宝石可能会引起人们的兴趣。


推荐阅读