summaryrefslogtreecommitdiff
path: root/Compiler/visitors/Main.cs
blob: 3b3239926397ebc3bfedc2bc8a442f36c845189a (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
namespace Q1.Compiler.visitors;

using System.Text;
using Antlr4.Runtime.Tree;
using Q1.Emulator;

public partial class CCompilerVisitor : CGrammarBaseVisitor<object?>
{
    private        int                                          _branchCount   = 1;
    private        List<string>                                 _instructions  = new();
    private        Stack<Dictionary<string, VariableReference>> _variableStack = new();
    private        List<FunctionReference>                      _methods       = new();
    private static int                                          _memLowest     = Q1Layout.FreeMemoryStart;
    private static int                                          _memPointer    = CCompilerVisitor._memLowest;

    private const int ColumnWidth = 30;

    public readonly CommentCompilationMode CommentMode;

    public CCompilerVisitor(CommentCompilationMode commentMode, Encoding encoding)
    {
        this.CommentMode = commentMode;
        this.Encoding = encoding;
    }

    private string GenerateBranchLabel(string type)
    {
        return $"_{type}_{this._branchCount++}";
    }
    private void Instruction(string instruction, string? generatedComment = null)
    {
        this._instructions.Add($"    {instruction}");
        if (generatedComment != null)
            this.CommentLastInstruction(generatedComment);
    }
    private void Blank()
    {
        this._instructions.Add("");
    }
    private void Branch(string name, string? generatedComment = null)
    {
        this._instructions.Add($"{name}:");
        if (generatedComment != null)
            this.CommentLastInstruction(generatedComment);
    }
    private void UserComment(string comment)
    {
        if (this.CommentMode.HasFlag(CommentCompilationMode.UserDefined))
            this._instructions.Add($"    ; {comment}");
    }

    private void GeneratedComment(string comment)
    {
        if (this.CommentMode.HasFlag(CommentCompilationMode.Generated))
            this._instructions.Add($"{"".PadRight(CCompilerVisitor.ColumnWidth)}; {comment}");
    }

    private void CommentLastInstruction(string comment)
    {
        if (!this.CommentMode.HasFlag(CommentCompilationMode.Generated))
            return;

        if (this._instructions.Count == 0)
            throw new Exception("Cannot add comment to last instruction, there are none");

        string lastInstruction = this._instructions[^1];
        lastInstruction = $"{lastInstruction.PadRight(CCompilerVisitor.ColumnWidth)}; {comment}";

        this._instructions[^1] = lastInstruction;
    }


    public IEnumerable<string> Compile(CGrammarParser.ProgramContext program)
    {
        this.Instruction("jmp _main");
        this.Visit(program);

        foreach ((CGrammarParser.FunctionDefinitionContext context, 
                     FunctionReference function, FunctionOverload overload, 
                     List<string> paramNames, List<CType> paramTypes) in this._functionBodies)
            this.VisitFunctionBody(context, function, overload, paramNames, paramTypes);

        return this._instructions;
    }

    private Dictionary<string, VariableReference> EnterScope()
    {
        Dictionary<string, VariableReference> scope = new();
        this._variableStack.Push(scope);

        return scope;
    }
    private void ExitScope()
    {
        foreach ((string key, VariableReference value) in this._variableStack.Peek())
        {
            // CCompilerVisitor._memPointer -= value.Type.Size;
            // if (CCompilerVisitor._memPointer < CCompilerVisitor._memLowest)
            //     throw new CompilerException("Memory pointer is lower than mem lowest!");
        }

        // Delete scope
        this._variableStack.Pop();
    }

    public void DynamicMove(CType type, string source, string dest, string? comment = null)
    {
        if (type.Size == 1)
            this.Instruction($"movb {source}, {dest}", comment);
        else if (type.Size == 2)
            this.Instruction($"mov {source}, {dest}", comment);
        else
            throw new CompilerException($"Cannot move {type.Size} bytes {source} to {dest}");
    }
    
    private CType VisitCType(CGrammarParser.TypeContext typeContext)
    {
        return GetCType(typeContext.GetText().Trim());
    }
    
    private CType GetCType(string type)
    {
        return type switch
        {
            "int"                     => CType.Int,
            "char"                    => CType.Char,
            _ when type.EndsWith("*") => new CTypePtr(this.GetCType(type[..^1])),
            _                         => throw new CompilerException($"Unknown CTYPE '{type}'")
        };
    }
    
    public override object? VisitErrorNode(IErrorNode node)
    {
        if (node.Symbol.Type == CGrammarParser.COMMENT)
        {
            // strip // and \n and whitespace
            string comment = node
                .Symbol.Text
                .TrimStart("//")
                .TrimEnd('\n')
                .Trim();

            this.UserComment(comment);
        }
        
        if (node.Symbol.Type == CGrammarParser.DIRECTIVE)
        {
            // strip // and \n and whitespace
            string directive = node
                .Symbol.Text
                .TrimStart("#")
                .TrimEnd('\n')
                .Trim();

            this.Instruction(directive);
        }

        return base.VisitErrorNode(node);
    }

    public override object? Visit(IParseTree tree)
    {
        if (tree is Context childCtx && tree.Parent is Context ctx)
            ctx.SyncProps(childCtx);

        return base.Visit(tree);
    }

    /// <summary>
    /// Basically identical to base version, except calls Visit on each child, making Visit not redundant.
    /// </summary>
    public override object? VisitChildren(IRuleNode node)
    {
        object? result = this.DefaultResult;
        int childCount = node.ChildCount;
        for (int i = 0; i < childCount && this.ShouldVisitNextChild(node, result); ++i)
        {
            object? nextResult = this.Visit(node.GetChild(i));
            result = this.AggregateResult(result, nextResult);
        }
        return result;
    }
}