hai. I'm trying to write a compiler for the first time (just a relatively simple toy language I thought up) and I'm not sure exactly how I should store the parse tree in memory. I'm writing the compiler in C. Any suggestions?
What you want is an AST(Abstract Syntax Tree). Each node of the tree has a type representing some instruction, and a list of parameters. Each parameter can be another node and so on.
A simpler way to explain this would be through a Lisp list:
1 + 2 * 3 => (+ 1 (* 2 3))
the first element of the list represents the instruction, while the rest are parameters.
Other decent representations can be Recursive variants in ML/Ocaml (Haskell has them too):
type Arith_AST =
Add of Expr * Expr |
Sub of Expr * Expr |
Mul of Expr * Expr |
Div of Expr * Expr |
Not of Expr;;
type Expr =
Expr of Arith_AST |
Int of int;;
How you choose to represent these structures in C is up to you, it's easy if you understand how it works in an abstract manner as shown in the Lisp and O'Caml examples.
>>3
Oh damn... at least I didn't spoonfeed him one of the many concrete representations possible in C, he'll have to figure out those trivialities himself.
>>2,4
yeah I understand that much about parser trees (although I thought it would better to use a concrete syntax tree rather than an AST. do you disagree?), I'm just not sure exactly how I should represent all of that in memory. right now I'm thinking on how a node could have an unlimited number of direct child nodes.
right now I'm thinking on how a node could have an unlimited number of direct child nodes.
Linked list of childer or growable arrays or <whatever_the_hell_you_want>
>>26
/* Universal Compiler
Compiles any source language to any target architecture or language.
Copyright (C)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Main include header for the Universal Compiler library */
#ifndef _UC_H
#define _UC_H
int compile(const char *langSrc, const char *langDest, const char* sFile);