RE: Complicated AST manipulation looks ugly in C++. How to refactor it?
January 25, 2022 at 2:52 am
(January 25, 2022 at 2:43 am)FlatAssembler Wrote: Here is a code I have recently written in the compiler for my programming language, written in C++:
It definitely looks incomprehensible. How would you write it better?Code:} else if (text.size() == 2 and
text[1] ==
'=') // The assignment operators "+=", "-=", "*=" and "/="...
{
if (children.at(0).text.back() ==
'[') { // https://github.com/FlatAssembler/AECforWebAssembly/issues/15
// https://discord.com/channels/530598289813536771/847014270922391563/934823770307301416
TreeNode fakeInnerFunctionNode("Does", lineNumber, columnNumber);
std::string subscriptName = "tmp" + std::to_string(rand());
TreeNode declarationOfSubscript("Integer32", lineNumber, columnNumber);
declarationOfSubscript.children.push_back(
TreeNode(subscriptName, lineNumber, columnNumber));
fakeInnerFunctionNode.children.push_back(declarationOfSubscript);
TreeNode subscriptAssignment(":=", lineNumber, columnNumber);
subscriptAssignment.children.push_back(
TreeNode(subscriptName, lineNumber, columnNumber));
subscriptAssignment.children.push_back(children[0].children.at(0));
fakeInnerFunctionNode.children.push_back(subscriptAssignment);
TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber);
convertedToSimpleAssignment.children.push_back(TreeNode(
children[0].text, children[0].lineNumber, children[0].columnNumber));
convertedToSimpleAssignment.children[0].children.push_back(
TreeNode(subscriptName, lineNumber, columnNumber));
convertedToSimpleAssignment.children.push_back(
TreeNode(text.substr(0, 1), lineNumber, columnNumber));
convertedToSimpleAssignment.children[1].children.push_back(TreeNode(
children[0].text, children[0].lineNumber, children[0].columnNumber));
convertedToSimpleAssignment.children[1].children[0].children.push_back(
TreeNode(subscriptName, lineNumber, columnNumber));
convertedToSimpleAssignment.children[1].children.push_back(
children.at(1));
fakeInnerFunctionNode.children.push_back(convertedToSimpleAssignment);
CompilationContext fakeContext = context;
fakeContext.stackSizeOfThisScope = 0;
fakeContext.stackSizeOfThisFunction = 0;
assembly += fakeInnerFunctionNode.compile(fakeContext) + "\n";
} else {
TreeNode convertedToSimpleAssignment(":=", lineNumber, columnNumber);
convertedToSimpleAssignment.children.push_back(children[0]);
convertedToSimpleAssignment.children.push_back(*this);
convertedToSimpleAssignment.children[1].text =
convertedToSimpleAssignment.children[1].text.substr(0, 1);
assembly += convertedToSimpleAssignment.compile(context);
}
I'd add dragons.
Possibly a couple of elves and a magical sword.
Playing Cluedo with my mum while I was at Uni:
"You did WHAT? With WHO? WHERE???"