How does an abstract syntax tree work?

204 views

I’ve been interested in learning what happens when keywords in code are parsed, i.e. the parser gets to the keyword “while” in python code. I think the parser then creates a node in the abstract syntax tree (I honestly don’t know what this means). What happens after that?

In: 1

6 Answers

Anonymous 0 Comments

A syntax tree is a way of representing a written set of commands. We can create a basic syntax tree from mathematical formulas.

You can imagine a basic syntax tree with each ‘node’ consisting of 3 parts – a left operand, an operator, and a right operand.

So, a basic math problem might look like

3 + 4 = ?

+
/
3 4

This syntax tree only has one node, with 3 as its left operand, 4 as its right operand and + as the operator.

If we make it a little more complicated, we can create a bigger tree:

3 + 4 * 6 = ?

+
/
3 *
/
4 6

In this tree, you can see that the bottom node needs to be calculated before the top node can be calculated.

You can create similar syntax trees with different rules and different numbers of members for virtually any kind of code or language.

You are viewing 1 out of 6 answers, click here to view all answers.