private void cacheImports(string fileName) { StringBuilder builder = new StringBuilder(); try { using (BufferedReader bufferedReader = new BufferedReader(new FileReader(Primitives.stripQuotes(fileName)))) { string line = bufferedReader.readLine(); while (line != null) { builder.Append(line); line = bufferedReader.readLine(); } } } catch (IOException e) { JuliarLogger.log(e); } importBuffer.Append(builder); int currentLineNumber = 0; importsInterfaceCallback.createTempCallback(importBuffer.ToString(), currentLineNumber); }
private void walkGraph(ControlFlowNode main) { try { main.visited = true; queue.addFirst(main.next); while (!queue.Empty) { ControlFlowNode g = queue.removeLast(); if (!g.visited) { g.visited = true; } while (g != null) { if (!g.visited) { queue.addFirst(g); } g = g.next; } } } catch (Exception e) { JuliarLogger.log(e); } }
public virtual IList <Node> execute(IList <Node> instructions) { try { foreach (Node currentNode in instructions) { NodeType nodeType = currentNode.Type; if (functionMap.ContainsKey(nodeType)) { Evaluate evaluate = functionMap[nodeType]; if (evaluate != null) { IList <Node> instructionsToExecute = evaluate.evaluate(currentNode, activationFrameStack.peek(), this); if (instructionsToExecute != null && instructionsToExecute.Count > 0) { execute(instructionsToExecute); } } else { evalNull(); } } } } catch (Exception ex) { JuliarLogger.log(ex); } return(new List <>()); }
public static string sysFileOpen(string path) { path = stripQuotes(path); try { int read = 1024; int N = 1024 * read; char[] buffer = new char[N]; StringBuilder text = new StringBuilder(); FileReader reader = new FileReader(path); BufferedReader bufferedReader = new BufferedReader(reader); while (true) { read = bufferedReader.read(buffer, 0, N); text.Append(new string(buffer, 0, read)); if (read < N) { break; } } return(text.ToString()); } catch (Exception fne) { JuliarLogger.log(fne.Message); } return(""); }
/* * Will execute the compiler or the interpreter. */ //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private static boolean excuteCompiler(com.juliar.parser.JuliarParser parser) throws java.io.IOException private static bool excuteCompiler(JuliarParser parser) { // Calls the parse CompileUnit method // to parse a complete program // then calls the code generator. JuliarParser.CompileUnitContext context = parser.compileUnit(); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: Visitor visitor = new Visitor((imports, linesToSkip) => { }, true); visitor.visit(context); if (errors.errorList().Count > 0 || visitor.ErrorList.Count > 0) { foreach (string error in errors.errorList()) { JuliarLogger.logerr(error); } foreach (string error in visitor.ErrorList) { JuliarLogger.logerr(error); } return(true); } new Interpreter(visitor.instructions()); return(false); }
public static void compile(string s) { InputStream b = new ByteArrayInputStream(s.GetBytes(StandardCharsets.UTF_8)); try { SymbolTable.clearSymbolTable(); JuliarParser parser = parse(b); errors = new ErrorListener(); parser.addErrorListener(errors); // call parse statement. // This will parse a single line to validate the syntax if (excuteCompiler(parser)) { errors.errorList(); } } catch (Exception ex) { JuliarLogger.log(ex.Message); } }
public static void Main(string[] args) { try { compile(args[0]); } catch (Exception) { JuliarLogger.log("Something went wrong"); } }
public static void sysFileWrite(string path) { try { IList <string> lines = Arrays.asList("Test Line 1", "Test Line 2"); Path file = Paths.get("the-file-name.txt"); Files.write(file, lines, Charset.forName("UTF-8")); } catch (IOException e) { JuliarLogger.log(e.Message + " sysFileWrite error"); } }
public static IList <Node> evalPrimitives(Node n, ActivationFrame activationFrame, Interpreter calback) { string functionName = ((FinalNode)n.Instructions[0]).dataString(); FinalNode finalNode = new FinalNode(); switch (functionName) { case "print": printLine(activationFrame, functionName, n.Instructions[2]); break; case "__getByteFromString": getByteFromString(activationFrame, n.Instructions[1], n.Instructions[2]); break; case "printLine": printLine(activationFrame, functionName, n.Instructions[1]); break; case "fileOpen": string data = fileOpen(n.Instructions[2]); finalNode.DataString = data; finalNode.VariableTypeByIntegralType = IntegralType.jstring; activationFrame.pushReturnNode(finalNode); //activationFrame.returnNode = finalNode; break; case "sysExec": string ex = sysExec(n.Instructions[2]); finalNode.DataString = ex; finalNode.VariableTypeByIntegralType = IntegralType.jstring; activationFrame.pushReturnNode(finalNode); //activationFrame.returnNode = finalNode; break; case "availableMemory": long value = availableMemory(); finalNode.DataString = value; finalNode.VariableTypeByIntegralType = IntegralType.jlong; activationFrame.pushReturnNode(finalNode); //activationFrame.returnNode = finalNode; break; default: JuliarLogger.log("function " + functionName + " does not exist"); break; } return(new List <>()); }
public override Node visitSubtract(JuliarParser.SubtractContext ctx) { string text = ctx.subtraction().Text; if ("subtract".Equals(text) || "-".Equals(text)) { if (ctx.types().size() == 2) { BinaryNode node = new BinaryNode(); try { /* * Node n = node.makeNode( * Operation.subtract, * ctx.types(0).accept(this), * ctx.types(1).accept(this)); * n.addInst( funcContextStack, n); */ } catch (Exception ex) { JuliarLogger.log(ex.Message, ex); } } if (ctx.types().size() > 2) { IList <IntegralTypeNode> data = new List <IntegralTypeNode>(); for (int i = 0; i < ctx.types().size(); i++) { data.Add((IntegralTypeNode)ctx.types(i).accept(this)); } AggregateNode aggregateNode = new AggregateNode(Operation.subtract, data); FunctionDeclNode functionDeclNode = (FunctionDeclNode)funcContextStack.Peek(); functionDeclNode.addInst(aggregateNode); } } return(null); }
public override Node visitCompileUnit(JuliarParser.CompileUnitContext ctx) { CompliationUnitNode node = new CompliationUnitNode(); try { string nodeName = node.ToString(); callStack.Push(nodeName); symbolTable.addLevel(nodeName); new IterateOverContext(this, ctx, this, node); instructionList.Add(node); popScope(node.Type); //cfa.walkGraph(); //symbolTable.dumpSymbolTable(); } catch (Exception ex) { JuliarLogger.log(ex.Message); } return(node); }
private IList <Node> evalBooleanNode(Node node, ActivationFrame frame, Interpreter callback) { Node variableType = node.Instructions[0]; if (node is BooleanOperatorNode) { // ((BooleanOperatorNode)node).evaluateExpression( frame , this); } try { Node lvalue = null; if (variableType is VariableNode) { string variableName = ((VariableNode)node.Instructions[0]).variableName; lvalue = frame.variableSet[variableName]; } else { lvalue = variableType; } bool isEqualEqual; Node rvalue = null; // This is ugly code. Need to find a better way to // handle these cases. // Multiple ifs will only cause confusion. FinalNode updatedLvalue = null; /* * if (node.getInstructions().size() == 1) { * //lvalue must be a single boolean expression * if (lvalue instanceof FinalNode) { * BooleanNode booleanNode = new BooleanNode(); * booleanNode.addInst(lvalue); * frame.pushReturnNode( booleanNode ); * return new ArrayList<>(); * } * * if (lvalue instanceof PrimitiveNode) { * updatedLvalue = (FinalNode) lvalue.getInstructions().get(0); * } * * } else if (node.getInstructions().size() > 1) { * //if (booleanOperatorNode.getInstructions().get(0) instanceof EqualEqualSignNode) { * //isEqualEqual; * //} * rvalue = node.getInstructions().get(2); * FinalNode updatedRvalue = null; * if (rvalue != null && rvalue instanceof PrimitiveNode) { * updatedRvalue = (FinalNode) rvalue.getInstructions().get(0); * } * * if (updatedLvalue != null) { * lvalue = updatedLvalue; * } * * if (updatedRvalue != null) { * rvalue = updatedRvalue; * } * * isEqualEqual = getFinalNodeFromAnyNode( lvalue) .dataString().equals( getFinalNodeFromAnyNode(rvalue).dataString()); * //else if (booleanOperatorNode.getInstructions().get(0) instanceof ) * FinalNode finalNode = new FinalNode(); * finalNode.setDataString(isEqualEqual); * * BooleanNode booleanNode = new BooleanNode(); * booleanNode.addInst(finalNode); * * frame.pushReturnNode( booleanNode ); * return new ArrayList<>(); * } */ } catch (Exception ex) { JuliarLogger.log(ex.Message); } return(new List <>()); }
/* * private class operatorBinding { * public * } */ public Interpreter(InstructionInvocation invocation) { if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; } try { EvaluateAssignments.create(this); IList <Node> inst = invocation.InstructionList; activationFrameStack.push(new ActivationFrame("compliationUnit")); functionNodeMap = invocation.FunctionNodeMap; functionMap[NodeType.VariableReassignmentType] = (EvaluateAssignments::evalReassignment); functionMap[NodeType.AssignmentType] = (EvaluateAssignments::evalAssignment); functionMap[NodeType.PrimitiveType] = (EvaluatePrimitives::evalPrimitives); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.CompliationUnitType] = ((n, activationFrame, callback) => evalCompilationUnit()); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.AddType] = ((n, activationFrame, callback) => evalAdd()); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.CommandType] = ((n, activationFrame, callback) => evalCommand(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.SummationType] = ((n, activationFrame, callback) => evalSummation()); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.FunctionaCallType] = ((n, activationFrame, callback) => evalFunctionCall(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.FunctionDeclType] = ((n, activationFrame, callback) => evalFunctionDecl(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.VariableType] = ((n, activationFrame, callback) => evalActivationFrame(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.BinaryType] = ((n, activationFrame, callback) => evalBinaryNode(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.StatementType] = ((n, activationFrame, callback) => evalStatement(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.ExpressionType] = ((n, activationFrame, callback) => evalStatement(n)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.FinalType] = ((n, activationFrame, callback) => evalFinal()); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.EvaluatableType] = ((n, activationFrame, callback) => evaluateEvauatable(n, activationFrame, callback)); //JAVA TO C# CONVERTER TODO TASK: Java lambdas satisfy functional interfaces, while .NET lambdas satisfy delegates - change the appropriate interface to a delegate: functionMap[NodeType.UserDefinedFunctionReferenceType] = ((n, activationFrameStack, callback) => evalUserDefinedFunctionCall(n)); functionMap[NodeType.AggregateType] = (this::evaluateAggregate); functionMap[NodeType.ReturnValueType] = (this::evalReturn); functionMap[NodeType.BooleanType] = (this::evalBooleanNode); functionMap[NodeType.BooleanOperatorType] = (this::evalBooleanOperator); functionMap[NodeType.IfExprType] = (this::evalIfStatement); functionMap[NodeType.WhileExpressionType] = (this::evalWhileExpression); functionMap[NodeType.VariableDeclarationType] = (this::evalVariableDeclration); //functionMap.put(NodeType.VariableDeclarationType, (n-> eval(n))); //functionMap.put(NodeType.ReturnValueType , (n-> evalReassignment(n) )); execute(inst); } catch (Exception ex) { JuliarLogger.log(ex); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void generate(java.util.List<Node> instructions, String outputfile) throws java.io.IOException public virtual void generate(IList <Node> instructions, string outputfile) { ClassWriter cw = new ClassWriter(0); cw.visit(V1_1, ACC_PUBLIC, outputfile, null, "java/lang/Object", null); // creates a MethodWriter for the (implicit) constructor MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); // pushes the 'this' variable mw.visitVarInsn(ALOAD, 0); // invokes the super class constructor mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mw.visitInsn(RETURN); // this code uses a maximum of one stack element and one local variable mw.visitMaxs(1, 1); mw.visitEnd(); // creates a MethodWriter for the 'main' method mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); // pushes the 'out' field (of type PrintStream) of the System class mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); // pushes the "Hello Juliar Future" String constant mw.visitLdcInsn("Now Calling generated Juliar Methods!"); // invokes the 'println' method (defined in the PrintStream class) mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); //mw.visitInsn(RETURN); // this code uses a maximum of two stack elements and two local // variables //mw.visitVarInsn(ALOAD,0); mw.visitMethodInsn(INVOKESTATIC, outputfile, "juliarMethod", "()V", false); mw.visitInsn(RETURN); mw.visitMaxs(2, 2); mw.visitEnd(); mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "juliarMethod", "()V", null, null); int?stackSize = 0; GeneratorAdapter ga = new GeneratorAdapter(mw, ACC_PUBLIC + ACC_STATIC, "juliarMethod", "()V"); evaluateExpressions(instructions, mw, ga, stackSize); mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mw.visitLdcInsn("Instructions:" + instructions); mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mw.visitInsn(RETURN); mw.visitMaxs(16, 6); mw.visitEnd(); /*MethodVisitor foo = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "foo", "()V", null, null); * * GeneratorAdapter ga1 = new GeneratorAdapter(foo, ACC_PUBLIC + ACC_STATIC, "foo", "()V"); * foo.visitInsn(RETURN); * foo.visitEnd();*/ // gets the bytecode of the Example class, and loads it dynamically sbyte[] code = cw.toByteArray(); //Create JAR output FileOutputStream fout = new FileOutputStream(outputfile + ".jar"); Manifest manifest = new Manifest(); manifest.MainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.MainAttributes.put(Attributes.Name.MAIN_CLASS, outputfile); JarOutputStream jarOut = new JarOutputStream(fout, manifest); try { jarOut.putNextEntry(new ZipEntry("com/juliar/pal/Primitives.class")); InputStream primitiveStream = typeof(Primitives).getResourceAsStream("Primitives.class"); jarOut.write(getBytes(primitiveStream)); jarOut.closeEntry(); jarOut.putNextEntry(new ZipEntry(outputfile + ".class")); jarOut.write(code); jarOut.closeEntry(); } catch (Exception e) { JuliarLogger.log(e); } jarOut.close(); fout.close(); /* * List<String> Dependencies = SomeClass.getDependencies(); * FileOutputStream fout = new FileOutputStream(outputfile+".jar"); * * JarOutputStream jarOut = new JarOutputStream(fout); * * //jarOut.putNextEntry(new ZipEntry("com/juliar/pal")); // Folders must end with "/". * //jarOut.putNextEntry(new ZipEntry("com/juliar/pal/Primitives.class")); * //jarOut.write(getBytes("com/juliar/pal/Primitives.class")); * //jarOut.closeEntry(); * * jarOut.putNextEntry(new ZipEntry(outputfile+".class")); * jarOut.write(getBytes(outputfile+".class")); * jarOut.closeEntry(); * * for(String dependency : Dependencies){ * int index = dependency.lastIndexOf( '/' ); * jarOut.putNextEntry(new ZipEntry(dependency.substring( index ))); // Folders must end with "/". * jarOut.putNextEntry(new ZipEntry(dependency)); * jarOut.write(getBytes(dependency)); * jarOut.closeEntry(); * } * * * jarOut.close(); * * fout.close();*/ }
private MethodVisitor evaluateExpressions(IList <Node> instructions, MethodVisitor mw, GeneratorAdapter ga, int?stackSize) { JuliarLogger.log("x"); foreach (Node instruction in instructions) { JuliarLogger.log("Instructions"); if (instruction is FunctionDeclNode) { IList <Node> t = instruction.Instructions; evaluateExpressions(t, mw, ga, stackSize); } if (instruction is PrimitiveNode) { string function = ((PrimitiveNode)instruction).PrimitiveName.ToString(); JuliarLogger.log(function); function = PrimitivesMap.getFunction(function); mw.visitLdcInsn(((PrimitiveNode)instruction).GetPrimitiveArgument.ToString()); mw.visitIntInsn(ASTORE, 0); mw.visitIntInsn(ALOAD, 0); mw.visitMethodInsn(INVOKESTATIC, "com/juliar/pal/Primitives", function, "(Ljava/lang/String;)Ljava/lang/String;", false); if ("printLine".Equals(function)) { function = "sysPrintLine"; mw.visitLdcInsn(((PrimitiveNode)instruction).GetPrimitiveArgument.ToString()); mw.visitIntInsn(ASTORE, 0); mw.visitIntInsn(ALOAD, 0); mw.visitMethodInsn(INVOKESTATIC, "com/juliar/pal/Primitives", function, "(Ljava/lang/String;)V", false); } if ("print".Equals(function)) { function = "sysPrint"; mw.visitLdcInsn(((PrimitiveNode)instruction).GetPrimitiveArgument.ToString()); mw.visitIntInsn(ASTORE, 0); mw.visitIntInsn(ALOAD, 0); mw.visitMethodInsn(INVOKESTATIC, "com/juliar/pal/Primitives", function, "(Ljava/lang/String;)V", false); } } if (instruction is CompliationUnitNode) { //WWLogger.log(((CompliationUnitNode) instructions).getInstructions().toString()); /*Logger.og(t.toString()); */ IList <Node> t = instruction.Instructions; evaluateExpressions(t, mw, ga, stackSize); /*for (List<Node> n : t) { * Logger.log(n.getNodeName().toString()); * Logger.log("HERE"); * evaluateExpressions(n, mw, ga, stackSize); * }*/ } if (instruction is StatementNode) { IList <Node> t = instruction.Instructions; evaluateExpressions(t, mw, ga, stackSize); } if (instruction is BinaryNode) { /* * JuliarLogger.log("BinaryNode"); * //Map<IntegralType,Integer> op = CodeGeneratorMap.generateMap(((BinaryNode)instruction).operation().toString()); * * BinaryNode b = ((BinaryNode)instruction); * if (isDebug) { * mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * } * * IntegralType addType; * IntegralTypeNode ln = (IntegralTypeNode)b.left(); * IntegralTypeNode rn = (IntegralTypeNode)b.right(); * * if (ln.getIntegralType() == IntegralType.jdouble || rn.getIntegralType() == IntegralType.jdouble){ * addType = IntegralType.jdouble; * } else if (ln.getIntegralType() == IntegralType.jfloat || rn.getIntegralType() == IntegralType.jfloat){ * addType = IntegralType.jfloat; * } else if (ln.getIntegralType() == IntegralType.jlong || rn.getIntegralType() == IntegralType.jlong){ * addType = IntegralType.jlong; * } else if (ln.getIntegralType() == IntegralType.jinteger || rn.getIntegralType() == IntegralType.jinteger){ * addType = IntegralType.jinteger; * } else{ * addType = null; * } * * pushIntegralType(ga, b.left(),addType); * ga.visitIntInsn(ISTORE, 1); * pushIntegralType(ga, b.right(),addType); * ga.visitIntInsn(ISTORE, 2); * ga.visitIntInsn(ILOAD, 1); * ga.visitIntInsn(ILOAD, 2); * //ga.visitInsn(op.get(addType)); * * mw.visitIntInsn(ILOAD, 0); * * debugPrintLine(mw,addType); */ } if (instruction is AggregateNode) { JuliarLogger.log("BinaryNode"); //Map<IntegralType,Integer> op = CodeGeneratorMap.generateMap(((AggregateNode)instruction).operation().toString()); IList <IntegralTypeNode> integralTypeNodes = ((AggregateNode)instruction).data(); int addCount = integralTypeNodes.Count - 1; if (isDebug) { mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); } //Scan Type to typecast correctly IntegralType addType = IntegralType.jinteger; int[] anArray = new int[5]; foreach (IntegralTypeNode integralTypeNode in integralTypeNodes) { switch (integralTypeNode.IntegralType) { case jdouble: anArray[0]++; break; case jfloat: anArray[1]++; break; case jlong: anArray[2]++; break; default: break; } } // if (anArray[0] != 0) { addType = IntegralType.jdouble; } else if (anArray[1] != 0) { addType = IntegralType.jfloat; } else if (anArray[2] != 0) { addType = IntegralType.jlong; } foreach (IntegralTypeNode integralTypeNode in integralTypeNodes) { pushIntegralType(ga, integralTypeNode, addType); } for (int i = 0; i < addCount; i++) { //ga.visitInsn(op.get(addType)); } debugPrintLine(mw, addType); } } return(mw); }