summaryrefslogtreecommitdiff
path: root/GenPySwift.cs
blob: 54390384fdd549c07607bd1fefa3962003ef945e (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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// GenPySwift.cs - Python/Swift code generator
//
// Copyright (C) 2020-2022  Piotr Fusik
//
// This file is part of CiTo, see https://github.com/pfusik/cito
//
// CiTo is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CiTo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with CiTo.  If not, see http://www.gnu.org/licenses/

using System;
using System.Diagnostics;

namespace Foxoft.Ci
{

public abstract class GenPySwift : GenBase
{
	void WriteDoc(string text)
	{
		foreach (char c in text) {
			if (c == '\n') {
				WriteLine();
				StartDocLine();
			}
			else
				Write(c);
		}
	}

	protected override void Write(CiDocPara para, bool many)
	{
		if (many) {
			WriteLine();
			StartDocLine();
			WriteLine();
			StartDocLine();
		}
		foreach (CiDocInline inline in para.Children) {
			switch (inline) {
			case CiDocText text:
				WriteDoc(text.Text);
				break;
			case CiDocCode code:
				Write('`');
				WriteDoc(code.Text);
				Write('`');
				break;
			default:
				throw new ArgumentException(inline.GetType().Name);
			}
		}
	}

	protected abstract string DocBullet { get; }

	protected override void Write(CiDocList list)
	{
		WriteLine();
		foreach (CiDocPara item in list.Items) {
			Write(this.DocBullet);
			Write(item, false);
			WriteLine();
		}
		StartDocLine();
	}

	protected override void WriteLocalName(CiSymbol symbol, CiPriority parent)
	{
		if (symbol is CiMember member && this.CurrentMethod != null) {
			if (member.IsStatic)
				WriteName(this.CurrentMethod.Parent);
			else
				Write("self");
			Write('.');
		}
		WriteName(symbol);
	}

	public override CiExpr Visit(CiCollection expr, CiPriority parent)
	{
		CiType type = ((CiArrayStorageType) expr.Type).ElementType;
		Write("[ ");
		WriteCoercedLiterals(type, expr.Items);
		Write(" ]");
		return expr;
	}

	protected override void WriteNew(CiClass klass, CiPriority parent)
	{
		WriteClassName(klass);
		Write("()");
	}

	public override CiExpr Visit(CiPrefixExpr expr, CiPriority parent)
	{
		switch (expr.Op) {
		case CiToken.Increment:
		case CiToken.Decrement:
			expr.Inner.Accept(this, parent);
			return expr;
		default:
			return base.Visit(expr, parent);
		}
	}

	public override CiExpr Visit(CiPostfixExpr expr, CiPriority parent)
	{
		switch (expr.Op) {
		case CiToken.Increment:
		case CiToken.Decrement:
			expr.Inner.Accept(this, parent);
			return expr;
		default:
			return base.Visit(expr, parent);
		}
	}

	protected virtual void WriteExpr(CiExpr expr, CiPriority parent)
	{
		expr.Accept(this, parent);
	}

	protected void WriteListAppend(CiExpr obj, CiExpr[] args)
	{
		obj.Accept(this, CiPriority.Primary);
		Write(".append(");
		if (args.Length == 0)
			WriteNewStorage(((CiCollectionType) obj.Type).ElementType);
		else
			args[0].Accept(this, CiPriority.Argument);
		Write(')');
	}

	protected virtual bool VisitPreCall(CiCallExpr call) => false;

	protected bool VisitXcrement<T>(CiExpr expr, bool write) where T : CiUnaryExpr
	{
		bool seen;
		switch (expr) {
		case CiVar def:
			return def.Value != null && VisitXcrement<T>(def.Value, write);
		case CiLiteral literal:
			return false;
		case CiInterpolatedString interp:
			seen = false;
			foreach (CiInterpolatedPart part in interp.Parts)
				seen |= VisitXcrement<T>(part.Argument, write);
			return seen;
		case CiSymbolReference symbol:
			return symbol.Left != null && VisitXcrement<T>(symbol.Left, write);
		case CiUnaryExpr unary:
			if (unary.Inner == null) // new C()
				return false;
			seen = VisitXcrement<T>(unary.Inner, write);
			if ((unary.Op == CiToken.Increment || unary.Op == CiToken.Decrement) && unary is T) {
				if (write) {
					WriteExpr(unary.Inner, CiPriority.Assign);
					WriteLine(unary.Op == CiToken.Increment ? " += 1" : " -= 1");
				}
				seen = true;
			}
			return seen;
		case CiBinaryExpr binary:
			seen = VisitXcrement<T>(binary.Left, write);
			if (binary.Op == CiToken.Is)
				return seen;
			if (binary.Op == CiToken.CondAnd || binary.Op == CiToken.CondOr)
				Trace.Assert(!VisitXcrement<T>(binary.Right, false));
			else
				seen |= VisitXcrement<T>(binary.Right, write);
			return seen;
		case CiSelectExpr select:
			seen = VisitXcrement<T>(select.Cond, write);
			Trace.Assert(!VisitXcrement<T>(select.OnTrue, false));
			Trace.Assert(!VisitXcrement<T>(select.OnFalse, false));
			return seen;
		case CiCallExpr call:
			seen = VisitXcrement<T>(call.Method, write);
			foreach (CiExpr item in call.Arguments)
				seen |= VisitXcrement<T>(item, write);
			if (typeof(T) == typeof(CiPrefixExpr))
				seen |= VisitPreCall(call);
			return seen;
		default:
			throw new NotImplementedException(expr.GetType().Name);
		}
	}

	public override void Visit(CiExpr statement)
	{
		VisitXcrement<CiPrefixExpr>(statement, true);
		if (!(statement is CiUnaryExpr unary) || (unary.Op != CiToken.Increment && unary.Op != CiToken.Decrement)) {
			WriteExpr(statement, CiPriority.Statement);
			WriteLine();
		}
		VisitXcrement<CiPostfixExpr>(statement, true);
	}

	protected abstract void OpenChild();

	protected abstract void CloseChild();

	protected override void WriteChild(CiStatement statement)
	{
		OpenChild();
		statement.Accept(this);
		CloseChild();
	}

	public override void Visit(CiBlock statement)
	{
		Write(statement.Statements);
	}

	bool OpenCond(string statement, CiExpr cond, CiPriority parent)
	{
		VisitXcrement<CiPrefixExpr>(cond, true);
		Write(statement);
		WriteExpr(cond, parent);
		OpenChild();
		return VisitXcrement<CiPostfixExpr>(cond, true);
	}

	protected virtual void WriteContinueDoWhile(CiExpr cond)
	{
		OpenCond("if ", cond, CiPriority.Argument);
		WriteLine("continue");
		CloseChild();
		VisitXcrement<CiPostfixExpr>(cond, true);
		WriteLine("break");
	}

	protected virtual bool NeedCondXcrement(CiLoop loop) => loop.Cond != null;

	void EndBody(CiLoop loop)
	{
		if (loop is CiFor forLoop) {
			if (forLoop.IsRange)
				return;
			forLoop.Advance?.Accept(this);
		}
		if (NeedCondXcrement(loop))
			VisitXcrement<CiPrefixExpr>(loop.Cond, true);
	}

	public override void Visit(CiContinue statement)
	{
		if (statement.Loop is CiDoWhile doWhile)
			WriteContinueDoWhile(doWhile.Cond);
		else {
			EndBody(statement.Loop);
			WriteLine("continue");
		}
	}

	void OpenWhileTrue()
	{
		Write("while ");
		WriteLiteral(true);
		OpenChild();
	}

	protected abstract string GetIfNot();

	public override void Visit(CiDoWhile statement)
	{
		OpenWhileTrue();
		statement.Body.Accept(this);
		if (statement.Body.CompletesNormally) {
			OpenCond(GetIfNot(), statement.Cond, CiPriority.Primary);
			WriteLine("break");
			CloseChild();
			VisitXcrement<CiPostfixExpr>(statement.Cond, true);
		}
		CloseChild();
	}

	protected virtual void OpenWhile(CiLoop loop)
	{
		OpenCond("while ", loop.Cond, CiPriority.Argument);
	}

	void CloseWhile(CiLoop loop)
	{
		loop.Body.Accept(this);
		if (loop.Body.CompletesNormally)
			EndBody(loop);
		CloseChild();
		if (NeedCondXcrement(loop)) {
			if (loop.HasBreak && VisitXcrement<CiPostfixExpr>(loop.Cond, false)) {
				Write("else");
				OpenChild();
				VisitXcrement<CiPostfixExpr>(loop.Cond, true);
				CloseChild();
			}
			else
				VisitXcrement<CiPostfixExpr>(loop.Cond, true);
		}
	}

	protected abstract void WriteForRange(CiVar iter, CiBinaryExpr cond, long rangeStep);

	public override void Visit(CiFor statement)
	{
		if (statement.IsRange) {
			CiVar iter = (CiVar) statement.Init;
			Write("for ");
			if (statement.IsIteratorUsed)
				WriteName(iter);
			else
				Write('_');
			Write(" in ");
			WriteForRange(iter, (CiBinaryExpr) statement.Cond, statement.RangeStep);
			WriteChild(statement.Body);
		}
		else {
			statement.Init?.Accept(this);
			if (statement.Cond != null)
				OpenWhile(statement);
			else
				OpenWhileTrue();
			CloseWhile(statement);
		}
	}

	protected abstract void WriteElseIf();

	public override void Visit(CiIf statement)
	{
		bool condPostXcrement = OpenCond("if ", statement.Cond, CiPriority.Argument);
		statement.OnTrue.Accept(this);
		CloseChild();
		if (statement.OnFalse == null && condPostXcrement && !statement.OnTrue.CompletesNormally)
			VisitXcrement<CiPostfixExpr>(statement.Cond, true);
		else if (statement.OnFalse != null || condPostXcrement) {
			if (!condPostXcrement && statement.OnFalse is CiIf childIf && !VisitXcrement<CiPrefixExpr>(childIf.Cond, false)) {
				WriteElseIf();
				Visit(childIf);
			}
			else {
				Write("else");
				OpenChild();
				VisitXcrement<CiPostfixExpr>(statement.Cond, true);
				statement.OnFalse?.Accept(this);
				CloseChild();
			}
		}
	}

	protected abstract void WriteResultVar();

	public override void Visit(CiReturn statement)
	{
		if (statement.Value == null)
			WriteLine("return");
		else {
			VisitXcrement<CiPrefixExpr>(statement.Value, true);
			if (VisitXcrement<CiPostfixExpr>(statement.Value, false)) {
				WriteResultVar(); // FIXME: name clash? only matters if return ... result++, unlikely
				Write(" = ");
				WriteCoercedExpr(this.CurrentMethod.Type, statement.Value);
				WriteLine();
				VisitXcrement<CiPostfixExpr>(statement.Value, true);
				WriteLine("return result");
			}
			else {
				Write("return ");
				WriteCoercedExpr(this.CurrentMethod.Type, statement.Value);
				WriteLine();
			}
		}
	}

	public override void Visit(CiWhile statement)
	{
		OpenWhile(statement);
		CloseWhile(statement);
	}
}

}