From 473b706ad985b9f3d2d19afa3c94131ac65f6395 Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Sun, 16 May 2021 00:42:37 -0700 Subject: [PATCH] clang-format config --- .clang-format | 166 ++++++++++ src/ast.c | 825 ++++++++++++++++++++++++----------------------- src/ast.h | 155 +++------ src/codegen.c | 735 +++++++++++++++++++++++++++-------------- src/identcheck.c | 564 +++++++++++++++++++------------- src/identcheck.h | 19 +- src/main.c | 36 ++- src/parser.c | 2 +- src/util.c | 21 +- src/util.h | 2 +- 10 files changed, 1520 insertions(+), 1005 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..8b0fdfa --- /dev/null +++ b/.clang-format @@ -0,0 +1,166 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveMacros: None +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: false +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +StatementAttributeLikeMacros: + - Q_EMIT +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 1000000 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... + diff --git a/src/ast.c b/src/ast.c index b3517d7..74ee4d9 100644 --- a/src/ast.c +++ b/src/ast.c @@ -1,138 +1,158 @@ #include "ast.h" -#include #include +#include #include "util.h" -const char* SyntaxKindString(SyntaxKind syntaxKind) +const char *SyntaxKindString(SyntaxKind syntaxKind) { - switch(syntaxKind) + switch (syntaxKind) { - case AccessExpression: return "AccessExpression"; - case AllocExpression: return "Alloc"; - case Assignment: return "Assignment"; - case BinaryExpression: return "BinaryExpression"; - case Comment: return "Comment"; - case CustomTypeNode: return "CustomTypeNode"; - case Declaration: return "Declaration"; - case ForLoop: return "ForLoop"; - case DeclarationSequence: return "DeclarationSequence"; - case FunctionArgumentSequence: return "FunctionArgumentSequence"; - case FunctionCallExpression: return "FunctionCallExpression"; - case FunctionDeclaration: return "FunctionDeclaration"; - case FunctionModifiers: return "FunctionModifiers"; - case FunctionSignature: return "FunctionSignature"; - case FunctionSignatureArguments: return "FunctionSignatureArguments"; - case Identifier: return "Identifier"; - case IfStatement: return "If"; - case IfElseStatement: return "IfElse"; - case Number: return "Number"; - case PrimitiveTypeNode: return "PrimitiveTypeNode"; - case ReferenceTypeNode: return "ReferenceTypeNode"; - case Return: return "Return"; - case StatementSequence: return "StatementSequence"; - case StaticModifier: return "StaticModifier"; - case StringLiteral: return "StringLiteral"; - case StructDeclaration: return "StructDeclaration"; - case Type: return "Type"; - case UnaryExpression: return "UnaryExpression"; - default: return "Unknown"; + case AccessExpression: + return "AccessExpression"; + case AllocExpression: + return "Alloc"; + case Assignment: + return "Assignment"; + case BinaryExpression: + return "BinaryExpression"; + case Comment: + return "Comment"; + case CustomTypeNode: + return "CustomTypeNode"; + case Declaration: + return "Declaration"; + case ForLoop: + return "ForLoop"; + case DeclarationSequence: + return "DeclarationSequence"; + case FunctionArgumentSequence: + return "FunctionArgumentSequence"; + case FunctionCallExpression: + return "FunctionCallExpression"; + case FunctionDeclaration: + return "FunctionDeclaration"; + case FunctionModifiers: + return "FunctionModifiers"; + case FunctionSignature: + return "FunctionSignature"; + case FunctionSignatureArguments: + return "FunctionSignatureArguments"; + case Identifier: + return "Identifier"; + case IfStatement: + return "If"; + case IfElseStatement: + return "IfElse"; + case Number: + return "Number"; + case PrimitiveTypeNode: + return "PrimitiveTypeNode"; + case ReferenceTypeNode: + return "ReferenceTypeNode"; + case Return: + return "Return"; + case StatementSequence: + return "StatementSequence"; + case StaticModifier: + return "StaticModifier"; + case StringLiteral: + return "StringLiteral"; + case StructDeclaration: + return "StructDeclaration"; + case Type: + return "Type"; + case UnaryExpression: + return "UnaryExpression"; + default: + return "Unknown"; } } -uint8_t IsPrimitiveType( - Node *typeNode -) { +uint8_t IsPrimitiveType(Node *typeNode) +{ return typeNode->type.typeNode->syntaxKind == PrimitiveTypeNode; } -Node* MakePrimitiveTypeNode( - PrimitiveType type -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakePrimitiveTypeNode(PrimitiveType type) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = PrimitiveTypeNode; node->primitiveType.type = type; return node; } -Node* MakeCustomTypeNode( - char *name -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeCustomTypeNode(char *name) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = CustomTypeNode; node->customType.name = strdup(name); return node; } -Node* MakeReferenceTypeNode( - Node *typeNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeReferenceTypeNode(Node *typeNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = ReferenceTypeNode; node->referenceType.type = typeNode; return node; } -Node* MakeTypeNode( - Node* typeNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeTypeNode(Node *typeNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Type; node->type.typeNode = typeNode; return node; } -Node* MakeIdentifierNode( - const char *id -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeIdentifierNode(const char *id) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Identifier; node->identifier.name = strdup(id); node->typeTag = NULL; return node; } -Node* MakeNumberNode( - const char *numberString -) { +Node *MakeNumberNode(const char *numberString) +{ char *ptr; - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Number; node->number.value = strtoul(numberString, &ptr, 10); return node; } -Node* MakeStringNode( - const char *string -) { +Node *MakeStringNode(const char *string) +{ size_t slen = strlen(string); - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = StringLiteral; node->stringLiteral.string = strndup(string + 1, slen - 2); return node; } -Node* MakeStaticNode() +Node *MakeStaticNode() { - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = StaticModifier; return node; } /* FIXME: this sucks */ -Node* MakeFunctionModifiersNode( - Node **pModifierNodes, - uint32_t modifierCount -) { +Node *MakeFunctionModifiersNode(Node **pModifierNodes, uint32_t modifierCount) +{ uint32_t i; - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionModifiers; node->functionModifiers.count = modifierCount; node->functionModifiers.sequence = NULL; if (modifierCount > 0) { - node->functionModifiers.sequence = malloc(sizeof(Node*) * node->functionModifiers.count); + node->functionModifiers.sequence = + malloc(sizeof(Node *) * node->functionModifiers.count); for (i = 0; i < modifierCount; i += 1) { node->functionModifiers.sequence[i] = pModifierNodes[i]; @@ -142,126 +162,118 @@ Node* MakeFunctionModifiersNode( return node; } -Node* MakeUnaryNode( - UnaryOperator operator, - Node *child -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeUnaryNode(UnaryOperator operator, Node * child) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = UnaryExpression; - node->unaryExpression.operator = operator; + node->unaryExpression.operator= operator; node->unaryExpression.child = child; return node; } -Node* MakeBinaryNode( - BinaryOperator operator, - Node *left, - Node *right -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeBinaryNode(BinaryOperator operator, Node * left, Node *right) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = BinaryExpression; node->binaryExpression.left = left; node->binaryExpression.right = right; - node->binaryExpression.operator = operator; + node->binaryExpression.operator= operator; return node; } -Node* MakeDeclarationNode( - Node* typeNode, - Node* identifierNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeDeclarationNode(Node *typeNode, Node *identifierNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Declaration; node->declaration.type = typeNode; node->declaration.identifier = identifierNode; return node; } -Node* MakeAssignmentNode( - Node *left, - Node *right -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeAssignmentNode(Node *left, Node *right) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Assignment; node->assignmentStatement.left = left; node->assignmentStatement.right = right; return node; } -Node* StartStatementSequenceNode( - Node *statementNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *StartStatementSequenceNode(Node *statementNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = StatementSequence; - node->statementSequence.sequence = (Node**) malloc(sizeof(Node*)); + node->statementSequence.sequence = (Node **)malloc(sizeof(Node *)); node->statementSequence.sequence[0] = statementNode; node->statementSequence.count = 1; return node; } -Node* AddStatement( - Node* statementSequenceNode, - Node *statementNode -) { - statementSequenceNode->statementSequence.sequence = realloc(statementSequenceNode->statementSequence.sequence, sizeof(Node*) * (statementSequenceNode->statementSequence.count + 1)); - statementSequenceNode->statementSequence.sequence[statementSequenceNode->statementSequence.count] = statementNode; +Node *AddStatement(Node *statementSequenceNode, Node *statementNode) +{ + statementSequenceNode->statementSequence.sequence = realloc( + statementSequenceNode->statementSequence.sequence, + sizeof(Node *) * (statementSequenceNode->statementSequence.count + 1)); + statementSequenceNode->statementSequence + .sequence[statementSequenceNode->statementSequence.count] = + statementNode; statementSequenceNode->statementSequence.count += 1; return statementSequenceNode; } -Node* MakeReturnStatementNode( - Node *expressionNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeReturnStatementNode(Node *expressionNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = Return; node->returnStatement.expression = expressionNode; return node; } -Node* MakeReturnVoidStatementNode() +Node *MakeReturnVoidStatementNode() { - Node *node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = ReturnVoid; return node; } -Node *StartFunctionSignatureArgumentsNode( - Node *argumentNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *StartFunctionSignatureArgumentsNode(Node *argumentNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionSignatureArguments; - node->functionSignatureArguments.sequence = (Node**) malloc(sizeof(Node*)); + node->functionSignatureArguments.sequence = (Node **)malloc(sizeof(Node *)); node->functionSignatureArguments.sequence[0] = argumentNode; node->functionSignatureArguments.count = 1; return node; } -Node* AddFunctionSignatureArgumentNode( - Node *argumentsNode, - Node *argumentNode -) { - argumentsNode->functionSignatureArguments.sequence = realloc(argumentsNode->functionSignatureArguments.sequence, sizeof(Node*) * (argumentsNode->functionSignatureArguments.count + 1)); - argumentsNode->functionSignatureArguments.sequence[argumentsNode->functionSignatureArguments.count] = argumentNode; +Node *AddFunctionSignatureArgumentNode(Node *argumentsNode, Node *argumentNode) +{ + argumentsNode->functionSignatureArguments.sequence = realloc( + argumentsNode->functionSignatureArguments.sequence, + sizeof(Node *) * (argumentsNode->functionSignatureArguments.count + 1)); + argumentsNode->functionSignatureArguments + .sequence[argumentsNode->functionSignatureArguments.count] = + argumentNode; argumentsNode->functionSignatureArguments.count += 1; return argumentsNode; } Node *MakeEmptyFunctionSignatureArgumentsNode() { - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionSignatureArguments; node->functionSignatureArguments.sequence = NULL; node->functionSignatureArguments.count = 0; return node; } -Node* MakeFunctionSignatureNode( +Node *MakeFunctionSignatureNode( Node *identifierNode, - Node* typeNode, - Node* arguments, - Node* modifiersNode -) { - Node* node = (Node*) malloc(sizeof(Node)); + Node *typeNode, + Node *arguments, + Node *modifiersNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionSignature; node->functionSignature.identifier = identifierNode; node->functionSignature.type = typeNode; @@ -270,138 +282,136 @@ Node* MakeFunctionSignatureNode( return node; } -Node* MakeFunctionDeclarationNode( - Node* functionSignatureNode, - Node* functionBodyNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeFunctionDeclarationNode( + Node *functionSignatureNode, + Node *functionBodyNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionDeclaration; node->functionDeclaration.functionSignature = functionSignatureNode; node->functionDeclaration.functionBody = functionBodyNode; return node; } -Node* MakeStructDeclarationNode( +Node *MakeStructDeclarationNode( Node *identifierNode, - Node *declarationSequenceNode -) { - Node* node = (Node*) malloc(sizeof(Node)); + Node *declarationSequenceNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = StructDeclaration; node->structDeclaration.identifier = identifierNode; node->structDeclaration.declarationSequence = declarationSequenceNode; return node; } -Node* StartDeclarationSequenceNode( - Node *declarationNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *StartDeclarationSequenceNode(Node *declarationNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = DeclarationSequence; - node->declarationSequence.sequence = (Node**) malloc(sizeof(Node*)); + node->declarationSequence.sequence = (Node **)malloc(sizeof(Node *)); node->declarationSequence.sequence[0] = declarationNode; node->declarationSequence.count = 1; return node; } -Node* AddDeclarationNode( - Node *declarationSequenceNode, - Node *declarationNode -) { - declarationSequenceNode->declarationSequence.sequence = (Node**) realloc(declarationSequenceNode->declarationSequence.sequence, sizeof(Node*) * (declarationSequenceNode->declarationSequence.count + 1)); - declarationSequenceNode->declarationSequence.sequence[declarationSequenceNode->declarationSequence.count] = declarationNode; +Node *AddDeclarationNode(Node *declarationSequenceNode, Node *declarationNode) +{ + declarationSequenceNode->declarationSequence.sequence = (Node **)realloc( + declarationSequenceNode->declarationSequence.sequence, + sizeof(Node *) * + (declarationSequenceNode->declarationSequence.count + 1)); + declarationSequenceNode->declarationSequence + .sequence[declarationSequenceNode->declarationSequence.count] = + declarationNode; declarationSequenceNode->declarationSequence.count += 1; return declarationSequenceNode; } -Node* StartFunctionArgumentSequenceNode( - Node *argumentNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *StartFunctionArgumentSequenceNode(Node *argumentNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionArgumentSequence; - node->functionArgumentSequence.sequence = (Node**) malloc(sizeof(Node*)); + node->functionArgumentSequence.sequence = (Node **)malloc(sizeof(Node *)); node->functionArgumentSequence.sequence[0] = argumentNode; node->functionArgumentSequence.count = 1; return node; } -Node* AddFunctionArgumentNode( - Node *argumentSequenceNode, - Node *argumentNode -) { - argumentSequenceNode->functionArgumentSequence.sequence = (Node**) realloc(argumentSequenceNode->functionArgumentSequence.sequence, sizeof(Node*) * (argumentSequenceNode->functionArgumentSequence.count + 1)); - argumentSequenceNode->functionArgumentSequence.sequence[argumentSequenceNode->functionArgumentSequence.count] = argumentNode; +Node *AddFunctionArgumentNode(Node *argumentSequenceNode, Node *argumentNode) +{ + argumentSequenceNode->functionArgumentSequence.sequence = (Node **)realloc( + argumentSequenceNode->functionArgumentSequence.sequence, + sizeof(Node *) * + (argumentSequenceNode->functionArgumentSequence.count + 1)); + argumentSequenceNode->functionArgumentSequence + .sequence[argumentSequenceNode->functionArgumentSequence.count] = + argumentNode; argumentSequenceNode->functionArgumentSequence.count += 1; return argumentSequenceNode; } Node *MakeEmptyFunctionArgumentSequenceNode() { - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionArgumentSequence; node->functionArgumentSequence.count = 0; node->functionArgumentSequence.sequence = NULL; return node; } -Node* MakeFunctionCallExpressionNode( +Node *MakeFunctionCallExpressionNode( Node *identifierNode, - Node *argumentSequenceNode -) { - Node* node = (Node*) malloc(sizeof(Node)); + Node *argumentSequenceNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = FunctionCallExpression; node->functionCallExpression.identifier = identifierNode; node->functionCallExpression.argumentSequence = argumentSequenceNode; return node; } -Node* MakeAccessExpressionNode( - Node *accessee, - Node *accessor -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeAccessExpressionNode(Node *accessee, Node *accessor) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = AccessExpression; node->accessExpression.accessee = accessee; node->accessExpression.accessor = accessor; return node; } -Node* MakeAllocNode(Node *typeNode) +Node *MakeAllocNode(Node *typeNode) { - Node* node = (Node*) malloc(sizeof(Node)); + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = AllocExpression; node->allocExpression.type = typeNode; return node; } -Node* MakeIfNode( - Node *expressionNode, - Node *statementSequenceNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeIfNode(Node *expressionNode, Node *statementSequenceNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = IfStatement; node->ifStatement.expression = expressionNode; node->ifStatement.statementSequence = statementSequenceNode; return node; } -Node* MakeIfElseNode( - Node *ifNode, - Node *elseNode -) { - Node* node = (Node*) malloc(sizeof(Node)); +Node *MakeIfElseNode(Node *ifNode, Node *elseNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = IfElseStatement; node->ifElseStatement.ifStatement = ifNode; node->ifElseStatement.elseStatement = elseNode; return node; } -Node* MakeForLoopNode( +Node *MakeForLoopNode( Node *declarationNode, Node *startNumberNode, Node *endNumberNode, - Node *statementSequenceNode -) { - Node* node = (Node*) malloc(sizeof(Node)); + Node *statementSequenceNode) +{ + Node *node = (Node *)malloc(sizeof(Node)); node->syntaxKind = ForLoop; node->forLoop.declaration = declarationNode; node->forLoop.startNumber = startNumberNode; @@ -410,14 +420,18 @@ Node* MakeForLoopNode( return node; } -static const char* PrimitiveTypeToString(PrimitiveType type) +static const char *PrimitiveTypeToString(PrimitiveType type) { switch (type) { - case Int: return "Int"; - case UInt: return "UInt"; - case Bool: return "Bool"; - case Void: return "Void"; + case Int: + return "Int"; + case UInt: + return "UInt"; + case Bool: + return "Bool"; + case Void: + return "Void"; } return "Unknown"; @@ -427,9 +441,9 @@ static void PrintUnaryOperator(UnaryOperator operator) { switch (operator) { - case Negate: - printf("!"); - break; + case Negate: + printf("!"); + break; } } @@ -437,17 +451,17 @@ static void PrintBinaryOperator(BinaryOperator operator) { switch (operator) { - case Add: - printf("(+)"); - break; + case Add: + printf("(+)"); + break; - case Subtract: - printf("(-)"); - break; + case Subtract: + printf("(-)"); + break; - case Multiply: - printf("(*)"); - break; + case Multiply: + printf("(*)"); + break; } } @@ -462,245 +476,264 @@ void PrintNode(Node *node, uint32_t tabCount) printf("%s: ", SyntaxKindString(node->syntaxKind)); switch (node->syntaxKind) { - case AccessExpression: - printf("\n"); - PrintNode(node->accessExpression.accessee, tabCount + 1); - PrintNode(node->accessExpression.accessor, tabCount + 1); - return; + case AccessExpression: + printf("\n"); + PrintNode(node->accessExpression.accessee, tabCount + 1); + PrintNode(node->accessExpression.accessor, tabCount + 1); + return; - case AllocExpression: - printf("\n"); - PrintNode(node->allocExpression.type, tabCount + 1); - return; + case AllocExpression: + printf("\n"); + PrintNode(node->allocExpression.type, tabCount + 1); + return; - case Assignment: - printf("\n"); - PrintNode(node->assignmentStatement.left, tabCount + 1); - PrintNode(node->assignmentStatement.right, tabCount + 1); - return; + case Assignment: + printf("\n"); + PrintNode(node->assignmentStatement.left, tabCount + 1); + PrintNode(node->assignmentStatement.right, tabCount + 1); + return; - case BinaryExpression: - PrintBinaryOperator(node->binaryExpression.operator); - printf("\n"); - PrintNode(node->binaryExpression.left, tabCount + 1); - PrintNode(node->binaryExpression.right, tabCount + 1); - return; + case BinaryExpression: + PrintBinaryOperator(node->binaryExpression.operator); + printf("\n"); + PrintNode(node->binaryExpression.left, tabCount + 1); + PrintNode(node->binaryExpression.right, tabCount + 1); + return; - case CustomTypeNode: - printf("%s\n", node->customType.name); - return; + case CustomTypeNode: + printf("%s\n", node->customType.name); + return; - case Declaration: - printf("\n"); - PrintNode(node->declaration.identifier, tabCount + 1); - PrintNode(node->declaration.type, tabCount + 1); - return; + case Declaration: + printf("\n"); + PrintNode(node->declaration.identifier, tabCount + 1); + PrintNode(node->declaration.type, tabCount + 1); + return; - case DeclarationSequence: - printf("\n"); - for (i = 0; i < node->declarationSequence.count; i += 1) - { - PrintNode(node->declarationSequence.sequence[i], tabCount + 1); - } - return; + case DeclarationSequence: + printf("\n"); + for (i = 0; i < node->declarationSequence.count; i += 1) + { + PrintNode(node->declarationSequence.sequence[i], tabCount + 1); + } + return; - case ForLoop: - printf("\n"); - PrintNode(node->forLoop.declaration, tabCount + 1); - PrintNode(node->forLoop.startNumber, tabCount + 1); - PrintNode(node->forLoop.endNumber, tabCount + 1); - PrintNode(node->forLoop.statementSequence, tabCount + 1); - return; + case ForLoop: + printf("\n"); + PrintNode(node->forLoop.declaration, tabCount + 1); + PrintNode(node->forLoop.startNumber, tabCount + 1); + PrintNode(node->forLoop.endNumber, tabCount + 1); + PrintNode(node->forLoop.statementSequence, tabCount + 1); + return; - case FunctionArgumentSequence: - printf("\n"); - for (i = 0; i < node->functionArgumentSequence.count; i += 1) - { - PrintNode(node->functionArgumentSequence.sequence[i], tabCount + 1); - } - return; + case FunctionArgumentSequence: + printf("\n"); + for (i = 0; i < node->functionArgumentSequence.count; i += 1) + { + PrintNode(node->functionArgumentSequence.sequence[i], tabCount + 1); + } + return; - case FunctionCallExpression: - printf("\n"); - PrintNode(node->functionCallExpression.identifier, tabCount + 1); - PrintNode(node->functionCallExpression.argumentSequence, tabCount + 1); - return; + case FunctionCallExpression: + printf("\n"); + PrintNode(node->functionCallExpression.identifier, tabCount + 1); + PrintNode(node->functionCallExpression.argumentSequence, tabCount + 1); + return; - case FunctionDeclaration: - printf("\n"); - PrintNode(node->functionDeclaration.functionSignature, tabCount + 1); - PrintNode(node->functionDeclaration.functionBody, tabCount + 1); - return; + case FunctionDeclaration: + printf("\n"); + PrintNode(node->functionDeclaration.functionSignature, tabCount + 1); + PrintNode(node->functionDeclaration.functionBody, tabCount + 1); + return; - case FunctionModifiers: - printf("\n"); - for (i = 0; i < node->functionModifiers.count; i += 1) - { - PrintNode(node->functionModifiers.sequence[i], tabCount + 1); - } - return; + case FunctionModifiers: + printf("\n"); + for (i = 0; i < node->functionModifiers.count; i += 1) + { + PrintNode(node->functionModifiers.sequence[i], tabCount + 1); + } + return; - case FunctionSignature: - printf("\n"); - PrintNode(node->functionSignature.identifier, tabCount + 1); - PrintNode(node->functionSignature.arguments, tabCount + 1); - PrintNode(node->functionSignature.type, tabCount + 1); - PrintNode(node->functionSignature.modifiers, tabCount + 1); - return; + case FunctionSignature: + printf("\n"); + PrintNode(node->functionSignature.identifier, tabCount + 1); + PrintNode(node->functionSignature.arguments, tabCount + 1); + PrintNode(node->functionSignature.type, tabCount + 1); + PrintNode(node->functionSignature.modifiers, tabCount + 1); + return; - case FunctionSignatureArguments: - printf("\n"); - for (i = 0; i < node->functionSignatureArguments.count; i += 1) - { - PrintNode(node->functionSignatureArguments.sequence[i], tabCount + 1); - } - return; + case FunctionSignatureArguments: + printf("\n"); + for (i = 0; i < node->functionSignatureArguments.count; i += 1) + { + PrintNode( + node->functionSignatureArguments.sequence[i], + tabCount + 1); + } + return; - case Identifier: - if (node->typeTag == NULL) { - printf("%s\n", node->identifier.name); - } else { - char *type = TypeTagToString(node->typeTag); - printf("%s<%s>\n", node->identifier.name, type); - } - return; + case Identifier: + if (node->typeTag == NULL) + { + printf("%s\n", node->identifier.name); + } + else + { + char *type = TypeTagToString(node->typeTag); + printf("%s<%s>\n", node->identifier.name, type); + } + return; - case IfStatement: - printf("\n"); - PrintNode(node->ifStatement.expression, tabCount + 1); - PrintNode(node->ifStatement.statementSequence, tabCount + 1); - return; + case IfStatement: + printf("\n"); + PrintNode(node->ifStatement.expression, tabCount + 1); + PrintNode(node->ifStatement.statementSequence, tabCount + 1); + return; - case IfElseStatement: - printf("\n"); - PrintNode(node->ifElseStatement.ifStatement, tabCount + 1); - PrintNode(node->ifElseStatement.elseStatement, tabCount + 1); - return; + case IfElseStatement: + printf("\n"); + PrintNode(node->ifElseStatement.ifStatement, tabCount + 1); + PrintNode(node->ifElseStatement.elseStatement, tabCount + 1); + return; - case Number: - printf("%lu\n", node->number.value); - return; + case Number: + printf("%lu\n", node->number.value); + return; - case PrimitiveTypeNode: - printf("%s\n", PrimitiveTypeToString(node->primitiveType.type)); - return; + case PrimitiveTypeNode: + printf("%s\n", PrimitiveTypeToString(node->primitiveType.type)); + return; - case ReferenceTypeNode: - printf("\n"); - PrintNode(node->referenceType.type, tabCount + 1); - return; + case ReferenceTypeNode: + printf("\n"); + PrintNode(node->referenceType.type, tabCount + 1); + return; - case Return: - printf("\n"); - PrintNode(node->returnStatement.expression, tabCount + 1); - return; + case Return: + printf("\n"); + PrintNode(node->returnStatement.expression, tabCount + 1); + return; - case ReturnVoid: - return; + case ReturnVoid: + return; - case StatementSequence: - printf("\n"); - for (i = 0; i < node->statementSequence.count; i += 1) - { - PrintNode(node->statementSequence.sequence[i], tabCount + 1); - } - return; + case StatementSequence: + printf("\n"); + for (i = 0; i < node->statementSequence.count; i += 1) + { + PrintNode(node->statementSequence.sequence[i], tabCount + 1); + } + return; - case StaticModifier: - printf("\n"); - return; + case StaticModifier: + printf("\n"); + return; - case StringLiteral: - printf("%s", node->stringLiteral.string); - return; + case StringLiteral: + printf("%s", node->stringLiteral.string); + return; - case StructDeclaration: - printf("\n"); - PrintNode(node->structDeclaration.identifier, tabCount + 1); - PrintNode(node->structDeclaration.declarationSequence, tabCount + 1); - return; + case StructDeclaration: + printf("\n"); + PrintNode(node->structDeclaration.identifier, tabCount + 1); + PrintNode(node->structDeclaration.declarationSequence, tabCount + 1); + return; - case Type: - printf("\n"); - PrintNode(node->type.typeNode, tabCount + 1); - return; + case Type: + printf("\n"); + PrintNode(node->type.typeNode, tabCount + 1); + return; - case UnaryExpression: - PrintUnaryOperator(node->unaryExpression.operator); - PrintNode(node->unaryExpression.child, tabCount + 1); - return; + case UnaryExpression: + PrintUnaryOperator(node->unaryExpression.operator); + PrintNode(node->unaryExpression.child, tabCount + 1); + return; } } -TypeTag* MakeTypeTag(Node *node) { - if (node == NULL) { - fprintf(stderr, "wraith: Attempted to call MakeTypeTag on null value.\n"); +TypeTag *MakeTypeTag(Node *node) +{ + if (node == NULL) + { + fprintf( + stderr, + "wraith: Attempted to call MakeTypeTag on null value.\n"); return NULL; } - TypeTag *tag = (TypeTag*)malloc(sizeof(TypeTag)); - switch (node->syntaxKind) { - case Type: - tag = MakeTypeTag(node->type.typeNode); - break; + TypeTag *tag = (TypeTag *)malloc(sizeof(TypeTag)); + switch (node->syntaxKind) + { + case Type: + tag = MakeTypeTag(node->type.typeNode); + break; - case PrimitiveTypeNode: - tag->type = Primitive; - tag->value.primitiveType = node->primitiveType.type; - break; + case PrimitiveTypeNode: + tag->type = Primitive; + tag->value.primitiveType = node->primitiveType.type; + break; - case ReferenceTypeNode: - tag->type = Reference; - tag->value.referenceType = MakeTypeTag(node->referenceType.type); - break; + case ReferenceTypeNode: + tag->type = Reference; + tag->value.referenceType = MakeTypeTag(node->referenceType.type); + break; - case CustomTypeNode: - tag->type = Custom; - tag->value.customType = strdup(node->customType.name); - break; + case CustomTypeNode: + tag->type = Custom; + tag->value.customType = strdup(node->customType.name); + break; - case Declaration: - tag = MakeTypeTag(node->declaration.type); - break; + case Declaration: + tag = MakeTypeTag(node->declaration.type); + break; - case StructDeclaration: - tag->type = Custom; - tag->value.customType = strdup(node->structDeclaration.identifier->identifier.name); - break; + case StructDeclaration: + tag->type = Custom; + tag->value.customType = + strdup(node->structDeclaration.identifier->identifier.name); + break; - case FunctionDeclaration: - tag = MakeTypeTag(node->functionDeclaration.functionSignature->functionSignature.type); - break; + case FunctionDeclaration: + tag = MakeTypeTag(node->functionDeclaration.functionSignature + ->functionSignature.type); + break; - default: - fprintf(stderr, - "wraith: Attempted to call MakeTypeTag on" - " node with unsupported SyntaxKind: %s\n", - SyntaxKindString(node->syntaxKind)); - return NULL; + default: + fprintf( + stderr, + "wraith: Attempted to call MakeTypeTag on" + " node with unsupported SyntaxKind: %s\n", + SyntaxKindString(node->syntaxKind)); + return NULL; } return tag; } -char* TypeTagToString(TypeTag *tag) { - if (tag == NULL) { - fprintf(stderr, "wraith: Attempted to call TypeTagToString with null value\n"); +char *TypeTagToString(TypeTag *tag) +{ + if (tag == NULL) + { + fprintf( + stderr, + "wraith: Attempted to call TypeTagToString with null value\n"); return NULL; } - switch (tag->type) { - case Unknown: - return "Unknown"; - case Primitive: - return PrimitiveTypeToString(tag->value.primitiveType); - case Reference: { - char *inner = TypeTagToString(tag->value.referenceType); - size_t innerStrLen = strlen(inner); - char *result = malloc(sizeof(char) * (innerStrLen + 5)); - sprintf(result, "Ref<%s>", inner); - return result; - } - case Custom: - return tag->value.customType; + switch (tag->type) + { + case Unknown: + return "Unknown"; + case Primitive: + return PrimitiveTypeToString(tag->value.primitiveType); + case Reference: + { + char *inner = TypeTagToString(tag->value.referenceType); + size_t innerStrLen = strlen(inner); + char *result = malloc(sizeof(char) * (innerStrLen + 5)); + sprintf(result, "Ref<%s>", inner); + return result; + } + case Custom: + return tag->value.customType; } } diff --git a/src/ast.h b/src/ast.h index ff97f3e..60e954d 100644 --- a/src/ast.h +++ b/src/ast.h @@ -1,8 +1,8 @@ #ifndef WRAITH_AST_H #define WRAITH_AST_H -#include #include "identcheck.h" +#include /* -Wpedantic nameless union/struct silencing */ #ifndef WRAITHNAMELESS @@ -279,130 +279,65 @@ struct Node IdNode *idLink; }; -const char* SyntaxKindString(SyntaxKind syntaxKind); +const char *SyntaxKindString(SyntaxKind syntaxKind); uint8_t IsPrimitiveType(Node *typeNode); -Node* MakePrimitiveTypeNode( - PrimitiveType type -); -Node* MakeCustomTypeNode( - char *string -); -Node* MakeReferenceTypeNode( - Node *typeNode -); -Node* MakeTypeNode( - Node *typeNode /* can be primitive, custom, or reference */ -); -Node* MakeIdentifierNode( - const char *id -); -Node* MakeNumberNode( - const char *numberString -); -Node* MakeStringNode( - const char *string -); -Node* MakeStaticNode(); -Node* MakeFunctionModifiersNode( - Node **pModifierNodes, - uint32_t modifierCount -); -Node* MakeUnaryNode( - UnaryOperator operator, - Node *child -); -Node* MakeBinaryNode( - BinaryOperator operator, - Node *left, - Node *right -); -Node* MakeDeclarationNode( - Node* typeNode, - Node* identifierNode -); -Node* MakeAssignmentNode( - Node *left, - Node *right -); -Node* StartStatementSequenceNode( - Node* statementNode -); -Node* AddStatement( - Node* statementSequenceNode, - Node *statementNode -); -Node* MakeReturnStatementNode( - Node *expressionNode -); -Node* MakeReturnVoidStatementNode(); -Node* StartFunctionSignatureArgumentsNode( - Node *argumentNode -); -Node* AddFunctionSignatureArgumentNode( - Node *argumentsNode, - Node *argumentNode -); +Node *MakePrimitiveTypeNode(PrimitiveType type); +Node *MakeCustomTypeNode(char *string); +Node *MakeReferenceTypeNode(Node *typeNode); +Node *MakeTypeNode(Node *typeNode); +Node *MakeIdentifierNode(const char *id); +Node *MakeNumberNode(const char *numberString); +Node *MakeStringNode(const char *string); +Node *MakeStaticNode(); +Node *MakeFunctionModifiersNode(Node **pModifierNodes, uint32_t modifierCount); +Node *MakeUnaryNode(UnaryOperator operator, Node * child); +Node *MakeBinaryNode(BinaryOperator operator, Node * left, Node *right); +Node *MakeDeclarationNode(Node *typeNode, Node *identifierNode); +Node *MakeAssignmentNode(Node *left, Node *right); +Node *StartStatementSequenceNode(Node *statementNode); +Node *AddStatement(Node *statementSequenceNode, Node *statementNode); +Node *MakeReturnStatementNode(Node *expressionNode); +Node *MakeReturnVoidStatementNode(); +Node *StartFunctionSignatureArgumentsNode(Node *argumentNode); +Node *AddFunctionSignatureArgumentNode(Node *argumentsNode, Node *argumentNode); Node *MakeEmptyFunctionSignatureArgumentsNode(); -Node* MakeFunctionSignatureNode( +Node *MakeFunctionSignatureNode( Node *identifierNode, - Node* typeNode, - Node* argumentsNode, - Node* modifiersNode -); -Node* MakeFunctionDeclarationNode( - Node* functionSignatureNode, - Node* functionBodyNode -); -Node* MakeStructDeclarationNode( + Node *typeNode, + Node *argumentsNode, + Node *modifiersNode); +Node *MakeFunctionDeclarationNode( + Node *functionSignatureNode, + Node *functionBodyNode); +Node *MakeStructDeclarationNode( Node *identifierNode, - Node *declarationSequenceNode -); -Node* StartDeclarationSequenceNode( - Node *declarationNode -); -Node* AddDeclarationNode( - Node *declarationSequenceNode, - Node *declarationNode -); -Node *StartFunctionArgumentSequenceNode( - Node *argumentNode -); -Node *AddFunctionArgumentNode( - Node *argumentSequenceNode, - Node *argumentNode -); + Node *declarationSequenceNode); +Node *StartDeclarationSequenceNode(Node *declarationNode); +Node *AddDeclarationNode(Node *declarationSequenceNode, Node *declarationNode); +Node *StartFunctionArgumentSequenceNode(Node *argumentNode); +Node *AddFunctionArgumentNode(Node *argumentSequenceNode, Node *argumentNode); Node *MakeEmptyFunctionArgumentSequenceNode(); -Node* MakeFunctionCallExpressionNode( +Node *MakeFunctionCallExpressionNode( Node *identifierNode, - Node *argumentSequenceNode -); -Node* MakeAccessExpressionNode( - Node *accessee, - Node *accessor -); -Node* MakeAllocNode( - Node *typeNode -); -Node* MakeIfNode( - Node *expressionNode, - Node *statementSequenceNode -); -Node* MakeIfElseNode( + Node *argumentSequenceNode); +Node *MakeAccessExpressionNode(Node *accessee, Node *accessor); +Node *MakeAllocNode(Node *typeNode); +Node *MakeIfNode(Node *expressionNode, Node *statementSequenceNode); +Node *MakeIfElseNode( Node *ifNode, Node *elseNode /* can be a conditional or a statement sequence */ ); -Node* MakeForLoopNode( +Node *MakeForLoopNode( Node *identifierNode, Node *startNumberNode, Node *endNumberNode, - Node *statementSequenceNode -); + Node *statementSequenceNode); void PrintNode(Node *node, uint32_t tabCount); -const char* SyntaxKindString(SyntaxKind syntaxKind); +const char *SyntaxKindString(SyntaxKind syntaxKind); -TypeTag* MakeTypeTag(Node *node); -char* TypeTagToString(TypeTag *tag); +TypeTag *MakeTypeTag(Node *node); +char *TypeTagToString(TypeTag *tag); #endif /* WRAITH_AST_H */ diff --git a/src/codegen.c b/src/codegen.c index e7492fe..e8a5fb9 100644 --- a/src/codegen.c +++ b/src/codegen.c @@ -2,16 +2,16 @@ #include #include -#include #include #include +#include #include -#include +#include +#include #include +#include #include #include -#include -#include #include "ast.h" @@ -71,7 +71,7 @@ typedef struct StructTypeDeclaration StructTypeDeclaration *structTypeDeclarations; uint32_t structTypeDeclarationCount; -static Scope* CreateScope() +static Scope *CreateScope() { Scope *scope = malloc(sizeof(Scope)); @@ -86,7 +86,9 @@ static Scope* CreateScope() static void PushScopeFrame(Scope *scope) { uint32_t index = scope->scopeStackCount; - scope->scopeStack = realloc(scope->scopeStack, sizeof(ScopeFrame) * (scope->scopeStackCount + 1)); + scope->scopeStack = realloc( + scope->scopeStack, + sizeof(ScopeFrame) * (scope->scopeStackCount + 1)); scope->scopeStack[index].localVariableCount = 0; scope->scopeStack[index].localVariables = NULL; @@ -109,19 +111,22 @@ static void PopScopeFrame(Scope *scope) scope->scopeStackCount -= 1; - scope->scopeStack = realloc(scope->scopeStack, sizeof(ScopeFrame) * scope->scopeStackCount); + scope->scopeStack = + realloc(scope->scopeStack, sizeof(ScopeFrame) * scope->scopeStackCount); } static void AddLocalVariable( Scope *scope, LLVMValueRef pointer, /* can be NULL */ - LLVMValueRef value, /* can be NULL */ - char *name -) { + LLVMValueRef value, /* can be NULL */ + char *name) +{ ScopeFrame *scopeFrame = &scope->scopeStack[scope->scopeStackCount - 1]; uint32_t index = scopeFrame->localVariableCount; - scopeFrame->localVariables = realloc(scopeFrame->localVariables, sizeof(LocalVariable) * (scopeFrame->localVariableCount + 1)); + scopeFrame->localVariables = realloc( + scopeFrame->localVariables, + sizeof(LocalVariable) * (scopeFrame->localVariableCount + 1)); scopeFrame->localVariables[index].name = strdup(name); scopeFrame->localVariables[index].pointer = pointer; scopeFrame->localVariables[index].value = value; @@ -133,17 +138,17 @@ static LLVMTypeRef WraithTypeToLLVMType(PrimitiveType type) { switch (type) { - case Int: - return LLVMInt64Type(); + case Int: + return LLVMInt64Type(); - case UInt: - return LLVMInt64Type(); + case UInt: + return LLVMInt64Type(); - case Bool: - return LLVMInt1Type(); + case Bool: + return LLVMInt1Type(); - case Void: - return LLVMVoidType(); + case Void: + return LLVMVoidType(); } fprintf(stderr, "Unrecognized type!"); @@ -165,7 +170,10 @@ static LLVMTypeRef FindStructType(char *name) return NULL; } -static LLVMValueRef FindStructFieldPointer(LLVMBuilderRef builder, LLVMValueRef structPointer, char *name) +static LLVMValueRef FindStructFieldPointer( + LLVMBuilderRef builder, + LLVMValueRef structPointer, + char *name) { int32_t i, j; @@ -185,8 +193,7 @@ static LLVMValueRef FindStructFieldPointer(LLVMBuilderRef builder, LLVMValueRef builder, structPointer, structTypeDeclarations[i].fields[j].index, - ptrName - ); + ptrName); free(ptrName); } } @@ -232,7 +239,10 @@ static LLVMValueRef FindVariableValue(LLVMBuilderRef builder, char *name) } else { - return LLVMBuildLoad(builder, scope->scopeStack[i].localVariables[j].pointer, name); + return LLVMBuildLoad( + builder, + scope->scopeStack[i].localVariables[j].pointer, + name); } } } @@ -247,11 +257,13 @@ static void AddStructDeclaration( LLVMTypeRef wStructPointerType, char *name, Node **fieldDeclarations, - uint32_t fieldDeclarationCount -) { + uint32_t fieldDeclarationCount) +{ uint32_t i; uint32_t index = structTypeDeclarationCount; - structTypeDeclarations = realloc(structTypeDeclarations, sizeof(StructTypeDeclaration) * (structTypeDeclarationCount + 1)); + structTypeDeclarations = realloc( + structTypeDeclarations, + sizeof(StructTypeDeclaration) * (structTypeDeclarationCount + 1)); structTypeDeclarations[index].structType = wStructType; structTypeDeclarations[index].structPointerType = wStructPointerType; structTypeDeclarations[index].name = strdup(name); @@ -262,8 +274,12 @@ static void AddStructDeclaration( for (i = 0; i < fieldDeclarationCount; i += 1) { - structTypeDeclarations[index].fields = realloc(structTypeDeclarations[index].fields, sizeof(StructTypeField) * (structTypeDeclarations[index].fieldCount + 1)); - structTypeDeclarations[index].fields[i].name = strdup(fieldDeclarations[i]->declaration.identifier->identifier.name); + structTypeDeclarations[index].fields = realloc( + structTypeDeclarations[index].fields, + sizeof(StructTypeField) * + (structTypeDeclarations[index].fieldCount + 1)); + structTypeDeclarations[index].fields[i].name = strdup( + fieldDeclarations[i]->declaration.identifier->identifier.name); structTypeDeclarations[index].fields[i].index = i; structTypeDeclarations[index].fieldCount += 1; } @@ -276,8 +292,8 @@ static void DeclareStructFunction( LLVMValueRef function, LLVMTypeRef returnType, uint8_t isStatic, - char *name -) { + char *name) +{ uint32_t i, index; for (i = 0; i < structTypeDeclarationCount; i += 1) @@ -285,7 +301,10 @@ static void DeclareStructFunction( if (structTypeDeclarations[i].structPointerType == wStructPointerType) { index = structTypeDeclarations[i].functionCount; - structTypeDeclarations[i].functions = realloc(structTypeDeclarations[i].functions, sizeof(StructTypeFunction) * (structTypeDeclarations[i].functionCount + 1)); + structTypeDeclarations[i].functions = realloc( + structTypeDeclarations[i].functions, + sizeof(StructTypeFunction) * + (structTypeDeclarations[i].functionCount + 1)); structTypeDeclarations[i].functions[index].name = strdup(name); structTypeDeclarations[i].functions[index].function = function; structTypeDeclarations[i].functions[index].returnType = returnType; @@ -315,11 +334,12 @@ static LLVMTypeRef LookupCustomType(char *name) return NULL; } -static LLVMTypeRef ResolveType(Node* typeNode) +static LLVMTypeRef ResolveType(Node *typeNode) { if (IsPrimitiveType(typeNode)) { - return WraithTypeToLLVMType(typeNode->type.typeNode->primitiveType.type); + return WraithTypeToLLVMType( + typeNode->type.typeNode->primitiveType.type); } else if (typeNode->type.typeNode->syntaxKind == CustomTypeNode) { @@ -327,7 +347,9 @@ static LLVMTypeRef ResolveType(Node* typeNode) } else if (typeNode->type.typeNode->syntaxKind == ReferenceTypeNode) { - return LLVMPointerType(ResolveType(typeNode->type.typeNode->referenceType.type), 0); + return LLVMPointerType( + ResolveType(typeNode->type.typeNode->referenceType.type), + 0); } else { @@ -340,8 +362,8 @@ static LLVMValueRef LookupFunctionByType( LLVMTypeRef structType, char *name, LLVMTypeRef *pReturnType, - uint8_t *pStatic -) { + uint8_t *pStatic) +{ uint32_t i, j; for (i = 0; i < structTypeDeclarationCount; i += 1) @@ -350,9 +372,11 @@ static LLVMValueRef LookupFunctionByType( { for (j = 0; j < structTypeDeclarations[i].functionCount; j += 1) { - if (strcmp(structTypeDeclarations[i].functions[j].name, name) == 0) + if (strcmp(structTypeDeclarations[i].functions[j].name, name) == + 0) { - *pReturnType = structTypeDeclarations[i].functions[j].returnType; + *pReturnType = + structTypeDeclarations[i].functions[j].returnType; *pStatic = structTypeDeclarations[i].functions[j].isStatic; return structTypeDeclarations[i].functions[j].function; } @@ -368,8 +392,8 @@ static LLVMValueRef LookupFunctionByPointerType( LLVMTypeRef structPointerType, char *name, LLVMTypeRef *pReturnType, - uint8_t *pStatic -) { + uint8_t *pStatic) +{ uint32_t i, j; for (i = 0; i < structTypeDeclarationCount; i += 1) @@ -378,9 +402,11 @@ static LLVMValueRef LookupFunctionByPointerType( { for (j = 0; j < structTypeDeclarations[i].functionCount; j += 1) { - if (strcmp(structTypeDeclarations[i].functions[j].name, name) == 0) + if (strcmp(structTypeDeclarations[i].functions[j].name, name) == + 0) { - *pReturnType = structTypeDeclarations[i].functions[j].returnType; + *pReturnType = + structTypeDeclarations[i].functions[j].returnType; *pStatic = structTypeDeclarations[i].functions[j].isStatic; return structTypeDeclarations[i].functions[j].function; } @@ -396,95 +422,110 @@ static LLVMValueRef LookupFunctionByInstance( LLVMValueRef structPointer, char *name, LLVMTypeRef *pReturnType, - uint8_t *pStatic -) { - return LookupFunctionByPointerType(LLVMTypeOf(structPointer), name, pReturnType, pStatic); + uint8_t *pStatic) +{ + return LookupFunctionByPointerType( + LLVMTypeOf(structPointer), + name, + pReturnType, + pStatic); } static void AddStructVariablesToScope( LLVMBuilderRef builder, - LLVMValueRef structPointer -) { + LLVMValueRef structPointer) +{ uint32_t i, j; for (i = 0; i < structTypeDeclarationCount; i += 1) { - if (structTypeDeclarations[i].structPointerType == LLVMTypeOf(structPointer)) + if (structTypeDeclarations[i].structPointerType == + LLVMTypeOf(structPointer)) { for (j = 0; j < structTypeDeclarations[i].fieldCount; j += 1) { - char *ptrName = strdup(structTypeDeclarations[i].fields[j].name); + char *ptrName = + strdup(structTypeDeclarations[i].fields[j].name); strcat(ptrName, "_ptr"); LLVMValueRef elementPointer = LLVMBuildStructGEP( builder, structPointer, structTypeDeclarations[i].fields[j].index, - ptrName - ); + ptrName); free(ptrName); AddLocalVariable( scope, elementPointer, NULL, - structTypeDeclarations[i].fields[j].name - ); + structTypeDeclarations[i].fields[j].name); } } } } -static LLVMValueRef CompileExpression( - LLVMBuilderRef builder, - Node *expression -); +static LLVMValueRef CompileExpression(LLVMBuilderRef builder, Node *expression); -static LLVMValueRef CompileNumber( - Node *numberExpression -) { +static LLVMValueRef CompileNumber(Node *numberExpression) +{ return LLVMConstInt(LLVMInt64Type(), numberExpression->number.value, 0); } static LLVMValueRef CompileString( LLVMBuilderRef builder, - Node *stringExpression -) { - return LLVMBuildGlobalStringPtr(builder, stringExpression->stringLiteral.string, "stringConstant"); + Node *stringExpression) +{ + return LLVMBuildGlobalStringPtr( + builder, + stringExpression->stringLiteral.string, + "stringConstant"); } static LLVMValueRef CompileBinaryExpression( LLVMBuilderRef builder, - Node *binaryExpression -) { - LLVMValueRef left = CompileExpression(builder, binaryExpression->binaryExpression.left); - LLVMValueRef right = CompileExpression(builder, binaryExpression->binaryExpression.right); + Node *binaryExpression) +{ + LLVMValueRef left = + CompileExpression(builder, binaryExpression->binaryExpression.left); + LLVMValueRef right = + CompileExpression(builder, binaryExpression->binaryExpression.right); switch (binaryExpression->binaryExpression.operator) { - case Add: - return LLVMBuildAdd(builder, left, right, "addResult"); + case Add: + return LLVMBuildAdd(builder, left, right, "addResult"); - case Subtract: - return LLVMBuildSub(builder, left, right, "subtractResult"); + case Subtract: + return LLVMBuildSub(builder, left, right, "subtractResult"); - case Multiply: - return LLVMBuildMul(builder, left, right, "multiplyResult"); + case Multiply: + return LLVMBuildMul(builder, left, right, "multiplyResult"); - /* FIXME: need type information for comparison */ - case LessThan: - return LLVMBuildICmp(builder, LLVMIntSLT, left, right, "lessThanResult"); + /* FIXME: need type information for comparison */ + case LessThan: + return LLVMBuildICmp( + builder, + LLVMIntSLT, + left, + right, + "lessThanResult"); - case GreaterThan: - return LLVMBuildICmp(builder, LLVMIntSGT, left, right, "greaterThanResult"); + case GreaterThan: + return LLVMBuildICmp( + builder, + LLVMIntSGT, + left, + right, + "greaterThanResult"); - case Mod: - return LLVMBuildSRem(builder, left, right, "modResult"); + case Mod: + return LLVMBuildSRem(builder, left, right, "modResult"); - case Equal: - return LLVMBuildICmp(builder, LLVMIntEQ, left, right, "equalResult"); + case Equal: + return LLVMBuildICmp(builder, LLVMIntEQ, left, right, "equalResult"); - case LogicalOr: - return LLVMBuildOr(builder, left, right, "orResult"); + case LogicalOr: + return LLVMBuildOr(builder, left, right, "orResult"); } return NULL; @@ -493,11 +534,14 @@ static LLVMValueRef CompileBinaryExpression( /* FIXME THIS IS ALL BROKEN */ static LLVMValueRef CompileFunctionCallExpression( LLVMBuilderRef builder, - Node *functionCallExpression -) { + Node *functionCallExpression) +{ uint32_t i; uint32_t argumentCount = 0; - LLVMValueRef args[functionCallExpression->functionCallExpression.argumentSequence->functionArgumentSequence.count + 1]; + LLVMValueRef args + [functionCallExpression->functionCallExpression.argumentSequence + ->functionArgumentSequence.count + + 1]; LLVMValueRef function; uint8_t isStatic; LLVMValueRef structInstance; @@ -506,25 +550,33 @@ static LLVMValueRef CompileFunctionCallExpression( /* FIXME: this needs to be recursive on access chains */ /* FIXME: this needs to be able to call same-struct functions implicitly */ - if (functionCallExpression->functionCallExpression.identifier->syntaxKind == AccessExpression) + if (functionCallExpression->functionCallExpression.identifier->syntaxKind == + AccessExpression) { LLVMTypeRef typeReference = FindStructType( - functionCallExpression->functionCallExpression.identifier->accessExpression.accessee->identifier.name - ); + functionCallExpression->functionCallExpression.identifier + ->accessExpression.accessee->identifier.name); if (typeReference != NULL) { function = LookupFunctionByType( typeReference, - functionCallExpression->functionCallExpression.identifier->accessExpression.accessor->identifier.name, + functionCallExpression->functionCallExpression.identifier + ->accessExpression.accessor->identifier.name, &functionReturnType, - &isStatic - ); + &isStatic); } else { - structInstance = FindVariablePointer(functionCallExpression->functionCallExpression.identifier->accessExpression.accessee->identifier.name); - function = LookupFunctionByInstance(structInstance, functionCallExpression->functionCallExpression.identifier->accessExpression.accessor->identifier.name, &functionReturnType, &isStatic); + structInstance = FindVariablePointer( + functionCallExpression->functionCallExpression.identifier + ->accessExpression.accessee->identifier.name); + function = LookupFunctionByInstance( + structInstance, + functionCallExpression->functionCallExpression.identifier + ->accessExpression.accessor->identifier.name, + &functionReturnType, + &isStatic); } } else @@ -539,9 +591,14 @@ static LLVMValueRef CompileFunctionCallExpression( argumentCount += 1; } - for (i = 0; i < functionCallExpression->functionCallExpression.argumentSequence->functionArgumentSequence.count; i += 1) + for (i = 0; i < functionCallExpression->functionCallExpression + .argumentSequence->functionArgumentSequence.count; + i += 1) { - args[argumentCount] = CompileExpression(builder, functionCallExpression->functionCallExpression.argumentSequence->functionArgumentSequence.sequence[i]); + args[argumentCount] = CompileExpression( + builder, + functionCallExpression->functionCallExpression.argumentSequence + ->functionArgumentSequence.sequence[i]); argumentCount += 1; } @@ -555,86 +612,111 @@ static LLVMValueRef CompileFunctionCallExpression( static LLVMValueRef CompileAccessExpressionForStore( LLVMBuilderRef builder, - Node *accessExpression -) { - LLVMValueRef accesseeValue = FindVariablePointer(accessExpression->accessExpression.accessee->identifier.name); - return FindStructFieldPointer(builder, accesseeValue, accessExpression->accessExpression.accessor->identifier.name); + Node *accessExpression) +{ + LLVMValueRef accesseeValue = FindVariablePointer( + accessExpression->accessExpression.accessee->identifier.name); + return FindStructFieldPointer( + builder, + accesseeValue, + accessExpression->accessExpression.accessor->identifier.name); } static LLVMValueRef CompileAccessExpression( LLVMBuilderRef builder, - Node *accessExpression -) { - LLVMValueRef accesseeValue = FindVariablePointer(accessExpression->accessExpression.accessee->identifier.name); - LLVMValueRef access = FindStructFieldPointer(builder, accesseeValue, accessExpression->accessExpression.accessor->identifier.name); - return LLVMBuildLoad(builder, access, accessExpression->accessExpression.accessor->identifier.name); + Node *accessExpression) +{ + LLVMValueRef accesseeValue = FindVariablePointer( + accessExpression->accessExpression.accessee->identifier.name); + LLVMValueRef access = FindStructFieldPointer( + builder, + accesseeValue, + accessExpression->accessExpression.accessor->identifier.name); + return LLVMBuildLoad( + builder, + access, + accessExpression->accessExpression.accessor->identifier.name); } static LLVMValueRef CompileAllocExpression( LLVMBuilderRef builder, - Node *allocExpression -) { + Node *allocExpression) +{ LLVMTypeRef type = ResolveType(allocExpression->allocExpression.type); return LLVMBuildMalloc(builder, type, "allocation"); } -static LLVMValueRef CompileExpression( - LLVMBuilderRef builder, - Node *expression -) { +static LLVMValueRef CompileExpression(LLVMBuilderRef builder, Node *expression) +{ switch (expression->syntaxKind) { - case AccessExpression: - return CompileAccessExpression(builder, expression); + case AccessExpression: + return CompileAccessExpression(builder, expression); - case AllocExpression: - return CompileAllocExpression(builder, expression); + case AllocExpression: + return CompileAllocExpression(builder, expression); - case BinaryExpression: - return CompileBinaryExpression(builder, expression); + case BinaryExpression: + return CompileBinaryExpression(builder, expression); - case FunctionCallExpression: - return CompileFunctionCallExpression(builder, expression); + case FunctionCallExpression: + return CompileFunctionCallExpression(builder, expression); - case Identifier: - return FindVariableValue(builder, expression->identifier.name); + case Identifier: + return FindVariableValue(builder, expression->identifier.name); - case Number: - return CompileNumber(expression); - - case StringLiteral: - return CompileString(builder, expression); + case Number: + return CompileNumber(expression); + case StringLiteral: + return CompileString(builder, expression); } fprintf(stderr, "Unknown expression kind!\n"); return NULL; } -static LLVMBasicBlockRef CompileStatement(LLVMBuilderRef builder, LLVMValueRef function, Node *statement); +static LLVMBasicBlockRef CompileStatement( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *statement); -static LLVMBasicBlockRef CompileReturn(LLVMBuilderRef builder, LLVMValueRef function, Node *returnStatemement) +static LLVMBasicBlockRef CompileReturn( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *returnStatemement) { - LLVMValueRef expression = CompileExpression(builder, returnStatemement->returnStatement.expression); + LLVMValueRef expression = CompileExpression( + builder, + returnStatemement->returnStatement.expression); LLVMBuildRet(builder, expression); return LLVMGetLastBasicBlock(function); } -static LLVMBasicBlockRef CompileReturnVoid(LLVMBuilderRef builder, LLVMValueRef function) +static LLVMBasicBlockRef CompileReturnVoid( + LLVMBuilderRef builder, + LLVMValueRef function) { LLVMBuildRetVoid(builder); return LLVMGetLastBasicBlock(function); } /* FIXME: path for reference types */ -static LLVMValueRef CompileFunctionVariableDeclaration(LLVMBuilderRef builder, LLVMValueRef function, Node *variableDeclaration) +static LLVMValueRef CompileFunctionVariableDeclaration( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *variableDeclaration) { LLVMValueRef variable; - char *variableName = variableDeclaration->declaration.identifier->identifier.name; + char *variableName = + variableDeclaration->declaration.identifier->identifier.name; char *ptrName = strdup(variableName); strcat(ptrName, "_ptr"); - variable = LLVMBuildAlloca(builder, ResolveType(variableDeclaration->declaration.type), ptrName); + variable = LLVMBuildAlloca( + builder, + ResolveType(variableDeclaration->declaration.type), + ptrName); free(ptrName); @@ -643,21 +725,36 @@ static LLVMValueRef CompileFunctionVariableDeclaration(LLVMBuilderRef builder, L return variable; } -static LLVMBasicBlockRef CompileAssignment(LLVMBuilderRef builder, LLVMValueRef function, Node *assignmentStatement) +static LLVMBasicBlockRef CompileAssignment( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *assignmentStatement) { - LLVMValueRef result = CompileExpression(builder, assignmentStatement->assignmentStatement.right); + LLVMValueRef result = CompileExpression( + builder, + assignmentStatement->assignmentStatement.right); LLVMValueRef identifier; - if (assignmentStatement->assignmentStatement.left->syntaxKind == AccessExpression) + if (assignmentStatement->assignmentStatement.left->syntaxKind == + AccessExpression) { - identifier = CompileAccessExpressionForStore(builder, assignmentStatement->assignmentStatement.left); + identifier = CompileAccessExpressionForStore( + builder, + assignmentStatement->assignmentStatement.left); } - else if (assignmentStatement->assignmentStatement.left->syntaxKind == Identifier) + else if ( + assignmentStatement->assignmentStatement.left->syntaxKind == Identifier) { - identifier = FindVariablePointer(assignmentStatement->assignmentStatement.left->identifier.name); + identifier = FindVariablePointer( + assignmentStatement->assignmentStatement.left->identifier.name); } - else if (assignmentStatement->assignmentStatement.left->syntaxKind == Declaration) + else if ( + assignmentStatement->assignmentStatement.left->syntaxKind == + Declaration) { - identifier = CompileFunctionVariableDeclaration(builder, function, assignmentStatement->assignmentStatement.left); + identifier = CompileFunctionVariableDeclaration( + builder, + function, + assignmentStatement->assignmentStatement.left); } else { @@ -670,10 +767,14 @@ static LLVMBasicBlockRef CompileAssignment(LLVMBuilderRef builder, LLVMValueRef return LLVMGetLastBasicBlock(function); } -static LLVMBasicBlockRef CompileIfStatement(LLVMBuilderRef builder, LLVMValueRef function, Node *ifStatement) +static LLVMBasicBlockRef CompileIfStatement( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *ifStatement) { uint32_t i; - LLVMValueRef conditional = CompileExpression(builder, ifStatement->ifStatement.expression); + LLVMValueRef conditional = + CompileExpression(builder, ifStatement->ifStatement.expression); LLVMBasicBlockRef block = LLVMAppendBasicBlock(function, "ifBlock"); LLVMBasicBlockRef afterCond = LLVMAppendBasicBlock(function, "afterCond"); @@ -682,9 +783,16 @@ static LLVMBasicBlockRef CompileIfStatement(LLVMBuilderRef builder, LLVMValueRef LLVMPositionBuilderAtEnd(builder, block); - for (i = 0; i < ifStatement->ifStatement.statementSequence->statementSequence.count; i += 1) + for (i = 0; + i < + ifStatement->ifStatement.statementSequence->statementSequence.count; + i += 1) { - CompileStatement(builder, function, ifStatement->ifStatement.statementSequence->statementSequence.sequence[i]); + CompileStatement( + builder, + function, + ifStatement->ifStatement.statementSequence->statementSequence + .sequence[i]); } LLVMBuildBr(builder, afterCond); @@ -693,10 +801,15 @@ static LLVMBasicBlockRef CompileIfStatement(LLVMBuilderRef builder, LLVMValueRef return afterCond; } -static LLVMBasicBlockRef CompileIfElseStatement(LLVMBuilderRef builder, LLVMValueRef function, Node *ifElseStatement) +static LLVMBasicBlockRef CompileIfElseStatement( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *ifElseStatement) { uint32_t i; - LLVMValueRef conditional = CompileExpression(builder, ifElseStatement->ifElseStatement.ifStatement->ifStatement.expression); + LLVMValueRef conditional = CompileExpression( + builder, + ifElseStatement->ifElseStatement.ifStatement->ifStatement.expression); LLVMBasicBlockRef ifBlock = LLVMAppendBasicBlock(function, "ifBlock"); LLVMBasicBlockRef elseBlock = LLVMAppendBasicBlock(function, "elseBlock"); @@ -706,25 +819,41 @@ static LLVMBasicBlockRef CompileIfElseStatement(LLVMBuilderRef builder, LLVMValu LLVMPositionBuilderAtEnd(builder, ifBlock); - for (i = 0; i < ifElseStatement->ifElseStatement.ifStatement->ifStatement.statementSequence->statementSequence.count; i += 1) + for (i = 0; i < ifElseStatement->ifElseStatement.ifStatement->ifStatement + .statementSequence->statementSequence.count; + i += 1) { - CompileStatement(builder, function, ifElseStatement->ifElseStatement.ifStatement->ifStatement.statementSequence->statementSequence.sequence[i]); + CompileStatement( + builder, + function, + ifElseStatement->ifElseStatement.ifStatement->ifStatement + .statementSequence->statementSequence.sequence[i]); } LLVMBuildBr(builder, afterCond); LLVMPositionBuilderAtEnd(builder, elseBlock); - if (ifElseStatement->ifElseStatement.elseStatement->syntaxKind == StatementSequence) + if (ifElseStatement->ifElseStatement.elseStatement->syntaxKind == + StatementSequence) { - for (i = 0; i < ifElseStatement->ifElseStatement.elseStatement->statementSequence.count; i += 1) + for (i = 0; i < ifElseStatement->ifElseStatement.elseStatement + ->statementSequence.count; + i += 1) { - CompileStatement(builder, function, ifElseStatement->ifElseStatement.elseStatement->statementSequence.sequence[i]); + CompileStatement( + builder, + function, + ifElseStatement->ifElseStatement.elseStatement + ->statementSequence.sequence[i]); } } else { - CompileStatement(builder, function, ifElseStatement->ifElseStatement.elseStatement); + CompileStatement( + builder, + function, + ifElseStatement->ifElseStatement.elseStatement); } LLVMBuildBr(builder, afterCond); @@ -733,15 +862,21 @@ static LLVMBasicBlockRef CompileIfElseStatement(LLVMBuilderRef builder, LLVMValu return afterCond; } -static LLVMBasicBlockRef CompileForLoopStatement(LLVMBuilderRef builder, LLVMValueRef function, Node *forLoopStatement) +static LLVMBasicBlockRef CompileForLoopStatement( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *forLoopStatement) { uint32_t i; LLVMBasicBlockRef entryBlock = LLVMAppendBasicBlock(function, "loopEntry"); LLVMBasicBlockRef checkBlock = LLVMAppendBasicBlock(function, "loopCheck"); LLVMBasicBlockRef bodyBlock = LLVMAppendBasicBlock(function, "loopBody"); - LLVMBasicBlockRef afterLoopBlock = LLVMAppendBasicBlock(function, "afterLoop"); - char *iteratorVariableName = forLoopStatement->forLoop.declaration->declaration.identifier->identifier.name; - LLVMTypeRef iteratorVariableType = ResolveType(forLoopStatement->forLoop.declaration->declaration.type); + LLVMBasicBlockRef afterLoopBlock = + LLVMAppendBasicBlock(function, "afterLoop"); + char *iteratorVariableName = forLoopStatement->forLoop.declaration + ->declaration.identifier->identifier.name; + LLVMTypeRef iteratorVariableType = + ResolveType(forLoopStatement->forLoop.declaration->declaration.type); PushScopeFrame(scope); @@ -751,30 +886,46 @@ static LLVMBasicBlockRef CompileForLoopStatement(LLVMBuilderRef builder, LLVMVal LLVMBuildBr(builder, checkBlock); LLVMPositionBuilderAtEnd(builder, checkBlock); - LLVMValueRef iteratorValue = LLVMBuildPhi(builder, iteratorVariableType, iteratorVariableName); + LLVMValueRef iteratorValue = + LLVMBuildPhi(builder, iteratorVariableType, iteratorVariableName); AddLocalVariable(scope, NULL, iteratorValue, iteratorVariableName); LLVMPositionBuilderAtEnd(builder, bodyBlock); LLVMValueRef nextValue = LLVMBuildAdd( builder, iteratorValue, - LLVMConstInt(iteratorVariableType, 1, 0), /* FIXME: add custom increment value */ - "next" - ); + LLVMConstInt( + iteratorVariableType, + 1, + 0), /* FIXME: add custom increment value */ + "next"); LLVMPositionBuilderAtEnd(builder, checkBlock); - LLVMValueRef iteratorEndValue = CompileNumber(forLoopStatement->forLoop.endNumber); - LLVMValueRef comparison = LLVMBuildICmp(builder, LLVMIntULE, iteratorValue, iteratorEndValue, "iteratorCompare"); + LLVMValueRef iteratorEndValue = + CompileNumber(forLoopStatement->forLoop.endNumber); + LLVMValueRef comparison = LLVMBuildICmp( + builder, + LLVMIntULE, + iteratorValue, + iteratorEndValue, + "iteratorCompare"); LLVMBuildCondBr(builder, comparison, bodyBlock, afterLoopBlock); LLVMPositionBuilderAtEnd(builder, bodyBlock); LLVMBasicBlockRef lastBlock; - for (i = 0; i < forLoopStatement->forLoop.statementSequence->statementSequence.count; i += 1) + for (i = 0; + i < + forLoopStatement->forLoop.statementSequence->statementSequence.count; + i += 1) { - lastBlock = CompileStatement(builder, function, forLoopStatement->forLoop.statementSequence->statementSequence.sequence[i]); + lastBlock = CompileStatement( + builder, + function, + forLoopStatement->forLoop.statementSequence->statementSequence + .sequence[i]); } LLVMBuildBr(builder, checkBlock); @@ -798,35 +949,38 @@ static LLVMBasicBlockRef CompileForLoopStatement(LLVMBuilderRef builder, LLVMVal return afterLoopBlock; } -static LLVMBasicBlockRef CompileStatement(LLVMBuilderRef builder, LLVMValueRef function, Node *statement) +static LLVMBasicBlockRef CompileStatement( + LLVMBuilderRef builder, + LLVMValueRef function, + Node *statement) { switch (statement->syntaxKind) { - case Assignment: - return CompileAssignment(builder, function, statement); + case Assignment: + return CompileAssignment(builder, function, statement); - case Declaration: - CompileFunctionVariableDeclaration(builder, function, statement); - return LLVMGetLastBasicBlock(function); + case Declaration: + CompileFunctionVariableDeclaration(builder, function, statement); + return LLVMGetLastBasicBlock(function); - case ForLoop: - return CompileForLoopStatement(builder, function, statement); + case ForLoop: + return CompileForLoopStatement(builder, function, statement); - case FunctionCallExpression: - CompileFunctionCallExpression(builder, statement); - return LLVMGetLastBasicBlock(function); + case FunctionCallExpression: + CompileFunctionCallExpression(builder, statement); + return LLVMGetLastBasicBlock(function); - case IfStatement: - return CompileIfStatement(builder, function, statement); + case IfStatement: + return CompileIfStatement(builder, function, statement); - case IfElseStatement: - return CompileIfElseStatement(builder, function, statement); + case IfElseStatement: + return CompileIfElseStatement(builder, function, statement); - case Return: - return CompileReturn(builder, function, statement); + case Return: + return CompileReturn(builder, function, statement); - case ReturnVoid: - return CompileReturnVoid(builder, function); + case ReturnVoid: + return CompileReturnVoid(builder, function); } fprintf(stderr, "Unknown statement kind!\n"); @@ -839,22 +993,29 @@ static void CompileFunction( LLVMTypeRef wStructPointerType, Node **fieldDeclarations, uint32_t fieldDeclarationCount, - Node *functionDeclaration -) { + Node *functionDeclaration) +{ uint32_t i; uint8_t hasReturn = 0; uint8_t isStatic = 0; - Node *functionSignature = functionDeclaration->functionDeclaration.functionSignature; + Node *functionSignature = + functionDeclaration->functionDeclaration.functionSignature; Node *functionBody = functionDeclaration->functionDeclaration.functionBody; - uint32_t argumentCount = functionSignature->functionSignature.arguments->functionSignatureArguments.count; + uint32_t argumentCount = functionSignature->functionSignature.arguments + ->functionSignatureArguments.count; LLVMTypeRef paramTypes[argumentCount + 1]; uint32_t paramIndex = 0; - if (functionSignature->functionSignature.modifiers->functionModifiers.count > 0) + if (functionSignature->functionSignature.modifiers->functionModifiers + .count > 0) { - for (i = 0; i < functionSignature->functionSignature.modifiers->functionModifiers.count; i += 1) + for (i = 0; i < functionSignature->functionSignature.modifiers + ->functionModifiers.count; + i += 1) { - if (functionSignature->functionSignature.modifiers->functionModifiers.sequence[i]->syntaxKind == StaticModifier) + if (functionSignature->functionSignature.modifiers + ->functionModifiers.sequence[i] + ->syntaxKind == StaticModifier) { isStatic = 1; break; @@ -871,22 +1032,36 @@ static void CompileFunction( PushScopeFrame(scope); /* FIXME: should work for non-primitive types */ - for (i = 0; i < functionSignature->functionSignature.arguments->functionSignatureArguments.count; i += 1) + for (i = 0; i < functionSignature->functionSignature.arguments + ->functionSignatureArguments.count; + i += 1) { - paramTypes[paramIndex] = ResolveType(functionSignature->functionSignature.arguments->functionSignatureArguments.sequence[i]->declaration.type); + paramTypes[paramIndex] = + ResolveType(functionSignature->functionSignature.arguments + ->functionSignatureArguments.sequence[i] + ->declaration.type); paramIndex += 1; } - LLVMTypeRef returnType = ResolveType(functionSignature->functionSignature.type); - LLVMTypeRef functionType = LLVMFunctionType(returnType, paramTypes, paramIndex, 0); + LLVMTypeRef returnType = + ResolveType(functionSignature->functionSignature.type); + LLVMTypeRef functionType = + LLVMFunctionType(returnType, paramTypes, paramIndex, 0); char *functionName = strdup(parentStructName); strcat(functionName, "_"); - strcat(functionName, functionSignature->functionSignature.identifier->identifier.name); + strcat( + functionName, + functionSignature->functionSignature.identifier->identifier.name); LLVMValueRef function = LLVMAddFunction(module, functionName, functionType); free(functionName); - DeclareStructFunction(wStructPointerType, function, returnType, isStatic, functionSignature->functionSignature.identifier->identifier.name); + DeclareStructFunction( + wStructPointerType, + function, + returnType, + isStatic, + functionSignature->functionSignature.identifier->identifier.name); LLVMBasicBlockRef entry = LLVMAppendBasicBlock(function, "entry"); LLVMBuilderRef builder = LLVMCreateBuilder(); @@ -898,23 +1073,38 @@ static void CompileFunction( AddStructVariablesToScope(builder, wStructPointer); } - for (i = 0; i < functionSignature->functionSignature.arguments->functionSignatureArguments.count; i += 1) + for (i = 0; i < functionSignature->functionSignature.arguments + ->functionSignatureArguments.count; + i += 1) { - char *ptrName = strdup(functionSignature->functionSignature.arguments->functionSignatureArguments.sequence[i]->declaration.identifier->identifier.name); + char *ptrName = strdup(functionSignature->functionSignature.arguments + ->functionSignatureArguments.sequence[i] + ->declaration.identifier->identifier.name); strcat(ptrName, "_ptr"); LLVMValueRef argument = LLVMGetParam(function, i + !isStatic); - LLVMValueRef argumentCopy = LLVMBuildAlloca(builder, LLVMTypeOf(argument), ptrName); + LLVMValueRef argumentCopy = + LLVMBuildAlloca(builder, LLVMTypeOf(argument), ptrName); LLVMBuildStore(builder, argument, argumentCopy); free(ptrName); - AddLocalVariable(scope, argumentCopy, NULL, functionSignature->functionSignature.arguments->functionSignatureArguments.sequence[i]->declaration.identifier->identifier.name); + AddLocalVariable( + scope, + argumentCopy, + NULL, + functionSignature->functionSignature.arguments + ->functionSignatureArguments.sequence[i] + ->declaration.identifier->identifier.name); } for (i = 0; i < functionBody->statementSequence.count; i += 1) { - CompileStatement(builder, function, functionBody->statementSequence.sequence[i]); + CompileStatement( + builder, + function, + functionBody->statementSequence.sequence[i]); } - hasReturn = LLVMGetBasicBlockTerminator(LLVMGetLastBasicBlock(function)) != NULL; + hasReturn = + LLVMGetBasicBlockTerminator(LLVMGetLastBasicBlock(function)) != NULL; if (LLVMGetTypeKind(returnType) == LLVMVoidTypeKind && !hasReturn) { @@ -930,11 +1120,15 @@ static void CompileFunction( LLVMDisposeBuilder(builder); } -static void CompileStruct(LLVMModuleRef module, LLVMContextRef context, Node *node) +static void CompileStruct( + LLVMModuleRef module, + LLVMContextRef context, + Node *node) { uint32_t i; uint32_t fieldCount = 0; - uint32_t declarationCount = node->structDeclaration.declarationSequence->declarationSequence.count; + uint32_t declarationCount = + node->structDeclaration.declarationSequence->declarationSequence.count; uint8_t packed = 1; LLVMTypeRef types[declarationCount]; Node *currentDeclarationNode; @@ -944,73 +1138,104 @@ static void CompileStruct(LLVMModuleRef module, LLVMContextRef context, Node *no PushScopeFrame(scope); LLVMTypeRef wStructType = LLVMStructCreateNamed(context, structName); - LLVMTypeRef wStructPointerType = LLVMPointerType(wStructType, 0); /* FIXME: is this address space correct? */ + LLVMTypeRef wStructPointerType = LLVMPointerType( + wStructType, + 0); /* FIXME: is this address space correct? */ /* first, build the structure definition */ for (i = 0; i < declarationCount; i += 1) { - currentDeclarationNode = node->structDeclaration.declarationSequence->declarationSequence.sequence[i]; + currentDeclarationNode = node->structDeclaration.declarationSequence + ->declarationSequence.sequence[i]; switch (currentDeclarationNode->syntaxKind) { - case Declaration: /* this is badly named */ - types[fieldCount] = ResolveType(currentDeclarationNode->declaration.type); - fieldDeclarations[fieldCount] = currentDeclarationNode; - fieldCount += 1; - break; + case Declaration: /* this is badly named */ + types[fieldCount] = + ResolveType(currentDeclarationNode->declaration.type); + fieldDeclarations[fieldCount] = currentDeclarationNode; + fieldCount += 1; + break; } } LLVMStructSetBody(wStructType, types, fieldCount, packed); - AddStructDeclaration(wStructType, wStructPointerType, structName, fieldDeclarations, fieldCount); + AddStructDeclaration( + wStructType, + wStructPointerType, + structName, + fieldDeclarations, + fieldCount); /* now we can wire up the functions */ for (i = 0; i < declarationCount; i += 1) { - currentDeclarationNode = node->structDeclaration.declarationSequence->declarationSequence.sequence[i]; + currentDeclarationNode = node->structDeclaration.declarationSequence + ->declarationSequence.sequence[i]; switch (currentDeclarationNode->syntaxKind) { - case FunctionDeclaration: - CompileFunction(module, structName, wStructPointerType, fieldDeclarations, fieldCount, currentDeclarationNode); - break; + case FunctionDeclaration: + CompileFunction( + module, + structName, + wStructPointerType, + fieldDeclarations, + fieldCount, + currentDeclarationNode); + break; } } PopScopeFrame(scope); } -static void Compile(LLVMModuleRef module, LLVMContextRef context, Node *declarationSequenceNode) +static void Compile( + LLVMModuleRef module, + LLVMContextRef context, + Node *declarationSequenceNode) { uint32_t i; for (i = 0; i < declarationSequenceNode->declarationSequence.count; i += 1) { - if (declarationSequenceNode->declarationSequence.sequence[i]->syntaxKind == StructDeclaration) + if (declarationSequenceNode->declarationSequence.sequence[i] + ->syntaxKind == StructDeclaration) { - CompileStruct(module, context, declarationSequenceNode->declarationSequence.sequence[i]); + CompileStruct( + module, + context, + declarationSequenceNode->declarationSequence.sequence[i]); } else { - fprintf(stderr, "top level declarations that are not structs are forbidden!\n"); + fprintf( + stderr, + "top level declarations that are not structs are forbidden!\n"); } } } /* TODO: move this to some kind of standard library file? */ -static void RegisterLibraryFunctions(LLVMModuleRef module, LLVMContextRef context) +static void RegisterLibraryFunctions( + LLVMModuleRef module, + LLVMContextRef context) { LLVMTypeRef structType = LLVMStructCreateNamed(context, "Console"); LLVMTypeRef structPointerType = LLVMPointerType(structType, 0); AddStructDeclaration(structType, structPointerType, "Console", NULL, 0); LLVMTypeRef printfArg = LLVMPointerType(LLVMInt8Type(), 0); - LLVMTypeRef printfFunctionType = LLVMFunctionType(LLVMInt32Type(), &printfArg, 1, 1); - LLVMValueRef printfFunction = LLVMAddFunction(module, "printf", printfFunctionType); + LLVMTypeRef printfFunctionType = + LLVMFunctionType(LLVMInt32Type(), &printfArg, 1, 1); + LLVMValueRef printfFunction = + LLVMAddFunction(module, "printf", printfFunctionType); LLVMSetLinkage(printfFunction, LLVMExternalLinkage); - LLVMTypeRef printLineFunctionType = LLVMFunctionType(LLVMInt32Type(), &printfArg, 1, 1); - LLVMValueRef printLineFunction = LLVMAddFunction(module, "printLine", printLineFunctionType); + LLVMTypeRef printLineFunctionType = + LLVMFunctionType(LLVMInt32Type(), &printfArg, 1, 1); + LLVMValueRef printLineFunction = + LLVMAddFunction(module, "printLine", printLineFunctionType); LLVMBuilderRef builder = LLVMCreateBuilder(); LLVMBasicBlockRef entry = LLVMAppendBasicBlock(printLineFunction, "entry"); @@ -1020,11 +1245,24 @@ static void RegisterLibraryFunctions(LLVMModuleRef module, LLVMContextRef contex LLVMValueRef printParams[LLVMCountParams(printLineFunction)]; LLVMGetParams(printLineFunction, printParams); - LLVMValueRef stringPrint = LLVMBuildCall(builder, printfFunction, printParams, LLVMCountParams(printLineFunction), "printfCall"); - LLVMValueRef newlinePrint = LLVMBuildCall(builder, printfFunction, &newLine, 1, "printNewLine"); - LLVMBuildRet(builder, LLVMBuildAnd(builder, stringPrint, newlinePrint, "and")); + LLVMValueRef stringPrint = LLVMBuildCall( + builder, + printfFunction, + printParams, + LLVMCountParams(printLineFunction), + "printfCall"); + LLVMValueRef newlinePrint = + LLVMBuildCall(builder, printfFunction, &newLine, 1, "printNewLine"); + LLVMBuildRet( + builder, + LLVMBuildAnd(builder, stringPrint, newlinePrint, "and")); - DeclareStructFunction(structPointerType, printLineFunction, LLVMInt8Type(), 1, "PrintLine"); + DeclareStructFunction( + structPointerType, + printLineFunction, + LLVMInt8Type(), + 1, + "PrintLine"); } int Codegen(Node *node, uint32_t optimizationLevel) @@ -1044,14 +1282,18 @@ int Codegen(Node *node, uint32_t optimizationLevel) /* add main call */ LLVMBuilderRef builder = LLVMCreateBuilder(); - LLVMTypeRef mainFunctionType = LLVMFunctionType(LLVMInt64Type(), NULL, 0, 0); - LLVMValueRef mainFunction = LLVMAddFunction(module, "main", mainFunctionType); + LLVMTypeRef mainFunctionType = + LLVMFunctionType(LLVMInt64Type(), NULL, 0, 0); + LLVMValueRef mainFunction = + LLVMAddFunction(module, "main", mainFunctionType); LLVMBasicBlockRef entry = LLVMAppendBasicBlock(mainFunction, "entry"); LLVMPositionBuilderAtEnd(builder, entry); - LLVMValueRef wraithMainFunction = LLVMGetNamedFunction(module, "Program_Main"); + LLVMValueRef wraithMainFunction = + LLVMGetNamedFunction(module, "Program_Main"); - LLVMValueRef mainResult = LLVMBuildCall(builder, wraithMainFunction, NULL, 0, "result"); + LLVMValueRef mainResult = + LLVMBuildCall(builder, wraithMainFunction, NULL, 0, "result"); LLVMBuildRet(builder, mainResult); LLVMDisposeBuilder(builder); @@ -1076,7 +1318,8 @@ int Codegen(Node *node, uint32_t optimizationLevel) LLVMSetTarget(module, LLVM_DEFAULT_TARGET_TRIPLE); LLVMTargetRef target; - if (LLVMGetTargetFromTriple(LLVM_DEFAULT_TARGET_TRIPLE, &target, &error) != 0) + if (LLVMGetTargetFromTriple(LLVM_DEFAULT_TARGET_TRIPLE, &target, &error) != + 0) { fprintf(stderr, "Failed to get target!\n"); fprintf(stderr, "%s\n", error); @@ -1086,13 +1329,17 @@ int Codegen(Node *node, uint32_t optimizationLevel) LLVMPassManagerRef passManager = LLVMCreatePassManager(); - LLVMPassManagerBuilderRef passManagerBuilder = LLVMPassManagerBuilderCreate(); + LLVMPassManagerBuilderRef passManagerBuilder = + LLVMPassManagerBuilderCreate(); LLVMPassManagerBuilderSetOptLevel(passManagerBuilder, optimizationLevel); - LLVMPassManagerBuilderPopulateModulePassManager(passManagerBuilder, passManager); + LLVMPassManagerBuilderPopulateModulePassManager( + passManagerBuilder, + passManager); LLVMRunPassManager(passManager, module); - if (LLVMWriteBitcodeToFile(module, "test.bc") != 0) { + if (LLVMWriteBitcodeToFile(module, "test.bc") != 0) + { fprintf(stderr, "error writing bitcode to file\n"); return EXIT_FAILURE; } @@ -1107,10 +1354,14 @@ int Codegen(Node *node, uint32_t optimizationLevel) features, LLVMCodeGenLevelDefault, LLVMRelocDefault, - LLVMCodeModelDefault - ); + LLVMCodeModelDefault); - if (LLVMTargetMachineEmitToFile(targetMachine, module, "test.o", LLVMObjectFile, &error) != 0) + if (LLVMTargetMachineEmitToFile( + targetMachine, + module, + "test.o", + LLVMObjectFile, + &error) != 0) { fprintf(stderr, "Failed to emit machine code!\n"); fprintf(stderr, "%s\n", error); diff --git a/src/identcheck.c b/src/identcheck.c index ab50c44..571a29e 100644 --- a/src/identcheck.c +++ b/src/identcheck.c @@ -1,14 +1,15 @@ #include +#include #include #include -#include #include #include "ast.h" #include "identcheck.h" -IdNode* MakeIdNode(NodeType type, char *name, IdNode *parent) { - IdNode *node = (IdNode*)malloc(sizeof(IdNode)); +IdNode *MakeIdNode(NodeType type, char *name, IdNode *parent) +{ + IdNode *node = (IdNode *)malloc(sizeof(IdNode)); node->type = type; node->name = strdup(name); node->parent = parent; @@ -19,283 +20,369 @@ IdNode* MakeIdNode(NodeType type, char *name, IdNode *parent) { return node; } -void AddChildToNode(IdNode *node, IdNode *child) { - if (child == NULL) return; +void AddChildToNode(IdNode *node, IdNode *child) +{ + if (child == NULL) + return; - if (node->children == NULL) { + if (node->children == NULL) + { node->childCapacity = 2; - node->children = (IdNode**) malloc(sizeof(IdNode*) * node->childCapacity); - } else if (node->childCount == node->childCapacity) { + node->children = + (IdNode **)malloc(sizeof(IdNode *) * node->childCapacity); + } + else if (node->childCount == node->childCapacity) + { node->childCapacity *= 2; - node->children = (IdNode**) realloc(node->children, sizeof(IdNode*) * node->childCapacity); + node->children = (IdNode **)realloc( + node->children, + sizeof(IdNode *) * node->childCapacity); } node->children[node->childCount] = child; node->childCount += 1; } -IdNode* MakeIdTree(Node *astNode, IdNode *parent) { +IdNode *MakeIdTree(Node *astNode, IdNode *parent) +{ uint32_t i; IdNode *mainNode; - switch (astNode->syntaxKind) { - case AccessExpression: - AddChildToNode(parent, MakeIdTree(astNode->accessExpression.accessee, parent)); - AddChildToNode(parent, MakeIdTree(astNode->accessExpression.accessor, parent)); - return NULL; + switch (astNode->syntaxKind) + { + case AccessExpression: + AddChildToNode( + parent, + MakeIdTree(astNode->accessExpression.accessee, parent)); + AddChildToNode( + parent, + MakeIdTree(astNode->accessExpression.accessor, parent)); + return NULL; - case AllocExpression: - AddChildToNode(parent, MakeIdTree(astNode->allocExpression.type, parent)); - return NULL; + case AllocExpression: + AddChildToNode( + parent, + MakeIdTree(astNode->allocExpression.type, parent)); + return NULL; - case Assignment: { - if (astNode->assignmentStatement.left->syntaxKind == Declaration) { - return MakeIdTree(astNode->assignmentStatement.left, parent); - } else { - AddChildToNode(parent, MakeIdTree(astNode->assignmentStatement.left, parent)); - AddChildToNode(parent, MakeIdTree(astNode->assignmentStatement.right, parent)); - return NULL; - } + case Assignment: + { + if (astNode->assignmentStatement.left->syntaxKind == Declaration) + { + return MakeIdTree(astNode->assignmentStatement.left, parent); } - - case BinaryExpression: - AddChildToNode(parent, MakeIdTree(astNode->binaryExpression.left, parent)); - AddChildToNode(parent, MakeIdTree(astNode->binaryExpression.right, parent)); - return NULL; - - case Declaration: { - Node *idNode = astNode->declaration.identifier; - mainNode = MakeIdNode(Variable, idNode->identifier.name, parent); - mainNode->typeTag = MakeTypeTag(astNode); - idNode->typeTag = mainNode->typeTag; - break; - } - - case DeclarationSequence: { - mainNode = MakeIdNode(UnorderedScope, "", parent); - for (i = 0; i < astNode->declarationSequence.count; i++) { - AddChildToNode( - mainNode, MakeIdTree(astNode->declarationSequence.sequence[i], mainNode)); - } - break; - } - - case ForLoop: { - Node *loopDecl = astNode->forLoop.declaration; - Node *loopBody = astNode->forLoop.statementSequence; - mainNode = MakeIdNode(OrderedScope, "for-loop", parent); - AddChildToNode(mainNode, MakeIdTree(loopDecl, mainNode)); - AddChildToNode(mainNode, MakeIdTree(loopBody, mainNode)); - break; - } - - case FunctionArgumentSequence: - for (i = 0; i < astNode->functionArgumentSequence.count; i++) { - AddChildToNode( - parent, MakeIdTree(astNode->functionArgumentSequence.sequence[i], parent)); - } - return NULL; - - case FunctionCallExpression: - AddChildToNode(parent, MakeIdTree(astNode->functionCallExpression.identifier, parent)); + else + { AddChildToNode( - parent, MakeIdTree(astNode->functionCallExpression.argumentSequence, parent)); - return NULL; - - case FunctionDeclaration: { - Node *sigNode = astNode->functionDeclaration.functionSignature; - Node *idNode = sigNode->functionSignature.identifier; - char *funcName = idNode->identifier.name; - mainNode = MakeIdNode(Function, funcName, parent); - mainNode->typeTag = MakeTypeTag(astNode); - idNode->typeTag = mainNode->typeTag; - MakeIdTree(sigNode->functionSignature.arguments, mainNode); - MakeIdTree(astNode->functionDeclaration.functionBody, mainNode); - break; - } - - case FunctionSignatureArguments: { - for (i = 0; i < astNode->functionSignatureArguments.count; i++) { - Node *argNode = astNode->functionSignatureArguments.sequence[i]; - AddChildToNode(parent, MakeIdTree(argNode, parent)); - } + parent, + MakeIdTree(astNode->assignmentStatement.left, parent)); + AddChildToNode( + parent, + MakeIdTree(astNode->assignmentStatement.right, parent)); return NULL; } + } - case Identifier: { - char *name = astNode->identifier.name; - mainNode = MakeIdNode(Placeholder, name, parent); - IdNode *lookupNode = LookupId(mainNode, NULL, name); - if (lookupNode == NULL) { - fprintf(stderr, "wraith: Could not find IdNode for id %s\n", name); - TypeTag *tag = (TypeTag*)malloc(sizeof(TypeTag)); - tag->type = Unknown; - astNode->typeTag = tag; - } else { - astNode->typeTag = lookupNode->typeTag; - } - break; + case BinaryExpression: + AddChildToNode( + parent, + MakeIdTree(astNode->binaryExpression.left, parent)); + AddChildToNode( + parent, + MakeIdTree(astNode->binaryExpression.right, parent)); + return NULL; + + case Declaration: + { + Node *idNode = astNode->declaration.identifier; + mainNode = MakeIdNode(Variable, idNode->identifier.name, parent); + mainNode->typeTag = MakeTypeTag(astNode); + idNode->typeTag = mainNode->typeTag; + break; + } + + case DeclarationSequence: + { + mainNode = MakeIdNode(UnorderedScope, "", parent); + for (i = 0; i < astNode->declarationSequence.count; i++) + { + AddChildToNode( + mainNode, + MakeIdTree(astNode->declarationSequence.sequence[i], mainNode)); } + break; + } - case IfStatement: { - Node *clause = astNode->ifStatement.expression; - Node *stmtSeq = astNode->ifStatement.statementSequence; - mainNode = MakeIdNode(OrderedScope, "if", parent); - MakeIdTree(clause, mainNode); - MakeIdTree(stmtSeq, mainNode); - break; + case ForLoop: + { + Node *loopDecl = astNode->forLoop.declaration; + Node *loopBody = astNode->forLoop.statementSequence; + mainNode = MakeIdNode(OrderedScope, "for-loop", parent); + AddChildToNode(mainNode, MakeIdTree(loopDecl, mainNode)); + AddChildToNode(mainNode, MakeIdTree(loopBody, mainNode)); + break; + } + + case FunctionArgumentSequence: + for (i = 0; i < astNode->functionArgumentSequence.count; i++) + { + AddChildToNode( + parent, + MakeIdTree( + astNode->functionArgumentSequence.sequence[i], + parent)); } + return NULL; - case IfElseStatement: { - Node *ifNode = astNode->ifElseStatement.ifStatement; - Node *elseStmts = astNode->ifElseStatement.elseStatement; - mainNode = MakeIdNode(OrderedScope, "if-else", parent); - IdNode *ifBranch = MakeIdTree(ifNode, mainNode); - AddChildToNode(mainNode, ifBranch); - IdNode *elseScope = MakeIdNode(OrderedScope, "else", mainNode); - MakeIdTree(elseStmts, elseScope); - AddChildToNode(mainNode, elseScope); - break; + case FunctionCallExpression: + AddChildToNode( + parent, + MakeIdTree(astNode->functionCallExpression.identifier, parent)); + AddChildToNode( + parent, + MakeIdTree( + astNode->functionCallExpression.argumentSequence, + parent)); + return NULL; + + case FunctionDeclaration: + { + Node *sigNode = astNode->functionDeclaration.functionSignature; + Node *idNode = sigNode->functionSignature.identifier; + char *funcName = idNode->identifier.name; + mainNode = MakeIdNode(Function, funcName, parent); + mainNode->typeTag = MakeTypeTag(astNode); + idNode->typeTag = mainNode->typeTag; + MakeIdTree(sigNode->functionSignature.arguments, mainNode); + MakeIdTree(astNode->functionDeclaration.functionBody, mainNode); + break; + } + + case FunctionSignatureArguments: + { + for (i = 0; i < astNode->functionSignatureArguments.count; i++) + { + Node *argNode = astNode->functionSignatureArguments.sequence[i]; + AddChildToNode(parent, MakeIdTree(argNode, parent)); } + return NULL; + } - case ReferenceTypeNode: - AddChildToNode(parent, MakeIdTree(astNode->referenceType.type, parent)); - return NULL; - - case Return: - AddChildToNode(parent, MakeIdTree(astNode->returnStatement.expression, parent)); - return NULL; - - case StatementSequence: { - for (i = 0; i < astNode->statementSequence.count; i++) { - Node *argNode = astNode->statementSequence.sequence[i]; - AddChildToNode(parent, MakeIdTree(argNode, parent)); - } - return NULL; + case Identifier: + { + char *name = astNode->identifier.name; + mainNode = MakeIdNode(Placeholder, name, parent); + IdNode *lookupNode = LookupId(mainNode, NULL, name); + if (lookupNode == NULL) + { + fprintf(stderr, "wraith: Could not find IdNode for id %s\n", name); + TypeTag *tag = (TypeTag *)malloc(sizeof(TypeTag)); + tag->type = Unknown; + astNode->typeTag = tag; } - - case StructDeclaration: { - Node *idNode = astNode->structDeclaration.identifier; - Node *declsNode = astNode->structDeclaration.declarationSequence; - mainNode = MakeIdNode(Struct, idNode->identifier.name, parent); - mainNode->typeTag = MakeTypeTag(astNode); - for (i = 0; i < declsNode->declarationSequence.count; i++) { - Node *decl = declsNode->declarationSequence.sequence[i]; - AddChildToNode(mainNode, MakeIdTree(decl, mainNode)); - } - break; + else + { + astNode->typeTag = lookupNode->typeTag; } + break; + } - case Type: - AddChildToNode(parent, MakeIdTree(astNode->type.typeNode, parent)); - return NULL; + case IfStatement: + { + Node *clause = astNode->ifStatement.expression; + Node *stmtSeq = astNode->ifStatement.statementSequence; + mainNode = MakeIdNode(OrderedScope, "if", parent); + MakeIdTree(clause, mainNode); + MakeIdTree(stmtSeq, mainNode); + break; + } - case UnaryExpression: - AddChildToNode(parent, MakeIdTree(astNode->unaryExpression.child, parent)); - return NULL; + case IfElseStatement: + { + Node *ifNode = astNode->ifElseStatement.ifStatement; + Node *elseStmts = astNode->ifElseStatement.elseStatement; + mainNode = MakeIdNode(OrderedScope, "if-else", parent); + IdNode *ifBranch = MakeIdTree(ifNode, mainNode); + AddChildToNode(mainNode, ifBranch); + IdNode *elseScope = MakeIdNode(OrderedScope, "else", mainNode); + MakeIdTree(elseStmts, elseScope); + AddChildToNode(mainNode, elseScope); + break; + } - case Comment: - case CustomTypeNode: - case FunctionModifiers: - case FunctionSignature: - case Number: - case PrimitiveTypeNode: - case ReturnVoid: - case StaticModifier: - case StringLiteral: - return NULL; + case ReferenceTypeNode: + AddChildToNode(parent, MakeIdTree(astNode->referenceType.type, parent)); + return NULL; + + case Return: + AddChildToNode( + parent, + MakeIdTree(astNode->returnStatement.expression, parent)); + return NULL; + + case StatementSequence: + { + for (i = 0; i < astNode->statementSequence.count; i++) + { + Node *argNode = astNode->statementSequence.sequence[i]; + AddChildToNode(parent, MakeIdTree(argNode, parent)); + } + return NULL; + } + + case StructDeclaration: + { + Node *idNode = astNode->structDeclaration.identifier; + Node *declsNode = astNode->structDeclaration.declarationSequence; + mainNode = MakeIdNode(Struct, idNode->identifier.name, parent); + mainNode->typeTag = MakeTypeTag(astNode); + for (i = 0; i < declsNode->declarationSequence.count; i++) + { + Node *decl = declsNode->declarationSequence.sequence[i]; + AddChildToNode(mainNode, MakeIdTree(decl, mainNode)); + } + break; + } + + case Type: + AddChildToNode(parent, MakeIdTree(astNode->type.typeNode, parent)); + return NULL; + + case UnaryExpression: + AddChildToNode( + parent, + MakeIdTree(astNode->unaryExpression.child, parent)); + return NULL; + + case Comment: + case CustomTypeNode: + case FunctionModifiers: + case FunctionSignature: + case Number: + case PrimitiveTypeNode: + case ReturnVoid: + case StaticModifier: + case StringLiteral: + return NULL; } astNode->idLink = mainNode; return mainNode; } -void PrintIdNode(IdNode *node) { - if (node == NULL) { - fprintf(stderr, "wraith: Attempted to call PrintIdNode with null value.\n"); +void PrintIdNode(IdNode *node) +{ + if (node == NULL) + { + fprintf( + stderr, + "wraith: Attempted to call PrintIdNode with null value.\n"); return; } - switch(node->type) { - case Placeholder: - printf("Placeholder (%s)\n", node->name); - break; - case OrderedScope: - printf("OrderedScope (%s)\n", node->name); - break; - case UnorderedScope: - printf("UnorderedScope (%s)\n", node->name); - break; - case Struct: - printf("%s : %s\n", node->name, TypeTagToString(node->typeTag)); - break; - case Function: - printf("%s : Function<%s>\n", node->name, TypeTagToString(node->typeTag)); - break; - case Variable: - printf("%s : %s\n", node->name, TypeTagToString(node->typeTag)); - break; + switch (node->type) + { + case Placeholder: + printf("Placeholder (%s)\n", node->name); + break; + case OrderedScope: + printf("OrderedScope (%s)\n", node->name); + break; + case UnorderedScope: + printf("UnorderedScope (%s)\n", node->name); + break; + case Struct: + printf("%s : %s\n", node->name, TypeTagToString(node->typeTag)); + break; + case Function: + printf( + "%s : Function<%s>\n", + node->name, + TypeTagToString(node->typeTag)); + break; + case Variable: + printf("%s : %s\n", node->name, TypeTagToString(node->typeTag)); + break; } } -void PrintIdTree(IdNode *tree, uint32_t tabCount) { - if (tree == NULL) { - fprintf(stderr, "wraith: Attempted to call PrintIdTree on a null value.\n"); +void PrintIdTree(IdNode *tree, uint32_t tabCount) +{ + if (tree == NULL) + { + fprintf( + stderr, + "wraith: Attempted to call PrintIdTree on a null value.\n"); return; } uint32_t i; - for (i = 0; i < tabCount; i++) { + for (i = 0; i < tabCount; i++) + { printf("| "); } PrintIdNode(tree); - for (i = 0; i < tree->childCount; i++) { + for (i = 0; i < tree->childCount; i++) + { PrintIdTree(tree->children[i], tabCount + 1); } } -int PrintAncestors(IdNode *node) { - if (node == NULL) return -1; +int PrintAncestors(IdNode *node) +{ + if (node == NULL) + return -1; int i; int indent = 1; indent += PrintAncestors(node->parent); - for (i = 0; i < indent; i++) { + for (i = 0; i < indent; i++) + { printf(" "); } PrintIdNode(node); return indent; } -IdNode* LookdownId(IdNode *root, NodeType targetType, char *targetName) { - if (root == NULL) { - fprintf(stderr, "wraith: Attempted to call LookdownId on a null value.\n"); +IdNode *LookdownId(IdNode *root, NodeType targetType, char *targetName) +{ + if (root == NULL) + { + fprintf( + stderr, + "wraith: Attempted to call LookdownId on a null value.\n"); return NULL; } IdNode *result = NULL; - IdNode **frontier = (IdNode**)malloc(sizeof(IdNode*)); + IdNode **frontier = (IdNode **)malloc(sizeof(IdNode *)); frontier[0] = root; uint32_t frontierCount = 1; - while (frontierCount > 0) { + while (frontierCount > 0) + { IdNode *current = frontier[0]; - if (current->type == targetType && strcmp(current->name, targetName) == 0) { + if (current->type == targetType && + strcmp(current->name, targetName) == 0) + { result = current; break; } uint32_t i; - for(i = 1; i < frontierCount; i++) { - frontier[i-1] = frontier[i]; + for (i = 1; i < frontierCount; i++) + { + frontier[i - 1] = frontier[i]; } size_t newSize = frontierCount + current->childCount - 1; - if (frontierCount != newSize) { - frontier = (IdNode**) realloc(frontier, sizeof(IdNode*) * newSize); + if (frontierCount != newSize) + { + frontier = (IdNode **)realloc(frontier, sizeof(IdNode *) * newSize); } - for (i = 0; i < current->childCount; i++) { + for (i = 0; i < current->childCount; i++) + { frontier[frontierCount + i - 1] = current->children[i]; } frontierCount = newSize; @@ -305,70 +392,89 @@ IdNode* LookdownId(IdNode *root, NodeType targetType, char *targetName) { return result; } -bool ScopeHasOrdering(IdNode *node) { - switch (node->type) { - case OrderedScope: - case Function: - case Variable: /* this is only technically true */ - return true; - default: - return false; +bool ScopeHasOrdering(IdNode *node) +{ + switch (node->type) + { + case OrderedScope: + case Function: + case Variable: /* this is only technically true */ + return true; + default: + return false; } } -IdNode* LookupId(IdNode *node, IdNode *prev, char *target) { - if (node == NULL) { +IdNode *LookupId(IdNode *node, IdNode *prev, char *target) +{ + if (node == NULL) + { return NULL; } - if (strcmp(node->name, target) == 0 && node->type != Placeholder) { + if (strcmp(node->name, target) == 0 && node->type != Placeholder) + { return node; } - /* If this is the start of our search, we should not attempt to look at child nodes. Only - * looking up the scope tree is valid at this point. + /* If this is the start of our search, we should not attempt to look at + * child nodes. Only looking up the scope tree is valid at this point. * - * This has the notable side-effect that this function will return NULL if you attempt to look - * up a struct's internals starting from the node representing the struct itself. This is - * because an IdNode corresponds to the location *where an identifier is first declared.* Thus, - * an identifier has no knowledge of identifiers declared "inside" of it. + * This has the notable side-effect that this function will return NULL if + * you attempt to look up a struct's internals starting from the node + * representing the struct itself. This is because an IdNode corresponds to + * the location *where an identifier is first declared.* Thus, an identifier + * has no knowledge of identifiers declared "inside" of it. */ - if (prev == NULL) { + if (prev == NULL) + { return LookupId(node->parent, node, target); } - /* If the current node forms an ordered scope then we want to prevent ourselves from looking - * up identifiers declared after the scope we have just come from. + /* If the current node forms an ordered scope then we want to prevent + * ourselves from looking up identifiers declared after the scope we have + * just come from. */ uint32_t idxLimit; - if (ScopeHasOrdering(node)) { + if (ScopeHasOrdering(node)) + { uint32_t i; - for (i = 0, idxLimit = 0; i < node->childCount; i++, idxLimit++) { - if (node->children[i] == prev) { + for (i = 0, idxLimit = 0; i < node->childCount; i++, idxLimit++) + { + if (node->children[i] == prev) + { break; } } - } else { + } + else + { idxLimit = node->childCount; } uint32_t i; - for (i = 0; i < idxLimit; i++) { + for (i = 0; i < idxLimit; i++) + { IdNode *child = node->children[i]; - if (child == prev || child->type == Placeholder) { + if (child == prev || child->type == Placeholder) + { /* Do not inspect the node we just came from or placeholders. */ continue; } - if (strcmp(child->name, target) == 0) { + if (strcmp(child->name, target) == 0) + { return child; } - if (child->type == Struct) { + if (child->type == Struct) + { uint32_t j; - for (j = 0; j < child->childCount; j++) { + for (j = 0; j < child->childCount; j++) + { IdNode *grandchild = child->children[j]; - if (strcmp(grandchild->name, target) == 0) { + if (strcmp(grandchild->name, target) == 0) + { return grandchild; } } diff --git a/src/identcheck.h b/src/identcheck.h index 2c75262..c0ccca6 100644 --- a/src/identcheck.h +++ b/src/identcheck.h @@ -10,7 +10,8 @@ struct TypeTag; struct Node; -typedef enum NodeType { +typedef enum NodeType +{ Placeholder, UnorderedScope, OrderedScope, @@ -19,7 +20,8 @@ typedef enum NodeType { Variable } NodeType; -typedef struct IdNode { +typedef struct IdNode +{ NodeType type; char *name; struct TypeTag *typeTag; @@ -29,18 +31,19 @@ typedef struct IdNode { uint32_t childCapacity; } IdNode; -typedef struct IdStatus { - enum StatusCode { +typedef struct IdStatus +{ + enum StatusCode + { Valid, } StatusCode; } IdStatus; - -IdNode* MakeIdTree(struct Node *astNode, IdNode *parent); +IdNode *MakeIdTree(struct Node *astNode, IdNode *parent); void PrintIdNode(IdNode *node); void PrintIdTree(IdNode *tree, uint32_t tabCount); int PrintAncestors(IdNode *node); -IdNode* LookdownId(IdNode *root, NodeType targetType, char *targetName); -IdNode* LookupId(IdNode *node, IdNode *prev, char* target); +IdNode *LookdownId(IdNode *root, NodeType targetType, char *targetName); +IdNode *LookupId(IdNode *node, IdNode *prev, char *target); #endif /* WRAITH_IDENTCHECK_H */ diff --git a/src/main.c b/src/main.c index 9ffb210..eda6895 100644 --- a/src/main.c +++ b/src/main.c @@ -1,9 +1,9 @@ -#include #include "../lib/dropt/dropt.h" +#include -#include "parser.h" #include "codegen.h" #include "identcheck.h" +#include "parser.h" int main(int argc, char *argv[]) { @@ -14,10 +14,27 @@ int main(int argc, char *argv[]) int exitCode = EXIT_SUCCESS; dropt_option options[] = { - { 'h', "help", "Shows help.", NULL, dropt_handle_bool, &showHelp, dropt_attr_halt }, - { 'v', "parse-verbose", "Shows verbose parser output.", NULL, dropt_handle_bool, &parseVerbose }, - { 'O', "optimize", "Sets optimization level of the output IR. Must be a value between 0 and 3.", "number", dropt_handle_uint, &optimizationLevel }, - { 0 } /* Required sentinel value. */ + {'h', + "help", + "Shows help.", + NULL, + dropt_handle_bool, + &showHelp, + dropt_attr_halt}, + {'v', + "parse-verbose", + "Shows verbose parser output.", + NULL, + dropt_handle_bool, + &parseVerbose}, + {'O', + "optimize", + "Sets optimization level of the output IR. Must be a value between 0 " + "and 3.", + "number", + dropt_handle_uint, + &optimizationLevel}, + {0} /* Required sentinel value. */ }; dropt_context *droptContext = dropt_new_context(options); @@ -33,10 +50,13 @@ int main(int argc, char *argv[]) } else { - char** rest = dropt_parse(droptContext, -1, &argv[1]); + char **rest = dropt_parse(droptContext, -1, &argv[1]); if (dropt_get_error(droptContext) != dropt_error_none) { - fprintf(stderr, "wraith: %s\n", dropt_get_error_message(droptContext)); + fprintf( + stderr, + "wraith: %s\n", + dropt_get_error_message(droptContext)); exitCode = EXIT_FAILURE; } else if (showHelp) diff --git a/src/parser.c b/src/parser.c index c7a5f34..2eae584 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1,7 +1,7 @@ #include -#include "y.tab.h" #include "ast.h" +#include "y.tab.h" extern FILE *yyin; extern int yydebug; diff --git a/src/util.c b/src/util.c index ae1654f..8001d03 100644 --- a/src/util.c +++ b/src/util.c @@ -1,16 +1,17 @@ #include "util.h" +#include #include -char* strdup (const char* s) +char *strdup(const char *s) { - size_t slen = strlen(s); - char* result = malloc(slen + 1); - if(result == NULL) - { - return NULL; - } + size_t slen = strlen(s); + char *result = (char *)malloc(slen + 1); + if (result == NULL) + { + return NULL; + } - memcpy(result, s, slen+1); - return result; -} \ No newline at end of file + memcpy(result, s, slen + 1); + return result; +} diff --git a/src/util.h b/src/util.h index 99ffaa7..884fa24 100644 --- a/src/util.h +++ b/src/util.h @@ -3,6 +3,6 @@ #include -char* strdup (const char* s); +char *strdup(const char *s); #endif /* WRAITH_UTIL_H */