Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unions #117

Merged
merged 7 commits into from
Dec 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import chalk from 'chalk';
import { CFunctionCallConvention } from '#constants';
import { IRVariable, isIRVariable } from 'frontend/ir/variables';
import { CBackendError, CBackendErrorCode } from 'backend/errors/CBackendError';
import { isStructLikeType } from 'frontend/analyze';
import { isStructLikeType, isUnionLikeType } from 'frontend/analyze';

import { getBaseTypeIfPtr } from 'frontend/analyze/types/utils';
import { getTypeOffsetByteSize } from 'frontend/ir/utils';
Expand Down Expand Up @@ -63,7 +63,7 @@ export class X86StdcallFnCaller implements X86ConventionalFnCaller {
const arg = callerInstruction.args[i];
const baseType = getBaseTypeIfPtr(arg.type);

if (isStructLikeType(baseType)) {
if (isStructLikeType(baseType) || isUnionLikeType(baseType)) {
if (!isIRVariable(arg)) {
throw new CBackendError(CBackendErrorCode.NON_CALLABLE_STRUCT_ARG);
}
Expand Down Expand Up @@ -230,15 +230,14 @@ export class X86StdcallFnCaller implements X86ConventionalFnCaller {
};
}

private getReturnReg({ context, declInstruction }: X86FnBasicCompilerAttrs) {
const regs = context.allocator.regs.ownership.getAvailableRegs();
private getReturnReg({ declInstruction }: X86FnBasicCompilerAttrs) {
const { returnType } = declInstruction;

if (!returnType || returnType.isVoid()) {
return null;
}

return regs.general.list[0];
return returnType.getByteSize() === 1 ? 'al' : 'ax';
}

private preserveConventionRegsAsm({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function compileStoreInstruction({
} else {
// handle normal variable assign
// *(a) = 5;
// todo: check if this .isStruct() is needed:
// todo: check if this .isStructOrUnion() is needed:
// char b = 'b';
// int k = b;
// struct Abc {
Expand All @@ -88,8 +88,8 @@ export function compileStoreInstruction({
if (isIRVariable(value)) {
// check if variable is struct or something bigger than that
if (
getBaseTypeIfPtr(value.type).isStruct() &&
getBaseTypeIfPtr(outputVar.type).isStruct() &&
getBaseTypeIfPtr(value.type).isStructOrUnion() &&
getBaseTypeIfPtr(outputVar.type).isStructOrUnion() &&
(!value.isTemporary() ||
isLabelOwnership(regs.ownership.getVarOwnership(value.name)))
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ export function compileArrayInitializerDefAsm({

// [1, 2, "as", 3] -> [[1, 2], "as", [3]]
const groupedDefs = initializer.fields.reduce(
({ prevFieldType, groups }, field) => {
const currentFieldType = typeof field;
({ prevFieldType, groups }, item) => {
const currentFieldType = typeof item?.value;

if (currentFieldType !== prevFieldType) {
groups.push([]);
}

R.last(groups).push(field);
R.last(groups).push(item?.value);

return {
prevFieldType: currentFieldType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
isIRVariable,
} from 'frontend/ir/variables';

import { isStructLikeType } from 'frontend/analyze';
import { isStructLikeType, isUnionLikeType } from 'frontend/analyze';

import { getByteSizeArgPrefixName } from '@ts-c-compiler/x86-assembler';
import {
Expand Down Expand Up @@ -123,7 +123,9 @@ export class X86BasicRegAllocator {

if (
!castToPointerIfArray(arg.type).isScalar() &&
(!isStructLikeType(arg.type) || !arg.type.canBeStoredInReg())
!isUnionLikeType(arg.type) &&
!isStructLikeType(arg.type) &&
!arg.type.canBeStoredInReg()
) {
throw new CBackendError(CBackendErrorCode.REG_ALLOCATOR_ERROR);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { isNil } from 'ramda';
import { isTreeNode } from '@ts-c-compiler/grammar';

import { CVariableInitializerVisitor } from './CVariableInitializerVisitor';
import {
CVariableInitializerTree,
CVariableInitializePair,
CVariableInitializeValue,
isInitializerTreeValue,
CVariableInitializerTree,
isInitializerValuePair,
} from '../../scope/variables/CVariableInitializerTree';

/**
Expand All @@ -17,23 +19,36 @@ export class CVariableInitializerPrintVisitor extends CVariableInitializerVisito
return this._reduced;
}

override enter(value: CVariableInitializeValue) {
override enter(
maybePair: CVariableInitializePair | CVariableInitializerTree,
) {
if (this._reduced && this._reduced[this._reduced.length - 2] !== '{') {
this._reduced += ', ';
}

let serializedValue = value;
if (isInitializerTreeValue(value)) {
let serializedValue: CVariableInitializeValue = '';

if (isTreeNode(maybePair)) {
serializedValue = '{ ';
} else if (isTreeNode(value)) {
serializedValue = '<expr>';
} else if (isInitializerValuePair(maybePair)) {
if (isTreeNode(maybePair.value)) {
serializedValue = '<expr>';
} else {
serializedValue = maybePair.value;
}
} else if (isNil(maybePair)) {
serializedValue = 'null';
}

this._reduced += serializedValue;
if (serializedValue) {
this._reduced += serializedValue;
}
}

override leave(value: CVariableInitializeValue) {
if (isInitializerTreeValue(value)) {
override leave(
maybePair: CVariableInitializePair | CVariableInitializerTree,
) {
if (isTreeNode(maybePair)) {
this._reduced += ' }';
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { isCompilerTreeNode } from 'frontend/parser';

import { AbstractTreeVisitor } from '@ts-c-compiler/grammar';
import { CVariableInitializeValue } from '../../scope/variables';
import {
CVariableInitializePair,
CVariableInitializerTree,
} from '../../scope/variables';

export class CVariableInitializerVisitor extends AbstractTreeVisitor<CVariableInitializeValue> {
shouldVisitNode(node: CVariableInitializeValue): boolean {
export class CVariableInitializerVisitor extends AbstractTreeVisitor<
CVariableInitializePair | CVariableInitializerTree
> {
shouldVisitNode(
node: CVariableInitializePair | CVariableInitializerTree,
): boolean {
return !isCompilerTreeNode(node);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ import {
typeofValueOrNode,
CPrimitiveType,
isPrimitiveLikeType,
isUnionLikeType,
} from '../../../types';

import {
CVariableInitializerTree,
CVariableInitializeValue,
CVariableInitializePair,
} from '../../../scope/variables';

import {
Expand Down Expand Up @@ -86,7 +87,7 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {

if (!this.tree) {
this.tree = new CVariableInitializerTree(baseType, node);
this.maxSize = this.tree.scalarValuesCount;
this.maxSize = this.tree.c89initializerFieldsCount;
}

const arrayType = isArrayLikeType(baseType);
Expand Down Expand Up @@ -222,15 +223,20 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {
}
}

this.appendNextOffsetValue(exprValue, noSizeCheck);
} else if (isCompilerTreeNode(exprValue)) {
this.appendNextOffsetValue(
this.parseTreeNodeExpressionValue(node, expectedType, exprValue),
{ type: expectedType, value: exprValue },
noSizeCheck,
);
} else if (isCompilerTreeNode(exprValue)) {
this.appendNextOffsetValue({
type: expectedType,
value: this.parseTreeNodeExpressionValue(node, expectedType, exprValue),
});
} else {
this.appendNextOffsetValue(
this.parseScalarValue(node, expectedType, exprValue),
);
this.appendNextOffsetValue({
type: expectedType,
value: this.parseScalarValue(node, expectedType, exprValue),
});
}
}

Expand All @@ -249,7 +255,7 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {

// .x = 1
if (identifier) {
if (!isStructLikeType(baseType)) {
if (!isStructLikeType(baseType) && !isUnionLikeType(baseType)) {
throw new CTypeCheckError(
CTypeCheckErrorCode.INCORRECT_NAMED_STRUCTURE_INITIALIZER_USAGE,
designation.loc.start,
Expand All @@ -267,8 +273,11 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {
);
}

offset += field.index;
baseType = field.type;

if ('index' in field) {
offset += field.index;
}
}

// [10] = x
Expand Down Expand Up @@ -307,7 +316,7 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {
offset +=
+constExprResult.right *
dimensions.reduce((acc, num, index) => (index ? acc * num : 1), 1) *
type.scalarValuesCount;
type.c89initializerFieldsCount;
}
}

Expand Down Expand Up @@ -420,16 +429,16 @@ export class CTypeInitializerBuilderVisitor extends CInnerTypeTreeVisitor {
* Appends next value to tree and increments currentKey if number
*/
private appendNextOffsetValue(
entryValue: CVariableInitializeValue,
entryValue: CVariableInitializePair,
noSizeCheck?: boolean,
) {
const { tree, maxSize, baseType } = this;
// handle struct Vec2 vec[] = { of_vector(), of_vector() }; initializers
const delta = isCompilerTreeNode(entryValue)
? entryValue.type.scalarValuesCount
? entryValue.type.c89initializerFieldsCount
: 1;

if (isStructLikeType(baseType)) {
if (isStructLikeType(baseType) || isUnionLikeType(baseType)) {
// increments offets, determine which field is initialized in struct and sets value
// used here: struct Vec2 vec = { 1, 2 };
tree.setAndExpand(this.currentOffset, entryValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
isArrayLikeType,
isPointerLikeType,
isStructLikeType,
isUnionLikeType,
} from '../../../types';

import { checkLeftTypeOverlapping } from '../../../checker';

export class ASTCPostfixExpressionTypeCreator extends ASTCTypeCreator<ASTCPostfixExpression> {
Expand Down Expand Up @@ -94,7 +96,7 @@ export class ASTCPostfixExpressionTypeCreator extends ASTCTypeCreator<ASTCPostfi
baseType = baseType.baseType;
}

if (isStructLikeType(baseType)) {
if (isStructLikeType(baseType) || isUnionLikeType(baseType)) {
if (!baseType.hasInnerTypeAttributes()) {
throw new CTypeCheckError(
CTypeCheckErrorCode.PROVIDED_TYPE_DOES_NOT_CONTAIN_PROPERTIES,
Expand All @@ -107,6 +109,7 @@ export class ASTCPostfixExpressionTypeCreator extends ASTCTypeCreator<ASTCPostfi

const { text: fieldName } = (node.dotExpression || node.ptrExpression)
.name;

const field = baseType.getField(fieldName);

if (!field) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {

import { extractEnumTypeFromNode } from './extractEnumTypeFromNode';
import { extractStructTypeFromNode } from './extractStructTypeFromNode';
import { extractUnionTypeFromNode } from './extractUnionTypeFromNode';

/**
* Extract type from ParameterDeclarationSpecifier
Expand All @@ -41,28 +42,30 @@ export function extractSpecifierType({
}

const qualifiers: CTypeQualifier[] = typeQualifiers?.items;
const { primitives, structs, enums, typedefs } =
const { primitives, structs, unions, enums, typedefs } =
typeSpecifiers.getGroupedSpecifiers();

const [hasPrimitives, hasStructs, hasEnums, hasTypedefs] = [
const [hasPrimitives, hasStructs, hasUnions, hasEnums, hasTypedefs] = [
!R.isEmpty(primitives),
!R.isEmpty(structs),
!R.isEmpty(unions),
!R.isEmpty(enums),
!R.isEmpty(typedefs),
];

// unsigned <typedef> var = 2; is not supported in GCC
if (hasTypedefs) {
if (+hasPrimitives + +hasStructs + +hasEnums > 0) {
if (+hasPrimitives + +hasStructs + +hasUnions + +hasEnums > 0) {
throw new CTypeCheckError(CTypeCheckErrorCode.INCORRECT_TYPE_SPECIFIERS);
}

return context.scope.findType(typedefs[0].typedefEntry.name);
}

if (
+hasPrimitives + +hasStructs + +hasEnums > 1 ||
+hasPrimitives + +hasStructs + +hasUnions + +hasEnums > 1 ||
structs.length > 1 ||
unions.length > 1 ||
enums.length > 1
) {
throw new CTypeCheckError(CTypeCheckErrorCode.INCORRECT_TYPE_SPECIFIERS);
Expand All @@ -79,16 +82,30 @@ export function extractSpecifierType({
);
}

if (hasEnums || hasStructs) {
if (hasEnums || hasStructs || hasUnions) {
let typeName: string = null;
const extractors = {
extractNamedEntryFromDeclaration,
extractNamedEntryFromDeclarator,
extractSpecifierType,
};

if (hasStructs) {
const structSpecifier = structs[0].structOrUnionSpecifier;
if (hasUnions) {
const unionSpecifier = unions[0].unionSpecifier;

// declare + definition
if (unionSpecifier.hasDeclarationList()) {
return extractUnionTypeFromNode({
...extractors,
unionSpecifier,
context,
});
}

// access by name
typeName = unionSpecifier.name.text;
} else if (hasStructs) {
const structSpecifier = structs[0].structSpecifier;

// declare + definition
if (structSpecifier.hasDeclarationList()) {
Expand Down
Loading
Loading