Preface
I am trying to write an interpreter/compiler for the first time. Tokenization and parsing are already a thing, that I seem to have figured out. I still find myself struggling because there are some language constructs that are hard to model. Please see the example code that I am trying to transform into an abstract syntax tree
.
class Class1 {
var someVariable = true;
}
class Class2 {
var instanceOf1 = new Class1();
func getSomething(): Class1 {
return instanceOf1;
}
}
class Class3 {
func assignFromChainedExpressions() {
var result = new Class2().getSomething().someVariable;
-----------1 -------------2 -----------3
}
func assignToChainedExpressions() {
new Class2().getSomething().someVariable = false;
-----------4 -------------5 -----------6
}
}
The underlined expressions are modeled in the AST
as:
1,4: ClassInstantiation
2,5: MethodCall
4,6: VariableAccess
Questions:
A. Should chained Expressions
be modeled as an array should they be nested into each other? What is the most practical model for later evaluation and traversal?
B. In the func
assignToChainedExpressions
, does it make sense to assign a value to a chain, where the first Expression
is a ClassInstantiation
? The instance
itself will be thrown away during runtime, I suppose.
C. Most examples use a very simple model for an Assignment
operation. See:
class Assignment { string Identifier { get; } Expression Expression { get; } }
How should a more complex assignment be modeled, if the left side of the operation is an Expression
as well?
Edit1:
Would it be a good idea to model assignFromChainedExpressions
like this:
AnonymousVariableDeclaration(value: new Class2()) // anon1
AnonymousVariableDeclaration(value: anon1.getSomeThing()) // anon2
VariableDeclaration(name: "result", value: anon2.someVariable);
Would it be a good idea to model assignToChainedExpressions
like this:
AnonymousVariableDeclaration(value: new Class2()) // anon1
AnonymousVariableDeclaration(value: anon1.getSomeThing()) // anon2
Assign(anon2.someVariable, false)