compiler

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 7340e14b35aabe79fa4fdf8ff2a197dab1e5635c
Author: Gabriel G. de Brito <me@gboncoffee.dev.br>
Date:   Sun,  1 Nov 2026 17:58:49 -0300

In the beginning there was darkness.

Diffstat:
A.clang-format | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
A.editorconfig | 17+++++++++++++++++
A.gitignore | 4++++
AMakefile | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AREADME.org | 3+++
Aconfig.mk | 4++++
Aexemplos.pas | 28++++++++++++++++++++++++++++
Asrc/arena.c | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/arena.h | 15+++++++++++++++
Asrc/codegen.c | 8++++++++
Asrc/codegen.h | 11+++++++++++
Asrc/compile.c | 41+++++++++++++++++++++++++++++++++++++++++
Asrc/compiler.h | 24++++++++++++++++++++++++
Asrc/main.c | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/parser.c | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/parser.h | 26++++++++++++++++++++++++++
Asrc/semantics.c | 8++++++++
Asrc/semantics.h | 10++++++++++
Asrc/tokenizer.c | 276+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/tokenizer.h | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
20 files changed, 1150 insertions(+), 0 deletions(-)

diff --git a/.clang-format b/.clang-format @@ -0,0 +1,52 @@ +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: Right +AlignConsecutiveAssignments: Consecutive +AlignConsecutiveBitFields: Consecutive +AlignConsecutiveDeclarations: Consecutive +AlignConsecutiveMacros: Consecutive +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: true +BinPackArguments: false +BinPackParameters: false +BitFieldColonSpacing: After +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Linux +BreakBeforeTernaryOperators: true +BreakStringLiterals: true +ColumnLimit: 80 +ContinuationIndentWidth: 4 +IncludeBlocks: Regroup +IndentCaseLabels: false +IndentGotoLabels: false +IndentPPDirectives: BeforeHash +IndentWidth: 4 +MaxEmptyLinesToKeep: 1 +PPIndentWidth: 2 +PointerAlignment: Left +QualifierAlignment: Custom +QualifierOrder: [static, volatile, inline, const, restrict, type] +ReflowComments: false +SeparateDefinitionBlocks: Always +SortIncludes: CaseInsensitive +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInContainerLiterals: true +SpacesInSquareBrackets: false +UseTab: Never diff --git a/.editorconfig b/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +[*{.c,.h}] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[{Makefile,*.mk}] +indent_style = tab diff --git a/.gitignore b/.gitignore @@ -0,0 +1,4 @@ +/compiler +/compiler-debug +/a.out +/build/ diff --git a/Makefile b/Makefile @@ -0,0 +1,363 @@ +# +# DON'T CONFIGURE THE BUILD HERE! USE config.mk INSTEAD! +# +# Generic Makefile that: +# - Autodetects C/C++ compilers to use, allowing to set defaults via cli params; +# - Autodetects all source files in the tree, compiling each one to a obj and +# linking everything together in a final executable. +# +# Written by Gabriel de Brito (@gboncoffee everywhere) designed specifically for +# the use cases of the HiPES research group (https://web.inf.ufpr.br/hipes/). +# +# This software is dual-licensed under Public Domain (CC0) or MIT. Choose what +# fits best for you. Licenses text below. +# +# Contact mails: +# - me@gboncoffee.dev.br (probably still exists). +# - ggb23@inf.ufpr.br (prefer this as it is my academic mail, but it may not +# exist anymore if you're reading far enough in the future). +# +# TODO: +# - Assembly files support; +# - Better compiler autodection technology (via a configurable list maybe?); +# - Autodetection of headers associated with a source file. +# + +# +# How to use and configure this build system: +# +# The targets that you should use are just target, debug and clean. The target +# target is the default and builds the "release mode". The debug builds the +# "debug mode", and clean removes the directory with objects and the binaries. +# +# Optionally set variables in the config.mk file. It works if that files doesn't +# even exist, so no worry, everything has a sane default. +# +# Variables: +# +# SRC (path): Directory with source files. Defaults to "src/". +# +# BUILD_TARGET (path): Directory with object files. Defaults to "build/". +# +# TARGET (path): Executable to create. Defaults to "a.out". +# +# DEBUG_SUFFIX (string): Will be appended to all objects and the target before +# extension, as to compile the versions with debug symbols. Defaults to +# "-debug". +# +# CPP_EXTENSION (string): File extension (without dot) to consider as C++ files, +# as some may use .cpp and some .cc. Defaults to "cpp". +# +# CC (path): Default C compiler to use. If this variable is set and the compiler +# does not exist in PATH, it autodetects between the following compilers (in +# this order): clang, gcc, cc. +# +# CPP (path): Same as CC but for C++. Autodetects between clang++, g++ and c++. +# +# FORCE_CC (bool): If this variable is set, refuses to try compiling with a +# different compiler than the default set with CC. Does nothing without CC being +# set. +# +# FORCE_CPP (bool): Same as FORCE_CC but for C++. +# +# CFLAGS (list): Default C compiler flags. Defaults to "-Wall -Wextra". +# +# C_DEBUG_FLAGS (list): Additional C compiler flags for debug build mode. +# Defaults to "-Og -g". +# +# C_RELEASE_FLAGS (list): Additional C compiler flags for release build mode. +# Defaults to "-O2". +# +# CPPFLAGS (list): Same as CFLAGS but for C++. Same defaults. +# +# CPP_DEBUG_FLAGS (list): Same as C_DEBUG_FLAGS but for C++. Same defaults. +# +# CPP_RELEASE_FLAGS (list): Same as C_RELEASE_FLAGS but for C++. Same defaults. +# +# LD_FLAGS (list): Flags to pass when linking. Defaults to none (unset). +# + +# +# License option: CC0 (Public Domain) +# +# Creative Commons Legal Code +# +# CC0 1.0 Universal +# +# CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE +# LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN +# ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS +# INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES +# REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS +# PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM +# THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED +# HEREUNDER. +# +# Statement of Purpose +# +# The laws of most jurisdictions throughout the world automatically confer +# exclusive Copyright and Related Rights (defined below) upon the creator +# and subsequent owner(s) (each and all, an "owner") of an original work of +# authorship and/or a database (each, a "Work"). +# +# Certain owners wish to permanently relinquish those rights to a Work for +# the purpose of contributing to a commons of creative, cultural and +# scientific works ("Commons") that the public can reliably and without fear +# of later claims of infringement build upon, modify, incorporate in other +# works, reuse and redistribute as freely as possible in any form whatsoever +# and for any purposes, including without limitation commercial purposes. +# These owners may contribute to the Commons to promote the ideal of a free +# culture and the further production of creative, cultural and scientific +# works, or to gain reputation or greater distribution for their Work in +# part through the use and efforts of others. +# +# For these and/or other purposes and motivations, and without any +# expectation of additional consideration or compensation, the person +# associating CC0 with a Work (the "Affirmer"), to the extent that he or she +# is an owner of Copyright and Related Rights in the Work, voluntarily +# elects to apply CC0 to the Work and publicly distribute the Work under its +# terms, with knowledge of his or her Copyright and Related Rights in the +# Work and the meaning and intended legal effect of CC0 on those rights. +# +# 1. Copyright and Related Rights. A Work made available under CC0 may be +# protected by copyright and related or neighboring rights ("Copyright and +# Related Rights"). Copyright and Related Rights include, but are not +# limited to, the following: +# +# i. the right to reproduce, adapt, distribute, perform, display, +# communicate, and translate a Work; +# ii. moral rights retained by the original author(s) and/or performer(s); +# iii. publicity and privacy rights pertaining to a person's image or +# likeness depicted in a Work; +# iv. rights protecting against unfair competition in regards to a Work, +# subject to the limitations in paragraph 4(a), below; +# v. rights protecting the extraction, dissemination, use and reuse of data +# in a Work; +# vi. database rights (such as those arising under Directive 96/9/EC of the +# European Parliament and of the Council of 11 March 1996 on the legal +# protection of databases, and under any national implementation +# thereof, including any amended or successor version of such +# directive); and +# vii. other similar, equivalent or corresponding rights throughout the +# world based on applicable law or treaty, and any national +# implementations thereof. +# +# 2. Waiver. To the greatest extent permitted by, but not in contravention +# of, applicable law, Affirmer hereby overtly, fully, permanently, +# irrevocably and unconditionally waives, abandons, and surrenders all of +# Affirmer's Copyright and Related Rights and associated claims and causes +# of action, whether now known or unknown (including existing as well as +# future claims and causes of action), in the Work (i) in all territories +# worldwide, (ii) for the maximum duration provided by applicable law or +# treaty (including future time extensions), (iii) in any current or future +# medium and for any number of copies, and (iv) for any purpose whatsoever, +# including without limitation commercial, advertising or promotional +# purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +# member of the public at large and to the detriment of Affirmer's heirs and +# successors, fully intending that such Waiver shall not be subject to +# revocation, rescission, cancellation, termination, or any other legal or +# equitable action to disrupt the quiet enjoyment of the Work by the public +# as contemplated by Affirmer's express Statement of Purpose. +# +# 3. Public License Fallback. Should any part of the Waiver for any reason +# be judged legally invalid or ineffective under applicable law, then the +# Waiver shall be preserved to the maximum extent permitted taking into +# account Affirmer's express Statement of Purpose. In addition, to the +# extent the Waiver is so judged Affirmer hereby grants to each affected +# person a royalty-free, non transferable, non sublicensable, non exclusive, +# irrevocable and unconditional license to exercise Affirmer's Copyright and +# Related Rights in the Work (i) in all territories worldwide, (ii) for the +# maximum duration provided by applicable law or treaty (including future +# time extensions), (iii) in any current or future medium and for any number +# of copies, and (iv) for any purpose whatsoever, including without +# limitation commercial, advertising or promotional purposes (the +# "License"). The License shall be deemed effective as of the date CC0 was +# applied by Affirmer to the Work. Should any part of the License for any +# reason be judged legally invalid or ineffective under applicable law, such +# partial invalidity or ineffectiveness shall not invalidate the remainder +# of the License, and in such case Affirmer hereby affirms that he or she +# will not (i) exercise any of his or her remaining Copyright and Related +# Rights in the Work or (ii) assert any associated claims and causes of +# action with respect to the Work, in either case contrary to Affirmer's +# express Statement of Purpose. +# +# 4. Limitations and Disclaimers. +# +# a. No trademark or patent rights held by Affirmer are waived, abandoned, +# surrendered, licensed or otherwise affected by this document. +# b. Affirmer offers the Work as-is and makes no representations or +# warranties of any kind concerning the Work, express, implied, +# statutory or otherwise, including without limitation warranties of +# title, merchantability, fitness for a particular purpose, non +# infringement, or the absence of latent or other defects, accuracy, or +# the present or absence of errors, whether or not discoverable, all to +# the greatest extent permissible under applicable law. +# c. Affirmer disclaims responsibility for clearing rights of other persons +# that may apply to the Work or any use thereof, including without +# limitation any person's Copyright and Related Rights in the Work. +# Further, Affirmer disclaims responsibility for obtaining any necessary +# consents, permissions or other rights required for any use of the +# Work. +# d. Affirmer understands and acknowledges that Creative Commons is not a +# party to this document and has no duty or obligation with respect to +# this CC0 or use of the Work. +# + +# +# License option: MIT +# +# Copyright (C) 2024 Gabriel de Brito +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +undefine CC +undefine CPP + +-include config.mk + +# Build variables. +SRC ?= src/ +BUILD_TARGET ?= build/ +TARGET ?= a.out +DEBUG_SUFFIX ?= -debug + +# C variables. +CFLAGS ?= -Wall -Wextra +C_DEBUG_FLAGS ?= -Og -g +C_RELEASE_FLAGS ?= -O2 + +# C++ variables. +CPPFLAGS ?= -Wall -Wextra +CPP_DEBUG_FLAGS ?= -Og -g +CPP_RELEASE_FLAGS ?= -O2 +CPP_EXTENSION ?= cpp + +# +# Compiler autodetection technology. This is particularly ugly because it looks +# like Richard Stallman doesn't know how elses work. +# + +ifdef FORCE_CC + ifndef CC + $(error "Refusing to compile without CC being set due to FORCE_CC being set.") + else + ifeq "$(shell which $(CC))" "" + $(error "Refusing to compile without $(CC) in PATH due to FORCE_CC being set.") + endif + endif +else + ifndef CC + CC = clang + ifeq "$(shell which clang)" "" + CC = gcc + ifeq "$(shell which gcc)" "" + CC = cc + ifeq "$(shell which cc)" "" + $(error "Could not detect C compiler. Set one with CC or install clang, gcc or cc.") + endif + endif + endif + endif +endif + +ifdef FORCE_CPP + ifndef CPP + $(error "Refusing to compile without CPP being set due to FORCE_CPP being set.") + else + ifeq "$(shell which $(CPP))" "" + $(error "Refusing to compile without $(CPP) in PATH due to FORCE_CPP being set.") + endif + endif +else + ifndef CC + CPP = clang++ + ifeq "$(shell which clang++)" "" + CPP = g++ + ifeq "$(shell which g++)" "" + CPP = c++ + ifeq "$(shell which c++)" "" + $(error "Could not detect C compiler. Set one with CPP or install clang++, g++ or c++.") + endif + endif + endif + endif +endif + +# +# Autodetection of source files technology. +# + +C_SRCS = $(shell find $(SRC) -type f -name "*.c") +C_OBJS = $(patsubst $(SRC)%.c, $(BUILD_TARGET)%.o, $(C_SRCS)) +C_DEBUG_OBJS = $(patsubst %.o, %$(DEBUG_SUFFIX).o, $(C_OBJS)) + +CPP_SRCS = $(shell find $(SRC) -type f -name "*.$(CPP_EXTENSION)") +CPP_OBJS = $(patsubst $(SRC)%.$(CPP_EXTENSION), $(BUILD_TARGET)%.o, $(CPP_SRCS)) +CPP_DEBUG_OBJS = $(patsubst %.o, %$(DEBUG_SUFFIX).o, $(CPP_OBJS)) + +# Autodetect directories that need to be created. This tries to create them +# every time, if someone has a better solution please tell me. +SRC_DIRECTORIES = $(shell find $(SRC) -type d) +BUILD_TARGET_DIRECTORIES = $(patsubst $(SRC)%, $(BUILD_TARGET)%, $(SRC_DIRECTORIES)) + +# +# Detect if we're going to link with $(CC) or $(CPP) by simply checking if we're +# going to compile any C++ at all. +# +ifeq "$(CPP_SRCS)" "" + LD = $(CC) +else + LD = $(CPP) +endif + +# +# Rules. +# + +.PHONY: target debug clean + +target: $(TARGET) + +debug: $(TARGET)$(DEBUG_SUFFIX) + +$(TARGET): $(CPP_OBJS) $(C_OBJS) | $(BUILD_TARGET_DIRECTORIES) + $(LD) $^ -o $@ $(LD_FLAGS) + +$(BUILD_TARGET)%.o: $(SRC)%.c | $(BUILD_TARGET_DIRECTORIES) + $(CC) $(CFLAGS) $(C_RELEASE_FLAGS) -c $^ -o $@ + +$(BUILD_TARGET)%.o: $(SRC)%.$(CPP_EXTENSION) | $(BUILD_TARGET_DIRECTORIES) + $(CPP) $(CPPFLAGS) $(CPP_RELEASE_FLAGS) -c $^ -o $@ + +$(TARGET)$(DEBUG_SUFFIX): $(CPP_DEBUG_OBJS) $(C_DEBUG_OBJS) | $(BUILD_TARGET_DIRECTORIES) + $(LD) $^ -o $@ $(LD_FLAGS) + +$(BUILD_TARGET)%$(DEBUG_SUFFIX).o: $(SRC)%.c | $(BUILD_TARGET_DIRECTORIES) + $(CC) $(CFLAGS) $(C_DEBUG_FLAGS) -c $^ -o $@ + +$(BUILD_TARGET)%$(DEBUG_SUFFIX).o: $(SRC)%.$(CPP_EXTENSION) | $(BUILD_TARGET_DIRECTORIES) + $(CPP) $(CPPFLAGS) $(CPP_DEBUG_FLAGS) -c $^ -o $@ + +$(BUILD_TARGET_DIRECTORIES): + -mkdir -p $@ + +clean: + -rm -r $(BUILD_TARGET) + -rm $(TARGET) + -rm $(TARGET)$(DEBUG_SUFFIX) diff --git a/README.org b/README.org @@ -0,0 +1,3 @@ +#+TITLE: Compiler + +Compiler for a Pascal clone made for the Compilers class. diff --git a/config.mk b/config.mk @@ -0,0 +1,4 @@ +TARGET = compiler +CFLAGS = -Wall -Wextra -std=c23 -pedantic +C_RELEASE_FLAGS = -O3 -march=native +C_DEBUG_FLAGS = -Og -g diff --git a/exemplos.pas b/exemplos.pas @@ -0,0 +1,28 @@ +program LCM (input, output); + var x, y, res: integer; + +function LCM(a,b: integer): integer; + var maior, menor: integer; +begin + if a > b then + begin + maior := a; + menor := b + end else + begin + maior := b; + menor := a + end; + LCM := maior; + while ( LCM mod menor ) <> 0 do + begin + LCM := LCM + maior + end +end; + +begin + read(x); + read(y); + res := LCM(x,y); + write(res) +end. diff --git a/src/arena.c b/src/arena.c @@ -0,0 +1,50 @@ +#include "arena.h" + +#include <stdlib.h> +#include <string.h> + +int constexpr BLOCK_ALIGNMENT = 16u; + +static unsigned int AlignedSize(unsigned long size) +{ + return (size + BLOCK_ALIGNMENT - 1) & ~(BLOCK_ALIGNMENT - 1); +} + +Arena* NewArena(long size) +{ + size = AlignedSize(size); + + Arena* arena = calloc(1, sizeof(*arena) + size); + arena->size = size; + + return arena; +} + +void DropArena(Arena* arena) +{ + if (arena == nullptr) + return; + Arena* next = arena->next; + free(arena); + DropArena(next); +} + +void* Calloc(Arena* arena, unsigned long size) +{ + size = AlignedSize(size); + + if (arena->size - arena->used < size) { + if (arena->next == nullptr) { + arena->next = NewArena(arena->size > size ? arena->size : size); + arena = arena->next; + } else { + Calloc(arena->next, size); + } + } + + void* ptr = (void*) &arena->heap[arena->used]; + memset(ptr, 0, size); + arena->used += size; + + return ptr; +} diff --git a/src/arena.h b/src/arena.h @@ -0,0 +1,15 @@ +#ifndef COMPILER_ARENA_H_ +#define COMPILER_ARENA_H_ + +typedef struct Arena { + struct Arena* next; + unsigned long size; + unsigned long used; + char heap[]; +} Arena; + +Arena* NewArena(long size); +void DropArena(Arena* a); +void* Calloc(Arena* a, unsigned long size); + +#endif // COMPILER_ARENA_H_ diff --git a/src/codegen.c b/src/codegen.c @@ -0,0 +1,8 @@ +#include "codegen.h" + +void Codegen(Arena* arena, Ast* ast, FILE* output) +{ + (void) arena; + (void) ast; + (void) output; +} diff --git a/src/codegen.h b/src/codegen.h @@ -0,0 +1,11 @@ +#ifndef COMPILER_CODEGEN_H_ +#define COMPILER_CODEGEN_H_ + +#include "arena.h" +#include "parser.h" + +#include <stdio.h> + +void Codegen(Arena* arena, Ast* ast, FILE* output); + +#endif // COMPILER_CODEGEN_H_ diff --git a/src/compile.c b/src/compile.c @@ -0,0 +1,41 @@ +#include "arena.h" +#include "codegen.h" +#include "compiler.h" +#include "parser.h" +#include "semantics.h" +#include "tokenizer.h" + +#include <assert.h> +#include <stdio.h> + +void PrintError(Error error, const char* file) +{ + printf( + "%s:%d:%d: %s: %s.\n", + file, + (int) error.line, + (int) error.column, + error.message, + error.dynamic + ); +} + +Errors* Compile(Arena* arena, char* program, FILE* output) +{ + Errors* errors = nullptr; + auto tokens = Tokenize(arena, program, &errors); + + auto tree = Parse(arena, tokens, &errors); + if (errors != nullptr) { + return errors; + } + + errors = SemanticAnalysis(arena, tree); + if (errors != nullptr) { + return errors; + } + + Codegen(arena, tree, output); + + return nullptr; +} diff --git a/src/compiler.h b/src/compiler.h @@ -0,0 +1,24 @@ +#ifndef COMPILER_COMPILER_H_ +#define COMPILER_COMPILER_H_ + +#include "arena.h" + +#include <stdio.h> + +typedef struct { + unsigned long line; + unsigned long column; + const char* message; + char* dynamic; +} Error; + +typedef struct Errors { + Error this; + struct Errors* next; +} Errors; + +void PrintError(Error error, const char* file); + +Errors* Compile(Arena* arena, char* program, FILE* output); + +#endif // COMPILER_COMPILER_H_ diff --git a/src/main.c b/src/main.c @@ -0,0 +1,50 @@ +#include "arena.h" +#include "compiler.h" + +#include <stdio.h> +#include <stdlib.h> + +void Usage(const char* program) +{ + printf("usage: %s <input file>\n", program); +} + +char* ReadFileOrDie(Arena* arena, const char* file) +{ + auto f = fopen(file, "r"); + if (f == NULL) { + perror("Couldn't read input file"); + exit(1); + } + + fseek(f, 0, SEEK_END); + auto size = ftell(f); + rewind(f); + + auto buffer = (char*) Calloc(arena, (size + 1) * sizeof(char)); + fread(buffer, 1, size, f); + + return buffer; +} + +int main(int argc, char* argv[]) +{ + if (argc <= 1) { + Usage(argv[0]); + return 1; + } + + auto arena = NewArena(32 * 4096); + + auto input = ReadFileOrDie(arena, argv[1]); + + FILE* output = fopen("a.out", "w"); + + auto errors = Compile(arena, input, output); + for (auto error = errors; error != nullptr; error = error->next) + PrintError(errors->this, argv[1]); + + DropArena(arena); + + return 0; +} diff --git a/src/parser.c b/src/parser.c @@ -0,0 +1,106 @@ +#include "parser.h" + +Ast* Parse(Arena* arena, Tokens* tokens, Errors** errors) +{ + for (auto token = tokens; token != nullptr; token = token->next) { + switch (token->this.kind) { + case TokenProgram: + printf("TokenProgram\n"); + break; + case TokenVar: + printf("TokenVar\n"); + break; + case TokenIdent: + printf( + "TokenIdent %.*s\n", + (int) token->this.lex.size, + token->this.lex.ptr + ); + break; + case TokenDigit: + printf( + "TokenDigit %.*s\n", + (int) token->this.lex.size, + token->this.lex.ptr + ); + break; + case TokenArray: + printf("TokenArray\n"); + break; + case TokenOf: + printf("TokenOf\n"); + break; + case TokenOpenSq: + printf("TokenOpenSq\n"); + break; + case TokenCloseSq: + printf("TokenCloseSq\n"); + break; + case TokenOpenParen: + printf("TokenOpenParen\n"); + break; + case TokenCloseParen: + printf("TokenCloseParen\n"); + break; + case TokenComma: + printf("TokenComma\n"); + break; + case TokenColon: + printf("TokenColon\n"); + break; + case TokenSemicolon: + printf("TokenSemicolon\n"); + break; + case TokenPeriod: + printf("TokenPeriod\n"); + break; + case TokenTwoPeriods: + printf("TokenTwoPeriods\n"); + break; + case TokenOperator: + printf( + "TokenOperator %.*s\n", + (int) token->this.lex.size, + token->this.lex.ptr + ); + break; + case TokenIf: + printf("TokenIf\n"); + break; + case TokenElse: + printf("TokenElse\n"); + break; + case TokenThen: + printf("TokenThen\n"); + break; + case TokenWhile: + printf("TokenWhile\n"); + break; + case TokenDo: + printf("TokenDo\n"); + break; + case TokenBegin: + printf("TokenBegin\n"); + break; + case TokenEnd: + printf("TokenEnd\n"); + break; + case TokenFunction: + printf("TokenFunction\n"); + break; + case TokenProcedure: + printf("TokenProcedure\n"); + break; + case TokenComment: + printf("TokenComment\n"); + break; + case TokenEOF: + printf("TokenEOF\n"); + break; + } + } + + (void) arena; + (void) errors; + return nullptr; +} diff --git a/src/parser.h b/src/parser.h @@ -0,0 +1,26 @@ +#ifndef COMPILER_PARSER_H_ +#define COMPILER_PARSER_H_ + +#include "compiler.h" +#include "tokenizer.h" + +typedef enum { + A, +} NodeKind; + +typedef struct { + union { + int a; + } this; + + NodeKind kind; +} Node; + +typedef struct Ast { + Node this; + struct Ast* next; +} Ast; + +Ast* Parse(Arena* arena, Tokens* tokens, Errors** errors); + +#endif // COMPILER_PARSER_H_ diff --git a/src/semantics.c b/src/semantics.c @@ -0,0 +1,8 @@ +#include "semantics.h" + +Errors* SemanticAnalysis(Arena* arena, Ast* tree) +{ + (void) arena; + (void) tree; + return nullptr; +} diff --git a/src/semantics.h b/src/semantics.h @@ -0,0 +1,10 @@ +#ifndef COMPILER_SEMANTICS_H_ +#define COMPILER_SEMANTICS_H_ + +#include "arena.h" +#include "compiler.h" +#include "parser.h" + +Errors* SemanticAnalysis(Arena* arena, Ast* tree); + +#endif // COMPILER_SEMANTICS_H_ diff --git a/src/tokenizer.c b/src/tokenizer.c @@ -0,0 +1,276 @@ +#include "tokenizer.h" + +#include <ctype.h> +#include <string.h> + +typedef enum { + StateInitial, + StateAlpha, + StateDigit, + StateOpenParen, + StateComment, + StateClosingComment, + StatePeriod, + StateOperator, +} State; + +typedef struct { + const char* keyword; + TokenKind kind; +} Keyword; + +static const Keyword keywords[] = { + { .keyword = "program", .kind = TokenProgram}, + { .keyword = "var", .kind = TokenVar}, + { .keyword = "array", .kind = TokenArray}, + { .keyword = "of", .kind = TokenOf}, + { .keyword = "then", .kind = TokenThen}, + { .keyword = "begin", .kind = TokenBegin}, + { .keyword = "do", .kind = TokenDo}, + { .keyword = "while", .kind = TokenWhile}, + { .keyword = "end", .kind = TokenEnd}, + { .keyword = "if", .kind = TokenIf}, + { .keyword = "else", .kind = TokenElse}, + { .keyword = "else", .kind = TokenElse}, + { .keyword = "function", .kind = TokenFunction}, + {.keyword = "procedure", .kind = TokenProcedure}, +}; + +constexpr unsigned long keywordsLen = sizeof(keywords) / sizeof(keywords[0]); + +#include <stdio.h> + +Errors* MakeTokenError( + Arena* arena, + const char* program, + Token* this, + const char* message, + char* dynamic +) +{ + int i = 0; + int line = 1; + int column = 1; + while (&program[i] <= this->lex.ptr) { + if (program[i] == '\n') { + column = 0; + line += 1; + } + i += 1; + column += 1; + } + + auto errors = (Errors*) Calloc(arena, sizeof(Errors)); + errors->next = nullptr; + errors->this.line = line; + errors->this.column = column; + errors->this.message = message; + errors->this.dynamic = dynamic; + + return errors; +} + +void MakeKeyword(Token* this) +{ + for (auto i = 0; i < (int) keywordsLen; i += 1) { + if ((strncmp(this->lex.ptr, keywords[i].keyword, this->lex.size) == + 0) && + strlen(keywords[i].keyword) == this->lex.size) { + this->kind = keywords[i].kind; + return; + } + } + + this->kind = TokenIdent; +} + +Tokens* Tokenize(Arena* arena, char* program, Errors** errors) +{ + (void) errors; + auto list = (Tokens*) Calloc(arena, sizeof(Tokens)); + auto token = list; + + for (int i = 0; program[i] != '\0'; i += 1) { + program[i] = tolower(program[i]); + } + + auto idx = 0; + auto state = StateInitial; + for (;;) { + const auto cchar = program[idx]; + const auto cint = (int) (unsigned char) cchar; + + switch (state) { + case StateInitial: + if (cchar == '\0') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenEOF; + token->next = nullptr; + return list; + } else if (isalpha(cint)) { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + state = StateAlpha; + idx += 1; + } else if (isdigit(cint)) { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + state = StateDigit; + idx += 1; + } else if (cchar == ';') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenSemicolon; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == ',') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenComma; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == ':') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenColon; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == '(') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + state = StateOpenParen; + idx += 1; + } else if (cchar == ')') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenCloseParen; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == '[') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenOpenSq; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == ']') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + token->this.kind = TokenCloseSq; + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + idx += 1; + } else if (cchar == '.') { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + state = StatePeriod; + idx += 1; + } else if (ispunct(cint)) { + token->this.lex.ptr = &program[idx]; + token->this.lex.size = 1; + state = StateOperator; + idx += 1; + } else { + idx += 1; + } + break; + case StateAlpha: + if (isalnum(cint)) { + token->this.lex.size += 1; + idx += 1; + } else { + MakeKeyword(&token->this); + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token = token->next; + state = StateInitial; + } + break; + case StateDigit: + if (isalnum(cint)) { + token->this.lex.size += 1; + idx += 1; + } else { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.kind = TokenDigit; + token = token->next; + state = StateInitial; + } + break; + case StateOpenParen: + if (cchar == '*') { + state = StateComment; + token->this.lex.size += 1; + idx += 1; + } else { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.kind = TokenOpenParen; + token = token->next; + state = StateInitial; + } + break; + case StateComment: + if (cchar == '*') { + state = StateClosingComment; + token->this.lex.size += 1; + idx += 1; + + } else if (cchar == '\0') { + *errors = MakeTokenError( + arena, program, &token->this, "unclosed comment", nullptr + ); + token->next = nullptr; + token->this.kind = TokenComment; + return list; + } else { + idx += 1; + token->this.lex.size += 1; + } + break; + case StateClosingComment: + if (cchar == ')') { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.lex.size += 1; + token->this.kind = TokenComment; + token = token->next; + state = StateInitial; + idx += 1; + } else { + idx += 1; + token->this.lex.size += 1; + state = StateComment; + } + break; + case StatePeriod: + if (cchar == '.') { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.lex.size += 1; + token->this.kind = TokenTwoPeriods; + token = token->next; + state = StateInitial; + idx += 1; + } else { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.kind = TokenPeriod; + token = token->next; + state = StateInitial; + } + break; + case StateOperator: + if (ispunct(cint)) { + token->this.lex.size += 1; + idx += 1; + } else { + token->next = (Tokens*) Calloc(arena, sizeof(*token->next)); + token->this.kind = TokenOperator; + token = token->next; + state = StateInitial; + } + break; + } + } +} diff --git a/src/tokenizer.h b/src/tokenizer.h @@ -0,0 +1,54 @@ +#ifndef COMPILER_TOKENIZER_H_ +#define COMPILER_TOKENIZER_H_ + +#include "arena.h" +#include "compiler.h" + +typedef struct { + const char* ptr; + unsigned long size; +} String; + +typedef enum { + TokenProgram, + TokenVar, + TokenIdent, + TokenDigit, + TokenArray, + TokenOf, + TokenOpenSq, + TokenCloseSq, + TokenOpenParen, + TokenCloseParen, + TokenComma, + TokenColon, + TokenSemicolon, + TokenPeriod, + TokenTwoPeriods, + TokenOperator, + TokenIf, + TokenElse, + TokenThen, + TokenWhile, + TokenDo, + TokenBegin, + TokenEnd, + TokenFunction, + TokenProcedure, + TokenComment, + TokenEOF, +} TokenKind; + +typedef struct { + String lex; + TokenKind kind; +} Token; + +typedef struct Tokens { + Token this; + struct Tokens* next; +} Tokens; + +Tokens* Tokenize(Arena* arena, char* program, Errors** errors); + +#endif // COMPILER_TOKENIZER_H_