Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

269
LINES

< > BotCompany Repo | #1035179 // ConvertLASToJava - not an exact conversion, but returns a template for porting a left-arrow script to Java

JavaX fragment (include) [tags: use-pretranspiled]

Transpiled version (32399L) is out of date.

1  
sclass ConvertLASToJava > Meta {
2  
  replace Tk with GazelleV_LeftArrowScript.
3  
  delegate Evaluable to Tk.
4  
  
5  
  S typeToJava(Type type) {
6  
    ret type == null ?: shortenClassNames(type.getTypeName());
7  
  }
8  
  
9  
  S typeToJava(LASValueDescriptor desc) {
10  
    ret typeToJava(or(desc == null ?: desc.javaClass(), O));
11  
  }
12  
  
13  
  O convert(LASClassDef.FieldDef field) {
14  
    ret "settable " + typeToJava(field.type()) + " " + field.name() + 
15  
      (field.initializer == null ? "" : " = " + convert(field.initializer)) + ";";
16  
  }
17  
  
18  
  S convert(Tk.FunctionDef f) {
19  
    if (f.synthetic()) ret "";
20  
    ret typeToJava(f.returnType) + " "
21  
      + f.name + "(" + joinWithComma(
22  
        countIterator(l(f.args), i
23  
          -> typeToJava(f.argTypes[i]) + " " + f.args[i])
24  
        ) + ") {\n"
25  
      + indentx(convert(f.body, true))
26  
      + "}\n\n";
27  
  }
28  
  
29  
  O convertWithLeadingSpace(Evaluable o) {
30  
    ret leadingSpace(o, "") + convert(o);
31  
  }
32  
  
33  
  O convertWithLeadingSpace2(Evaluable o) {
34  
    ret replaceIfEqual(leadingSpace(o, ""), " ", "") + convert(o);
35  
  }
36  
  
37  
  S leadingSpace(Evaluable o, S defaultSpace) {
38  
    S space = null;
39  
    var src = o.tokenRangeWithSrc();
40  
    if (src != null)
41  
      space = src.startPtr().mapIdx(idx -> idx & ~1)!;
42  
    ret or2(space, defaultSpace);
43  
  }
44  
  
45  
  S trailingSpace(Evaluable o, S defaultSpace) {
46  
    S space = null;
47  
    var src = o.tokenRangeWithSrc();
48  
    if (src != null) {
49  
      S rawSpace = src.endPtr().mapIdx(idx -> idx & ~1)!;
50  
      space = replaceRegexp(rawSpace, "\n[ \t]+$", "\n");
51  
      if (scaffoldingEnabled()) printVars trailingSpace(rawSpace := quote(rawSpace), space := quote(space));
52  
    }
53  
    ret or2(space, defaultSpace);
54  
  }
55  
  
56  
  O getInstruction(Evaluable o) {
57  
    O inner = convert(o);
58  
    
59  
    bool needSemicolon = !o instanceof Tk.ClassDef
60  
      && !o instanceof Tk.ForEachBase;
61  
    
62  
    S space = trailingSpace(o, "\n");
63  
    if (scaffoldingEnabled()) printVars(+space, o := className(o), srcText := quote(o.srcText()), +inner);
64  
    ret inner + (needSemicolon ? ";" : "") + space;
65  
  }
66  
67  
  O convert(Tk.Script script, bool returnLastResult) {
68  
    var steps = asList(script.steps);
69  
    
70  
    if (returnLastResult) {
71  
      if (empty(steps)) ret "return null;";
72  
      var last = last(steps);
73  
      if (!last instanceof Tk.ReturnFromScript
74  
        && !last instanceof Tk.ClassDef)
75  
        setLast(steps, new Tk.ReturnFromScript(script, last));
76  
    }
77  
    
78  
    ret concatMapStrings(i -> str(getInstruction(i)), steps);
79  
  }
80  
  
81  
  O convert(Evaluable o, bool returnLastResult) {
82  
    if (o cast Tk.Script)
83  
      ret convert(o, returnLastResult);
84  
    ret convert(o);
85  
  }
86  
  
87  
  O convert(Evaluable o) {
88  
    if (o == null) null;
89  
    
90  
    // These are the properly implemented cases
91  
    
92  
    if (o cast Tk.GetVar)
93  
      ret o.var;
94  
    
95  
    if (o cast Tk.Script)
96  
      ret convert(o, false);
97  
      
98  
    if (o cast Tk.ClassDef) {
99  
      LASClassDef c = o.lasClass.classDef;
100  
      ret spaceCombine(
101  
        "class",
102  
        c.userGivenName,
103  
        eqOneOf(c.superClass, null, O) ? null : "extends " + typeToJava(c.superClass),
104  
        empty(c.interfaces) ? null : "is " + joinWithComma(map typeToJava(c.interfaces)),
105  
        curly("\n" + appendNewLineIfNempty(indentx(
106  
        
107  
        joinNemptiesWithEmptyLines(
108  
          lines_rtrim(map convert(c.fields)),
109  
          
110  
          convertInitializers(c),
111  
          
112  
          paragraphs(nempties(map convert(c.methods))))
113  
      ))));
114  
    }
115  
    
116  
    if (o cast Tk.Assignment)
117  
      ret o.var + " = " + convert(o.expression);
118  
      
119  
    if (o cast Tk.VarDeclaration)
120  
      ret "var " + o.var + " = " + convert(o.expression);
121  
      
122  
    if (o cast Tk.CallMethod) {
123  
      S targetStr = null;
124  
      var targetType = o.target.returnType();
125  
      if (targetType != null && targetType.knownValue()) {
126  
        O target = targetType.value();
127  
        if (target cast Class && eqOneOf(shortClassName(target), "main", "utils"))
128  
          targetStr = "";
129  
      }
130  
      if (targetStr == null)
131  
        targetStr = str(convert(o.target));
132  
      ret (empty(targetStr) ? "" : targetStr + ".")
133  
        + FunctionCall(o.methodName, map convertWithLeadingSpace2(o.args));
134  
    }
135  
      
136  
    if (o cast Tk.SetField)
137  
      ret convert(o.target) + "." + o.name + " = " + convert(o.expr);
138  
      
139  
    if (o cast Tk.CallMethodOrGetField)
140  
      ret convert(o.target) + "." + o.name + "()";
141  
      
142  
    if (o cast Tk.DirectMethodCallOnKnownTarget)
143  
      ret o.target + "." + FunctionCall(o.method.getName(), map convert(o.args));
144  
145  
    if (o cast Tk.NewObject) {
146  
      S className;
147  
      var o2 = o;
148  
      if (o2 cast Tk.NewObject_LASClass) {
149  
        className = o2.lasClass.userGivenName();
150  
      } else
151  
        className = typeToJava(o.c);
152  
        
153  
      ret "new " + FunctionCall(className, map convert(o.args));
154  
    }
155  
      
156  
    if (o cast Tk.IfThen)
157  
      ret "if (" + convert(o.condition) + ") "
158  
        + curlyIfScript(o.body)
159  
        + (o.elseBranch == null ? "" : " else "
160  
          + curlyIfScript(o.elseBranch));
161  
      
162  
    if (o cast Tk.Const) {
163  
      O val = o.value;
164  
      if (val cast Tk.FunctionDef)
165  
        ret convert(val);
166  
  
167  
      var c = o;
168  
      try object c?.srcText();
169  
      pcall {
170  
        ret toJava(val);
171  
      }
172  
    }
173  
174  
    if (o cast Tk.ForEach)
175  
      ret "fOr (" + o.var + " : " + convert(o.collection) + ") {\n"
176  
        + indentx(convert(o.body, false)) + "\n}";
177  
        
178  
    if (o cast Tk.ForIntTo)
179  
      ret "for " + o.var + " to " + convert(o.endValue) + ": {\n"
180  
        + indentx(convert(o.body, false)) + "\n}";
181  
        
182  
    if (o cast Tk.CurriedScriptFunctionLambda) {
183  
      int nArgs = o.implementedMethod.getParameterCount();
184  
      LS args = countIteratorToList_incl(1, nArgs, i ->"_" + i);
185  
      L fullArgs = concatLists(allToString(map convert(o.curriedArgs)), args);
186  
      ret roundBracketed(typeToJava(o.intrface))
187  
        + " " + lambdaArgsToString_pureJava(args) + " -> "
188  
        + FunctionCall(o.f.name, fullArgs);
189  
    }
190  
        
191  
    if (o cast Tk.LambdaDef)
192  
      ret roundBracketed(typeToJava(o.intrface))
193  
        + " " 
194  
        + joinNemptiesWithSpace(lambdaArgsToString_pureJava(o.args), "-> "
195  
          + curlyIfScript(o.body));
196  
          
197  
    if (o cast Tk.ReturnFromScript)
198  
      ret "ret " + convert(o.value);
199  
    
200  
    if (o cast Tk.GetStaticField)
201  
      ret typeToJava(o.field.getDeclaringClass()) + "." + o.field.getName();
202  
    
203  
    if (o cast Tk.BoolAnd)
204  
      ret roundBracketed(str(convert(o.a))) + " && " + roundBracketed(str(convert(o.b)));
205  
      
206  
    if (o cast Tk.BoolOr)
207  
      ret roundBracketed(str(convert(o.a))) + " || " + roundBracketed(str(convert(o.b)));
208  
      
209  
    if (o cast Tk.GetField)
210  
      ret convert(o.target) + "." + o.name;
211  
      
212  
    if (o cast Tk.CallFunction)
213  
      ret FunctionCall(o.f.name, map convert(o.args));
214  
    
215  
    if (o cast Tk.While)
216  
      ret "while (" + convert(o.condition) + ") {\n"
217  
        + indentx(convert(o.body, false)) + "\n}";
218  
        
219  
    if (o cast Tk.TryCatch)
220  
      ret "try {\n"
221  
        + indentx(convert(o.body, false)) + "\n"
222  
        + "} catch " + o.var + " {\n"
223  
        + indentx(convert(o.catchBlock, false)) + "\n}";
224  
        
225  
    if (o cast Tk.TryFinally)
226  
      ret "try {\n"
227  
        + indentx(convert(o.body, false)) + "\n"
228  
        + "} finally {\n"
229  
        + indentx(convert(o.finallyBlock, false)) + "\n}";
230  
        
231  
    // add more explicitly handled cases here
232  
    
233  
    warn("Can't convert to Java: " + className(o));
234  
    
235  
    // Retain original script text as a default
236  
    if (o cast Tk.Base) {
237  
      var b = o;
238  
      try object b?.srcText();
239  
    }
240  
    
241  
    // If that fails (it shouldn't), just return the toString
242  
    warn("No source reference in script object: " + className(o));
243  
    ret str(o);
244  
  }
245  
  
246  
  O curlyIfScript(Evaluable o) {
247  
    if (o cast Tk.Script)
248  
      ret "{\n" + indentx(convert(o)) + "\n}";
249  
    ret convert(o);
250  
  }
251  
  
252  
  // get is convert + postProcess
253  
  S get(Evaluable o, bool returnLastResult) {
254  
    S src = strOrEmpty(convert(o, returnLastResult));
255  
    LS tok = javaTok(src);
256  
    jreplace(tok, "this.", "");
257  
    JavaXPeepholeShortener shortener = new(tok);
258  
    shortener.run();
259  
    ret join(shortener.tok);
260  
  }
261  
  
262  
  S convertInitializers(LASClassDef c) {
263  
    ret lines_rtrim(nempties(mapWithIndex(c.initializers, (idx, i) -> {
264  
      if (c.isFieldInitializer.get(idx))
265  
        null;
266  
      ret "{ " + addSuffix(rtrim(str(convert(i))), ";") + " }";
267  
    })));
268  
  }
269  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035179
Snippet name: ConvertLASToJava - not an exact conversion, but returns a template for porting a left-arrow script to Java
Eternal ID of this version: #1035179/118
Text MD5: 07719fcaaeace2012df9f4f1e9097a1b
Author: stefan
Category: javax / gazelle 22
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2023-04-02 18:37:25
Source code size: 8613 bytes / 269 lines
Pitched / IR pitched: No / No
Views / Downloads: 395 / 884
Version history: 117 change(s)
Referenced in: [show references]