aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.58k stars 484 forks source link

Unable to deserialize short-form intrinsic functions #521

Open ganeshnj opened 4 years ago

ganeshnj commented 4 years ago

What is intrinsic functions? AWS CloudFormation provides several built-in functions that help you manage your stacks. Use intrinsic functions in your templates to assign values to properties that are not available until runtime. Read more

Syntax for the full function name:

Fn::Sub:
  - String
  - Var1Name: Var1Value
    Var2Name: Var2Value

Syntax for the short form:

!Sub
  - String
  - Var1Name: Var1Value
    Var2Name: Var2Value

Issue Short form intrinsic function deserialization fails with

YamlDotNet.Core.YamlException: '(Line: 47, Col: 20, Idx: 1302) - (Line: 47, Col: 94, Idx: 1376): Encountered an unresolved tag '!Sub''

Sample project ConsoleApp1.zip

ganeshnj commented 4 years ago

I played around with node deserilization classes and able to correctly parse the short form intrinsic functions. (Using YamlDotNet 4.2.1.0)

class NodeDeserializer : INodeDeserializer
{
    private readonly HashSet<string> intrinsicFunctionShortForms;
    private readonly IDeserializer deserializer;

    public IntrinsicFunctionShortFormNodeDeserializer(IDeserializer deserializer)
    {
        this.deserializer = deserializer;
    }

    public IntrinsicFunctionShortFormNodeDeserializer(IDeserializer deserializer, HashSet<string> intrinsicFunctionShortForms)
    {
        this.deserializer = deserializer;
        this.intrinsicFunctionShortForms = intrinsicFunctionShortForms;
    }

    public bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
    {
        if (reader.Accept<Scalar>(out var scalar))
        {
            if (intrinsicFunctionShortForms.Contains(scalar.Tag))
            {
                value = $"{scalar.Tag} {scalar.Value}";
                reader.MoveNext();
                return true;
            }
        }

        value = null;
        return false;
    }
}

class NodeTypeResolver : INodeTypeResolver
{
    private readonly HashSet<string> intrinsicFunctionShortForms;

    public IntrinsicFunctionShortFormINodeTypeResolver(HashSet<string> intrinsicFunctionShortForms)
    {
        this.intrinsicFunctionShortForms = intrinsicFunctionShortForms;
    }

    public bool Resolve(NodeEvent nodeEvent, ref Type currentType)
    {
        if (!string.IsNullOrEmpty(nodeEvent.Tag) && intrinsicFunctionShortForms.Contains(nodeEvent.Tag))
        {
            currentType = typeof(string);
            return true;
        }
        return false;
    }
} 
philasmar commented 1 year ago

Any update on this?