Classes/Renderers.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# These classes are the renderers that provide custom format functions for use in StringTemplates.
using namespace Antlr4.StringTemplate

enum IndentKind {
    Space;
    Tab;
}

# Base class for custom format functions in StringTemplates.
#
# TODO: Add indentation frames similar to in CustomControlBuilder to avoid having to fix indentation
# post template invocation.
class StringExpressionRenderer : StringRenderer {
    [IndentKind] $IndentKind = [IndentKind]::Space;

    [string] ToString([object] $o, [string] $formatString, [cultureinfo] $culture) {
        if ($formatString -and $this.psobject.Methods.Match($formatString)) {
            return $this.$formatString($o)
        } elseif ($formatString) {
            return ([StringRenderer]$this).ToString($o, $formatString, $culture)
        }
        return $o -as [string]
    }

    [string] ToCamelCase([string] $o) {
        if (-not $o) { return $o }

        if ($o.Length -gt 1) {
            return '{0}{1}' -f $o.Substring(0, 1).ToLower(), $o.SubString(1, $o.Length - 1)
        } else {
            return $o.ToLower()
        }
    }

    # Allows inserting multiple tabs with one template call.
    [string] Tab([string] $o) {
        return $this.GetIndent() * [int]$o
    }

    # Currently always returns spaces.
    # TODO: Rig this up as a setting, or preferably get it from PSES.
    hidden [string] GetIndent() {
        if ($this.IndentKind -eq [IndentKind]::Space) {
            return ' '
        } else {
            return "`t"
        }
    }
}
# Format functions specific to Expand-MemberExpression.
class MemberExpressionRenderer : StringExpressionRenderer {
    # Transform member name for use as a variable name.
    [string] TransformMemberName([string] $o) {
        return $this.ToCamelCase(($o -replace '^\.ctor', 'new'))
    }
}

# Format function to allow using [TypeExpressionHelper] in StringTemplates.
class TypeRenderer : StringRenderer {
    [string] ToString([object] $o, [string] $formatString, [cultureinfo] $culture) {
        if ($o -is [type]) {
            return [TypeExpressionHelper]::Create($o)
        }
        return ([StringRenderer]$this).ToString($o, $formatString, $culture)
    }
}