1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Making a Java compiler made in Java (HELP)

Discussion in 'Mac Programming' started by Fraaaa, Dec 3, 2012.

  1. macrumors 65816

    Fraaaa

    #1
    Hi guys,

    I am making this compiler on Java so that would be multi platform. I love CodeRunner and its simplicity, but I know that there is not something like it on Windows and Linux (as far as I know). Also CodeRunner cost few $$.

    Anyways, I was wondering if you could help out.

    Here my mess so far:

    JCompiler
    Code:
    import java.awt.Font;
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.Component;
    
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    
    import javax.swing.text.BadLocationException;
    import javax.swing.GroupLayout.*;
    
    import javax.tools.JavaCompiler;
    import javax.tools.ToolProvider;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.OutputStream;
    import java.io.InputStream;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.BufferedWriter;
    import java.io.OutputStreamWriter;
    
    public class JCompiler extends JFrame implements KeyListener, ActionListener, MouseListener
    {
    	String text;
    	JTextArea textArea = new JTextArea(50, 0);
    	JTextArea terminal = new JTextArea(20, 0);
    	JButton compileBtn = new JButton("Compile");
    	JButton jarBtn = new JButton("Jar");
    	JButton newBtn = new JButton("+");
    	public static Tab[] tabs;
    	int noClasses = 0;
    	int newId = 0;
    	int id;
    	public static boolean[] isOver;
    	
    	Font font = new Font("Monaco", Font.PLAIN, 12);
    	FileWriter out;
    	File file;
    	String fileName, man;
    	String selectedFile = "";
    	
    	public JCompiler()
    	{
    		// GRAPHICS		----------------------------------------
    		textArea.setFont(font);
    		terminal.setFont(font);
    		//"class Untitled\n{\n\tpublic static void main(String[] args)\n\t{\n\t\tSystem.out.println(\"Hello world\");\n\t}\n}"
    		textArea.setText("");
    		//terminal.setText("");
    		JScrollPane scrollingArea = new JScrollPane(textArea);
    		JScrollPane scrollTerminal = new JScrollPane(terminal);
    
    		newBtn.setBounds(14, 1, 40, 25);
    		compileBtn.setBounds(502, 1, 90, 25);
    		jarBtn.setBounds(420, 1, 90, 25);
    		//run btn
    		//stop btn
    		addTab();
    		
    		scrollingArea.setBounds(20, 40, 565, 630);
    		scrollTerminal.setBounds(20, 670, 565, 100);
    		
    		add(scrollingArea, BorderLayout.CENTER);
    		add(scrollTerminal);
    		add(compileBtn);
    		add(jarBtn);
    		add(newBtn);
    
    		newBtn.addActionListener(this);
    		textArea.addKeyListener(this);
    		compileBtn.addActionListener(this);
    		jarBtn.addActionListener(this);
    		//exec();
    	}
    	
    	// KEY EVENT		----------------------------------------
    	public void keyPressed(KeyEvent e)
    	{
    		
    	}
    	
    	public void keyReleased(KeyEvent e)
    	{
    		//--
    	}
    	
    	public void keyTyped(KeyEvent e)
    	{
    		//--
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		if (e.getSource() == compileBtn)
    		{
    			saveFile("Empty.java");
    			String[] files = {"Empty.java"};
    			compile(files);
    		}
    		else if (e.getSource() == jarBtn)
    		{
    			saveFile("Untitled.java");
    			String[] files = {"Untitled.java"};
    			compile(files);
    			
    			String mainClass = "Untitled";
    			String[] classes = {"Untitled.class"};
    			manifest(mainClass);
    			String jarFiles = "Untitled.class";
    			jar("j.jar", jarFiles);
    		}
    		else if (e.getSource() == newBtn)
    		{
    			addTab();
    		}
    		else if (e.getSource() == tabs)
    		{
    			System.out.println("test");
    		}
    	}
    	
    	public void addTab()
    	{
    		noClasses++;
    		if (noClasses == 4)
    		{
    			newBtn.setEnabled(false);
    			newBtn.setBounds(14+noClasses*91, 1, 40, 25);
    		}
    		else
    		{
    			newBtn.setBounds(14+noClasses*91, 1, 40, 25);
    		}
    		
    		isOver = new boolean[noClasses];
    		if (noClasses > 1)
    		{
    			Tab[] tempTabs = tabs.clone();
    			tabs = new Tab[noClasses];
    			int in = 0;
    			for (Tab t : tempTabs)
    			{
    				tabs[in] = tempTabs[in];
    				in++;
    			}
    		}
    		else
    		{
    			tabs = new Tab[noClasses];
    		}
    		
    		tabs[newId] = new Tab("new class", newId);
    		tabs[newId].selected = true;
    		for (int i = 0; i < noClasses && i < 4; i++)
    		{
    			tabs[i].setBounds(20 + i * 91, 1, 90, 25);
    		}
    		tabs[newId].addMouseListener(new MouseAdapter()
    				{ 
    					public void mouseClicked(MouseEvent me)
    					{
    						//repaint();
    					}
    					public void mouseEntered(MouseEvent me)
    					{
    						repaint();
    					}
    					public void mouseExited(MouseEvent me)
    					{
    						repaint();
    					}
    				});
    		tabs[newId].cross.addMouseListener(new MouseAdapter()
    				{ 
    					public void mouseClicked(MouseEvent me)
    					{
    						removeTab(me.getComponent().getParent());
    						repaint();
    					}
    				});
    		add(tabs[newId]);
    		System.out.println("new tab" + newId);
    		newId++;
    	}
    	
    	public void removeTab(Component t)
    	{
    		remove(t);
    		repaint();
    	}
    	
    	public void saveFile(String fileName)
    	{
    		try
    		{
    			file = new File(fileName);
    			out = new FileWriter(file);
    			out.write(textArea.getText());
    			out.close();
    		}
    		catch (Exception e)
    		{
    			
    		}
    	}
    	
    	public void compile(String[] fileToCompile)
    	{
    		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    		int compilationResult = compiler.run(null, null, null, fileToCompile);
    		if(compilationResult == 0)
    		{
    			System.out.println("Compilation Successful.");
    		}
    		else
    		{
    			System.out.println("Compilation Failed.");
    		}
    	}
    	
    	public void manifest(String mainClass)
    	{
    		man = "Main-Class: " + mainClass + "\n\n";
    		try
    		{
    			file = new File("Manifest.txt");
    			out = new FileWriter(file);
    			out.write(man);
    			out.close();
    		}
    		catch (Exception e)
    		{
    			
    		}
    	}
    	
    	public void jar(String jarName, String files)
    	{
    		try
    		{
    			Process p = Runtime.getRuntime().exec("jar cfm " + jarName + " Manifest.txt " + files);
    			p.waitFor();
    		}
    		catch (Exception e)
    		{
    			
    		}
    	}
    
    	// to be sorted
    	public void exec()
    	{
    		try
    		{
    			Process p = Runtime.getRuntime().exec("java -jar j.jar");
    			p.waitFor();
    			OutputStream stdin = p.getOutputStream();
    			InputStream stderr = p.getErrorStream();
    			InputStream stdout = p.getInputStream();
    
    			BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
    			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
    			
    			terminal.setText(reader.readLine());
    		}
    		catch (Exception e)
    		{
    			
    		}
    	}
    
    	public void mouseClicked(MouseEvent e)
        {
    		
    	}
    	
    	public void mouseEntered(MouseEvent e)
        {
    		
        }
    
        public void mouseExited(MouseEvent e)
        {
    
        }
    
        public void mousePressed(MouseEvent e)
        {
    		//System.out.println("pressed");
        }
    
        public void mouseReleased(MouseEvent e)
        {
    		//System.out.println("released");
        }
    	
    	// MAIN				----------------------------------------
    	public static void main(String[] args)
    	{
    		JFrame win = new JCompiler();
    		win.setTitle("JCompiler v0.1");
    		win.setLayout(null);
    		win.setSize(600, 800);
    		win.setLocation(450, 0);
    		win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		win.getContentPane().setBackground(Color.WHITE);
    		win.setResizable(false);
    		win.setVisible(true);
    	}
    }

    Tab
    Code:
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.InputEvent;
    
    public class Tab extends JButton
    {
    	public boolean selected;
    	public boolean mouseOver;
    	private String label;
    	private Dimension size = new Dimension(90, 25);
    	public int id;
    	public CloseCross cross;
    	
        public Tab(String label, int id)
    	{
    		super(label);
    		this.label = label;
    		this.id = id;
    		selected = false;
    		setSize(size.width, size.height);
    		setLayout(null);
    		cross = new CloseCross();
    		cross.setBounds(70, 3, 16, 16);
    		this.addMouseListener(new MouseAdapter()
    			{
    				public void mouseClicked(MouseEvent e)
    				{
    					
    				}
    				public void mouseEntered(MouseEvent e)
    				{
    					mouseOver = true;
    				}
    				public void mouseExited(MouseEvent e)
    				{
    					mouseOver = false;
    				}
    			});
    		add(cross);
        }
    
        public Dimension getPreferredSize()
        {
            return new Dimension(getWidth(), getHeight());
        }
    
        protected void paintComponent(Graphics g)
    	{
            super.paintComponent(g);
    		
    		if (!selected)
    		{
    			g.setColor(Color.BLACK);
    			g.drawRect(0, 0, getWidth()-1, getHeight()-1);
    			g.setColor(Color.WHITE);
    			g.fillRect(1, 1, getWidth()-2, getHeight()-2);
    			g.setColor(Color.BLACK);
    			//int length = label.length();
    			g.drawString(label, 5, 18);
    		}
    		else
    		{
    			g.setColor(Color.BLACK);
    			g.drawRect(0, 0, getWidth()-1, getHeight()-1);
    			g.setColor(Color.WHITE);
    			g.fillRect(1, 1, getWidth()-2, getHeight()-1);
    			g.setColor(Color.BLACK);
    			//int length = label.length();
    			g.drawString(label, 5, 18);
    		}
        }
    
    	class CloseCross extends JButton
    	{
    		private Dimension size = new Dimension(16, 16);
    		
    	    public CloseCross()
    		{
    			super("");
    			setSize(16, 16);
    			this.addMouseListener(new MouseAdapter()
    				{
    					public void mouseEntered(MouseEvent e)
    					{
    						mouseOver = true;
    					}
    					public void mouseExited(MouseEvent e)
    					{
    						mouseOver = false;
    					}
    				});
    	    }
    
    	    protected void paintComponent(Graphics g)
    		{
    	        super.paintComponent(g);
    			
    			if (!mouseOver)
    			{
    				g.setColor(Color.WHITE);
    				g.fillRect(0, 0, getWidth(), getHeight());
    			}
    			else
    			{
    				g.setColor(Color.WHITE);
    				g.fillRect(0, 0, getWidth(), getHeight());
    				g.setColor(Color.GRAY);
    				g.fillOval(0, 0, 15, 15);
    				g.setColor(Color.WHITE);
    				g.drawString("x", 4, 11);
    			}
    		}
    	}
    }
    At the moment I am working on the tabs. I made my own, but is quite a chore, so I might just replace them with Tabbed Panes later.

    If you have any advice or want to help would be appreciated.
     
  2. macrumors 68040

    lee1210

    #2
    Are you trying to write a compiler that will translate Java source code into Byte code that will run on a JVM? Or are you trying to write an (Integrated Development Environment (IDE) that leverages the existing compiler (javac) and allows the user to write code, compile, run, and debug without having to interact with these underlying programs?

    Are you doing this for sport or do you feel that such a tool is not available on your platform of choice?

    -Lee
     
  3. macrumors 65816

    Fraaaa

    #3
    Hi,

    is just an editor that invokes javac to compile, and I am doing this for sport, and to learn something new. I am using CodeRunner on my Mac, but I would like to use this on the Raspberry Pi.
     
  4. macrumors 65816

    #4
    Using java to create a java compiler? Might that tear a hole in the fabric of the universe?

    Check this:
    http://netbeans.org/features/platform/

    I understand you are doing it for fun, but this is also fun or funner in the universe beyond the tear.

    just spinning out of control
     
  5. macrumors 68040

    lee1210

    #5
    There are already a number of Java IDEs in Java. Eclipse is probably the most popular. You shouldn't bother looking at the eclipse source at this stage, though. Focus instead on a small task at a time. One text field, one button that runs javac then Java, and displaying the output. Don't deal with multiple files, don't deal with packages, no jar files, no command line arguments. Do the most basic task, then iterate and expand.

    To 960design: What language should a Java compiler be written in? C? Then what language should a C compiler be written in? What language should an assembler be written in? If a language is Turing complete, any set of data can be manipulated in any manner you wish. There's no reason a Java compiler can't be written in Java. It's certainly going to be a challenge, but writing a compiler in any language is. There's nothing intrinsically different about the input (Java source) or the output (Java byte code) that prohibits this. In fact, there's no reason one would be limited to byte code as the output. The result could be C source code, some flavor of assembly, or machine code.

    -Lee
     
  6. macrumors 6502

    #6
    I'm fairly certain he was making a Java joke (a common meme)....

    To the OP:

    Your best bet might be to find an open source editor and extend it to fit your needs. A Raspberry Pi doesn't have a lot of CPU power so a full blown IDE with good performance isn't going to be easy to pull off. I'd suggest tweaking a command line editor to do what you'd like it to do. Emacs is very extensible (though through Lisp rather than Java) and Nano is very small but has most of the features you'd want in an IDE (syntax coloring, multiple file buffers, line counts, search, find & replace) and should be easy to get a handle on the code base (but its C based, perhaps not what you want).
     
  7. macrumors newbie

    #7
    Compiler

    Hi Man. I also had exam to make compiler for microJava. We made it like structure of compiler is. Lexical analyzer. syntax, semantical and code generator at the end which translates code to mips. All of them are in different classes.

    Code generator is not finished completely, just for logical operations and if statement. All analysers work fine, make some mistakes in test code and you will see. I didnt write comments on methods, but names of methods are clear, and i hope it will not be difficult to understand a code. I will write comments next time. Check result of lexical analyzer, and follow it while you are watching methods in other classes. It's the best way to understand. In lexical analyzer you have String variables "code" and "codee". Use second one to test mips. First is with for statement which is not translated to mips, but test it for analyzers.

    Program is made in 12 days, for exam, also, so, sorry for mistakes. There is no GUI...

    Link is:
    http://www.sendspace.com/file/ct7gr3 .
     
  8. macrumors 65816

    #8
    And IDEs for several other languages written in Java, as well.

    Unfortunately.
     

Share This Page