-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
444 lines (368 loc) · 12.8 KB
/
main.go
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
parser "github.com/ZacxDev/evolang/antlr-out"
"github.com/antlr4-go/antlr/v4"
"golang.org/x/tools/imports"
)
type EvoLangVisitor struct {
*parser.BaseEvoLangParserVisitor
// Add fields to store state as needed
}
func NewEvoLangVisitor() *EvoLangVisitor {
return &EvoLangVisitor{
BaseEvoLangParserVisitor: &parser.BaseEvoLangParserVisitor{
BaseParseTreeVisitor: &antlr.BaseParseTreeVisitor{},
}, // Proper initialization
}
}
// Implement other visit methods...
func (v *EvoLangVisitor) VisitProg(ctx *parser.ProgContext) interface{} {
var goCode string
for _, child := range ctx.GetChildren() {
if childResult := v.Visit(child.(antlr.ParseTree)); childResult != nil {
goCode += childResult.(string)
}
}
return goCode
}
func (v *EvoLangVisitor) VisitStatement(ctx *parser.StatementContext) interface{} {
var goCode string
switch {
case ctx.ModelDef() != nil:
modelDefCtx := ctx.ModelDef().(*parser.ModelDefContext)
goCode = v.VisitModelDef(modelDefCtx).(string)
case ctx.EnumDef() != nil:
enumDefCtx := ctx.EnumDef().(*parser.EnumDefContext)
goCode = v.VisitEnumDef(enumDefCtx).(string)
case ctx.RuleDef() != nil:
ruleDefCtx := ctx.RuleDef().(*parser.RuleDefContext)
ruleDefGoCode := v.VisitRuleDef(ruleDefCtx)
if ruleDefGoCode == nil {
goCode = "RULEDEF: UNIMPLEMENTED"
} else {
goCode = ruleDefGoCode.(string)
}
case ctx.MutationDef() != nil:
mutationDefCtx := ctx.MutationDef().(*parser.MutationDefContext)
mutationDefGoCode := v.VisitMutationDef(mutationDefCtx)
if mutationDefGoCode == nil {
goCode = "MUTATIONDEF: UNIMPLEMENTED"
} else {
goCode = mutationDefGoCode.(string)
}
case ctx.InputDef() != nil:
inputDefCtx := ctx.InputDef().(*parser.InputDefContext)
inputDefGoCode := v.VisitInputDef(inputDefCtx)
if inputDefGoCode == nil {
goCode = "INPUTDEF: UNIMPLEMENTED"
} else {
goCode = inputDefGoCode.(string)
}
case ctx.MainFunction() != nil:
mainFunctionCtx := ctx.MainFunction().(*parser.MainFunctionContext)
goCode = v.VisitMainFunction(mainFunctionCtx).(string)
}
return goCode
}
func (v *EvoLangVisitor) VisitModelBody(ctx *parser.ModelBodyContext) interface{} {
var goCode string
for _, child := range ctx.GetChildren() {
switch c := child.(type) {
case *parser.ModelFieldDefContext:
goCode += v.VisitModelFieldDef(c).(string) + "\n"
case *parser.EventDefContext:
goCode += v.VisitEventDef(c).(string) + "\n"
// Add cases for other possible child types
}
}
return goCode
}
func (v *EvoLangVisitor) VisitModelFieldDef(ctx *parser.ModelFieldDefContext) interface{} {
fieldName := ctx.ID().GetText()
fieldType := ctx.TypeDef().GetText()
if !isValidType(fieldType) {
log.Fatalf("Invalid type: %s", fieldType)
}
return fieldName + " " + goType(fieldType)
}
// Helper function to convert EvoLang types to Go types
func goType(t string) string {
switch t {
case "Int":
return "int"
case "String":
return "string"
case "Boolean":
return "bool"
// Add other type conversions as necessary
default:
return "interface{}" // or any default type
}
}
// Helper function to validate types
func isValidType(t string) bool {
// Define logic to validate type
return true
}
func (v *EvoLangVisitor) VisitModelDef(ctx *parser.ModelDefContext) interface{} {
modelName := ctx.ID().GetText()
goCode := "type " + modelName + " struct {\n"
// Correctly access the field definitions
for _, fieldCtxInterface := range ctx.ModelBody().AllModelFieldDef() {
// Type assertion to convert IFieldDefContext to *FieldDefContext
fieldCtx := fieldCtxInterface.(*parser.ModelFieldDefContext)
fieldCode := v.VisitModelFieldDef(fieldCtx).(string)
goCode += "\t" + fieldCode + "\n"
}
goCode += "}\n"
return goCode
}
func (v *EvoLangVisitor) VisitEnumDef(ctx *parser.EnumDefContext) interface{} {
enumName := ctx.ID(0).GetText() // Get the first ID, which should be the enum name
goCode := "type " + enumName + " int\nconst (\n"
enumVals := ctx.AllID()[1:] // Skip the first ID as it's the enum name
for i, enumVal := range enumVals {
goCode += "\t" + enumVal.GetText() + " " + enumName
if i == 0 {
goCode += " = iota"
}
goCode += "\n"
}
goCode += ")\n"
return goCode
}
func (v *EvoLangVisitor) VisitChildren(node antlr.RuleNode) interface{} {
var result string
for _, child := range node.GetChildren() {
// Type assert child to antlr.ParseTree
if parseTree, ok := child.(antlr.ParseTree); ok {
childResult := parseTree.Accept(v)
if childResult != nil {
result += childResult.(string)
}
}
}
return result
}
func (v *EvoLangVisitor) VisitEventDef(ctx *parser.EventDefContext) interface{} {
// Process event definition
// This will depend on how events are structured in your DSL
return v.VisitChildren(ctx)
}
// Similar methods for each expression and literal context
func (v *EvoLangVisitor) VisitIdExpr(ctx *parser.IdExprContext) interface{} {
return ctx.GetText()
}
func (v *EvoLangVisitor) VisitStringLiteral(ctx *parser.StringLiteralContext) interface{} {
return ctx.GetText()
}
func (v *EvoLangVisitor) VisitTypeDef(ctx *parser.TypeDefContext) interface{} {
// Process type definitions
return ctx.GetText()
}
func (v *EvoLangVisitor) VisitMulDivExpr(ctx *parser.MulDivExprContext) interface{} {
left := v.Visit(ctx.GetLeft()).(string)
right := v.Visit(ctx.GetRight()).(string)
op := ctx.GetOp().GetText()
return left + " " + op + " " + right
}
func (v *EvoLangVisitor) VisitAddSubExpr(ctx *parser.AddSubExprContext) interface{} {
left := v.Visit(ctx.GetLeft()).(string)
right := v.Visit(ctx.GetRight()).(string)
op := ctx.GetOp().GetText()
return left + " " + op + " " + right
}
func (v *EvoLangVisitor) VisitLogicalExpr(ctx *parser.LogicalExprContext) interface{} {
left := v.Visit(ctx.GetLeft()).(string)
right := v.Visit(ctx.GetRight()).(string)
op := ctx.GetOp().GetText()
return left + " " + op + " " + right
}
func (v *EvoLangVisitor) VisitRelationalExpr(ctx *parser.RelationalExprContext) interface{} {
left := v.Visit(ctx.GetLeft()).(string)
right := v.Visit(ctx.GetRight()).(string)
op := ctx.GetOp().GetText()
return left + " " + op + " " + right
}
func (v *EvoLangVisitor) VisitParenExpr(ctx *parser.ParenExprContext) interface{} {
inner := v.Visit(ctx.Expression()).(string)
return "(" + inner + ")"
}
func (v *EvoLangVisitor) VisitFunctionCall(ctx *parser.FunctionCallContext) interface{} {
functionName := ctx.ID().GetText()
// Perform a type assertion on ctx.ExprList()
exprListCtx := ctx.ExprList().(*parser.ExprListContext)
arguments := v.VisitExprList(exprListCtx).(string)
return functionName + "(" + arguments + ")"
}
func (v *EvoLangVisitor) VisitExprList(ctx *parser.ExprListContext) interface{} {
var args []string
for _, expr := range ctx.AllExpression() {
args = append(args, v.Visit(expr).(string))
}
return strings.Join(args, ", ")
}
func (v *EvoLangVisitor) VisitIntLiteral(ctx *parser.IntLiteralContext) interface{} {
return ctx.GetText()
}
func (v *EvoLangVisitor) VisitBooleanLiteral(ctx *parser.BooleanLiteralContext) interface{} {
return ctx.GetText()
}
func (v *EvoLangVisitor) VisitPrintStatement(ctx *parser.PrintStatementContext) interface{} {
text := ctx.STRING().GetText()
// Remove the surrounding quotes from the string
unquotedText := text[1 : len(text)-1]
return "fmt.Println(\"" + unquotedText + "\")"
}
func (v *EvoLangVisitor) VisitServerStatement(ctx *parser.ServerStatementContext) interface{} {
serverName := ctx.ID().GetText() // Get the server name
port := ctx.INT().GetText() // Get the port number
// Generate the Go code to set up the server and listen on the specified port
goCode := fmt.Sprintf("setup%sServer()\n", serverName) // Assuming a setup function for the server
goCode += fmt.Sprintf("http.ListenAndServe(\":%s\", nil)\n", port)
return goCode
}
func (v *EvoLangVisitor) VisitEventChannelHandler(ctx *parser.EventChannelHandlerContext) interface{} {
// Extract the channel name, old value, new value identifiers, and sandbox content
channelName := ctx.ID(0).GetText() // Assuming first ID is the channel name
oldValue := ctx.ID(1).GetText() // Assuming second ID is the old value identifier
newValue := ctx.ID(2).GetText() // Assuming third ID is the new value identifier
// Handle the sandbox content
sandboxContent := ctx.SANDBOX().GetText()
return "TODO: implement this lol" + channelName + oldValue + newValue + sandboxContent
// Process the extracted information as needed
// ...
// Return any specific result or simply nil
return nil
}
// VisitAction handles actions defined in access control.
func (v *EvoLangVisitor) VisitAction(ctx *parser.ActionContext) interface{} {
// Translate action into a Go function or method call
return ""
}
// VisitParamList handles parameter lists, possibly in function calls.
func (v *EvoLangVisitor) VisitParamList(ctx *parser.ParamListContext) interface{} {
// Translate parameter list into Go function parameters
return ""
}
// VisitBodyDef handles body definitions in endpoints.
func (v *EvoLangVisitor) VisitBodyDef(ctx *parser.BodyDefContext) interface{} {
// Translate body definition into Go code
return ""
}
// VisitAuthenticateDef handles authentication definitions in endpoints.
func (v *EvoLangVisitor) VisitAuthenticateDef(ctx *parser.AuthenticateDefContext) interface{} {
// Implement logic for authentication, translating into Go code
return ""
}
// VisitReturnDef handles return definitions in endpoints.
func (v *EvoLangVisitor) VisitReturnDef(ctx *parser.ReturnDefContext) interface{} {
// Translate return definition into Go code
return ""
}
// VisitArrayDef handles array type definitions.
func (v *EvoLangVisitor) VisitArrayDef(ctx *parser.ArrayDefContext) interface{} {
// Translate array definitions into Go slice types
return "[]" + v.Visit(ctx.TypeDef()).(string)
}
// VisitEventType handles event type definitions.
func (v *EvoLangVisitor) VisitEventType(ctx *parser.EventTypeContext) interface{} {
// Translate event types into Go code
return ""
}
// VisitMainStatements handles statements in the main function.
func (v *EvoLangVisitor) VisitMainStatements(ctx *parser.MainStatementsContext) interface{} {
var code string
for _, stmt := range ctx.AllMainStatement() {
code += v.Visit(stmt).(string) + "\n"
}
return code
}
// VisitMainStatement handles a single statement in the main function.
func (v *EvoLangVisitor) VisitMainStatement(ctx *parser.MainStatementContext) interface{} {
// Translate main statements into Go code
return v.VisitChildren(ctx)
}
func (v *EvoLangVisitor) VisitMainFunction(ctx *parser.MainFunctionContext) interface{} {
goCode := "func main() {\n"
for _, stmtCtx := range ctx.MainStatements().AllMainStatement() {
code, ok := v.Visit(stmtCtx).(string)
if ok {
goCode += code + "\n"
}
}
goCode += "}\n"
return goCode
}
func (v *EvoLangVisitor) Visit(tree antlr.ParseTree) interface{} {
return tree.Accept(v)
}
const goImports = `package main
import (
"fmt"
// other standard imports
)
`
func main() {
if len(os.Args) < 2 {
log.Fatalf("Usage: %s <file.evo>", os.Args[0])
}
// Read EvoLang source file
filename := os.Args[1]
source, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading file: %s", err)
}
// Parse the source
inputStream := antlr.NewInputStream(string(source))
lexer := parser.NewEvoLangLexer(inputStream)
tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
p := parser.NewEvoLangParser(tokenStream)
// Use the visitor to generate Go code
visitor := NewEvoLangVisitor()
goCode := visitor.Visit(p.Prog()).(string)
goCodeWithPkgAndStaticImports := goImports + goCode
outputDir := ".evo-out"
goFileName := "output.go"
outputFile := filepath.Join(outputDir, goFileName)
// Create the output directory if it does not exist
err = os.MkdirAll(outputDir, 0755)
if err != nil {
log.Fatalf("Error creating output directory: %s", err)
}
// Step 1: Write goCode to the file in the output directory
err = os.WriteFile(outputFile, []byte(goCodeWithPkgAndStaticImports), 0644)
if err != nil {
log.Fatalf("Error writing Go code to file: %s", err)
}
// Process the file with goimports
opt := &imports.Options{
Comments: true,
TabIndent: true,
TabWidth: 8,
FormatOnly: false,
}
res, err := imports.Process(outputFile, nil, opt)
if err != nil {
log.Fatalf("goimports processing failed: %s", err)
}
// Write the processed code back to the file
err = os.WriteFile(outputFile, res, 0644)
if err != nil {
log.Fatalf("Error writing processed code to file: %s", err)
}
// Step 2: Compile the Go file into an executable
execName := filepath.Join(outputDir, "output") // Name of the executable
cmd := exec.Command("go", "build", "-o", execName, outputFile)
err = cmd.Run()
if err != nil {
log.Fatalf("Error compiling Go code: %s", err)
}
fmt.Println("Compiled successfully. Executable: ", execName)
}