93 Commits
Author SHA1 Message Date
samsonium 0fc6406e97 fix: missing freeing and type (in CIF prepare) 2026-11-08 18:46:21 +03:00
samsonium d09b4f2761 wip: working on externs loading
- Feat: finish FFI CIF prepare
2026-11-08 18:40:44 +03:00
samsonium 2488e9fb07 fix: add loaded symbols count increment 2026-11-08 17:26:46 +03:00
samsonium 899c22eece ref: move extern fns prepare into main 2026-11-08 17:26:32 +03:00
samsonium 1c57525604 wip: working on externs loading
- WIP: add extern objects initializing/freeing functions
- Feat: add extern objects loading in VM initializer
2026-11-08 17:12:31 +03:00
samsonium 5de995a3c2 feat: add debug print for CALL_EXTERN opcode 2026-11-06 14:06:18 +03:00
samsonium 7759136aa8 feat: add linking tests 2026-11-06 14:06:07 +03:00
samsonium d38365f10c feat: add extern functions call support 2026-11-06 14:06:01 +03:00
samsonium 317b846108 feat+fix: add extern fns reading; fix VM reading issues 2026-11-06 13:32:41 +03:00
samsonium 376e7bd1b4 fix: add strings terminators 2026-11-06 12:02:37 +03:00
samsonium d95ff88b66 wip: working on extern in VM
- Feat: add usage of vm reader instead of old way in vm.c
- Ref: update debug opcodes printing
2026-11-05 23:23:38 +03:00
samsonium 1db42c1e8e wip: working on extern in VM
- Feat: add writer externs writing fns
- Feat: add VM reader functions
2026-11-05 21:48:40 +03:00
samsonium 84572edb0d feat: implement extern libs data writing 2026-11-05 18:40:02 +03:00
samsonium d91ba3d63a fix: add missing RM_ENVTABLE opcode 2026-11-05 18:39:48 +03:00
samsonium de0e88f2e9 wip: begin writer impl for externs 2026-11-05 04:01:23 +03:00
samsonium 66f31ab865 fix: fix parser/generator issues 2026-11-05 03:46:16 +03:00
samsonium bd8272abc7 feat: finish generator 2026-11-05 00:04:12 +03:00
samsonium 181458ecda feat: add prepared error/null ok returns from gen_* functions 2026-11-04 22:52:40 +03:00
samsonium aae183c0c0 ref: add type/classname result for each gen_* function 2026-11-04 22:25:25 +03:00
samsonium b278e8bb74 wip: working on generator
- Feat: add break handler
- Feat: add class handler
- Feat: add format string handler
- Feat: add loop handler
2026-11-04 20:04:33 +03:00
samsonium 7fe3fe3ff3 wip: working on generator
- Feat: add typedefs' branches
2026-11-04 19:33:17 +03:00
samsonium 731b662cfc wip: working on generator
- Feat: add extern type resolving to type slot
- Feat: add extern block handling
- Feat: add extern function handling
2026-11-04 18:30:02 +03:00
samsonium f2b88e448e feat: add .clangd 2026-11-04 17:16:52 +03:00
samsonium c5c522cde8 feat: add generators' main entry 2026-11-04 17:10:21 +03:00
samsonium c0bd0d95b2 fix: add classname value for structs and handles 2026-11-04 17:04:09 +03:00
samsonium 26decf2626 wip: working on extern
- Feat: add new generator scope to replace walker
- Feat: add generators' context functions
- Feat: add generators' ops array functions
- Feat: add generators' utility functions
2026-11-04 17:03:48 +03:00
samsonium 358ede4c8c wip: working on extern
- Feat: stabilize extern header
- Feat: add externs to walker
- Feat: add extern node walking logic
2026-11-02 20:31:43 +03:00
samsonium 6a035a71eb wip: working on extern
- Ref: move extern header into common scope
- Feat: add extern symbols descriptors
- Feat: add `is_out` flag in declaration node
2026-11-02 19:24:09 +03:00
samsonium 8975d2fece feat: add out type arg info storing in declaration node 2026-11-02 18:55:40 +03:00
samsonium 3dd70ac293 wip: working on extern
Add TODOs for new nodes
2026-11-01 21:24:23 +03:00
samsonium 4d9c4ddd21 wip: working on walker (externs)
Begin working on extern walking (libs metadata collet + opcode gen)
2026-10-31 18:45:33 +03:00
samsonium a4aa220cfa feat: implement extern block analyzer 2026-10-31 01:58:10 +03:00
samsonium 5c96f96220 wip: working on dynamic linking
- Feat: add analyzers for:
  - external functions
  - reference
  - structures
  - type definitions
- Feat: add new nodes to debug print (ast)
2026-10-30 20:32:14 +03:00
samsonium f769313169 feat: implement extern block reading and parsing 2026-10-29 22:13:28 +03:00
samsonium 0448be0d38 ref: update linking example 2026-10-29 20:24:06 +03:00
samsonium 01dabd2bdd ref: remove build-release dependency from install make target 2026-10-29 20:23:54 +03:00
samsonium 6f54286724 doc: update project building steps 2026-10-29 18:18:50 +03:00
samsonium fe5fcd7b96 feat: add compiler installation step
- Ref: add `-debug` suffix to debug targets
- Ref: remove `-release` suffix from release targets
- Feat: add `make install` command
- Feat: add cmake variables:
  - `FZL_TESTS` for enable testing
  - `FZL_SKIP_C` to not build the compiler
  - `FZL_SKIP_VM` to not build the vm
2026-10-29 18:18:35 +03:00
samsonium a885746fdd feat: add object escaping on assing to variable in outer env 2026-10-29 17:46:56 +03:00
samsonium 2cf96d06c6 fix: fmtstring printing 2026-10-29 17:46:20 +03:00
samsonium bbdf91ee02 fix: cutted space in string literal begin 2026-10-29 17:46:08 +03:00
samsonium 27374a96eb fix: AST levels print 2026-10-29 17:45:39 +03:00
samsonium dcab2a8875 feat: add runtime speed comparison between fz, c and cpython 2026-10-29 05:21:31 +03:00
samsonium 7b804b8809 feat: optimize runtime (2x+ faster) 2026-10-29 05:21:00 +03:00
samsonium eeca5e653d feat: add benchmar Make target 2026-10-29 03:25:48 +03:00
samsonium f4c97795fa feat: optimize VM using dispatch table 2026-10-29 02:59:38 +03:00
samsonium e2de23ed57 fix: suppress libffi cmake warnings 2026-10-29 00:26:33 +03:00
samsonium 8c90d54782 ref: split parser into separate files 2026-10-29 00:08:44 +03:00
samsonium 62b0030e4a ref: move analyzer fn defs into compiler/iternals 2026-10-28 23:24:17 +03:00
samsonium bbdaa4a9b9 ref: split reader into separate files 2026-10-28 23:12:46 +03:00
samsonium 7c04d8b7ec ref: remove unused loop checker 2026-10-28 23:12:06 +03:00
samsonium 567bf49d27 wip: working on dynamic linking
- Feat: add example for wrapping dynamically linked library
- Feat: add new tokens (import, extern, type, handle, struct, ref, out)
2026-10-28 21:43:56 +03:00
samsonium d93c315359 fix: clear first AST node if got error inside parse_program 2026-10-28 19:37:17 +03:00
samsonium e11089c90f feat: implement format strings 2026-10-28 17:57:18 +03:00
samsonium ea28c470d2 wip: begin dynamic library loading dev 2026-10-28 15:20:58 +03:00
samsonium 70bf63e2ea feat: add libffi cmake dependency 2026-10-28 00:31:09 +03:00
samsonium b24cefee96 Merge pull request 'Impl analyzer' (#5) from impl-analyzer into v1.1
Reviewed-on: #5
2026-10-27 12:43:08 +00:00
samsonium 6498c73960 ref: move linked list example into tests folder 2026-10-27 15:42:02 +03:00
samsonium dc80de66e4 fix: review problems 2026-10-27 15:40:25 +03:00
samsonium c61322718d fix: some analysis stage problems 2026-10-27 14:12:09 +03:00
samsonium 411d291a2c feat: add VM protection for classes w/o fields 2026-10-27 12:55:46 +03:00
samsonium aa7a06bd22 feat: finish implementing analyzer 2026-10-27 12:50:58 +03:00
samsonium a263b6206f wip: working on analyzer
- Feat: add assigns analysis
- Fix: change node check condition in binary math analysis
- Feat: add unary and binary conditions analysis
- Fix: add type passtrough in declaration analysis
- Feat: add unary math analysis
2026-10-27 12:21:49 +03:00
samsonium 25991c6f15 wip: working on analyzer
- Feat: add binary math analysis
- Fix: check for function context in block analysis
- Feat: add 'break' analysis
- Fix: few fixes in call analysis
- Feat: add class analysis
- Feat: add construct analysis
- Feat: add declaration analysis
- Feat: add field analysis
- Feat: add function analysis
- Feat: add loop analysis
- Ref: updated utilities and context functions
2026-10-27 05:18:36 +03:00
samsonium d7630dbb6a wip: working on analyzer
- Feat: implement return analyzer
- Fix: add block return check if inside function
2026-10-26 22:20:09 +03:00
samsonium a70ad011f3 wip: working on analyzer
- Feat: add `nest_ctx` and `fin_ctx` fns for working with context and
environment
- Feat: add block analyzer
- Feat: add conditional statement analyzer
2026-10-26 21:34:54 +03:00
samsonium 62ae05b4cd wip: working on analyzer
- Feat: now symbols table store node on PUT
- Feat: call analyzer with callee resolving and arguments validate
- Feat: identifier analyzer
- Feat: analyzer utils (types compat, tok-to-type, type-to-string)
2026-10-26 20:47:24 +03:00
samsonium 4904f40037 wip: working on analyzer 2026-10-25 19:24:02 +03:00
samsonium 562b1b2e0a Merge pull request 'Implement loops' (#4) from feat-loops into v1.1
- Fix: memory leaks in parser
- Feat: `for` and `while` loops
- Feat: `break` for exit from loops
- Doc: new examples in `exl` directory
- Feat: optimized tests calling CMakeLists
2026-10-25 02:01:47 +00:00
samsonium 6d1f1ce66e fix: memory leak in postfix parsing function 2026-10-25 04:57:01 +03:00
samsonium c03fddf47f fix: fixes in compiler 2026-10-25 04:52:18 +03:00
samsonium 3bb60071bb feat: add infinite loop control args 2026-10-25 04:52:07 +03:00
samsonium 04fdd58e4f fix: fix typo in examples 2026-10-25 04:51:37 +03:00
samsonium e00e609589 ref: rename 'hard-1' test to 'linked-list' 2026-10-25 01:56:20 +03:00
samsonium a37b8cfe6e ref: remove test examples 2026-10-25 01:56:07 +03:00
samsonium c4eb148d17 ref: temporary comment out infinite loop check 2026-10-25 01:54:49 +03:00
samsonium dbca3129ab feat: add "while-not-null" test 2026-10-25 01:54:07 +03:00
samsonium e3878047d7 upd: rename neg1 tests (for negative in runtime) to negr 2026-10-25 01:53:46 +03:00
samsonium 7cfb8efef4 feat: implement break 2026-10-22 21:30:32 +03:00
samsonium b5ae959d14 feat: add test name format for runtime-only error 2026-10-22 21:30:17 +03:00
samsonium 0e319308a7 wip: working on infinite loop handling in vm 2026-10-22 20:25:48 +03:00
samsonium a20743a835 feat: implement simple infinite loop checker 2026-10-22 20:24:48 +03:00
samsonium 5dde75523d wip: working on loop infinity checker 2026-10-22 18:25:07 +03:00
samsonium cc5bbd61f2 feat: implement loops 2026-10-22 18:24:28 +03:00
samsonium 0188991f4d feat: add new tests for loops 2026-10-22 03:39:04 +03:00
samsonium 73a2a50a0b feat: add error message for variable redefenition attempt 2026-10-21 04:42:58 +03:00
samsonium 4a366cb0ac fix: missing ';' in variables example 2026-10-21 04:42:41 +03:00
samsonium c7cce94119 fix: add AST freeing on errors; add checks for parser, walker and writer are not NULL 2026-10-21 04:31:57 +03:00
samsonium 673a28fbc7 fix: check for EOF on block parsing (closing brace) 2026-10-21 04:31:02 +03:00
samsonium 160c6c6488 fix: incorrect test file directory prefix 2026-10-21 04:30:16 +03:00
samsonium c8f3cd61f4 ref: add build-release make target for building c/vm without sanitizer libs 2026-10-21 04:01:23 +03:00
samsonium 138d503bce feat: add examples with descriptions 2026-10-21 04:00:48 +03:00
samsonium e49ebba346 feat: add new tests 2026-10-21 04:00:03 +03:00
208 changed files with 11825 additions and 3911 deletions
+4
View File
@@ -0,0 +1,4 @@
Style:
AngledHeaders: [".*"]
QuotedHeaders: []
+1
View File
@@ -5,6 +5,7 @@ skip is
skip -rfunction fzl_mk* skip -rfunction fzl_mk*
skip -rfunction fzl_free* skip -rfunction fzl_free*
skip -rfunction fzl_symt* skip -rfunction fzl_symt*
skip -rfunction fzl_linked*
skip add_const skip add_const
skip push_op skip push_op
skip push_word skip push_word
+4 -1
View File
@@ -3,15 +3,18 @@
# Dirs # Dirs
!/docs !/docs
!/exl !/exl
!/benchmarks
!/include !/include
!/scripts
!/src !/src
!/tests
# Files # Files
!/.clang-format !/.clang-format
!/.clangd
!/.gdbinit !/.gdbinit
!/.gitignore !/.gitignore
!/CMakeLists.txt !/CMakeLists.txt
!/Makefile !/Makefile
!/README.md !/README.md
!/README.ru.md !/README.ru.md
+186 -100
View File
@@ -8,135 +8,221 @@ add_compile_options(-Wall -Wextra -Werror=implicit-function-declaration)
if (CMAKE_BUILD_TYPE STREQUAL "Debug") if (CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_options(-fsanitize=address,undefined -g) add_compile_options(-fsanitize=address,undefined -g)
add_link_options(-fsanitize=address,undefined) add_link_options(-fsanitize=address,undefined)
set(FZL_TESTS TRUE)
endif() endif()
include_directories(include) include_directories(include)
include(FetchContent)
# --- libffi ---
set(PREV_SUPPRESS_DEV ${CMAKE_SUPPRESS_DEVELOPER_WARNINGS})
set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS TRUE CACHE INTERNAL "")
FetchContent_Declare(ffi
GIT_REPOSITORY "https://git.samsonium.dev/samsonium/libffi.git"
GIT_TAG "main"
)
FetchContent_MakeAvailable(ffi)
set(CMAKE_SUPPRESS_DEVELOPER_WARNINGS ${PREV_SUPPRESS_DEV} CACHE INTERNAL "")
# --------------
# Compiler # Compiler
if (NOT FZL_SKIP_C)
add_executable(fzc add_executable(fzc
src/compiler/fzl_token.c
src/compiler/fzl_reader.c
src/compiler/fzl_parser.c
src/compiler/fzl_debug.c
src/compiler/fzl_walker.c
src/compiler/fzl_writer.c
src/compiler/utils/fzl_const_pool.c src/compiler/utils/fzl_const_pool.c
src/compiler/utils/fzl_symtable.c src/compiler/utils/fzl_symtable.c
src/compiler/utils/fzl_linked.c src/compiler/utils/fzl_linked.c
src/compiler/utils/fzl_options.c src/compiler/utils/fzl_options.c
src/compiler/utils/fzl_ctable.c src/compiler/utils/fzl_ctable.c
src/compiler/analyzer/utility.c
src/compiler/analyzer/context.c
src/compiler/analyzer/an_assign.c
src/compiler/analyzer/an_binmath.c
src/compiler/analyzer/an_block.c
src/compiler/analyzer/an_break.c
src/compiler/analyzer/an_call.c
src/compiler/analyzer/an_class.c
src/compiler/analyzer/an_common.c
src/compiler/analyzer/an_condition.c
src/compiler/analyzer/an_conditional.c
src/compiler/analyzer/an_construct.c
src/compiler/analyzer/an_declaration.c
src/compiler/analyzer/an_extern.c
src/compiler/analyzer/an_externfn.c
src/compiler/analyzer/an_field.c
src/compiler/analyzer/an_function.c
src/compiler/analyzer/an_identifier.c
src/compiler/analyzer/an_loop.c
src/compiler/analyzer/an_ref.c
src/compiler/analyzer/an_return.c
src/compiler/analyzer/an_strfmt.c
src/compiler/analyzer/an_struct.c
src/compiler/analyzer/an_typedef.c
src/compiler/analyzer/an_unarycond.c
src/compiler/analyzer/an_unarymath.c
src/compiler/generator/context.c
src/compiler/generator/op.c
src/compiler/generator/utility.c
src/compiler/generator/gen_alias.c
src/compiler/generator/gen_assign.c
src/compiler/generator/gen_block.c
src/compiler/generator/gen_break.c
src/compiler/generator/gen_call.c
src/compiler/generator/gen_class.c
src/compiler/generator/gen_common.c
src/compiler/generator/gen_compare.c
src/compiler/generator/gen_condition.c
src/compiler/generator/gen_construct.c
src/compiler/generator/gen_declaration.c
src/compiler/generator/gen_extern.c
src/compiler/generator/gen_externfn.c
src/compiler/generator/gen_field.c
src/compiler/generator/gen_fmtstr.c
src/compiler/generator/gen_fn.c
src/compiler/generator/gen_handle.c
src/compiler/generator/gen_identifier.c
src/compiler/generator/gen_literal.c
src/compiler/generator/gen_logical.c
src/compiler/generator/gen_loop.c
src/compiler/generator/gen_math.c
src/compiler/generator/gen_reference.c
src/compiler/generator/gen_return.c
src/compiler/generator/gen_struct.c
src/compiler/generator/gen_typedef.c
src/compiler/generator/gen_unary_logical.c
src/compiler/generator/gen_unary_math.c
src/compiler/parser/utility.c
src/compiler/parser/pa_and.c
src/compiler/parser/pa_assignment.c
src/compiler/parser/pa_block.c
src/compiler/parser/pa_break.c
src/compiler/parser/pa_class.c
src/compiler/parser/pa_cond.c
src/compiler/parser/pa_expression.c
src/compiler/parser/pa_extern.c
src/compiler/parser/pa_externfn.c
src/compiler/parser/pa_factor.c
src/compiler/parser/pa_for.c
src/compiler/parser/pa_function.c
src/compiler/parser/pa_if.c
src/compiler/parser/pa_loop.c
src/compiler/parser/pa_new.c
src/compiler/parser/pa_or.c
src/compiler/parser/pa_postfix.c
src/compiler/parser/pa_power.c
src/compiler/parser/pa_primary.c
src/compiler/parser/pa_program.c
src/compiler/parser/pa_ref.c
src/compiler/parser/pa_return.c
src/compiler/parser/pa_statement.c
src/compiler/parser/pa_struct.c
src/compiler/parser/pa_term.c
src/compiler/parser/pa_typedef.c
src/compiler/parser/pa_unary.c
src/compiler/parser/pa_while.c
src/compiler/reader/rd_fmtstr.c
src/compiler/reader/rd_name.c
src/compiler/reader/rd_number.c
src/compiler/reader/rd_string_literal.c
src/compiler/reader/utility.c
src/compiler/writer/wr_consts.c
src/compiler/writer/wr_extern_fns.c
src/compiler/writer/wr_extern_libs.c
src/compiler/writer/wr_extern_types.c
src/compiler/writer/wr_ops.c
src/compiler/fzl_analyzer.c
src/compiler/fzl_debug.c
src/compiler/fzl_gen.c
src/compiler/fzl_parser.c
src/compiler/fzl_reader.c
src/compiler/fzl_token.c
src/compiler/fzl_writer.c
src/compiler/main.c) src/compiler/main.c)
endif ()
# Virtual machine # Virtual machine
if (NOT FZL_SKIP_VM)
add_executable(fz add_executable(fz
src/vm/handlers/group_and_or.c
src/vm/handlers/group_cmp.c
src/vm/handlers/group_ctx.c
src/vm/handlers/group_flow.c
src/vm/handlers/group_fn.c
src/vm/handlers/group_math.c
src/vm/handlers/group_not.c
src/vm/handlers/group_obj.c
src/vm/handlers/group_objcmp.c
src/vm/handlers/group_stack.c
src/vm/handlers/group_str.c
src/vm/handlers/group_strcmp.c
src/vm/handlers/master.c
src/vm/reader/utility.c
src/vm/reader/vm_rd_consts.c
src/vm/reader/vm_rd_extern_fns.c
src/vm/reader/vm_rd_extern_libs.c
src/vm/reader/vm_rd_extern_types.c
src/vm/reader/vm_rd_header.c
src/vm/reader/vm_rd_ops.c
src/vm/reader/vm_rd_sections_sz.c
src/vm/fzl_vm.c src/vm/fzl_vm.c
src/vm/fzl_vm_env.c src/vm/fzl_vm_env.c
src/vm/fzl_vm_extern.c
src/vm/fzl_vm_reader.c
src/vm/fzl_vm_debug.c src/vm/fzl_vm_debug.c
src/vm/main.c) src/vm/main.c)
target_link_libraries(fz PRIVATE ffi_static dl)
endif ()
# #
# ========== Compilation tests ========== # ========== Installtion ===========
# #
if (NOT FZL_SKIP_C)
install (TARGETS fzc RUNTIME DESTINATION bin)
endif ()
if (NOT FZL_SKIP_VM)
install (TARGETS fz RUNTIME DESTINATION bin)
endif ()
#
# ========== Tests ==========
#
if (FZL_TESTS)
enable_testing() enable_testing()
add_test( file(GLOB TEST_LIBS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "tests/libs/*.c")
NAME compile_hw foreach (TEST_LIB IN LISTS TEST_LIBS)
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/hw.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/hw.fzs" get_filename_component(LIB_NAME "${TEST_LIB}" NAME_WE)
) add_library("${LIB_NAME}" ${TEST_LIB})
add_test( endforeach ()
NAME compile_print_empty
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/print_empty.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/print_empty.fzs"
)
add_test(
NAME compile_problematic_hw
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/problematic_hw.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/problematic_hw.fzs"
)
add_test(
NAME compile_base_math
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/base_math.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/base_math.fzs"
)
add_test(
NAME compile_variables
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/variables.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/variables.fzs"
)
add_test(
NAME compile_conditions
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/conditions.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/conditions.fzs"
)
add_test(
NAME compile_fn
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/fn.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/fn.fzs"
)
add_test(
NAME compile_comment
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/comment.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/comment.fzs"
)
add_test(
NAME compile_class
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/class.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/class.fzs"
)
add_test(
NAME compile_raii
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/raii.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/raii.fzs"
)
add_test(
NAME compile_borrow
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/borrow.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/borrow.fzs"
)
add_test(
NAME compile_hard_1
COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/hard-1.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/exl/hard-1.fzs"
)
set_tests_properties(compile_problematic_hw PROPERTIES WILL_FAIL TRUE) file(GLOB TEST_PROGS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "tests/programs/*.fzs")
foreach (TEST_FILE IN LISTS TEST_PROGS)
# get_filename_component(TEST_NAME "${TEST_FILE}" NAME_WE)
# ========== Runtime tests ==========
#
add_test( add_test(
NAME runtime_hw NAME "progs_compile_${TEST_NAME}"
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/hw.fzb" COMMAND fzc -o "${CMAKE_CURRENT_BINARY_DIR}/p_${TEST_NAME}.fzb" "${CMAKE_CURRENT_SOURCE_DIR}/${TEST_FILE}"
) )
add_test( add_test(
NAME runtime_print_empty NAME "progs_runtime_${TEST_NAME}"
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/print_empty.fzb" COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/p_${TEST_NAME}.fzb"
)
add_test(
NAME runtime_base_math
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/base_math.fzb"
)
add_test(
NAME runtime_variables
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/variables.fzb"
)
add_test(
NAME runtime_conditions
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/conditions.fzb"
)
add_test(
NAME runtime_fn
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/fn.fzb"
)
add_test(
NAME runtime_comment
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/comment.fzb"
)
add_test(
NAME runtime_class
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/class.fzb"
)
add_test(
NAME runtime_raii
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/raii.fzb"
)
add_test(
NAME runtime_borrow
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/borrow.fzb"
)
add_test(
NAME runtime_hard_1
COMMAND fz "${CMAKE_CURRENT_BINARY_DIR}/hard-1.fzb"
) )
if (TEST_NAME MATCHES "neg_")
set_tests_properties("progs_compile_${TEST_NAME}" PROPERTIES WILL_FAIL TRUE)
set_tests_properties("progs_runtime_${TEST_NAME}" PROPERTIES WILL_FAIL TRUE)
endif()
if (TEST_NAME MATCHES "negr_")
set_tests_properties("progs_runtime_${TEST_NAME}" PROPERTIES WILL_FAIL TRUE)
endif ()
endforeach ()
endif ()
+48 -7
View File
@@ -1,17 +1,58 @@
.PHONY: configure build debug-c debug-vm test .PHONY: build debug-c debug-vm test bench
configure: BENCH_FILE ?= benchmarks/loop.fzs
RUNS ?= 7
WARMUP ?= 2
MAX_ITER ?= 2000000
current_time = python3 -c "import time; print(time.time())"
build-debug:
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug
build: configure
cmake --build build cmake --build build
debug-c: build build:
gdb --args ./build/fzc ${FILE} cmake -S . -B build -DCMAKE_BUILD_TYPE=Release $(COMPARING)
cmake --build build $(COMPARING)
debug-vm: build install:
cmake --install build
debug-c: build-debug
gdb --args ./build/fzc -v ${FILE}
debug-vm: build-debug
gdb --args ./build/fz ${FILE} gdb --args ./build/fz ${FILE}
test-debug: build-debug
ctest --output-on-failure --test-dir build
test: build test: build
ctest --output-on-failure --test-dir build ctest --output-on-failure --test-dir build
bench: COMPARING=&>/dev/null
bench: build
@./build/fzc -o build/benchmark.fzb $(BENCH_FILE)
@python3 scripts/benchmark.py --runs $(RUNS) --warmup $(WARMUP) \
--max-iter $(MAX_ITER) --vm ./build/fz --program build/benchmark.fzb
compare: COMPARING=&>/dev/null
compare: build
@echo "=== Million sums benchmark ==="
@./build/fzc -o build/bench.fzb $(BENCH_FILE) 1>/dev/null 2>/dev/null
@ST=$$($(current_time)); \
./build/fz --allow-infinite build/bench.fzb 1>/dev/null 2>/dev/null; \
ET=$$($(current_time)); \
python3 -c "delta = ($$ET - $$ST) * 1000; print(f'FZLang : {delta:.5f} ms')"
@ST=$$($(current_time)); \
./benchmarks/loop-c 1>/dev/null 2>/dev/null; \
ET=$$($(current_time)); \
python3 -c "delta = ($$ET - $$ST) * 1000; print(f'C : {delta:.5f} ms')"
@ST=$$($(current_time)); \
python3 ./benchmarks/loop.py 1>/dev/null 2>/dev/null; \
ET=$$($(current_time)); \
python3 -c "delta = ($$ET - $$ST) * 1000; print(f'CPython: {delta:.5f} ms')"
+1 -1
View File
@@ -27,7 +27,7 @@ Working examples of code can be found in `exl/` directory.
## Building ## Building
1. Clone the repository: `git clone https://git.samsonium.dev/samsonium/fz-lang.git` 1. Clone the repository: `git clone https://git.samsonium.dev/samsonium/fz-lang.git`
2. Build: `make build` 2. Build: `make build-release`
After this, a "build" directory will appear in the project root. It will contain two executable files: After this, a "build" directory will appear in the project root. It will contain two executable files:
+18 -5
View File
@@ -28,11 +28,7 @@
1. Склонировать проект: `git clone https://git.samsonium.dev/samsonium/fz-lang.git` 1. Склонировать проект: `git clone https://git.samsonium.dev/samsonium/fz-lang.git`
2. Собрать проект: `make build` 2. Собрать проект: `make build`
3. Установить проект: `sudo make install`
После этого в корне появится директория **"build"**. В ней будут лежать два скомпилированных бинарных файла:
- `fzc` - компилятор
- `fz` - виртуальная машина
Оба бинарных файла предоставляют справку по использованию при запуске с флагом `--help` (или `-h`). Оба бинарных файла предоставляют справку по использованию при запуске с флагом `--help` (или `-h`).
@@ -51,3 +47,20 @@ $ make debug-c FILE=exl/hw.fzs
Для проверки новых фич, нужно использовать make-таргет `test`, а тесты писать в `CMakeLists.txt`. Для проверки новых фич, нужно использовать make-таргет `test`, а тесты писать в `CMakeLists.txt`.
### Бенчмаркинг
`make bench` собирает Release-версию, компилирует `benchmarks/loop.fzs` один раз и
измеряет время запуска программы в виртуальной машине. По умолчанию выполняются
2 прогрева и 7 замеров; выводятся медиана, среднее, минимум и максимум. Компиляция
исходника в измерения не входит.
Параметры можно переопределить:
```shell
make bench RUNS=15 WARMUP=3
make bench BENCH_FILE=path/to/program.fzs MAX_ITER=2000000
```
Измеряется полное время запуска процесса `fz` (включая загрузку программы), а не
только цикл интерпретации. Для сопоставимых результатов запускайте бенчмарк на
одной машине и не меняйте нагрузку между прогонами.
BIN
View File
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
// Integer loop workload for measuring VM execution without I/O.
uint i = 0;
uint sum = 0;
for (i = 0; i < 1000000; i = i + 1)
sum = sum + i;
printline(sum);
+4
View File
@@ -0,0 +1,4 @@
s = 0
for i in range(1_000_000):
s += i
print(s)
+32
View File
@@ -0,0 +1,32 @@
// There are two ways to work with variables
// 1. Declare variable:
str someString = "world, hello!";
// 2. Change variable value:
someString = "hello, world!";
// Variables help you store values to use it later
int a = 2;
int b = a + a * a;
int c = a * b;
printline("Now we got 12:");
printline(c);
// Also, there are many different variable types to help your program
// work with many things:
int signedInteger;
uint unsignedInteger;
str string;
bool boolean;
i8 integer1; // 8-byte int
i16 integer2; // 16-byte int
i32 integer3; // 32-byte int
i64 integer4; // 64-byte int
u8 integer5; // unsigned 8-byte integer
u16 integer6; // unsigned 16-byte integer
u32 integer7; // unsigned 32-byte integer
u64 integer8; // unsigned 64-byte integer
+30
View File
@@ -0,0 +1,30 @@
// When you need to check some value
// a conditional statement might help you
int valueToCheck = 2 + 2;
if (valueToCheck == 4)
{
printline("Yay! 2 + 2 = 4");
}
// Conditional statement uses condition in parenthesis
// after `if` keyword and executes command(s) after
// if condition turns out to be true
// Otherwise, to execute block when condition turns
// out to be false, you can use `else` keyword:
int age = 30;
if (age <= 20)
printline("You're too young");
else
{
age = 20;
printline("You look too young!");
}
// NOTE: If you need to execute only one statement
// inside `if` or `else` block, then the curly
// braces can be omitted.
+30
View File
@@ -0,0 +1,30 @@
// If you have some code section which is
// duplicated in program several times
// then it means your program needs some
// functions!
fn doSomeWork()
{
printline("Some work");
}
// If the function makes some kind of
// calculations then you should specify
// the result type
fn sum(int a, int b) int
{
return a + b;
}
// The `return` keyword can be used to
// actually return the value from the
// function. Also, you can specify list
// of arguments that you will use inside
// the function
int first = 5;
int second = 6;
int result = sum(first, second);
printline(result);
-46
View File
@@ -1,46 +0,0 @@
class A
{
uint some;
}
fn doSome(A a) A
{
// NOTE: section below won't change `a.some` value
if (a.some < 1)
{
a.some = 1;
return a;
}
return a;
}
fn doSomeNew() A
{
if (1 == 1)
{
return new A;
}
}
A a = new A;
a.some = 0;
if (a.some != 0)
{
printline("Test failed (first a.some != 0)");
exit(1);
}
else printline(a);
a = doSome(a);
if (a.some != 1)
{
printline("Test failed (2nd a.some != 1)");
exit(1);
}
else printline(a);
A b = doSomeNew();
printline(b);
-36
View File
@@ -1,36 +0,0 @@
class Point
{
int x;
int y;
// Move point by [dx,dy]
fn move(int dx, int dy) {
this.x = this.x + dx;
this.y = this.y + dy;
}
}
Point obj = new Point;
obj.x = 1;
obj.y = 2;
printline("Current X,Y:");
printline(obj.x);
printline(obj.y);
// NOTE: WHY THE FUCK THIS FUCKING COMPILER REQUIRES ';' AFTER '='?!
// |
// v
obj.move(9, 8);
printline("X,Y after move:");
printline(obj.x);
printline(obj.y);
if (obj.x == 10 && obj.y == 10)
printline("Test passed");
else
{
printline("Test failed");
exit(1);
}
-3
View File
@@ -1,3 +0,0 @@
// I'm a comment
printline("Comment is skipped");;;;;
-20
View File
@@ -1,20 +0,0 @@
bool flag = true;
if (!flag)
{
printline("buhhh, flag is not true");
exit(1);
}
else if (2 + 2 >= 4)
{
printline ("two plus two is four");
}
else {
printline("gotcha");
exit(1);
}
{
printline("block after");
}
-32
View File
@@ -1,32 +0,0 @@
fn fib(int n) int
{
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
fn sum(uint a, uint b) uint
{
return a + b;
}
printline("Test #1: fibonacci");
int result = fib(7);
if (result == 13)
printline("Recurse test passed");
else
{
printline("Recurse test failed");
exit(1);
}
printline("Test #2: sum");
if (sum(2, 2) == 4)
printline("Sum test passed");
else
{
printline("Sum test failed");
exit(1);
}
-2
View File
@@ -1,2 +0,0 @@
printline('hello, world');
+41
View File
@@ -0,0 +1,41 @@
extern "libglfw" {
// Opaque types
type GLFWwindow handle;
type GLFWmonitor handle;
// Struct definition
type GLFWvidmode struct {
int width;
int height;
int redBits;
int greenBits;
int blueBits;
int refreshRate;
};
/// GLFWvidmode*
type GLFWvidmodeRef ref GLFWvidmode;
/// Create window with specified [width], [height] and [title]
fn glfw_mkWindow(
int width,
int height,
str title,
GLFWmonitor mon,
GLFWwindow shr
) GLFWwindow = "glfwCreateWindow";
/// Get videomode from monitor [mon]
fn glfw_getVideoMode(
GLFWmonitor mon
) GLFWvidmodeRef = "glfwGetVideoMode";
/// Get framebuffer [width] and [height]
fn glfw_getFrameBufferSize(
GLFWwindow win,
out int width,
out int height
) = "glfwGetFramebufferSize";
}
-1
View File
@@ -1 +0,0 @@
printline("");
-1
View File
@@ -1 +0,0 @@
printline("hello);
-46
View File
@@ -1,46 +0,0 @@
class Animal
{
str type;
str name;
int age;
fn copy() Animal
{
Animal cp = new Animal;
cp.type = this.type;
cp.name = this.name;
cp.age = this.age;
return cp;
}
}
Animal a = new Animal;
a.type = "Cow";
a.name = "Buryatka";
a.age = 5;
Animal b = a.copy();
b.name = "Gavryusha";
b.age = 10;
printline(a);
printline(b);
printline("Types are same:");
printline(a.type == b.type);
printline("Names are NOT the same");
printline(a.name != b.name);
printline("1st age less than 2nd");
printline(a.age < b.age);
if (a.type == b.type && a.name != b.name && a.age < b.age)
printline("Test passed");
else
{
printline("Test failed");
exit(1);
}
+86
View File
@@ -0,0 +1,86 @@
#ifndef FZL_EXTERN_H
#define FZL_EXTERN_H
#include <common/fzl_types.h>
#include <stdbool.h>
#include <stddef.h>
typedef enum
{
FZL_EXTERN_KIND_HANDLE,
FZL_EXTERN_KIND_STRUCT,
FZL_EXTERN_KIND_REF,
FZL_EXTERN_KIND_ALIAS,
} fzl_extern_kind_t;
// Type reference descriptor
typedef struct
{
bool is_primitive;
union
{
fzl_type_t primitive;
size_t type_slot;
};
} fzl_extern_type_ref_t;
// Structure field descriptor
typedef struct
{
char *name;
fzl_extern_type_ref_t type;
} fzl_extern_struct_field_t;
// Type descriptor
typedef struct
{
size_t lib_slot;
char *name;
fzl_extern_kind_t kind;
union
{
// Structure
struct
{
fzl_extern_struct_field_t *fields;
size_t fields_count;
} structure;
// Pointer (ref)
fzl_extern_type_ref_t ref_target;
// Alias
fzl_extern_type_ref_t alias_target;
};
} fzl_extern_type_t;
// Function argument descriptor
typedef struct
{
char *name;
fzl_extern_type_ref_t type;
bool is_out;
} fzl_extern_arg_t;
// Function descriptor
typedef struct
{
size_t lib_slot;
char *symbol_name;
char *used_name;
bool has_return;
fzl_extern_type_ref_t ret_type;
fzl_extern_arg_t *args;
size_t args_count;
} fzl_extern_fn_t;
// Library descriptor
typedef struct
{
char *name;
} fzl_extern_lib_t;
#endif // FZL_EXTERN_H
+5
View File
@@ -14,12 +14,15 @@ typedef enum
FZL_OPCODE_STORE = 0xF10003, // Push variable to environment table FZL_OPCODE_STORE = 0xF10003, // Push variable to environment table
FZL_OPCODE_LOOKUP_ENV = 0xF10004, // Lookup name in environment table FZL_OPCODE_LOOKUP_ENV = 0xF10004, // Lookup name in environment table
FZL_OPCODE_WRITE = 0xF10005, // Wirte into variable FZL_OPCODE_WRITE = 0xF10005, // Wirte into variable
FZL_OPCODE_LOAD_LOCAL = 0xF10006, // Load local variable
FZL_OPCODE_STORE_LOCAL = 0xF10007, // Store local variable
FZL_OPCODE_JMP = 0xF20001, // Jump to specified IP address FZL_OPCODE_JMP = 0xF20001, // Jump to specified IP address
FZL_OPCODE_JZ = 0xF20002, // Jump if top value in dstack is zero FZL_OPCODE_JZ = 0xF20002, // Jump if top value in dstack is zero
FZL_OPCODE_CALL = 0xF30001, // Call function FZL_OPCODE_CALL = 0xF30001, // Call function
FZL_OPCODE_RET = 0xF30002, // Return from function FZL_OPCODE_RET = 0xF30002, // Return from function
FZL_OPCODE_CALL_EXTERN = 0xF30003, // Call external function
FZL_OPCODE_ALLOC_OBJECT = 0xFA0001, // Allocate N slots FZL_OPCODE_ALLOC_OBJECT = 0xFA0001, // Allocate N slots
FZL_OPCODE_GET_FIELD = 0xFA0002, // Get field N of an object at dstack FZL_OPCODE_GET_FIELD = 0xFA0002, // Get field N of an object at dstack
@@ -35,6 +38,8 @@ typedef enum
FZL_OPCODE_MOD = 0xA00006, // Get module of two numbers in dstack FZL_OPCODE_MOD = 0xA00006, // Get module of two numbers in dstack
FZL_OPCODE_NEG = 0xA00007, // Negotiate number in dstack FZL_OPCODE_NEG = 0xA00007, // Negotiate number in dstack
FZL_OPCODE_BUILD_STR = 0xA10001, // Build a string from N values in dstack
FZL_OPCODE_CMP_EQ = 0xB00001, // Equal FZL_OPCODE_CMP_EQ = 0xB00001, // Equal
FZL_OPCODE_CMP_NEQ = 0xB00002, // Not equal FZL_OPCODE_CMP_NEQ = 0xB00002, // Not equal
FZL_OPCODE_CMP_LT = 0xB00003, // Less than FZL_OPCODE_CMP_LT = 0xB00003, // Less than
+4
View File
@@ -6,6 +6,10 @@ typedef enum
FZL_TYPE_NULL, FZL_TYPE_NULL,
FZL_TYPE_OBJECT, FZL_TYPE_OBJECT,
FZL_TYPE_EXTERN_FN,
FZL_TYPE_HANDLE,
FZL_TYPE_STRUCT,
FZL_TYPE_STRING, FZL_TYPE_STRING,
FZL_TYPE_CHAR, FZL_TYPE_CHAR,
FZL_TYPE_BOOL, FZL_TYPE_BOOL,
+79
View File
@@ -0,0 +1,79 @@
#ifndef FZL_ANALYZER_H
#define FZL_ANALYZER_H
#include <common/fzl_types.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
// Analyzing context type
typedef enum
{
FZL_AN_CTX_TYPE_UNNECESSARY, // default type
FZL_AN_CTX_TYPE_FUNCTION, // when analyzing function
FZL_AN_CTX_TYPE_LOOP, // when analyzing loop
FZL_AN_CTX_TYPE_CLASS, // when analyzing class
} fzl_an_ctx_type_t;
// Inner node analyzing result descriptor
typedef struct
{
bool error;
fzl_type_t type;
char *classname;
} fzl_an_res_t;
// Current node context descriptor
typedef struct fzl_an_ctx
{
struct fzl_an_ctx *parent;
fzl_an_ctx_type_t type;
fzl_symtable_t *symbols;
size_t symbols_level;
union
{
fzl_node_t *fn;
char *classname;
};
} fzl_an_ctx_t;
// Analyzer descriptor
typedef struct
{
char *warnings[256];
size_t warnings_top;
char *errors[256];
size_t errors_top;
fzl_symtable_t *symbols[256];
size_t symbols_top;
char *alloc_names[256];
size_t alloc_names_top;
fzl_node_t *root;
fzl_an_ctx_t *ctx;
} fzl_analyzer_t;
// Allocate analyzer
fzl_analyzer_t *fzl_mkanalyzer(fzl_node_t *node);
// Push error to errors list
bool an_push_error(fzl_analyzer_t *analyzer, fzl_token_t *tok, char *error);
// Push warning to warnings list
bool an_push_warning(fzl_analyzer_t *analyzer, fzl_token_t *tok, char *warning);
// Analyze AST
void fzl_analyze(fzl_analyzer_t *analyzer);
// Free analyzer
void fzl_freeanalyzer(fzl_analyzer_t *analyzer);
#endif // FZL_ANALYZER_H
+77
View File
@@ -0,0 +1,77 @@
#ifndef FZL_GENERATOR_H
#define FZL_GENERATOR_H
#include <common/fzl_extern.h>
#include <compiler/fzl_parser.h>
#include <compiler/utils/fzl_const_pool.h>
#include <compiler/utils/fzl_ctable.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
// Generator context type
typedef enum
{
FZL_GEN_CTX_TYPE_UNECCESSARY,
FZL_GEN_CTX_TYPE_FUNCTION,
FZL_GEN_CTX_TYPE_CLASS,
FZL_GEN_CTX_TYPE_LOOP
} fzl_gen_ctx_type_t;
// Generator context descriptor
typedef struct fzl_gen_ctx
{
fzl_gen_ctx_type_t type;
struct fzl_gen_ctx *parent;
size_t level;
union
{
fzl_node_t *function;
struct
{
size_t breaks[256];
size_t breaks_count;
} loop;
};
} fzl_gen_ctx_t;
// Generator descriptor
typedef struct
{
fzl_node_t *root;
fzl_const_hash_pool_t *consts;
fzl_gen_ctx_t *ctx;
size_t *ops;
size_t ops_count;
size_t ops_remainder;
fzl_symtable_t *syms[256];
size_t syms_top;
fzl_ctable_t *classes[64];
size_t classes_count;
fzl_extern_lib_t extern_libs[64];
size_t extern_libs_count;
fzl_extern_type_t extern_types[256];
size_t extern_types_count;
fzl_extern_fn_t extern_fns[256];
size_t extern_fns_count;
} fzl_gen_t;
// Allocate new generator
fzl_gen_t *fzl_mkgen(fzl_node_t *root);
// Run program generation
bool fzl_gen_run(fzl_gen_t *gen);
// Free generator
void fzl_freegen(fzl_gen_t *gen);
#endif // FZL_GENERATOR_H
+70 -1
View File
@@ -3,22 +3,40 @@
#include <compiler/fzl_reader.h> #include <compiler/fzl_reader.h>
#include <compiler/fzl_token.h> #include <compiler/fzl_token.h>
#include <stdbool.h>
#include <stddef.h> #include <stddef.h>
// AST node type // AST node type
typedef enum typedef enum
{ {
FZL_NODETYPE_TYPEDEF,
FZL_NODETYPE_HANDLE,
FZL_NODETYPE_ALIAS,
FZL_NODETYPE_STRUCT,
FZL_NODETYPE_REFERENCE,
FZL_NODETYPE_EXTERN_FN,
FZL_NODETYPE_EXTERN,
FZL_NODETYPE_BLOCK, FZL_NODETYPE_BLOCK,
FZL_NODETYPE_CALL,
FZL_NODETYPE_LITERAL, FZL_NODETYPE_LITERAL,
FZL_NODETYPE_FMT_STRING,
FZL_NODETYPE_IDENTIFIER, FZL_NODETYPE_IDENTIFIER,
FZL_NODETYPE_CONDITIONAL, FZL_NODETYPE_CONDITIONAL,
FZL_NODETYPE_FUNCTION, FZL_NODETYPE_FUNCTION,
FZL_NODETYPE_RETURN, FZL_NODETYPE_RETURN,
FZL_NODETYPE_CALL,
FZL_NODETYPE_CLASS, FZL_NODETYPE_CLASS,
FZL_NODETYPE_FIELD, FZL_NODETYPE_FIELD,
FZL_NODETYPE_CONSTRUCT, FZL_NODETYPE_CONSTRUCT,
FZL_NODETYPE_LOOP,
FZL_NODETYPE_BREAK,
FZL_NODETYPE_ADD, FZL_NODETYPE_ADD,
FZL_NODETYPE_SUB, FZL_NODETYPE_SUB,
FZL_NODETYPE_MUL, FZL_NODETYPE_MUL,
@@ -89,6 +107,7 @@ typedef struct fzl_node
{ {
fzl_token_t *type; fzl_token_t *type;
struct fzl_node *identifier; struct fzl_node *identifier;
bool is_out;
} var; } var;
// Conditional blocks // Conditional blocks
@@ -140,6 +159,56 @@ typedef struct fzl_node
{ {
struct fzl_node *name; struct fzl_node *name;
} construct; } construct;
// Loop
struct
{
struct fzl_node *init;
struct fzl_node *cond;
struct fzl_node *step;
struct fzl_node *body;
} loop;
// Extern library
struct
{
char *libname;
struct fzl_node **typedefs;
size_t typedefs_count;
struct fzl_node **fns;
size_t fns_count;
} ext;
// Type definition
struct
{
char *typename;
struct fzl_node *type;
} typedefinition;
// Structure
struct
{
char *original_name;
struct fzl_node **entries;
size_t entries_count;
} structure;
// External function
struct
{
char *name;
char *original_name;
fzl_token_t *type;
struct fzl_node **args;
size_t args_count;
} ext_fn;
}; };
} fzl_node_t; } fzl_node_t;
+45 -30
View File
@@ -8,53 +8,68 @@
// Token type // Token type
typedef enum typedef enum
{ {
FZL_TOKTYPE_CLASS, // class FZL_TOKTYPE_IMPORT, // `import`
FZL_TOKTYPE_NEW, // new FZL_TOKTYPE_EXTERN, // `extern`
FZL_TOKTYPE_TYPEDEF, // `type`
FZL_TOKTYPE_HANDLE, // `handle`
FZL_TOKTYPE_STRUCT, // `struct`
FZL_TOKTYPE_REFERENCE, // `ref`
FZL_TOKTYPE_OUT, // `out`
FZL_TOKTYPE_FUNCTION, // fn FZL_TOKTYPE_CLASS, // `class`
FZL_TOKTYPE_RETURN, // return FZL_TOKTYPE_NEW, // `new`
FZL_TOKTYPE_IF, // if FZL_TOKTYPE_FUNCTION, // `fn`
FZL_TOKTYPE_ELSE, // else FZL_TOKTYPE_RETURN, // `return`
FZL_TOKTYPE_FOR, // `for`
FZL_TOKTYPE_WHILE, // `while`
FZL_TOKTYPE_BREAK, // `break`
FZL_TOKTYPE_IF, // `if`
FZL_TOKTYPE_ELSE, // `else`
FZL_TOKTYPE_NAME, // abc FZL_TOKTYPE_NAME, // abc
FZL_TOKTYPE_TYPE, // i16 FZL_TOKTYPE_TYPE, // i16
FZL_TOKTYPE_DDASH, // // :D FZL_TOKTYPE_DDASH, // `//` :D
FZL_TOKTYPE_LPAREN, // ( FZL_TOKTYPE_LPAREN, // `(`
FZL_TOKTYPE_RPAREN, // ) FZL_TOKTYPE_RPAREN, // `)`
FZL_TOKTYPE_LBRACE, // { FZL_TOKTYPE_LBRACE, // `{`
FZL_TOKTYPE_RBRACE, // } FZL_TOKTYPE_RBRACE, // `}`
FZL_TOKTYPE_COMMA, // , FZL_TOKTYPE_COMMA, // `,`
FZL_TOKTYPE_DOT, // . FZL_TOKTYPE_DOT, // `.`
FZL_TOKTYPE_SEMICOLON, // ; FZL_TOKTYPE_SEMICOLON, // `;`
FZL_TOKTYPE_STR_LITERAL, // "" FZL_TOKTYPE_STR_LITERAL, // ""
FZL_TOKTYPE_NUM_LITERAL, // 123 FZL_TOKTYPE_NUM_LITERAL, // 123
FZL_TOKTYPE_BOOL_LITERAL, // true FZL_TOKTYPE_BOOL_LITERAL, // true
FZL_TOKTYPE_NULL_LITERAL, // null FZL_TOKTYPE_NULL_LITERAL, // null
FZL_TOKTYPE_DAMPERSAND, // && FZL_TOKTYPE_STR_FORMAT_START, // `$` before `"`
FZL_TOKTYPE_DVBAR, // || FZL_TOKTYPE_STR_FORMAT_END, // end of string formatting sequence
FZL_TOKTYPE_EQEQ, // == FZL_TOKTYPE_DAMPERSAND, // `&&`
FZL_TOKTYPE_REQ, // >= FZL_TOKTYPE_DVBAR, // `||`
FZL_TOKTYPE_LEQ, // <=
FZL_TOKTYPE_NEQ, // !=
FZL_TOKTYPE_LANGLE, // <
FZL_TOKTYPE_RANGLE, // >
FZL_TOKTYPE_NOT, // !
FZL_TOKTYPE_STAR, // * FZL_TOKTYPE_EQEQ, // `==`
FZL_TOKTYPE_SLASH, // / FZL_TOKTYPE_REQ, // `>=`
FZL_TOKTYPE_PLUS, // + FZL_TOKTYPE_LEQ, // `<=`
FZL_TOKTYPE_MINUS, // - FZL_TOKTYPE_NEQ, // `!=`
FZL_TOKTYPE_CARET, // ^ FZL_TOKTYPE_LANGLE, // `<`
FZL_TOKTYPE_PERCENT, // % FZL_TOKTYPE_RANGLE, // `>`
FZL_TOKTYPE_NOT, // `!`
FZL_TOKTYPE_EQ // = FZL_TOKTYPE_STAR, // `*`
FZL_TOKTYPE_SLASH, // `/`
FZL_TOKTYPE_PLUS, // `+`
FZL_TOKTYPE_MINUS, // `-`
FZL_TOKTYPE_CARET, // `^`
FZL_TOKTYPE_PERCENT, // `%`
FZL_TOKTYPE_EQ // `=`
} fzl_toktype_t; } fzl_toktype_t;
// Token descriptor // Token descriptor
-76
View File
@@ -1,76 +0,0 @@
#ifndef FZL_WALKER_H
#define FZL_WALKER_H
#include <common/fzl_opcodes.h>
#include <common/fzl_types.h>
#include <compiler/fzl_parser.h>
#include <compiler/utils/fzl_const_pool.h>
#include <compiler/utils/fzl_ctable.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
// Type of context
typedef enum
{
FZL_WALK_CTX_TYPE_GLOBAL,
FZL_WALK_CTX_TYPE_FN,
FZL_WALK_CTX_TYPE_CLASS,
FZL_WALK_CTX_TYPE_ASSIGN
} fzl_walk_ctx_type_t;
// Internal walk function result
typedef struct
{
fzl_type_t type;
char *error_msg;
bool error;
char *classname;
} fzl_walk_res_t;
// Function context descriptor
typedef struct fzl_walk_ctx
{
fzl_walk_ctx_type_t type;
struct fzl_walk_ctx *parent;
fzl_node_t *fn;
size_t initial_env_lvl;
} fzl_walk_ctx_t;
// Walker descriptor
typedef struct
{
fzl_node_t *root;
fzl_const_hash_pool_t *consts;
uint64_t *ops;
size_t op_count;
size_t op_remainder;
fzl_symtable_t *syms[64];
size_t sym_top;
fzl_walk_ctx_t *ctx;
fzl_ctable_t *classes[64];
size_t classes_count;
} fzl_walker_t;
// Allocate new walker
fzl_walker_t *fzl_mkwalker(fzl_node_t *root);
// Walk throught the entire AST and build:
// 1. Constants table
// 2. Operations
int fzl_walk(fzl_walker_t *walker);
// Get last error message
char *fzl_walker_geterror();
// Free walker
void fzl_freewalker(fzl_walker_t *walker);
#endif // FZL_WALKER_H
+2 -2
View File
@@ -1,7 +1,7 @@
#ifndef FZL_WRITER_H #ifndef FZL_WRITER_H
#define FZL_WRITER_H #define FZL_WRITER_H
#include <compiler/fzl_walker.h> #include <compiler/fzl_gen.h>
#include <compiler/utils/fzl_const_pool.h> #include <compiler/utils/fzl_const_pool.h>
// File writer descriptor // File writer descriptor
@@ -14,7 +14,7 @@ typedef struct
fzl_writer_t *fzl_mkwriter(const char *filepath); fzl_writer_t *fzl_mkwriter(const char *filepath);
// Write out a file // Write out a file
int fzl_write(fzl_writer_t *writer, fzl_walker_t *walker); int fzl_write(fzl_writer_t *writer, fzl_gen_t *gen);
// Get last writer error message // Get last writer error message
char *fzl_writer_geterror(); char *fzl_writer_geterror();
+45
View File
@@ -0,0 +1,45 @@
#ifndef INTERNALS_ANALYZER_H
#define INTERNALS_ANALYZER_H
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <stdbool.h>
extern char an_problem[256];
bool an_is_compatible(fzl_type_t a, fzl_type_t b, char *ac, char *bc);
char *an_typetostr(fzl_type_t type, char *classname);
fzl_type_t an_toktotype(fzl_analyzer_t *analyzer, fzl_token_t *tok,
bool *sym_found);
fzl_an_res_t analyze_common(fzl_analyzer_t *analyzer, fzl_node_t *node);
fzl_an_res_t analyze_call(fzl_analyzer_t *analyzer, fzl_node_t *call_node);
fzl_an_res_t analyze_identifier(fzl_analyzer_t *analyzer, fzl_node_t *id);
fzl_an_res_t analyze_conditional(fzl_analyzer_t *analyzer, fzl_node_t *cond);
fzl_an_res_t analyze_function(fzl_analyzer_t *analyzer, fzl_node_t *fn_node);
fzl_an_res_t analyze_block(fzl_analyzer_t *analyzer, fzl_node_t *block_node);
fzl_an_res_t analyze_return(fzl_analyzer_t *analyzer, fzl_node_t *ret_node);
fzl_an_res_t analyze_class(fzl_analyzer_t *analyzer, fzl_node_t *class_node);
fzl_an_res_t analyze_field(fzl_analyzer_t *analyzer, fzl_node_t *field);
fzl_an_res_t analyze_declaration(fzl_analyzer_t *analyzer, fzl_node_t *decl);
fzl_an_res_t analyze_construct(fzl_analyzer_t *analyzer, fzl_node_t *construct);
fzl_an_res_t analyze_loop(fzl_analyzer_t *analyzer, fzl_node_t *loop_node);
fzl_an_res_t analyze_break(fzl_analyzer_t *analyzer, fzl_node_t *break_node);
fzl_an_res_t analyze_binmath(fzl_analyzer_t *analyzer, fzl_node_t *bin_node);
fzl_an_res_t analyze_unarymath(fzl_analyzer_t *analyzer, fzl_node_t *unary);
fzl_an_res_t analyze_condition(fzl_analyzer_t *analyzer, fzl_node_t *cond_node);
fzl_an_res_t analyze_unarycond(fzl_analyzer_t *analyzer, fzl_node_t *unary);
fzl_an_res_t analyze_assign(fzl_analyzer_t *analyzer, fzl_node_t *assign_node);
fzl_an_res_t analyze_strfmt(fzl_analyzer_t *analyzer, fzl_node_t *strfmt_node);
fzl_an_res_t analyze_typedef(fzl_analyzer_t *analyzer, fzl_node_t *td_node);
fzl_an_res_t analyze_struct(fzl_analyzer_t *analyzer, fzl_node_t *struct_node);
fzl_an_res_t analyze_ref(fzl_analyzer_t *analyzer, fzl_node_t *ref_node);
fzl_an_res_t analyze_externfn(fzl_analyzer_t *analyzer, fzl_node_t *externfn);
fzl_an_res_t analyze_extern(fzl_analyzer_t *analyzer, fzl_node_t *extern_node);
fzl_an_ctx_t *an_nest_ctx(fzl_analyzer_t *analyzer, fzl_an_ctx_type_t type);
fzl_an_ctx_t *an_fin_ctx(fzl_analyzer_t *analyzer);
#endif // INTERNALS_ANALYZER_H
+69
View File
@@ -0,0 +1,69 @@
#ifndef INTERNALS_GEN_H
#define INTERNALS_GEN_H
#include <common/fzl_extern.h>
#include <common/fzl_opcodes.h>
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/utils/fzl_const_pool.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
typedef struct
{
bool error;
fzl_type_t type;
char *classname;
} gen_res_t;
extern gen_res_t gen_error;
extern gen_res_t gen_ok_null;
extern char *null_name;
extern fzl_extern_type_t type_buf;
bool gen_resolve_name(fzl_gen_t *gen, char *name, fzl_sym_t *sym);
bool gen_resolve_type(fzl_gen_t *gen, fzl_token_t *tok, fzl_type_t *t, char *c);
ssize_t gen_resolve_extern_type(fzl_gen_t *gen, char *name);
bool gen_is_types_compatible(fzl_type_t t1, fzl_type_t t2, char *c1, char *c2);
size_t gen_add_const(fzl_gen_t *gen, fzl_const_t c);
void gen_op(fzl_gen_t *gen, fzl_opcode_t opcode);
void gen_word(fzl_gen_t *gen, size_t word);
fzl_gen_ctx_t *gen_ctx(fzl_gen_t *gen, fzl_gen_ctx_type_t type,
fzl_node_t *node);
fzl_gen_ctx_t *gen_fin_ctx(fzl_gen_t *gen);
gen_res_t gen_common(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_extern(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_externfn(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_reference(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_struct(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_alias(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_handle(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_typedef(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_fmtstr(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_break(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_loop(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_class(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_construct(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_field(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_fn(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_return(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_unary_logical(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_compare(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_logical(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_condition(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_unary_math(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_declaration(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_identifier(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_block(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_call(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_literal(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_math(fzl_gen_t *gen, fzl_node_t *node);
gen_res_t gen_assign(fzl_gen_t *gen, fzl_node_t *node);
#endif // FZL_INTERNALS_GEN_H
+51
View File
@@ -0,0 +1,51 @@
#ifndef INTERNALS_PARSER_H
#define INTERNALS_PARSER_H
#include "compiler/fzl_parser.h"
#include "compiler/fzl_token.h"
extern char plast_err[256];
extern fzl_token_t *last_known_tok;
extern fzl_token_t null_tok;
extern fzl_token_t this_tok;
fzl_token_t *peek(fzl_parser_t *parser);
fzl_token_t *consume(fzl_parser_t *parser);
bool is(fzl_parser_t *parser, fzl_toktype_t type);
fzl_nodetype_t math_op_to_type(fzl_toktype_t type);
fzl_nodetype_t unary_op_to_type(fzl_toktype_t type);
fzl_node_t *pa_primary(fzl_parser_t *parser);
fzl_node_t *pa_postfix(fzl_parser_t *parser);
fzl_node_t *pa_unary(fzl_parser_t *parser);
fzl_node_t *pa_power(fzl_parser_t *parser);
fzl_node_t *pa_factor(fzl_parser_t *parser);
fzl_node_t *pa_term(fzl_parser_t *parser);
fzl_node_t *pa_cond(fzl_parser_t *parser);
fzl_node_t *pa_and(fzl_parser_t *parser);
fzl_node_t *pa_or(fzl_parser_t *parser);
fzl_node_t *pa_new(fzl_parser_t *parser);
fzl_node_t *pa_assignment(fzl_parser_t *parser);
fzl_node_t *pa_expression(fzl_parser_t *parser);
fzl_node_t *pa_struct(fzl_parser_t *parser);
fzl_node_t *pa_ref(fzl_parser_t *parser);
fzl_node_t *pa_typedef(fzl_parser_t *parser);
fzl_node_t *pa_externfn(fzl_parser_t *parser);
fzl_node_t *pa_class(fzl_parser_t *parser);
fzl_node_t *pa_function(fzl_parser_t *parser);
fzl_node_t *pa_return(fzl_parser_t *parser);
fzl_node_t *pa_if(fzl_parser_t *parser);
fzl_node_t *pa_block(fzl_parser_t *parser);
fzl_node_t *pa_for(fzl_parser_t *parser);
fzl_node_t *pa_while(fzl_parser_t *parser);
fzl_node_t *pa_loop(fzl_parser_t *parser);
fzl_node_t *pa_break(fzl_parser_t *parser);
fzl_node_t *pa_extern(fzl_parser_t *parser);
fzl_node_t *pa_statement(fzl_parser_t *parser);
fzl_node_t *pa_program(fzl_parser_t *parser);
#endif // INTERNALS_PARSER_H
+19
View File
@@ -0,0 +1,19 @@
#ifndef INTERNALS_READER_H
#define INTERNALS_READER_H
#include <compiler/fzl_reader.h>
#include <stddef.h>
extern char last_err[256];
size_t move(fzl_reader_t *reader, size_t len);
void rd_comment(fzl_reader_t *reader);
fzl_token_t *rd_name(fzl_reader_t *reader);
fzl_token_t *rd_string_literal(fzl_reader_t *reader);
fzl_token_t *rd_number(fzl_reader_t *reader);
fzl_token_t *rd_single(fzl_reader_t *reader, fzl_toktype_t type);
fzl_token_t *rd_double(fzl_reader_t *reader, fzl_toktype_t type);
fzl_token_t *rd_fmtstr(fzl_reader_t *reader);
#endif // INTERNALS_READER_H
+16
View File
@@ -0,0 +1,16 @@
#ifndef INTERNALS_WRITER_H
#define INTERNALS_WRITER_H
#include <common/fzl_extern.h>
#include <compiler/utils/fzl_const_pool.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
bool wr_consts(FILE *fd, fzl_const_hash_pool_t *consts);
bool wr_extern_libs(FILE *fd, fzl_extern_lib_t *libs, size_t libs_count);
bool wr_extern_types(FILE *fd, fzl_extern_type_t *types, size_t types_count);
bool wr_extern_fns(FILE *fd, fzl_extern_fn_t *fns, size_t fns_count);
bool wr_ops(FILE *fd, size_t *ops, size_t ops_count);
#endif // INTERNALS_WRITER_H
+12 -2
View File
@@ -2,6 +2,7 @@
#define FZL_SYMTABLE_H #define FZL_SYMTABLE_H
#include <common/fzl_types.h> #include <common/fzl_types.h>
#include <compiler/fzl_parser.h>
#include <stdbool.h> #include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
@@ -19,8 +20,12 @@ typedef struct
{ {
char *name; char *name;
fzl_type_t type; fzl_type_t type;
fzl_node_t *node;
size_t ip; size_t ip;
bool slot_set;
size_t slot;
char *classname; char *classname;
} fzl_sym_t; } fzl_sym_t;
@@ -30,6 +35,8 @@ typedef struct
size_t size; size_t size;
size_t remainder; size_t remainder;
size_t free_slot;
fzl_sym_t *symbols; fzl_sym_t *symbols;
} fzl_symtable_t; } fzl_symtable_t;
@@ -37,13 +44,16 @@ typedef struct
fzl_symtable_t *fzl_mksymt(); fzl_symtable_t *fzl_mksymt();
// Put new entry into symtable // Put new entry into symtable
fzl_symtable_res_t fzl_symt_put(fzl_symtable_t *symt, char *name, fzl_symtable_res_t fzl_symt_put(fzl_symtable_t *symt, fzl_node_t *node,
fzl_type_t type, uint64_t ip); char *name, fzl_type_t type, uint64_t ip);
// Assign class name to object type // Assign class name to object type
fzl_symtable_res_t fzl_symt_setobjclass(fzl_symtable_t *symt, char *name, fzl_symtable_res_t fzl_symt_setobjclass(fzl_symtable_t *symt, char *name,
char *classname); char *classname);
// Assign a local slot to a variable
int fzl_symt_setslot(fzl_symtable_t *symt, char *name);
// Get entry from specified symtable // Get entry from specified symtable
bool fzl_symt_get(fzl_symtable_t *symt, char *name, fzl_sym_t *res); bool fzl_symt_get(fzl_symtable_t *symt, char *name, fzl_sym_t *res);
+9 -9
View File
@@ -1,24 +1,24 @@
#ifndef FZL_VM_H #ifndef FZL_VM_H
#define FZL_VM_H #define FZL_VM_H
#include <common/fzl_value.h> #include <stdbool.h>
#include <compiler/utils/fzl_const_pool.h> // NOTE: move outside compiler scope to common
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <vm/fzl_vm_env.h> #include <vm/fzl_vm_env.h>
#include <vm/fzl_vm_object.h> #include <vm/fzl_vm_extern.h>
#include <vm/fzl_vm_reader.h>
// VM descriptor // VM descriptor
typedef struct typedef struct
{ {
fzl_const_t *consts; fzl_vm_reader_t *reader;
size_t consts_count; fzl_vm_extern_t *prep_fns;
uint64_t *ops;
size_t ops_count;
size_t ip; size_t ip;
bool allow_infinite;
size_t max_iter;
// Data stack // Data stack
fzl_value_t dstack[256]; fzl_value_t dstack[256];
size_t dtop; size_t dtop;
@@ -33,7 +33,7 @@ typedef struct
} fzl_vm_t; } fzl_vm_t;
// Allocate FZL VM // Allocate FZL VM
fzl_vm_t *fzl_mkvm(const char *filepath); fzl_vm_t *fzl_mkvm(fzl_vm_reader_t *reader);
// Load and run code // Load and run code
int fzl_vm_run(fzl_vm_t *vm); int fzl_vm_run(fzl_vm_t *vm);
+35
View File
@@ -0,0 +1,35 @@
#ifndef FZL_VM_EXTERN_H
#define FZL_VM_EXTERN_H
#include <ffi.h>
#include <stddef.h>
#include <vm/fzl_vm_reader.h>
// Loaded extern function definition
typedef struct
{
void *func_ptr;
ffi_cif cif;
ffi_type **arg_types;
} fzl_vm_sym_t;
// Extern object descriptor
typedef struct
{
void **libs;
size_t libs_loaded;
fzl_vm_sym_t *syms;
size_t syms_loaded;
} fzl_vm_extern_t;
// Load externs
fzl_vm_extern_t *fzl_vm_init_externs(fzl_vm_reader_t *reader);
// Get last error from externs loader
char *fzl_vm_externs_geterror();
// Close and free externs
void fzl_vm_free_externs(fzl_vm_extern_t *ex);
#endif // FZL_VM_EXTERN_H
+43
View File
@@ -0,0 +1,43 @@
#ifndef FZL_VM_READER_H
#define FZL_VM_READER_H
#include <common/fzl_extern.h>
#include <common/fzl_value.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
// Binary file reader descriptor
typedef struct
{
char *filepath;
fzl_value_t *consts;
uint16_t consts_count;
size_t *ops;
size_t ops_count;
char **extern_libs;
uint16_t extern_libs_count;
fzl_extern_type_t *extern_types;
uint16_t extern_types_count;
fzl_extern_fn_t *extern_fns;
uint16_t extern_fns_count;
} fzl_vm_reader_t;
// Allocate binary file reader
fzl_vm_reader_t *fzl_vm_mkreader(char *filepath);
// Read the file
bool fzl_vm_read(fzl_vm_reader_t *reader);
// Get last error message from the reader
char *fzl_vm_getreadererror();
// Free file reader
void fzl_vm_freereader(fzl_vm_reader_t *reader);
#endif // FZL_VM_READER_H
+112
View File
@@ -0,0 +1,112 @@
#ifndef INTERNALS_OPCODE_H
#define INTERNALS_OPCODE_H
#include "vm/fzl_vm.h"
#include <stddef.h>
// Opcode handler descriptor
typedef int (*opcode_handler)(fzl_vm_t *);
extern char last_err[512];
extern size_t last_jmp_ip;
extern size_t total_jmp_on_same;
void print_object(fzl_vm_object_t *obj);
void print_err_data(fzl_vm_t *vm);
void escape_recursive(fzl_vm_env_t *current, fzl_vm_env_t *parent,
fzl_vm_object_t *obj);
// --- stack ---
extern const opcode_handler group_stack[];
int op_loadconst(fzl_vm_t *vm);
int op_call_builtin(fzl_vm_t *vm);
int op_pushnum(fzl_vm_t *vm);
int op_pushbool(fzl_vm_t *vm);
// --- context ---
extern const opcode_handler group_ctx[];
int op_mk_envtable(fzl_vm_t *vm);
int op_rm_envtable(fzl_vm_t *vm);
int op_store(fzl_vm_t *vm);
int op_lookup_env(fzl_vm_t *vm);
int op_write(fzl_vm_t *vm);
int op_load_local(fzl_vm_t *vm);
int op_store_local(fzl_vm_t *vm);
// --- flow ---
extern const opcode_handler group_flow[];
int op_jmp(fzl_vm_t *vm);
int op_jz(fzl_vm_t *vm);
// --- functions ---
extern const opcode_handler group_fn[];
int op_call(fzl_vm_t *vm);
int op_ret(fzl_vm_t *vm);
int op_call_extern(fzl_vm_t *vm);
// --- objects ---
extern const opcode_handler group_obj[];
int op_alloc_object(fzl_vm_t *vm);
int op_get_field(fzl_vm_t *vm);
int op_set_field(fzl_vm_t *vm);
int op_escape_object(fzl_vm_t *vm);
int op_dereference(fzl_vm_t *vm);
// --- math ---
extern const opcode_handler group_math[];
int op_add(fzl_vm_t *vm);
int op_sub(fzl_vm_t *vm);
int op_mul(fzl_vm_t *vm);
int op_div(fzl_vm_t *vm);
int op_pow(fzl_vm_t *vm);
int op_mod(fzl_vm_t *vm);
int op_neg(fzl_vm_t *vm);
// --- strings ---
extern const opcode_handler group_str[];
int op_build_str(fzl_vm_t *vm);
// --- conditions ---
extern const opcode_handler group_cmp[];
int op_cmp_eq(fzl_vm_t *vm);
int op_cmp_neq(fzl_vm_t *vm);
int op_cmp_lt(fzl_vm_t *vm);
int op_cmp_lteq(fzl_vm_t *vm);
int op_cmp_gt(fzl_vm_t *vm);
int op_cmp_gteq(fzl_vm_t *vm);
extern const opcode_handler group_strcmp[];
int op_cmp_eq_str(fzl_vm_t *vm);
int op_cmp_neq_str(fzl_vm_t *vm);
extern const opcode_handler group_objcmp[];
int op_cmp_eq_obj(fzl_vm_t *vm);
int op_cmp_neq_obj(fzl_vm_t *vm);
extern const opcode_handler group_and_or[];
int op_and(fzl_vm_t *vm);
int op_or(fzl_vm_t *vm);
extern const opcode_handler group_not[];
int op_not(fzl_vm_t *vm);
// ------------------------
extern const opcode_handler *const master_tbl[];
#endif // INTERNALS_OPCODE_H
+24
View File
@@ -0,0 +1,24 @@
#ifndef INTERNALS_VM_READER_H
#define INTERNALS_VM_READER_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <vm/fzl_vm_reader.h>
extern char internal_error[256];
bool vm_rd_char(FILE *fd, size_t count, char *outbuf);
bool vm_rd_u16(FILE *fd, size_t count, uint16_t *outbuf);
bool vm_rd_word(FILE *fd, size_t count, size_t *outbuf);
bool vm_rd_header(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_sections_sz(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_consts(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_extern_libs(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_extern_types(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_extern_fns(fzl_vm_reader_t *reader, FILE *fd);
bool vm_rd_ops(fzl_vm_reader_t *reader, FILE *fd);
#endif // INTERNALS_VM_READER_H
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Run an FZL VM benchmark and report wall-clock timing statistics."""
import argparse
import statistics
import subprocess
import sys
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--runs", type=int, default=7, help="measured runs")
parser.add_argument("--warmup", type=int, default=2, help="warm-up runs")
parser.add_argument("--max-iter", type=int, default=2_000_000)
parser.add_argument("--vm", required=True, help="path to the fz executable")
parser.add_argument("--program", required=True, help="compiled .fzb program")
args = parser.parse_args()
if args.runs < 1 or args.warmup < 0 or args.max_iter < 1:
parser.error("runs/max-iter must be positive and warmup must be non-negative")
command = [args.vm, "--max-iter", str(args.max_iter), args.program]
for _ in range(args.warmup):
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
sys.stderr.write(result.stdout)
sys.stderr.write(result.stderr)
raise SystemExit(result.returncode)
measurements = []
for _ in range(args.runs):
start = time.perf_counter()
result = subprocess.run(
command, capture_output=True, text=True
)
elapsed = time.perf_counter() - start
if result.returncode != 0:
sys.stderr.write(result.stdout)
sys.stderr.write(result.stderr)
raise SystemExit(result.returncode)
measurements.append(elapsed)
print(f"Runs: {args.runs} (warm-up: {args.warmup})")
print(f"Median: {statistics.median(measurements):.6f} s")
print(f"Mean: {statistics.mean(measurements):.6f} s")
print(f"Min: {min(measurements):.6f} s")
print(f"Max: {max(measurements):.6f} s")
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stdio.h>
// Analyze assigns
fzl_an_res_t analyze_assign(fzl_analyzer_t *analyzer, fzl_node_t *assign_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!assign_node || assign_node->type != FZL_NODETYPE_ASSIGN)
{
an_push_error(analyzer, NULL, "node is not assignment");
return (fzl_an_res_t){.error = true};
}
fzl_node_t *left = assign_node->binary_op.left;
fzl_an_res_t leftside = analyze_common(analyzer, left);
if (leftside.error)
return (fzl_an_res_t){.error = true};
fzl_an_res_t rightside =
analyze_common(analyzer, assign_node->binary_op.right);
if (rightside.error)
return (fzl_an_res_t){.error = true};
if (left->type != FZL_NODETYPE_DECLARATION &&
left->type != FZL_NODETYPE_IDENTIFIER && left->type != FZL_NODETYPE_FIELD)
{
an_push_error(analyzer, left->token,
"left side must be one of these: declaration, identifier or "
"field access");
return (fzl_an_res_t){.error = true};
}
if (!an_is_compatible(leftside.type, rightside.type, leftside.classname,
rightside.classname))
{
snprintf(an_problem, sizeof(an_problem),
"incompatible types - '%s' is expected, got '%s'",
an_typetostr(leftside.type, leftside.classname),
an_typetostr(rightside.type, rightside.classname));
an_push_error(analyzer, assign_node->binary_op.right->token, an_problem);
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
}
+51
View File
@@ -0,0 +1,51 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stdio.h>
// Analyze binary arithmetics
fzl_an_res_t analyze_binmath(fzl_analyzer_t *analyzer, fzl_node_t *bin_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!bin_node || (bin_node->type != FZL_NODETYPE_ADD &&
bin_node->type != FZL_NODETYPE_SUB &&
bin_node->type != FZL_NODETYPE_MUL &&
bin_node->type != FZL_NODETYPE_DIV &&
bin_node->type != FZL_NODETYPE_POW &&
bin_node->type != FZL_NODETYPE_MOD))
{
an_push_error(analyzer, NULL, "node is not binary math operator");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t left = analyze_common(analyzer, bin_node->binary_op.left);
if (left.error)
return (fzl_an_res_t){.error = true};
fzl_an_res_t right = analyze_common(analyzer, bin_node->binary_op.right);
if (right.error)
return (fzl_an_res_t){.error = true};
if (left.type < FZL_TYPE_INT8)
{
snprintf(an_problem, sizeof(an_problem),
"integer type is expected, got '%s'",
an_typetostr(left.type, left.classname));
an_push_error(analyzer, bin_node->binary_op.left->token, an_problem);
return (fzl_an_res_t){.error = true};
}
if (right.type < FZL_TYPE_INT8)
{
snprintf(an_problem, sizeof(an_problem),
"integer type is expected, got '%s'",
an_typetostr(right.type, right.classname));
an_push_error(analyzer, bin_node->binary_op.right->token, an_problem);
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){.error = false, .type = left.type, .classname = NULL};
}
+99
View File
@@ -0,0 +1,99 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
// Analyze block
fzl_an_res_t analyze_block(fzl_analyzer_t *analyzer, fzl_node_t *block_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!block_node || block_node->type != FZL_NODETYPE_BLOCK)
{
snprintf(an_problem, sizeof(an_problem), "node is not a block");
an_push_error(analyzer, NULL, an_problem);
return (fzl_an_res_t){.error = true};
}
an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_UNNECESSARY);
bool has_return = false;
bool error = false;
for (size_t i = 0; i < block_node->list.entry_count; i++)
{
if (has_return)
an_push_warning(analyzer, block_node->list.entries[i]->token,
"this statement will never execute");
fzl_an_res_t entry_res =
analyze_common(analyzer, block_node->list.entries[i]);
if (entry_res.error)
error = true;
if (block_node->list.entries[i]->type == FZL_NODETYPE_RETURN)
has_return = true;
}
fzl_an_ctx_t *fnctx = analyzer->ctx;
while (fnctx != NULL)
{
if (fnctx && fnctx->type == FZL_AN_CTX_TYPE_FUNCTION)
break;
fnctx = fnctx->parent;
}
if (fnctx && fnctx->type == FZL_AN_CTX_TYPE_FUNCTION)
{
bool found = false;
fzl_type_t rettype = an_toktotype(analyzer, fnctx->fn->fn.type, &found);
char *classname = NULL;
char *rettype_str = an_typetostr(rettype, classname);
if (!found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)fnctx->fn->fn.type->value);
an_push_error(analyzer, fnctx->fn->fn.type, an_problem);
return (fzl_an_res_t){.error = true};
}
if (rettype == FZL_TYPE_OBJECT)
classname = (char *)fnctx->fn->fn.type->value;
if (rettype != FZL_TYPE_NULL)
{
if (!has_return || block_node->list.entry_count < 1)
{
snprintf(an_problem, sizeof(an_problem),
"'return <%s>' is expected in the function with non-null "
"return type",
rettype_str);
an_push_error(analyzer, block_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
fzl_node_t *last_node =
block_node->list.entries[block_node->list.entry_count - 1];
if (last_node->type != FZL_NODETYPE_RETURN)
{
// NOTE: replace with ghost walker to check if all branch return an
// expected value type
snprintf(an_problem, sizeof(an_problem),
"expected last statement in block to be 'return <%s>'",
rettype_str);
an_push_error(analyzer, last_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
}
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = error, .type = FZL_TYPE_NULL};
}
+36
View File
@@ -0,0 +1,36 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
// Analyze break node
fzl_an_res_t analyze_break(fzl_analyzer_t *analyzer, fzl_node_t *break_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!break_node || break_node->type != FZL_NODETYPE_BREAK)
{
an_push_error(analyzer, NULL, "node is not a break statement");
return (fzl_an_res_t){.error = true};
}
fzl_an_ctx_t *ctx = analyzer->ctx;
while (ctx != NULL)
{
if (ctx && ctx->type == FZL_AN_CTX_TYPE_LOOP)
break;
ctx = ctx->parent;
}
if (!ctx || ctx->type != FZL_AN_CTX_TYPE_LOOP)
{
an_push_error(analyzer, break_node->token,
"cannot use 'break' outside the loop");
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
}
+278
View File
@@ -0,0 +1,278 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *tmp_method_name = NULL;
char *tmp_fnname = NULL;
char *tmp_classname = NULL;
// Try to get symbol name from callee
char *resolve_callee(fzl_analyzer_t *analyzer, fzl_node_t *callee, bool *method)
{
*method = false;
if (callee->type == FZL_NODETYPE_IDENTIFIER)
return (char *)callee->token->value;
if (callee->type != FZL_NODETYPE_FIELD)
{
an_push_error(analyzer, callee->token, "unknown call format");
return NULL;
}
*method = true;
fzl_an_res_t parent_res = analyze_common(analyzer, callee->memb.parent);
if (parent_res.type != FZL_TYPE_OBJECT || !parent_res.classname)
return NULL;
char *fn_name = callee->memb.field->token->value;
tmp_fnname = fn_name;
tmp_classname = parent_res.classname;
size_t classname_len = strlen(parent_res.classname);
size_t methodname_len = strlen(fn_name);
tmp_method_name = malloc(classname_len + methodname_len + 2);
if (!tmp_method_name)
{
an_push_error(analyzer, callee->token, "out of memory");
return NULL;
}
strcpy(tmp_method_name, parent_res.classname);
tmp_method_name[classname_len] = '_';
strcpy(tmp_method_name + classname_len + 1, fn_name);
tmp_method_name[classname_len + methodname_len + 1] = 0;
return tmp_method_name;
}
// Analyze call node
fzl_an_res_t analyze_call(fzl_analyzer_t *analyzer, fzl_node_t *call_node)
{
if (!call_node || call_node->type != FZL_NODETYPE_CALL)
{
an_push_error(analyzer, NULL, "node is not call");
return (fzl_an_res_t){.error = true};
}
fzl_node_t *callee = call_node->call.callee;
bool is_method = false;
char *callee_name = resolve_callee(analyzer, callee, &is_method);
if (!callee_name)
{
an_push_error(analyzer, callee->token, "expression is not callable");
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
// NOTE: move into `compiler/analyzer/builtins.c`
if (strcmp(callee_name, "printline") == 0 || strcmp(callee_name, "exit") == 0)
{
if (call_node->call.args_count != 1)
{
snprintf(an_problem, sizeof(an_problem),
"'%s' builtin should be called with 1 argument instead of %zu",
callee_name, call_node->call.args_count);
an_push_error(analyzer, call_node->token, an_problem);
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
}
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], callee_name, &sym)))
break;
}
if (!sym_found)
{
snprintf(an_problem, sizeof(an_problem), "cannot resolve symbol '%s'",
callee_name);
an_push_error(analyzer, call_node->token, an_problem);
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
if (sym.node->type != FZL_NODETYPE_FUNCTION &&
sym.node->type != FZL_NODETYPE_EXTERN_FN)
{
snprintf(an_problem, sizeof(an_problem), "'%s' is not callable",
callee_name);
an_push_error(analyzer, call_node->token, an_problem);
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
size_t offset = is_method ? 1 : 0;
size_t args_count = sym.node->type == FZL_NODETYPE_EXTERN_FN
? sym.node->ext_fn.args_count
: sym.node->fn.args_count;
if ((args_count - offset) != call_node->call.args_count)
{
if (is_method)
{
snprintf(an_problem, sizeof(an_problem),
"method '%s.%s' is expecting %zu argument(s), got %zu",
tmp_classname, tmp_fnname, args_count,
call_node->call.args_count - offset);
}
else
{
snprintf(an_problem, sizeof(an_problem),
"function '%s' is expecting %zu argument(s), got %zu",
callee_name, args_count, call_node->call.args_count - offset);
}
an_push_error(analyzer, call_node->token, an_problem);
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
fzl_node_t **args = sym.node->type == FZL_NODETYPE_EXTERN_FN
? sym.node->ext_fn.args
: sym.node->fn.args;
for (size_t i = offset; i < sym.node->fn.args_count; i++)
{
fzl_node_t *arg = args[i];
bool found = false;
fzl_type_t req_type = an_toktotype(analyzer, arg->var.type, &found);
char *req_classname = NULL;
if (!found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)arg->var.type->value);
an_push_error(analyzer, arg->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
if (req_type == FZL_TYPE_OBJECT)
req_classname = arg->var.type->value;
fzl_an_res_t got =
analyze_common(analyzer, call_node->call.args[i - offset]);
if (got.error)
{
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
if (!an_is_compatible(req_type, got.type, req_classname, got.classname))
{
if (is_method)
{
snprintf(an_problem, sizeof(an_problem),
"method '%s.%s' is expecting %zu argument to have type '%s', "
"got '%s'",
tmp_classname, tmp_fnname, i + 1 - offset,
an_typetostr(req_type, req_classname),
an_typetostr(got.type, got.classname));
}
else
{
snprintf(an_problem, sizeof(an_problem),
"function '%s' is expecting %zu argument to have type '%s', "
"got '%s'",
callee_name, i + 1 - offset,
an_typetostr(req_type, req_classname),
an_typetostr(got.type, got.classname));
}
an_push_error(analyzer, call_node->token, an_problem);
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = true};
}
}
bool type_found = false;
fzl_token_t *ret_tok = NULL;
void *ret_name = NULL;
if (sym.node->type == FZL_NODETYPE_EXTERN_FN)
{
ret_tok = sym.node->ext_fn.type;
ret_name = sym.node->ext_fn.name;
}
else
{
ret_tok = sym.node->fn.type;
ret_name = sym.node->fn.name;
}
fzl_type_t type = an_toktotype(analyzer, ret_tok, &type_found);
char *classname = sym.classname;
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)ret_name);
an_push_error(analyzer, ret_tok, an_problem);
return (fzl_an_res_t){.error = true};
}
if (tmp_method_name != NULL)
{
free(tmp_method_name);
tmp_method_name = NULL;
}
return (fzl_an_res_t){.error = false, .type = type, .classname = classname};
}
+72
View File
@@ -0,0 +1,72 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdio.h>
// Analyze class declaration
fzl_an_res_t analyze_class(fzl_analyzer_t *analyzer, fzl_node_t *class_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!class_node || class_node->type != FZL_NODETYPE_CLASS)
{
an_push_error(analyzer, NULL, "node is not class");
return (fzl_an_res_t){.error = true};
}
char *classname = (char *)class_node->class.name->value;
fzl_an_ctx_t *ctx = an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_CLASS);
ctx->classname = classname;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], classname, &sym)))
break;
}
fzl_symtable_res_t res =
fzl_symt_put(analyzer->symbols[analyzer->symbols_top - 2], class_node,
classname, FZL_TYPE_NULL, 0);
if (res != FZL_SYMTABLE_RESULT_OK)
{
if (res == FZL_SYMTABLE_RESULT_EXISTS)
{
snprintf(an_problem, sizeof(an_problem),
"name '%s' already has been declared", classname);
an_push_error(analyzer, class_node->token, an_problem);
}
else
{
snprintf(an_problem, sizeof(an_problem), "cannot store name '%s'",
classname);
an_push_error(analyzer, class_node->token, an_problem);
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = true};
}
bool error = false;
for (size_t i = 0; i < class_node->class.fields_count; i++)
{
fzl_an_res_t res = analyze_common(analyzer, class_node->class.fields[i]);
if (res.error)
error = true;
}
for (size_t i = 0; i < class_node->class.methods_count; i++)
{
fzl_an_res_t res = analyze_common(analyzer, class_node->class.methods[i]);
if (res.error)
error = true;
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = error, .type = FZL_TYPE_NULL};
}
+161
View File
@@ -0,0 +1,161 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
// Analyzer main function
fzl_an_res_t analyze_common(fzl_analyzer_t *analyzer, fzl_node_t *node)
{
if (!analyzer || !node)
return (fzl_an_res_t){.error = true};
fzl_an_res_t res = {.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
switch (node->type)
{
case FZL_NODETYPE_EXTERN:
res = analyze_extern(analyzer, node);
break;
case FZL_NODETYPE_EXTERN_FN:
res = analyze_externfn(analyzer, node);
break;
case FZL_NODETYPE_REFERENCE:
res = analyze_ref(analyzer, node);
break;
case FZL_NODETYPE_STRUCT:
res = analyze_struct(analyzer, node);
break;
case FZL_NODETYPE_ALIAS:
res.type = an_toktotype(analyzer, node->token, NULL);
break;
case FZL_NODETYPE_HANDLE:
res.type = FZL_TYPE_HANDLE;
break;
case FZL_NODETYPE_TYPEDEF:
res = analyze_typedef(analyzer, node);
break;
case FZL_NODETYPE_FMT_STRING:
res = analyze_strfmt(analyzer, node);
break;
case FZL_NODETYPE_ASSIGN:
res = analyze_assign(analyzer, node);
break;
case FZL_NODETYPE_NOT:
res = analyze_unarycond(analyzer, node);
break;
case FZL_NODETYPE_OR:
case FZL_NODETYPE_AND:
case FZL_NODETYPE_LESS:
case FZL_NODETYPE_LESS_EQUAL:
case FZL_NODETYPE_GREATER:
case FZL_NODETYPE_GREATER_EQUAL:
case FZL_NODETYPE_EQUAL:
case FZL_NODETYPE_NEQUAL:
res = analyze_condition(analyzer, node);
break;
case FZL_NODETYPE_UNARY_MINUS:
case FZL_NODETYPE_UNARY_PLUS:
res = analyze_unarymath(analyzer, node);
break;
case FZL_NODETYPE_ADD:
case FZL_NODETYPE_SUB:
case FZL_NODETYPE_MUL:
case FZL_NODETYPE_DIV:
case FZL_NODETYPE_POW:
case FZL_NODETYPE_MOD:
res = analyze_binmath(analyzer, node);
break;
case FZL_NODETYPE_BREAK:
res = analyze_break(analyzer, node);
break;
case FZL_NODETYPE_LOOP:
res = analyze_loop(analyzer, node);
break;
case FZL_NODETYPE_CONSTRUCT:
res = analyze_construct(analyzer, node);
break;
case FZL_NODETYPE_DECLARATION:
res = analyze_declaration(analyzer, node);
break;
case FZL_NODETYPE_FIELD:
res = analyze_field(analyzer, node);
break;
case FZL_NODETYPE_CLASS:
res = analyze_class(analyzer, node);
break;
case FZL_NODETYPE_RETURN:
res = analyze_return(analyzer, node);
break;
case FZL_NODETYPE_FUNCTION:
res = analyze_function(analyzer, node);
break;
case FZL_NODETYPE_CONDITIONAL:
res = analyze_conditional(analyzer, node);
break;
case FZL_NODETYPE_IDENTIFIER:
res = analyze_identifier(analyzer, node);
break;
case FZL_NODETYPE_BLOCK:
res = analyze_block(analyzer, node);
break;
case FZL_NODETYPE_CALL:
res = analyze_call(analyzer, node);
break;
case FZL_NODETYPE_LITERAL:
switch (node->token->type)
{
case FZL_TOKTYPE_STR_LITERAL:
res.type = FZL_TYPE_STRING;
break;
case FZL_TOKTYPE_NUM_LITERAL:
res.type = FZL_TYPE_INT;
break;
case FZL_TOKTYPE_BOOL_LITERAL:
res.type = FZL_TYPE_BOOL;
break;
case FZL_TOKTYPE_NULL_LITERAL:
res.type = FZL_TYPE_OBJECT;
res.classname = "null";
break;
default:
an_push_error(analyzer, node->token, "unknown literal type");
res.error = true;
break;
}
break;
}
return res;
}
+115
View File
@@ -0,0 +1,115 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stdio.h>
// Analyze binary conditional nodes
fzl_an_res_t analyze_condition(fzl_analyzer_t *analyzer, fzl_node_t *cond_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!cond_node || (cond_node->type != FZL_NODETYPE_OR &&
cond_node->type != FZL_NODETYPE_AND &&
cond_node->type != FZL_NODETYPE_LESS &&
cond_node->type != FZL_NODETYPE_LESS_EQUAL &&
cond_node->type != FZL_NODETYPE_GREATER &&
cond_node->type != FZL_NODETYPE_GREATER_EQUAL &&
cond_node->type != FZL_NODETYPE_EQUAL &&
cond_node->type != FZL_NODETYPE_NEQUAL))
{
an_push_error(analyzer, NULL, "node is not a binary conditional operator");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t left = analyze_common(analyzer, cond_node->binary_op.left);
if (left.error)
return (fzl_an_res_t){.error = true};
fzl_an_res_t right = analyze_common(analyzer, cond_node->binary_op.right);
if (right.error)
return (fzl_an_res_t){.error = true};
if (cond_node->type == FZL_NODETYPE_OR || cond_node->type == FZL_NODETYPE_AND)
{
if (left.type != FZL_TYPE_BOOL)
an_push_warning(analyzer, cond_node->binary_op.left->token,
"left operand is not resulting with boolean type");
if (right.type != FZL_TYPE_BOOL)
an_push_warning(analyzer, cond_node->binary_op.right->token,
"right operand is not resulting with boolean type");
}
else if (cond_node->type == FZL_NODETYPE_LESS ||
cond_node->type == FZL_NODETYPE_LESS_EQUAL ||
cond_node->type == FZL_NODETYPE_GREATER ||
cond_node->type == FZL_NODETYPE_GREATER_EQUAL)
{
if (left.type < FZL_TYPE_INT8)
{
an_push_error(analyzer, cond_node->binary_op.left->token,
"left operand must have integer type");
return (fzl_an_res_t){.error = true};
}
if (left.type < FZL_TYPE_INT8)
{
an_push_error(analyzer, cond_node->binary_op.left->token,
"right operand must have integer type");
return (fzl_an_res_t){.error = true};
}
}
else if (left.type >= FZL_TYPE_INT8)
{
if (right.type < FZL_TYPE_INT8)
{
an_push_error(analyzer, cond_node->binary_op.right->token,
"right operand must have integer type");
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
else if (left.type == FZL_TYPE_OBJECT)
{
if (!left.classname || !right.classname)
{
an_push_error(analyzer, cond_node->binary_op.left->token,
"unhandled error :(");
return (fzl_an_res_t){.error = true};
}
if (!an_is_compatible(left.type, right.type, left.classname,
right.classname))
{
snprintf(an_problem, sizeof(an_problem), "'%s' and '%s' are incompatible",
an_typetostr(left.type, left.classname),
an_typetostr(right.type, right.classname));
an_push_error(analyzer, cond_node->binary_op.right->token, an_problem);
return (fzl_an_res_t){.error = true};
}
}
else if (left.type == FZL_TYPE_STRING)
{
if (right.type != FZL_TYPE_STRING)
{
an_push_error(analyzer, cond_node->binary_op.right->token,
"right operand must be a string");
return (fzl_an_res_t){.error = true};
}
}
else if (!an_is_compatible(left.type, right.type, left.classname,
right.classname))
{
snprintf(an_problem, sizeof(an_problem),
"equality not supported between %s and %s",
an_typetostr(left.type, left.classname),
an_typetostr(right.type, right.classname));
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
+45
View File
@@ -0,0 +1,45 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <stdio.h>
// Analyze conditional statement
fzl_an_res_t analyze_conditional(fzl_analyzer_t *analyzer, fzl_node_t *cond)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!cond || cond->type != FZL_NODETYPE_CONDITIONAL)
{
an_push_error(analyzer, NULL, "provided node is a condition");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t cond_res = analyze_common(analyzer, cond->cond.condition);
fzl_an_res_t true_res = analyze_common(analyzer, cond->cond.true_block);
if (cond->cond.else_block)
{
fzl_an_res_t else_res = analyze_common(analyzer, cond->cond.else_block);
if (else_res.error)
return (fzl_an_res_t){.error = true};
}
if (cond_res.error || true_res.error)
return (fzl_an_res_t){.error = true};
if (cond_res.type != FZL_TYPE_BOOL)
an_push_warning(analyzer, cond->cond.condition->token,
"resulting type is not bool");
if (cond->cond.condition->token->type == FZL_TOKTYPE_BOOL_LITERAL)
{
snprintf(an_problem, sizeof(an_problem), "condition is always %s",
(char *)cond->cond.condition->token->value);
an_push_warning(analyzer, cond->cond.condition->token, an_problem);
}
return (fzl_an_res_t){.error = false, .type = FZL_TYPE_NULL};
}
+39
View File
@@ -0,0 +1,39 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
// Analyze class construct
fzl_an_res_t analyze_construct(fzl_analyzer_t *analyzer, fzl_node_t *construct)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!construct || construct->type != FZL_NODETYPE_CONSTRUCT)
{
an_push_error(analyzer, NULL, "node is not a construct");
return (fzl_an_res_t){.error = true};
}
char *classname = (char *)construct->construct.name->token->value;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], classname, &sym)))
break;
}
if (!sym_found)
{
snprintf(an_problem, sizeof(an_problem), "class '%s' not found", classname);
an_push_error(analyzer, construct->token, an_problem);
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_OBJECT, .classname = classname};
}
+76
View File
@@ -0,0 +1,76 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
// Analyze variable/field/argument declaration
fzl_an_res_t analyze_declaration(fzl_analyzer_t *analyzer, fzl_node_t *decl)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!decl || decl->type != FZL_NODETYPE_DECLARATION)
{
an_push_error(analyzer, NULL, "node is not a declaration");
return (fzl_an_res_t){.error = true};
}
char *name = (char *)decl->var.identifier->token->value;
bool type_found = false;
fzl_type_t type = an_toktotype(analyzer, decl->var.type, &type_found);
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)decl->var.type->value);
an_push_error(analyzer, decl->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
char *classname = NULL;
if (type == FZL_TYPE_OBJECT)
classname = decl->var.type->value;
fzl_symtable_res_t res = fzl_symt_put(
analyzer->symbols[analyzer->symbols_top - 1], decl, name, type, 0);
if (res != FZL_SYMTABLE_RESULT_OK)
{
if (res == FZL_SYMTABLE_RESULT_EXISTS)
snprintf(an_problem, sizeof(an_problem), "'%s' already has been declared",
name);
else
snprintf(an_problem, sizeof(an_problem), "cannot store '%s'", name);
an_push_error(analyzer, decl->token, an_problem);
return (fzl_an_res_t){.error = true};
}
if (type == FZL_TYPE_OBJECT)
{
fzl_sym_t class;
bool class_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((class_found = fzl_symt_get(analyzer->symbols[i],
decl->var.type->value, &class)))
break;
}
if (!class_found || class.node->type != FZL_NODETYPE_CLASS)
{
snprintf(an_problem, sizeof(an_problem), "class '%s' does not exists",
(char *)decl->var.type->value);
an_push_error(analyzer, decl->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
fzl_symt_setobjclass(analyzer->symbols[analyzer->symbols_top - 1], name,
classname);
}
return (fzl_an_res_t){.error = false, .type = type, .classname = classname};
}
+50
View File
@@ -0,0 +1,50 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stddef.h>
#include <stdio.h>
// Analyze extern block definition
fzl_an_res_t analyze_extern(fzl_analyzer_t *analyzer, fzl_node_t *extern_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!extern_node || extern_node->type != FZL_NODETYPE_EXTERN)
{
an_push_error(analyzer, NULL, "node is not an extern block");
return (fzl_an_res_t){.error = true};
}
if (extern_node->ext.typedefs_count < 1 && extern_node->ext.fns_count < 1)
an_push_warning(analyzer, extern_node->token, "extern is empty");
for (size_t i = 0; i < extern_node->ext.typedefs_count; i++)
{
fzl_node_t *node = extern_node->ext.typedefs[i];
fzl_an_res_t res = analyze_common(analyzer, node);
if (res.error)
return (fzl_an_res_t){.error = true};
if (node->type != FZL_NODETYPE_TYPEDEF &&
node->type != FZL_NODETYPE_EXTERN_FN)
{
snprintf(an_problem, sizeof(an_problem),
"unexpected statement '%s' inside extern block",
(char *)node->token->value);
an_push_error(analyzer, node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
}
for (size_t i = 0; i < extern_node->ext.fns_count; i++)
{
fzl_an_res_t res = analyze_common(analyzer, extern_node->ext.fns[i]);
if (res.error)
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
}
+79
View File
@@ -0,0 +1,79 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
// Analyze external function definition
fzl_an_res_t analyze_externfn(fzl_analyzer_t *analyzer, fzl_node_t *externfn)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!externfn || externfn->type != FZL_NODETYPE_EXTERN_FN)
{
an_push_error(analyzer, NULL, "node is not an external function");
return (fzl_an_res_t){.error = true};
}
an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_UNNECESSARY);
for (size_t i = 0; i < externfn->ext_fn.args_count; i++)
{
fzl_an_res_t res = analyze_common(analyzer, externfn->ext_fn.args[i]);
if (res.error)
return (fzl_an_res_t){.error = true};
}
if (externfn->ext_fn.type->type == FZL_TOKTYPE_NAME)
{
fzl_sym_t sym;
bool found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((found = fzl_symt_get(analyzer->symbols[i],
(char *)externfn->ext_fn.type->value, &sym)))
break;
}
if (!found)
{
snprintf(an_problem, sizeof(an_problem),
"cannot find '%s' used as return type",
(char *)externfn->ext_fn.type->value);
an_push_error(analyzer, externfn->ext_fn.type, an_problem);
return (fzl_an_res_t){.error = true};
}
}
fzl_symtable_res_t wrres =
fzl_symt_put(analyzer->symbols[0], externfn,
(char *)externfn->ext_fn.name, FZL_TYPE_EXTERN_FN, 0);
if (wrres != FZL_SYMTABLE_RESULT_OK)
{
if (wrres == FZL_SYMTABLE_RESULT_EXISTS)
{
snprintf(an_problem, sizeof(an_problem),
"symbol '%s' already has been declared", externfn->ext_fn.name);
an_push_error(analyzer, externfn->token, an_problem);
return (fzl_an_res_t){.error = true};
}
else
{
snprintf(an_problem, sizeof(an_problem), "cannot store symbol '%s'",
externfn->ext_fn.name);
}
an_push_error(analyzer, externfn->token, an_problem);
return (fzl_an_res_t){.error = true};
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_EXTERN_FN, .classname = NULL};
}
+90
View File
@@ -0,0 +1,90 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
// Analyze field access
fzl_an_res_t analyze_field(fzl_analyzer_t *analyzer, fzl_node_t *field)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!field || field->type != FZL_NODETYPE_FIELD)
{
an_push_error(analyzer, NULL, "node is not field access");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t parent = analyze_common(analyzer, field->memb.parent);
if (parent.error)
return (fzl_an_res_t){.error = true};
if (parent.type != FZL_TYPE_OBJECT || parent.classname == NULL)
{
snprintf(an_problem, sizeof(an_problem), "access to non-object value (%s)",
an_typetostr(parent.type, parent.classname));
an_push_error(analyzer, field->token, an_problem);
return (fzl_an_res_t){.error = true};
}
char *field_name = field->memb.field->token->value;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found =
fzl_symt_get(analyzer->symbols[i], parent.classname, &sym)))
break;
}
if (!sym_found)
{
snprintf(an_problem, sizeof(an_problem), "class '%s' not found",
parent.classname);
an_push_error(analyzer, field->parent->token, an_problem);
return (fzl_an_res_t){.error = true};
}
fzl_node_t *field_node = NULL;
for (size_t i = 0; i < sym.node->class.fields_count; i++)
{
if (strcmp(sym.node->class.fields[i]->var.identifier->token->value,
field_name) == 0)
{
field_node = sym.node->class.fields[i];
break;
}
}
if (field_node == NULL)
{
snprintf(an_problem, sizeof(an_problem), "field '%s.%s' does not exists",
parent.classname, field_name);
an_push_error(analyzer, field->memb.field->token, an_problem);
return (fzl_an_res_t){.error = true};
}
bool type_found = false;
fzl_type_t field_type =
an_toktotype(analyzer, field_node->var.type, &type_found);
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)field_node->var.type->value);
an_push_error(analyzer, field_node->var.type, an_problem);
return (fzl_an_res_t){.error = true};
}
char *classname = NULL;
if (field_type == FZL_TYPE_OBJECT)
classname = field_node->var.type->value;
return (fzl_an_res_t){
.error = false, .type = field_type, .classname = classname};
}
+139
View File
@@ -0,0 +1,139 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
fzl_an_res_t analyze_function(fzl_analyzer_t *analyzer, fzl_node_t *fn_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!fn_node || fn_node->type != FZL_NODETYPE_FUNCTION)
{
an_push_error(analyzer, NULL, "node is not a function");
return (fzl_an_res_t){.error = true};
}
fzl_an_ctx_t *fnctx = an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_FUNCTION);
fnctx->fn = fn_node;
for (size_t i = 0; i < fn_node->fn.args_count; i++)
{
fzl_an_res_t res = analyze_common(analyzer, fn_node->fn.args[i]);
if (res.error)
return (fzl_an_res_t){.error = true};
}
fzl_an_ctx_t *ctx = analyzer->ctx;
while (ctx != NULL)
{
if (ctx->type == FZL_AN_CTX_TYPE_CLASS)
break;
ctx = ctx->parent;
}
bool type_found = false;
fzl_type_t rettype = an_toktotype(analyzer, fn_node->fn.type, &type_found);
char *classname = NULL;
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)fn_node->fn.type->value);
an_push_error(analyzer, fn_node->fn.type, an_problem);
return (fzl_an_res_t){.error = true};
}
if (rettype == FZL_TYPE_OBJECT)
classname = (char *)fn_node->fn.type->value;
if (ctx != NULL && ctx->type == FZL_AN_CTX_TYPE_CLASS)
{
for (size_t i = 0; i < fn_node->fn.args_count; i++)
{
fzl_node_t *decl = fn_node->fn.args[i];
if (decl->type != FZL_NODETYPE_DECLARATION)
{
an_push_error(analyzer, decl->token, "argument must be a declaration");
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = true};
}
char *argname = (char *)decl->var.identifier->token->value;
if (strcmp(argname, "this") == 0 && i > 0)
{
an_push_error(analyzer, decl->token,
"manual declaration of 'this' is not allowed in methods");
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = true};
}
}
size_t classname_len = strlen(ctx->classname);
size_t methodname_len = strlen((char *)fn_node->fn.name->value);
char *methodname = malloc(classname_len + methodname_len + 2);
strcpy(methodname, ctx->classname);
methodname[classname_len] = '_';
strcpy(methodname + classname_len + 1, fn_node->fn.name->value);
methodname[classname_len + methodname_len + 1] = 0;
analyzer->alloc_names[analyzer->alloc_names_top++] = methodname;
fzl_symtable_res_t putres =
fzl_symt_put(analyzer->symbols[ctx->symbols_level - 1], fn_node,
methodname, rettype, 0);
if (putres != FZL_SYMTABLE_RESULT_OK)
{
if (putres == FZL_SYMTABLE_RESULT_EXISTS)
{
snprintf(an_problem, sizeof(an_problem),
"method '%s.%s' already has been declared", classname,
(char *)fn_node->fn.name->value);
an_push_error(analyzer, fn_node->token, an_problem);
}
else
an_push_error(analyzer, fn_node->token, "failed to store method");
free(analyzer->alloc_names[--analyzer->alloc_names_top]);
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = true};
}
fzl_symt_setobjclass(analyzer->symbols[ctx->symbols_level - 1], methodname,
classname);
}
else
{
fzl_symtable_res_t putres =
fzl_symt_put(analyzer->symbols[analyzer->symbols_top - 2], fn_node,
(char *)fn_node->fn.name->value, rettype, 0);
if (putres != FZL_SYMTABLE_RESULT_OK)
{
if (putres == FZL_SYMTABLE_RESULT_EXISTS)
{
snprintf(an_problem, sizeof(an_problem),
"function '%s' already has been declared",
(char *)fn_node->fn.name->value);
an_push_error(analyzer, fn_node->token, an_problem);
}
else
an_push_error(analyzer, fn_node->token, "failed to store function");
free(analyzer->alloc_names[--analyzer->alloc_names_top]);
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = true};
}
}
fzl_an_res_t body_res = analyze_common(analyzer, fn_node->fn.body);
an_fin_ctx(analyzer);
return (fzl_an_res_t){
.error = body_res.error, .type = rettype, .classname = classname};
}
+38
View File
@@ -0,0 +1,38 @@
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdio.h>
// Analyze identifier
fzl_an_res_t analyze_identifier(fzl_analyzer_t *analyzer, fzl_node_t *id)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!id || id->type != FZL_NODETYPE_IDENTIFIER)
{
an_push_error(analyzer, NULL, "node is not an identifier");
return (fzl_an_res_t){.error = true};
}
char *symname = id->token->value;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], symname, &sym)))
break;
}
if (!sym_found)
{
snprintf(an_problem, sizeof(an_problem), "cannot find symbol '%s'",
symname);
an_push_error(analyzer, id->token, an_problem);
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = sym.type, .classname = sym.classname};
}
+465
View File
@@ -0,0 +1,465 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
// Init block analysis result
typedef struct
{
bool has_var;
char *name;
fzl_type_t type;
char *classname;
} init_analysis;
// Check init block
init_analysis check_init(fzl_analyzer_t *analyzer, fzl_node_t *init)
{
if (!analyzer || !init)
return (init_analysis){.has_var = false};
if (init->type == FZL_NODETYPE_IDENTIFIER)
{
char *name = init->token->value;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], name, &sym)))
break;
}
if (!sym_found)
return (init_analysis){.has_var = false};
char *classname = NULL;
if (sym.type == FZL_TYPE_OBJECT)
classname = sym.classname;
return (init_analysis){.has_var = true,
.name = name,
.type = sym.type,
.classname = classname};
}
else if (init->type == FZL_NODETYPE_DECLARATION)
{
char *name = init->var.identifier->token->value;
bool type_found = false;
fzl_type_t type = an_toktotype(analyzer, init->var.type, &type_found);
char *classname = NULL;
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)init->var.type->value);
}
if (type == FZL_TYPE_OBJECT)
classname = init->var.type->value;
return (init_analysis){
.has_var = true, .name = name, .type = type, .classname = classname};
}
else if (init->type == FZL_NODETYPE_ASSIGN)
{
return (init_analysis)check_init(analyzer, init->binary_op.left);
}
return (init_analysis){.has_var = false};
}
// Condition block analysis result type
typedef enum
{
COND_TYPE_CONST_TRUE, // `true` is used as condition
COND_TYPE_CONST_FALSE, // `false` is used as condition
COND_TYPE_VAR_LESS, // until variable value is less
COND_TYPE_VAR_GREATER, // until variable value is greater
COND_TYPE_UNKNOWN, // cannot determine in compilation time
} cond_type;
// Condition block analysis result
typedef struct
{
cond_type type;
bool result_bool;
char *varname;
fzl_type_t vartype;
char *classname;
} cond_analysis;
// Check condition block
cond_analysis check_condition(fzl_analyzer_t *analyzer, fzl_node_t *cond,
bool report)
{
if (!cond)
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .result_bool = false};
switch (cond->type)
{
case FZL_NODETYPE_LITERAL:
if (cond->token->type == FZL_TOKTYPE_STR_LITERAL)
{
if (report)
an_push_warning(analyzer, cond->token,
"string literal is used as condition");
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .result_bool = false};
}
else if (cond->token->type == FZL_TOKTYPE_NULL_LITERAL)
{
if (report)
an_push_warning(analyzer, cond->token,
"null literal is used as condition");
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .result_bool = false};
}
else if (cond->token->type == FZL_TOKTYPE_BOOL_LITERAL)
{
if (strcmp(cond->token->value, "true") == 0)
return (cond_analysis){.type = COND_TYPE_CONST_TRUE,
.result_bool = true};
else
return (cond_analysis){.type = COND_TYPE_CONST_FALSE,
.result_bool = true};
}
else if (cond->token->type == FZL_TOKTYPE_NUM_LITERAL)
{
if (strcmp(cond->token->value, "0") == 0)
return (cond_analysis){.type = COND_TYPE_CONST_FALSE,
.result_bool = false};
else
return (cond_analysis){.type = COND_TYPE_CONST_TRUE,
.result_bool = false};
}
break;
case FZL_NODETYPE_LESS:
case FZL_NODETYPE_LESS_EQUAL:
{
fzl_node_t *comp_left = cond->binary_op.left;
cond_analysis left_check = check_condition(analyzer, comp_left, false);
if (left_check.varname != NULL)
return (cond_analysis){.type = COND_TYPE_VAR_LESS,
.result_bool = true,
.varname = left_check.varname,
.vartype = left_check.vartype,
.classname = left_check.classname};
fzl_node_t *comp_right = cond->binary_op.right;
cond_analysis right_check = check_condition(analyzer, comp_right, false);
if (right_check.varname != NULL)
return (cond_analysis){.type = COND_TYPE_VAR_GREATER,
.result_bool = true,
.varname = right_check.varname,
.vartype = right_check.vartype,
.classname = right_check.classname};
return (cond_analysis){.type = COND_TYPE_UNKNOWN};
}
case FZL_NODETYPE_GREATER:
case FZL_NODETYPE_GREATER_EQUAL:
{
fzl_node_t *comp_left = cond->binary_op.left;
cond_analysis left_check = check_condition(analyzer, comp_left, false);
if (left_check.varname != NULL)
return (cond_analysis){.type = COND_TYPE_VAR_GREATER,
.result_bool = true,
.varname = left_check.varname,
.vartype = left_check.vartype,
.classname = left_check.classname};
fzl_node_t *comp_right = cond->binary_op.right;
cond_analysis right_check = check_condition(analyzer, comp_right, false);
if (right_check.varname != NULL)
return (cond_analysis){.type = COND_TYPE_VAR_LESS,
.result_bool = true,
.varname = right_check.varname,
.vartype = right_check.vartype,
.classname = right_check.classname};
return (cond_analysis){.type = COND_TYPE_UNKNOWN};
}
case FZL_NODETYPE_IDENTIFIER:
{
char *name = cond->token->value;
fzl_sym_t sym;
bool sym_found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((sym_found = fzl_symt_get(analyzer->symbols[i], name, &sym)))
break;
}
if (!sym_found)
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .varname = NULL};
return (cond_analysis){.type = COND_TYPE_UNKNOWN,
.varname = name,
.vartype = sym.type,
.classname = sym.classname};
}
default:
break;
}
fzl_an_res_t custom_res = analyze_common(analyzer, cond);
if (custom_res.type == FZL_TYPE_BOOL)
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .result_bool = true};
return (cond_analysis){.type = COND_TYPE_UNKNOWN, .result_bool = false};
}
// Step block change direction
typedef enum
{
STEP_DIR_TYPE_INCREASE,
STEP_DIR_TYPE_DECREASE,
STEP_DIR_TYPE_STALL,
STEP_DIR_UNKNOWN,
} step_dir_type;
// Step block analysis
typedef struct
{
bool changing;
char *changing_var;
step_dir_type dir;
} step_analysis;
// Check step block
step_analysis check_step(fzl_node_t *step)
{
if (!step)
return (step_analysis){.changing = false};
if (step->type == FZL_NODETYPE_ASSIGN)
{
if (step->binary_op.left->type != FZL_NODETYPE_IDENTIFIER)
return (step_analysis){
.changing = true, .changing_var = "-", .dir = STEP_DIR_UNKNOWN};
int dir = 0;
fzl_node_t *right = step->binary_op.right;
fzl_node_t *num = NULL;
char *varname = NULL;
if (right->binary_op.left->type != FZL_NODETYPE_IDENTIFIER)
{
num = right->binary_op.left;
if (right->binary_op.right->type == FZL_NODETYPE_IDENTIFIER)
varname = right->binary_op.right->token->value;
}
else
{
num = right->binary_op.right;
if (right->binary_op.left->type == FZL_NODETYPE_IDENTIFIER)
varname = right->binary_op.left->token->value;
}
if (right->type == FZL_NODETYPE_ADD || right->type == FZL_NODETYPE_MUL ||
right->type == FZL_NODETYPE_POW)
dir = 1;
else if (right->type == FZL_NODETYPE_SUB ||
right->type == FZL_NODETYPE_DIV || right->type == FZL_NODETYPE_MOD)
dir = -1;
if (num && num->type == FZL_NODETYPE_UNARY_MINUS)
dir *= -1;
step_dir_type dirtype = varname == NULL ? STEP_DIR_UNKNOWN
: dir > 0 ? STEP_DIR_TYPE_INCREASE
: dir < 0 ? STEP_DIR_TYPE_DECREASE
: STEP_DIR_TYPE_STALL;
return (step_analysis){.changing = varname != NULL && dir != 0,
.changing_var = varname,
.dir = dirtype};
}
return (step_analysis){.changing = false, .dir = STEP_DIR_UNKNOWN};
}
// Body analysis result
typedef struct
{
bool has_exit;
} body_analysis;
body_analysis check_body(fzl_node_t *body, bool nested_loop)
{
body_analysis result = {.has_exit = false};
switch (body->type)
{
case FZL_NODETYPE_RETURN:
result.has_exit = true;
break;
case FZL_NODETYPE_BREAK:
if (!nested_loop)
result.has_exit = true;
break;
case FZL_NODETYPE_LOOP:
if (body->loop.body)
{
body_analysis res = check_body(body->loop.body, true);
if (res.has_exit)
result.has_exit = true;
}
break;
case FZL_NODETYPE_CONDITIONAL:
if (check_body(body->cond.true_block, nested_loop).has_exit)
{
result.has_exit = true;
break;
}
break;
case FZL_NODETYPE_BLOCK:
for (size_t i = 0; i < body->list.entry_count; i++)
{
body_analysis res = check_body(body->list.entries[i], nested_loop);
if (res.has_exit)
{
result.has_exit = true;
break;
}
}
break;
default:
break;
}
return result;
}
// Analyze loop
fzl_an_res_t analyze_loop(fzl_analyzer_t *analyzer, fzl_node_t *loop_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!loop_node || loop_node->type != FZL_NODETYPE_LOOP)
{
an_push_error(analyzer, NULL, "node is not typeof LOOP");
return (fzl_an_res_t){.error = true};
}
an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_LOOP);
init_analysis init_data = {
.has_var = false, .type = FZL_TYPE_NULL, .name = NULL, .classname = NULL};
if (loop_node->loop.init)
{
fzl_an_res_t init_res = analyze_common(analyzer, loop_node->loop.init);
if (init_res.error)
return (fzl_an_res_t){.error = true};
init_data = check_init(analyzer, loop_node->loop.init);
}
cond_analysis cond_data = {.type = COND_TYPE_CONST_TRUE,
.varname = NULL,
.vartype = FZL_TYPE_NULL,
.classname = NULL};
if (loop_node->loop.cond)
{
fzl_an_res_t cond_res = analyze_common(analyzer, loop_node->loop.cond);
if (cond_res.error)
return (fzl_an_res_t){.error = true};
cond_data = check_condition(analyzer, loop_node->loop.cond, true);
if (!cond_data.result_bool && cond_data.type != COND_TYPE_UNKNOWN)
an_push_warning(analyzer, loop_node->loop.cond->token,
"resulting type is not boolean");
if (cond_data.type == COND_TYPE_CONST_FALSE)
an_push_warning(analyzer, loop_node->loop.cond->token,
"loop will never execute");
if (init_data.name && cond_data.varname &&
strcmp(init_data.name, cond_data.varname) != 0)
{
snprintf(an_problem, sizeof(an_problem),
"'%s' is used in condition but '%s' is declared. Maybe there is "
"mistake?",
cond_data.varname, init_data.name);
an_push_warning(analyzer, loop_node->loop.cond->token, an_problem);
}
}
step_analysis step_data = {
.changing = false, .changing_var = NULL, .dir = STEP_DIR_UNKNOWN};
if (loop_node->loop.step)
{
fzl_an_res_t step_res = analyze_common(analyzer, loop_node->loop.step);
if (step_res.error)
return (fzl_an_res_t){.error = true};
step_data = check_step(loop_node->loop.step);
if (step_data.dir != STEP_DIR_UNKNOWN)
{
if (step_data.changing_var && cond_data.varname &&
strcmp(step_data.changing_var, cond_data.varname) != 0)
{
snprintf(an_problem, sizeof(an_problem),
"changing '%s' but condition checking '%s'",
step_data.changing_var, cond_data.varname);
an_push_warning(analyzer, loop_node->loop.step->token, an_problem);
}
if (cond_data.type == COND_TYPE_VAR_GREATER &&
step_data.dir == STEP_DIR_TYPE_INCREASE)
{
snprintf(an_problem, sizeof(an_problem),
"'%s' is increasing while condition is 'greater than'",
step_data.changing_var);
an_push_warning(analyzer, loop_node->loop.step->token, an_problem);
}
else if (cond_data.type == COND_TYPE_VAR_LESS &&
step_data.dir == STEP_DIR_TYPE_DECREASE)
{
snprintf(an_problem, sizeof(an_problem),
"'%s' is decreasing while condition is 'less than'",
step_data.changing_var);
an_push_warning(analyzer, loop_node->loop.step->token, an_problem);
}
else if ((cond_data.type == COND_TYPE_VAR_LESS ||
cond_data.type == COND_TYPE_VAR_GREATER) &&
step_data.dir == STEP_DIR_TYPE_STALL)
{
snprintf(an_problem, sizeof(an_problem), "'%s' is stalled",
cond_data.varname);
an_push_warning(analyzer, loop_node->loop.step->token, an_problem);
}
}
}
body_analysis body_data = {.has_exit = false};
if (cond_data.type != COND_TYPE_CONST_FALSE)
{
fzl_an_res_t body_res = analyze_common(analyzer, loop_node->loop.body);
if (body_res.error)
return (fzl_an_res_t){.error = true};
body_data = check_body(loop_node->loop.body, false);
if (cond_data.type == COND_TYPE_CONST_TRUE && !body_data.has_exit)
an_push_warning(analyzer, loop_node->token, "possibly infinite loop");
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){.error = false, .type = FZL_TYPE_NULL};
}
+39
View File
@@ -0,0 +1,39 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
// Analyze reference
fzl_an_res_t analyze_ref(fzl_analyzer_t *analyzer, fzl_node_t *ref_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!ref_node || ref_node->type != FZL_NODETYPE_REFERENCE)
{
an_push_error(analyzer, NULL, "node is not a reference");
return (fzl_an_res_t){.error = true};
}
char *refto = (char *)ref_node->token->value;
fzl_sym_t sym;
bool found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((found = fzl_symt_get(analyzer->symbols[i], refto, &sym)))
break;
}
if (!found)
{
snprintf(an_problem, sizeof(an_problem), "cannot find name '%s'", refto);
an_push_error(analyzer, ref_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_HANDLE, .classname = refto};
}
+113
View File
@@ -0,0 +1,113 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <stdbool.h>
#include <stdio.h>
// Analyze return statement
fzl_an_res_t analyze_return(fzl_analyzer_t *analyzer, fzl_node_t *ret_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!ret_node || ret_node->type != FZL_NODETYPE_RETURN)
{
an_push_error(analyzer, NULL, "node is not a return statement");
return (fzl_an_res_t){.error = false};
}
fzl_an_ctx_t *fnctx = analyzer->ctx;
while (fnctx != NULL)
{
if (fnctx->type == FZL_AN_CTX_TYPE_FUNCTION)
break;
fnctx = fnctx->parent;
}
fzl_an_ctx_t *classctx = analyzer->ctx;
while (classctx != NULL)
{
if (classctx && classctx->type == FZL_AN_CTX_TYPE_CLASS)
break;
classctx = classctx->parent;
}
bool is_in_method =
classctx != NULL && classctx->type == FZL_AN_CTX_TYPE_CLASS;
if (!fnctx || fnctx->type != FZL_AN_CTX_TYPE_FUNCTION)
{
an_push_error(analyzer, ret_node->token,
"cannot use 'return' outside the function");
return (fzl_an_res_t){.error = true};
}
bool type_found = false;
fzl_type_t rettype = an_toktotype(analyzer, fnctx->fn->fn.type, &type_found);
char *classname = NULL;
if (!type_found)
{
snprintf(an_problem, sizeof(an_problem), "symbol '%s' not found",
(char *)fnctx->fn->fn.type->value);
an_push_error(analyzer, fnctx->fn->fn.type, an_problem);
return (fzl_an_res_t){.error = true};
}
if (rettype == FZL_TYPE_OBJECT)
classname = (char *)fnctx->fn->fn.type->value;
char *rettype_str = an_typetostr(rettype, classname);
if (rettype != FZL_TYPE_NULL)
{
if (ret_node->ret.value == NULL)
{
if (is_in_method)
{
snprintf(an_problem, sizeof(an_problem),
"cannot return null as method '%s.%s' have return type '%s'",
classctx->classname, (char *)fnctx->fn->fn.name->value,
rettype_str);
}
else
{
snprintf(an_problem, sizeof(an_problem),
"cannot return null as function '%s' have return type '%s'",
(char *)fnctx->fn->fn.name->value, rettype_str);
}
an_push_error(analyzer, ret_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t ret_res = analyze_common(analyzer, ret_node->ret.value);
if (ret_res.error)
return (fzl_an_res_t){.error = true};
if (!an_is_compatible(ret_res.type, rettype, ret_res.classname, classname))
{
if (is_in_method)
{
snprintf(an_problem, sizeof(an_problem),
"method '%s.%s' is expecting return type '%s', got '%s'",
classctx->classname, (char *)fnctx->fn->fn.name->value,
rettype_str, an_typetostr(ret_res.type, ret_res.classname));
}
else
{
snprintf(an_problem, sizeof(an_problem),
"function '%s' is expecting return type '%s', got '%s'",
(char *)fnctx->fn->fn.name->value, rettype_str,
an_typetostr(ret_res.type, ret_res.classname));
}
an_push_error(analyzer, ret_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
}
return (fzl_an_res_t){
.error = false, .type = rettype, .classname = classname};
}
+39
View File
@@ -0,0 +1,39 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stddef.h>
// Analyze format string
fzl_an_res_t analyze_strfmt(fzl_analyzer_t *analyzer, fzl_node_t *strfmt_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!strfmt_node || strfmt_node->type != FZL_NODETYPE_FMT_STRING)
{
an_push_error(analyzer, NULL, "node is not format string");
return (fzl_an_res_t){.error = true};
}
for (size_t i = 0; i < strfmt_node->list.entry_count; i++)
{
fzl_node_t *node = strfmt_node->list.entries[i];
if (node->type != FZL_NODETYPE_LITERAL &&
node->type != FZL_NODETYPE_IDENTIFIER)
{
an_push_error(
analyzer, node->token,
"format string can only contain string literals and identifiers");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t node_res = analyze_common(analyzer, node);
if (node_res.error)
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_STRING, .classname = NULL};
}
+56
View File
@@ -0,0 +1,56 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stdbool.h>
#include <stddef.h>
// Analyze structure definition
fzl_an_res_t analyze_struct(fzl_analyzer_t *analyzer, fzl_node_t *struct_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!struct_node || struct_node->type != FZL_NODETYPE_STRUCT)
{
an_push_error(analyzer, NULL, "node is not a structure");
return (fzl_an_res_t){.error = true};
}
an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_UNNECESSARY);
if (struct_node->structure.entries_count < 1)
{
an_push_warning(analyzer, struct_node->token, "empty structure");
return (fzl_an_res_t){.error = false};
}
for (size_t i = 0; i < struct_node->structure.entries_count; i++)
{
fzl_node_t *entry = struct_node->structure.entries[i];
if (entry->type != FZL_NODETYPE_DECLARATION &&
entry->type != FZL_NODETYPE_IDENTIFIER)
{
an_push_error(
analyzer, entry->token,
"structure can contain only declarations and another structures");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t res = analyze_common(analyzer, entry);
if (res.error)
return (fzl_an_res_t){.error = true};
if (res.type == FZL_TYPE_OBJECT)
{
an_push_error(analyzer, entry->token,
"cannot store object inside struct");
return (fzl_an_res_t){.error = true};
}
}
an_fin_ctx(analyzer);
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_STRUCT, .classname = NULL};
}
+57
View File
@@ -0,0 +1,57 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdio.h>
// Analyze type definition
fzl_an_res_t analyze_typedef(fzl_analyzer_t *analyzer, fzl_node_t *td_node)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!td_node || td_node->type != FZL_NODETYPE_TYPEDEF)
{
an_push_error(analyzer, NULL, "node is not a type definition");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t res = analyze_common(analyzer, td_node->typedefinition.type);
if (res.error)
return (fzl_an_res_t){.error = true};
fzl_nodetype_t type = td_node->typedefinition.type->type;
if (type != FZL_NODETYPE_ALIAS && type != FZL_NODETYPE_STRUCT &&
type != FZL_NODETYPE_HANDLE && type != FZL_NODETYPE_REFERENCE)
{
an_push_error(
analyzer, td_node->token,
"only alias, structure, reference and handle are allowed in type "
"definition value");
return (fzl_an_res_t){.error = true};
}
fzl_symtable_res_t putres =
fzl_symt_put(analyzer->symbols[0], td_node,
td_node->typedefinition.typename, res.type, 0);
if (putres != FZL_SYMTABLE_RESULT_OK)
{
if (putres == FZL_SYMTABLE_RESULT_EXISTS)
snprintf(an_problem, sizeof(an_problem),
"symbol '%s' already has been declared",
td_node->typedefinition.typename);
else
snprintf(an_problem, sizeof(an_problem), "cannot store symbol '%s'",
td_node->typedefinition.typename);
an_push_error(analyzer, td_node->token, an_problem);
return (fzl_an_res_t){.error = true};
}
if (res.type == FZL_TYPE_STRUCT || res.type == FZL_TYPE_HANDLE)
fzl_symt_setobjclass(analyzer->symbols[0], td_node->typedefinition.typename,
td_node->typedefinition.typename);
return (fzl_an_res_t){.error = false, .type = res.type, .classname = NULL};
}
+31
View File
@@ -0,0 +1,31 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
// Analyze unary condition
fzl_an_res_t analyze_unarycond(fzl_analyzer_t *analyzer, fzl_node_t *unary)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!unary || unary->type != FZL_NODETYPE_NOT)
{
an_push_error(analyzer, NULL, "node is not an unary condition operator");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t operand_res = analyze_common(analyzer, unary->unary_op.operand);
if (operand_res.error)
return (fzl_an_res_t){.error = true};
if (operand_res.type != FZL_TYPE_BOOL && operand_res.type < FZL_TYPE_INT8)
{
an_push_error(analyzer, unary->unary_op.operand->token,
"unary condition only support bool and integer types");
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
+33
View File
@@ -0,0 +1,33 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/analyzer.h>
#include <stdbool.h>
// Analyze unary arithmetic
fzl_an_res_t analyze_unarymath(fzl_analyzer_t *analyzer, fzl_node_t *unary)
{
if (!analyzer)
return (fzl_an_res_t){.error = true};
if (!unary || (unary->type != FZL_NODETYPE_UNARY_MINUS &&
unary->type != FZL_NODETYPE_UNARY_PLUS))
{
an_push_error(analyzer, NULL, "node is not an unary math operator");
return (fzl_an_res_t){.error = true};
}
fzl_an_res_t operand_res = analyze_common(analyzer, unary->unary_op.operand);
if (operand_res.error)
return (fzl_an_res_t){.error = true};
if (operand_res.type < FZL_TYPE_INT8)
{
an_push_error(analyzer, unary->unary_op.operand->token,
"unary operator only support integer types");
return (fzl_an_res_t){.error = true};
}
return (fzl_an_res_t){
.error = false, .type = operand_res.type, .classname = NULL};
}
+47
View File
@@ -0,0 +1,47 @@
#include <compiler/fzl_analyzer.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdlib.h>
#include <string.h>
// Nest context
fzl_an_ctx_t *an_nest_ctx(fzl_analyzer_t *analyzer, fzl_an_ctx_type_t type)
{
if (!analyzer)
return NULL;
fzl_an_ctx_t *ctx = malloc(sizeof(fzl_an_ctx_t));
if (!ctx)
return NULL;
memset(ctx, 0, sizeof(fzl_an_ctx_t));
ctx->type = type;
if (analyzer->ctx != NULL)
ctx->parent = analyzer->ctx;
else
ctx->parent = NULL;
ctx->symbols = fzl_mksymt();
ctx->symbols_level = analyzer->symbols_top;
analyzer->ctx = ctx;
analyzer->symbols[analyzer->symbols_top++] = ctx->symbols;
return ctx;
}
// Close context and return parent
fzl_an_ctx_t *an_fin_ctx(fzl_analyzer_t *analyzer)
{
if (!analyzer || analyzer->ctx == NULL)
return NULL;
fzl_an_ctx_t *current = analyzer->ctx;
fzl_an_ctx_t *parent = current->parent;
analyzer->ctx = parent;
free(current);
fzl_freesymt(analyzer->symbols[--analyzer->symbols_top]);
return parent;
}
+160
View File
@@ -0,0 +1,160 @@
#include <common/fzl_types.h>
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
// Check compatibility between A and B types (and classnames)
bool an_is_compatible(fzl_type_t a, fzl_type_t b, char *ac, char *bc)
{
if (a == b)
return true;
if (a == FZL_TYPE_OBJECT && b == FZL_TYPE_OBJECT)
{
if (strcmp(ac, "null") == 0 || strcmp(bc, "null") == 0)
return true;
return strcmp(ac, bc) == 0;
}
if (a >= FZL_TYPE_INT8 && b >= FZL_TYPE_INT8)
return true;
return false;
}
// Convert type to string
char *an_typetostr(fzl_type_t type, char *classname)
{
if (classname)
return classname;
switch (type)
{
case FZL_TYPE_NULL:
return "null";
case FZL_TYPE_BOOL:
return "boolean";
case FZL_TYPE_STRING:
return "string";
case FZL_TYPE_CHAR:
return "char";
case FZL_TYPE_INT8:
return "i8";
case FZL_TYPE_INT16:
return "i16";
case FZL_TYPE_INT32:
return "i32";
case FZL_TYPE_INT64:
return "i64";
case FZL_TYPE_UINT8:
return "u8";
case FZL_TYPE_UINT16:
return "u16";
case FZL_TYPE_UINT32:
return "u32";
case FZL_TYPE_UINT64:
return "u64";
case FZL_TYPE_INT:
return "int";
case FZL_TYPE_UINT:
return "uint";
default:
return "<unknown>";
}
}
// Convert type token to type
fzl_type_t an_toktotype(fzl_analyzer_t *analyzer, fzl_token_t *tok,
bool *sym_found)
{
if (!tok)
return FZL_TYPE_NULL;
if (tok->type == FZL_TOKTYPE_NAME)
{
fzl_sym_t sym;
bool found = false;
for (ssize_t i = analyzer->symbols_top - 1; i >= 0; i--)
{
if ((found = fzl_symt_get(analyzer->symbols[i], tok->value, &sym)))
break;
}
if (sym_found)
*sym_found = found;
if (found && sym.node->type == FZL_NODETYPE_CLASS)
return FZL_TYPE_OBJECT;
if (found && sym.node->type != FZL_NODETYPE_CLASS &&
sym.node->type != FZL_NODETYPE_TYPEDEF)
{
snprintf(an_problem, sizeof(an_problem), "cannot use '%s' as type",
sym.name);
an_push_error(analyzer, sym.node->token, an_problem);
return FZL_TYPE_NULL;
}
return (found || (tok->value && strcmp(tok->value, "null") == 0))
? sym.type
: FZL_TYPE_NULL;
}
if (sym_found)
*sym_found = true;
if (strcmp(tok->value, "null") == 0)
return FZL_TYPE_NULL;
if (strcmp((char *)tok->value, "i8") == 0)
return FZL_TYPE_INT8;
if (strcmp((char *)tok->value, "i16") == 0)
return FZL_TYPE_INT16;
if (strcmp((char *)tok->value, "i32") == 0)
return FZL_TYPE_INT32;
if (strcmp((char *)tok->value, "i64") == 0)
return FZL_TYPE_INT64;
if (strcmp((char *)tok->value, "u8") == 0)
return FZL_TYPE_UINT8;
if (strcmp((char *)tok->value, "u16") == 0)
return FZL_TYPE_UINT16;
if (strcmp((char *)tok->value, "u32") == 0)
return FZL_TYPE_UINT32;
if (strcmp((char *)tok->value, "u64") == 0)
return FZL_TYPE_UINT64;
if (strcmp((char *)tok->value, "int") == 0)
return FZL_TYPE_INT;
if (strcmp((char *)tok->value, "uint") == 0)
return FZL_TYPE_UINT;
if (strcmp((char *)tok->value, "bool") == 0)
return FZL_TYPE_BOOL;
if (strcmp((char *)tok->value, "str") == 0)
return FZL_TYPE_STRING;
if (strcmp((char *)tok->value, "char") == 0)
return FZL_TYPE_CHAR;
return FZL_TYPE_NULL;
}
+119
View File
@@ -0,0 +1,119 @@
#include <compiler/fzl_analyzer.h>
#include <compiler/fzl_parser.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/analyzer.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char aerrors[256][256];
size_t aerrors_top;
char awarnings[256][256];
size_t awarnings_top;
char an_problem[256];
fzl_analyzer_t *fzl_mkanalyzer(fzl_node_t *node)
{
if (!node)
return NULL;
fzl_analyzer_t *analyzer = malloc(sizeof(fzl_analyzer_t));
if (!analyzer)
return NULL;
analyzer->root = node;
analyzer->warnings_top = 0;
analyzer->errors_top = 0;
analyzer->symbols_top = 0;
analyzer->alloc_names_top = 0;
memset(analyzer->errors, 0, sizeof(analyzer->errors));
memset(analyzer->warnings, 0, sizeof(analyzer->warnings));
memset(analyzer->symbols, 0, sizeof(analyzer->symbols));
memset(analyzer->alloc_names, 0, sizeof(analyzer->alloc_names));
memset(aerrors, 0, sizeof(aerrors));
memset(awarnings, 0, sizeof(awarnings));
return analyzer;
}
bool an_push_error(fzl_analyzer_t *analyzer, fzl_token_t *tok, char *error)
{
if (analyzer->errors_top >= 256 || !analyzer || !error)
return false;
size_t ei = aerrors_top++;
if (tok != NULL)
snprintf(aerrors[ei], sizeof(aerrors[ei]), "'%s':%zu:%zu => %s",
tok->filename, tok->ln, tok->cn, error);
else
snprintf(aerrors[ei], sizeof(aerrors[ei]), "<unknown location> => %s",
error);
analyzer->errors[analyzer->errors_top++] = aerrors[ei];
return true;
}
bool an_push_warning(fzl_analyzer_t *analyzer, fzl_token_t *tok, char *warning)
{
if (analyzer->warnings_top >= 256 || !analyzer || !warning)
return false;
size_t wi = awarnings_top++;
if (tok != NULL)
snprintf(awarnings[wi], sizeof(awarnings[wi]), "'%s':%zu:%zu => %s",
tok->filename, tok->ln, tok->cn, warning);
else
snprintf(awarnings[wi], sizeof(awarnings[wi]), "<unknown location> => %s",
warning);
analyzer->warnings[analyzer->warnings_top++] = awarnings[wi];
return true;
}
void fzl_analyze(fzl_analyzer_t *analyzer)
{
if (!analyzer)
return;
if (an_nest_ctx(analyzer, FZL_AN_CTX_TYPE_UNNECESSARY) == NULL)
{
an_push_error(analyzer, NULL, "failed to make global context");
return;
}
fzl_node_t *current = analyzer->root;
while (current != NULL)
{
fzl_an_res_t res = analyze_common(analyzer, current);
if (res.error)
break;
current = current->next;
}
for (ssize_t i = analyzer->symbols_top; i > 0; i--)
an_fin_ctx(analyzer);
}
void fzl_freeanalyzer(fzl_analyzer_t *analyzer)
{
if (!analyzer)
return;
if (analyzer->alloc_names_top > 0)
for (ssize_t i = analyzer->alloc_names_top - 1; i >= 0; i--)
free(analyzer->alloc_names[i]);
memset(analyzer->errors, 0, sizeof(analyzer->errors));
memset(analyzer->warnings, 0, sizeof(analyzer->warnings));
memset(analyzer->symbols, 0, sizeof(analyzer->symbols));
memset(analyzer->alloc_names, 0, sizeof(analyzer->alloc_names));
free(analyzer);
}
+83 -3
View File
@@ -27,10 +27,93 @@ void print_node(fzl_node_t *node, int level)
if (!node) if (!node)
return; return;
print_level(levelbuf, level);
strcpy(printbuf, levelbuf); strcpy(printbuf, levelbuf);
switch (node->type) switch (node->type)
{ {
case FZL_NODETYPE_EXTERN:
printf("%s Extern bindings to library '%s':\n", levelbuf,
node->ext.libname);
printf("-%s Types:\n", levelbuf);
for (size_t i = 0; i < node->ext.typedefs_count; i++)
print_node(node->ext.typedefs[i], level + 2);
printf("-%s Functions:\n", levelbuf);
for (size_t i = 0; i < node->ext.fns_count; i++)
print_node(node->ext.fns[i], level + 2);
break;
case FZL_NODETYPE_EXTERN_FN:
printf("%s External function '%s' (original name %s), rettype '%s':\n",
levelbuf, node->ext_fn.name, node->ext_fn.original_name,
(char *)node->ext_fn.type->value);
printf("-%s Arguments:\n", levelbuf);
for (size_t i = 0; i < node->ext_fn.args_count; i++)
print_node(node->ext_fn.args[i], level + 2);
break;
case FZL_NODETYPE_REFERENCE:
printf("%s Reference (pointer type) to '%s'\n", levelbuf,
(char *)node->token->value);
break;
case FZL_NODETYPE_STRUCT:
printf("%s Structure '%s' (original name %s):\n", levelbuf,
(char *)node->token->value, node->structure.original_name);
for (size_t i = 0; i < node->structure.entries_count; i++)
print_node(node->structure.entries[i], level + 1);
break;
case FZL_NODETYPE_ALIAS:
printf("%s Type alias to '%s'\n", levelbuf, (char *)node->token->value);
break;
case FZL_NODETYPE_HANDLE:
printf("%s Opaque pointer (handle)\n", levelbuf);
break;
case FZL_NODETYPE_TYPEDEF:
printf("%s Type definition '%s':\n", levelbuf,
node->typedefinition.typename);
print_node(node->typedefinition.type, level + 1);
break;
case FZL_NODETYPE_UNARY_MINUS:
printf("%s Unary '-':\n", levelbuf);
print_node(node->unary_op.operand, level + 1);
break;
case FZL_NODETYPE_UNARY_PLUS:
printf("%s Unary '+':\n", levelbuf);
print_node(node->unary_op.operand, level + 1);
break;
case FZL_NODETYPE_BREAK:
printf("%s Break\n", levelbuf);
break;
case FZL_NODETYPE_FMT_STRING:
printf("%s Format string:\n", levelbuf);
for (size_t i = 0; i < node->list.entry_count; i++)
print_node(node->list.entries[i], level + 1);
break;
case FZL_NODETYPE_LOOP:
printf("%s Loop:\n", levelbuf);
printf("-%s Init:\n", levelbuf);
if (node->loop.init)
print_node(node->loop.init, level + 2);
printf("-%s Condition:\n", levelbuf);
if (node->loop.cond)
print_node(node->loop.cond, level + 2);
printf("-%s Step:\n", levelbuf);
if (node->loop.step)
print_node(node->loop.step, level + 2);
printf("-%s Body:\n", levelbuf);
if (node->loop.body)
print_node(node->loop.body, level + 2);
break;
case FZL_NODETYPE_CONSTRUCT: case FZL_NODETYPE_CONSTRUCT:
printf("%s Construct class '%s':\n", levelbuf, printf("%s Construct class '%s':\n", levelbuf,
(char *)node->construct.name->token->value); (char *)node->construct.name->token->value);
@@ -156,9 +239,6 @@ void print_node(fzl_node_t *node, int level)
case FZL_NODETYPE_IDENTIFIER: case FZL_NODETYPE_IDENTIFIER:
printf("%s Identifier ('%s')\n", levelbuf, (char *)node->token->value); printf("%s Identifier ('%s')\n", levelbuf, (char *)node->token->value);
break; break;
default:
printf("%s Secure node\n", levelbuf);
} }
} }
+107
View File
@@ -0,0 +1,107 @@
#include <common/fzl_opcodes.h>
#include <compiler/fzl_gen.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/gen.h>
#include <compiler/utils/fzl_const_pool.h>
#include <compiler/utils/fzl_ctable.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
fzl_gen_t *fzl_mkgen(fzl_node_t *root)
{
if (!root)
return NULL;
fzl_gen_t *gen = malloc(sizeof(fzl_gen_t));
if (!gen)
return NULL;
memset(gen, 0, sizeof(fzl_gen_t));
gen->root = root;
gen->consts = fzl_mkconstpool();
if (!gen->consts)
{
free(gen);
return NULL;
}
gen->ops_remainder = 2;
gen->ops = malloc(gen->ops_remainder * sizeof(size_t));
gen->ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_UNECCESSARY, NULL);
if (!gen->ctx)
{
fzl_consts_pool_free(gen->consts);
free(gen->ops);
free(gen);
return NULL;
}
return gen;
}
bool fzl_gen_run(fzl_gen_t *gen)
{
if (!gen)
return false;
gen_op(gen, FZL_OPCODE_MK_ENVTABLE);
fzl_node_t *current = gen->root;
while (current != NULL)
{
if (gen_common(gen, current).error)
return false;
current = current->next;
}
gen_op(gen, FZL_OPCODE_RM_ENVTABLE);
return true;
}
void fzl_freegen(fzl_gen_t *gen)
{
if (!gen)
return;
if (gen->consts)
fzl_consts_pool_free(gen->consts);
if (gen->ops)
free(gen->ops);
while (gen->ctx != NULL)
gen_fin_ctx(gen);
if (gen->syms_top > 0)
for (ssize_t i = gen->syms_top - 1; i >= 0; i--)
fzl_freesymt(gen->syms[i]);
if (gen->classes_count > 0)
for (ssize_t i = gen->classes_count - 1; i >= 0; i--)
fzl_freectable(gen->classes[i]);
for (size_t i = 0; i < gen->extern_types_count; i++)
{
fzl_extern_type_t *type = &gen->extern_types[i];
if (type->kind == FZL_EXTERN_KIND_STRUCT)
if (type->structure.fields)
free(type->structure.fields);
}
for (size_t i = 0; i < gen->extern_fns_count; i++)
{
fzl_extern_fn_t *fn = &gen->extern_fns[i];
if (fn->args)
free(fn->args);
}
free(gen);
}
+41 -1001
View File
File diff suppressed because it is too large Load Diff
+49 -251
View File
@@ -1,6 +1,7 @@
#include "compiler/fzl_token.h"
#include "compiler/utils/fzl_linked.h"
#include <compiler/fzl_reader.h> #include <compiler/fzl_reader.h>
#include <compiler/fzl_token.h>
#include <compiler/internals/reader.h>
#include <compiler/utils/fzl_linked.h>
#include <stdbool.h> #include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <stdio.h> #include <stdio.h>
@@ -8,7 +9,7 @@
#include <string.h> #include <string.h>
// Last error from reader // Last error from reader
static char last_err[256] = {0}; char last_err[256];
fzl_reader_t *fzl_mkreader(fzl_linked_t *linked) fzl_reader_t *fzl_mkreader(fzl_linked_t *linked)
{ {
@@ -24,300 +25,99 @@ fzl_reader_t *fzl_mkreader(fzl_linked_t *linked)
reader->size = linked->total_sz; reader->size = linked->total_sz;
reader->position = 0; reader->position = 0;
memset(last_err, 0, sizeof(last_err));
return reader; return reader;
} }
// --- Read zone ---
// Move cursor forward
// @deprecated
static size_t move(fzl_reader_t *reader, size_t len)
{
if (!reader)
return 0;
return reader->position += len;
}
// Try parse name
fzl_token_t *parse_name(fzl_reader_t *reader)
{
size_t lpos = reader->position;
size_t size = 0;
do
{
lpos++;
size++;
} while ((reader->source[lpos] >= 'A' && reader->source[lpos] <= 'Z') ||
(reader->source[lpos] >= 'a' && reader->source[lpos] <= 'z') ||
(reader->source[lpos] >= '0' && reader->source[lpos] <= '9') ||
(reader->source[lpos] == '_'));
char *value = malloc(size + 1);
memcpy(value, reader->source + reader->position, size);
value[size] = '\0';
size_t start = reader->position;
move(reader, size);
fzl_token_t *tok;
fzl_file_loc l;
bool ok = fzl_linked_getpos(reader->linked, start, &l);
if (!ok)
{
snprintf(last_err, sizeof(last_err), "failed to locate line:col");
return NULL;
}
if (strcmp(value, "class") == 0)
tok =
fzl_mktoken(FZL_TOKTYPE_CLASS, l.line, l.col, value, size, l.filename);
else if (strcmp(value, "new") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_NEW, l.line, l.col, value, size, l.filename);
else if (strcmp(value, "fn") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_FUNCTION, l.line, l.col, value, size,
l.filename);
else if (strcmp(value, "return") == 0)
tok =
fzl_mktoken(FZL_TOKTYPE_RETURN, l.line, l.col, value, size, l.filename);
else if (strcmp(value, "if") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_IF, l.line, l.col, value, size, l.filename);
else if (strcmp(value, "else") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_ELSE, l.line, l.col, value, size, l.filename);
else if (strcmp(value, "true") == 0 || strcmp(value, "false") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_BOOL_LITERAL, l.line, l.col, value, size,
l.filename);
else if (strcmp(value, "null") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_NULL_LITERAL, l.line, l.col, value, size,
l.filename);
else if (strcmp(value, "str") == 0 || strcmp(value, "char") == 0 ||
strcmp(value, "bool") == 0 || strcmp(value, "uint") == 0 ||
strcmp(value, "int") == 0 || strcmp(value, "i8") == 0 ||
strcmp(value, "i16") == 0 || strcmp(value, "i32") == 0 ||
strcmp(value, "i64") == 0 || strcmp(value, "u8") == 0 ||
strcmp(value, "u16") == 0 || strcmp(value, "u32") == 0 ||
strcmp(value, "u64") == 0)
tok = fzl_mktoken(FZL_TOKTYPE_TYPE, l.line, l.col, value, size, l.filename);
else
tok = fzl_mktoken(FZL_TOKTYPE_NAME, l.line, l.col, value, size, l.filename);
free(value);
return tok;
}
// Try parse string literal
fzl_token_t *parse_string_literal(fzl_reader_t *reader)
{
size_t lpos = reader->position;
size_t size = 0;
if (reader->source[lpos] != '\'' && reader->source[lpos] != '"')
return NULL;
char open_symbol = reader->source[lpos];
char close_symbol = '\0';
do
{
lpos++;
size++;
if (reader->source[lpos] == open_symbol)
close_symbol = open_symbol;
} while (reader->source[lpos] != open_symbol && lpos < reader->size);
size++;
fzl_file_loc l;
bool ok = fzl_linked_getpos(reader->linked, reader->position, &l);
if (!ok)
{
snprintf(last_err, sizeof(last_err), "failed to locate line:col");
return NULL;
}
if (close_symbol != open_symbol)
{
snprintf(last_err, sizeof(last_err), "'%s': unterminated string at %ld:%ld",
l.filename, l.line, l.col);
return NULL;
}
if (size == 2)
{
fzl_token_t *tok =
fzl_mktoken(FZL_TOKTYPE_STR_LITERAL, l.line, l.col, "", 0, l.filename);
move(reader, 2);
return tok;
}
char *value = malloc(size - 2);
memcpy(value, reader->source + reader->position + 1, size - 2);
fzl_token_t *tok = fzl_mktoken(FZL_TOKTYPE_STR_LITERAL, l.line, l.col, value,
size - 2, l.filename);
free(value);
move(reader, size);
return tok;
}
// Parse numeric literal
fzl_token_t *parse_number(fzl_reader_t *reader)
{
if (!reader)
return NULL;
size_t size = 0;
size_t lpos = reader->position;
do
{
size++;
lpos++;
} while ((reader->source[lpos] >= '0' && reader->source[lpos] <= '9') &&
lpos < reader->size);
char *value = malloc(size * sizeof(char) + 1);
memcpy(value, reader->source + reader->position, size);
value[size] = '\0';
fzl_file_loc l;
bool ok = fzl_linked_getpos(reader->linked, reader->position, &l);
if (!ok)
{
snprintf(last_err, sizeof(last_err), "failed to locate line:col");
return NULL;
}
fzl_token_t *tok = fzl_mktoken(FZL_TOKTYPE_NUM_LITERAL, l.line, l.col, value,
size, l.filename);
free(value);
if (!tok)
return NULL;
move(reader, size);
return tok;
}
// Add single-char token
fzl_token_t *add_single(fzl_reader_t *reader, fzl_toktype_t type)
{
fzl_file_loc l;
bool ok = fzl_linked_getpos(reader->linked, reader->position, &l);
if (!ok)
{
snprintf(last_err, sizeof(last_err), "failed to locate line:col");
return NULL;
}
move(reader, 1);
return fzl_mktoken(type, l.line, l.col, "", 0, l.filename);
}
// Add double-char token
fzl_token_t *add_double(fzl_reader_t *reader, fzl_toktype_t type)
{
fzl_file_loc l;
bool ok = fzl_linked_getpos(reader->linked, reader->position, &l);
if (!ok)
{
snprintf(last_err, sizeof(last_err), "failed to locate line:col");
return NULL;
}
move(reader, 2);
return fzl_mktoken(type, l.line, l.col, "", 0, l.filename);
}
// Skip symbols until '\n' or EOF
void skip_comment(fzl_reader_t *reader)
{
move(reader, 2);
while (reader->position < reader->size)
{
if (reader->source[reader->position++] == '\n')
break;
}
}
int fzl_read(fzl_reader_t *reader) int fzl_read(fzl_reader_t *reader)
{ {
if (reader->position >= reader->size) if (reader->position >= reader->size)
return 0; return 0;
bool is_format_str = false;
do do
{ {
size_t p = reader->position; size_t p = reader->position;
fzl_token_t *token; fzl_token_t *token;
char curr = reader->source[p]; char curr = reader->source[p];
if (curr == '\n' || curr == ' ' || curr == '\r') if (is_format_str)
{
token = rd_fmtstr(reader);
if (token && token->type == FZL_TOKTYPE_STR_FORMAT_END)
is_format_str = false;
}
else if (curr == '\n' || curr == ' ' || curr == '\r')
{ {
move(reader, 1); move(reader, 1);
continue; continue;
} }
else if (curr == '\'' || curr == '"')
if (curr == '\'' || curr == '"') token = rd_string_literal(reader);
token = parse_string_literal(reader);
else if (curr == '/' && reader->source[p + 1] == '/') else if (curr == '/' && reader->source[p + 1] == '/')
{ {
skip_comment(reader); rd_comment(reader);
continue; continue;
} }
else if (curr == '=' && reader->source[p + 1] == '=') else if (curr == '=' && reader->source[p + 1] == '=')
token = add_double(reader, FZL_TOKTYPE_EQEQ); token = rd_double(reader, FZL_TOKTYPE_EQEQ);
else if (curr == '>' && reader->source[p + 1] == '=') else if (curr == '>' && reader->source[p + 1] == '=')
token = add_double(reader, FZL_TOKTYPE_REQ); token = rd_double(reader, FZL_TOKTYPE_REQ);
else if (curr == '<' && reader->source[p + 1] == '=') else if (curr == '<' && reader->source[p + 1] == '=')
token = add_double(reader, FZL_TOKTYPE_LEQ); token = rd_double(reader, FZL_TOKTYPE_LEQ);
else if (curr == '!' && reader->source[p + 1] == '=') else if (curr == '!' && reader->source[p + 1] == '=')
token = add_double(reader, FZL_TOKTYPE_NEQ); token = rd_double(reader, FZL_TOKTYPE_NEQ);
else if (curr == '|' && reader->source[p + 1] == '|') else if (curr == '|' && reader->source[p + 1] == '|')
token = add_double(reader, FZL_TOKTYPE_DVBAR); token = rd_double(reader, FZL_TOKTYPE_DVBAR);
else if (curr == '&' && reader->source[p + 1] == '&') else if (curr == '&' && reader->source[p + 1] == '&')
token = add_double(reader, FZL_TOKTYPE_DAMPERSAND); token = rd_double(reader, FZL_TOKTYPE_DAMPERSAND);
else if (curr == '>') else if (curr == '>')
token = add_single(reader, FZL_TOKTYPE_RANGLE); token = rd_single(reader, FZL_TOKTYPE_RANGLE);
else if (curr == '<') else if (curr == '<')
token = add_single(reader, FZL_TOKTYPE_LANGLE); token = rd_single(reader, FZL_TOKTYPE_LANGLE);
else if (curr == '!') else if (curr == '!')
token = add_single(reader, FZL_TOKTYPE_NOT); token = rd_single(reader, FZL_TOKTYPE_NOT);
else if (curr == ';') else if (curr == ';')
token = add_single(reader, FZL_TOKTYPE_SEMICOLON); token = rd_single(reader, FZL_TOKTYPE_SEMICOLON);
else if (curr == '{') else if (curr == '{')
token = add_single(reader, FZL_TOKTYPE_LBRACE); token = rd_single(reader, FZL_TOKTYPE_LBRACE);
else if (curr == '}') else if (curr == '}')
token = add_single(reader, FZL_TOKTYPE_RBRACE); token = rd_single(reader, FZL_TOKTYPE_RBRACE);
else if (curr == '(') else if (curr == '(')
token = add_single(reader, FZL_TOKTYPE_LPAREN); token = rd_single(reader, FZL_TOKTYPE_LPAREN);
else if (curr == ')') else if (curr == ')')
token = add_single(reader, FZL_TOKTYPE_RPAREN); token = rd_single(reader, FZL_TOKTYPE_RPAREN);
else if (curr == ',') else if (curr == ',')
token = add_single(reader, FZL_TOKTYPE_COMMA); token = rd_single(reader, FZL_TOKTYPE_COMMA);
else if (curr == '.') else if (curr == '.')
token = add_single(reader, FZL_TOKTYPE_DOT); token = rd_single(reader, FZL_TOKTYPE_DOT);
else if (curr == '*') else if (curr == '*')
token = add_single(reader, FZL_TOKTYPE_STAR); token = rd_single(reader, FZL_TOKTYPE_STAR);
else if (curr == '/') else if (curr == '/')
token = add_single(reader, FZL_TOKTYPE_SLASH); token = rd_single(reader, FZL_TOKTYPE_SLASH);
else if (curr == '+') else if (curr == '+')
token = add_single(reader, FZL_TOKTYPE_PLUS); token = rd_single(reader, FZL_TOKTYPE_PLUS);
else if (curr == '-') else if (curr == '-')
token = add_single(reader, FZL_TOKTYPE_MINUS); token = rd_single(reader, FZL_TOKTYPE_MINUS);
else if (curr == '^') else if (curr == '^')
token = add_single(reader, FZL_TOKTYPE_CARET); token = rd_single(reader, FZL_TOKTYPE_CARET);
else if (curr == '%') else if (curr == '%')
token = add_single(reader, FZL_TOKTYPE_PERCENT); token = rd_single(reader, FZL_TOKTYPE_PERCENT);
else if (curr == '=') else if (curr == '=')
token = add_single(reader, FZL_TOKTYPE_EQ); token = rd_single(reader, FZL_TOKTYPE_EQ);
else if (curr == '$' && reader->source[p + 1] == '"')
{
move(reader, 2);
is_format_str = true;
token = fzl_mktoken(FZL_TOKTYPE_STR_FORMAT_START, 0, 0, NULL, 0, "");
}
else if ((curr >= 'A' && curr <= 'Z') || (curr >= 'a' && curr <= 'z') || else if ((curr >= 'A' && curr <= 'Z') || (curr >= 'a' && curr <= 'z') ||
curr == '_') curr == '_')
token = parse_name(reader); token = rd_name(reader);
else if (curr >= '0' && curr <= '9') else if (curr >= '0' && curr <= '9')
token = parse_number(reader); token = rd_number(reader);
else else
{ {
fzl_file_loc l; fzl_file_loc l;
@@ -363,8 +163,6 @@ int fzl_read(fzl_reader_t *reader)
return 0; return 0;
} }
// --- Read zone end ---
char *fzl_reader_geterror() { return last_err; } char *fzl_reader_geterror() { return last_err; }
void free_node_and_next(fzl_reader_ll_t *node) void free_node_and_next(fzl_reader_ll_t *node)
+5 -1
View File
@@ -30,7 +30,11 @@ fzl_token_t *fzl_mktoken(const fzl_toktype_t type, size_t line, size_t col,
// Free allocated token // Free allocated token
void fzl_freetoken(fzl_token_t *tok) void fzl_freetoken(fzl_token_t *tok)
{ {
if (tok->store_value) if (!tok)
return;
if (tok->store_value && tok->value)
free(tok->value); free(tok->value);
free(tok); free(tok);
} }
File diff suppressed because it is too large Load Diff
+55 -23
View File
@@ -1,4 +1,6 @@
#include <compiler/fzl_gen.h>
#include <compiler/fzl_writer.h> #include <compiler/fzl_writer.h>
#include <compiler/internals/writer.h>
#include <compiler/utils/fzl_const_pool.h> #include <compiler/utils/fzl_const_pool.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
@@ -11,52 +13,82 @@ char wrlast_err[256];
fzl_writer_t *fzl_mkwriter(const char *filepath) fzl_writer_t *fzl_mkwriter(const char *filepath)
{ {
if (strlen(filepath) < 1) if (strlen(filepath) < 1)
return NULL; return nullptr;
fzl_writer_t *writer = malloc(sizeof(fzl_writer_t)); fzl_writer_t *writer = malloc(sizeof(fzl_writer_t));
if (!writer) if (!writer)
return NULL; return nullptr;
writer->filepath = filepath; writer->filepath = filepath;
return writer; return writer;
} }
int fzl_write(fzl_writer_t *writer, fzl_walker_t *walker) int fzl_write(fzl_writer_t *writer, fzl_gen_t *gen)
{ {
if (!writer || !walker) if (!writer || !gen)
return -1; return -1;
FILE *fp = fopen(writer->filepath, "wb"); FILE *fd = fopen(writer->filepath, "wb");
if (!fp) if (!fd)
{ {
snprintf(wrlast_err, sizeof(wrlast_err), "failed to open '%s' to write", snprintf(wrlast_err, sizeof(wrlast_err), "failed to open '%s' to write",
writer->filepath); writer->filepath);
return -1; return -1;
} }
const char hdr[5] = {'F', 'Z', 'L', 0x0, 0x1}; constexpr char hdr[5] = {'F', 'Z', 'L', 0x0, 0x2};
fwrite(hdr, sizeof(char), 5, fp); fwrite(hdr, sizeof(char), 5, fd);
fwrite(&walker->consts->size, sizeof(size_t), 1, fp); fwrite(&gen->consts->size, sizeof(uint16_t), 1, fd);
fwrite(&walker->op_count, sizeof(size_t), 1, fp); fwrite(&gen->extern_libs_count, sizeof(uint16_t), 1, fd);
fwrite(&gen->extern_types_count, sizeof(uint16_t), 1, fd);
fwrite(&gen->extern_fns_count, sizeof(uint16_t), 1, fd);
fwrite(&gen->ops_count, sizeof(size_t), 1, fd);
for (size_t i = 0; i < walker->consts->size; i++) bool result = wr_consts(fd, gen->consts);
if (!result)
{ {
fzl_const_t c = walker->consts->array[i]; snprintf(wrlast_err, sizeof(wrlast_err), "failed to write constants table");
fwrite(&c.type, sizeof(fzl_consttype_t), 1, fp); fclose(fd);
return -1;
if (c.type == FZL_CONSTTYPE_STRING)
{
size_t strlen = c.as.string.length;
fwrite(&c.as.string.length, sizeof(size_t), 1, fp);
fwrite(c.as.string.chars, sizeof(char), strlen, fp);
}
} }
if (walker->op_count > 0) result = wr_extern_libs(fd, gen->extern_libs, gen->extern_libs_count);
fwrite(walker->ops, sizeof(uint64_t), walker->op_count, fp); if (!result)
{
snprintf(wrlast_err, sizeof(wrlast_err),
"failed to write external lib names");
fclose(fd);
return -1;
}
fclose(fp); result = wr_extern_types(fd, gen->extern_types, gen->extern_types_count);
if (!result)
{
snprintf(wrlast_err, sizeof(wrlast_err),
"failed to write extern lib types");
fclose(fd);
return -1;
}
result = wr_extern_fns(fd, gen->extern_fns, gen->extern_fns_count);
if (!result)
{
snprintf(wrlast_err, sizeof(wrlast_err),
"failed to write extern lib functions");
fclose(fd);
return -1;
}
result = wr_ops(fd, gen->ops, gen->ops_count);
if (!result)
{
snprintf(wrlast_err, sizeof(wrlast_err), "failed to write opcodes");
fclose(fd);
return -1;
}
fclose(fd);
return 0; return 0;
} }
+84
View File
@@ -0,0 +1,84 @@
#include "compiler/fzl_parser.h"
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <compiler/utils/fzl_symtable.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
// Nest context
fzl_gen_ctx_t *gen_ctx(fzl_gen_t *gen, fzl_gen_ctx_type_t type,
fzl_node_t *node)
{
if (!gen)
return NULL;
fzl_gen_ctx_t *ctx = malloc(sizeof(fzl_gen_ctx_t));
if (!ctx)
return NULL;
memset(ctx, 0, sizeof(fzl_gen_ctx_t));
ctx->type = type;
if (ctx->type != FZL_GEN_CTX_TYPE_CLASS)
{
fzl_symtable_t *symt = fzl_mksymt();
if (!symt)
{
free(ctx);
return NULL;
}
gen->syms[gen->syms_top++] = symt;
}
size_t level = 0;
fzl_gen_ctx_t *parent = gen->ctx;
while (parent != NULL)
{
level++;
parent = parent->parent;
}
ctx->level = level;
ctx->parent = gen->ctx;
if (type == FZL_GEN_CTX_TYPE_FUNCTION)
{
if (node->type == FZL_NODETYPE_FUNCTION ||
node->type == FZL_NODETYPE_EXTERN_FN)
ctx->function = node;
else
{
fzl_freesymt(gen->syms[--gen->syms_top]);
free(ctx);
return NULL;
}
}
gen->ctx = ctx;
return gen->ctx;
}
fzl_gen_ctx_t *gen_fin_ctx(fzl_gen_t *gen)
{
if (!gen)
return NULL;
fzl_gen_ctx_t *ctx = gen->ctx;
if (!ctx)
return NULL;
if (ctx->type != FZL_GEN_CTX_TYPE_CLASS)
{
fzl_symtable_t *sym = gen->syms[--gen->syms_top];
if (sym)
fzl_freesymt(sym);
}
gen->ctx = ctx->parent;
free(ctx);
return gen->ctx;
}
+31
View File
@@ -0,0 +1,31 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
char alias_typecn[256];
// Type aliasing
gen_res_t gen_alias(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_type_t type;
memset(alias_typecn, 0, sizeof(alias_typecn));
bool resolved = gen_resolve_type(gen, node->token, &type, alias_typecn);
if (!resolved)
return gen_error;
ssize_t slot = gen_resolve_extern_type(gen, alias_typecn);
if (slot == -1)
type_buf.alias_target =
(fzl_extern_type_ref_t){.is_primitive = true, .primitive = type};
else
type_buf.alias_target =
(fzl_extern_type_ref_t){.is_primitive = false, .type_slot = slot};
return gen_ok_null;
}
+122
View File
@@ -0,0 +1,122 @@
#include <compiler/fzl_gen.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/gen.h>
#include <string.h>
// Assignment to declaration
gen_res_t assign_declaration(fzl_gen_t *gen, fzl_node_t *node)
{
gen_res_t rres = gen_common(gen, node->binary_op.right);
if (rres.error)
return gen_error;
gen_res_t lres = gen_common(gen, node->binary_op.left);
if (lres.error)
return gen_error;
if (!gen_is_types_compatible(rres.type, lres.type, rres.classname,
lres.classname))
return gen_error;
gen_op(gen, FZL_OPCODE_WRITE);
return (gen_res_t){
.error = false, .type = rres.type, .classname = rres.classname};
}
// Assignment to identifier
gen_res_t assign_id(fzl_gen_t *gen, fzl_node_t *node)
{
gen_res_t rres = gen_common(gen, node->binary_op.right);
if (rres.error)
return gen_error;
char *name = (char *)node->binary_op.left->token->value;
fzl_sym_t sym;
bool found = false;
ssize_t i = gen->syms_top - 1;
for (; i >= 0; i--)
if ((found = fzl_symt_get(gen->syms[i], name, &sym)))
break;
if (!found)
return gen_error;
if (!gen_is_types_compatible(sym.type, rres.type, sym.classname,
rres.classname))
return gen_error;
if (!sym.slot_set)
return gen_error;
size_t depth = gen->syms_top - 1 - i;
gen_op(gen, FZL_OPCODE_STORE_LOCAL);
gen_word(gen, depth);
gen_word(gen, sym.slot);
return (gen_res_t){
.error = false, .type = rres.type, .classname = rres.classname};
}
// Assignment to field
gen_res_t assign_field(fzl_gen_t *gen, fzl_node_t *node)
{
gen_res_t rres = gen_common(gen, node->binary_op.right);
if (rres.error)
return gen_error;
fzl_node_t *field_node = node->binary_op.left;
gen_res_t obj_res = gen_common(gen, field_node->memb.parent);
if (obj_res.error)
return gen_error;
fzl_ctable_t *ct = NULL;
for (size_t i = 0; i < gen->classes_count; i++)
{
if (strcmp(obj_res.classname, gen->classes[i]->name) == 0)
{
ct = gen->classes[i];
break;
}
}
if (!ct)
return gen_error;
fzl_ctable_field_t *ctf = NULL;
for (size_t i = 0; i < ct->fields_count; i++)
{
if (strcmp(field_node->memb.field->token->value, ct->fields[i].name) == 0)
{
ctf = &ct->fields[i];
break;
}
}
if (!ctf)
return gen_error;
gen_op(gen, FZL_OPCODE_SET_FIELD);
gen_word(gen, ctf->slot_index);
return (gen_res_t){
.error = false, .type = rres.type, .classname = rres.classname};
}
// Assignment
gen_res_t gen_assign(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
if (node->binary_op.left->type == FZL_NODETYPE_DECLARATION)
return assign_declaration(gen, node);
if (node->binary_op.left->type == FZL_NODETYPE_IDENTIFIER)
return assign_id(gen, node);
if (node->binary_op.left->type == FZL_NODETYPE_FIELD)
return assign_field(gen, node);
return gen_error;
}
+27
View File
@@ -0,0 +1,27 @@
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
// Block definition
gen_res_t gen_block(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_gen_ctx_t *ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_UNECCESSARY, node);
if (!ctx)
return gen_error;
gen_op(gen, FZL_OPCODE_MK_ENVTABLE);
if (node->list.entry_count > 0)
for (size_t i = 0; i < node->list.entry_count; i++)
if (gen_common(gen, node->list.entries[i]).error)
return gen_error;
ctx = gen_fin_ctx(gen);
if (!ctx)
return gen_error;
gen_op(gen, FZL_OPCODE_RM_ENVTABLE);
return gen_ok_null;
}
+33
View File
@@ -0,0 +1,33 @@
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
// Break keyword
gen_res_t gen_break(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_gen_ctx_t *ctx = gen->ctx;
while (ctx != NULL)
{
if (ctx && ctx->type == FZL_GEN_CTX_TYPE_LOOP)
break;
ctx = ctx->parent;
}
if (!ctx || ctx->type != FZL_GEN_CTX_TYPE_LOOP)
return gen_error;
for (size_t i = gen->syms_top - 1; i > ctx->level + 1; i--)
gen_op(gen, FZL_OPCODE_RM_ENVTABLE);
gen_op(gen, FZL_OPCODE_JMP);
ctx->loop.breaks[ctx->loop.breaks_count++] = gen->ops_count;
gen_word(gen, 0);
return gen_ok_null;
}
+230
View File
@@ -0,0 +1,230 @@
#include <common/fzl_builtins.h>
#include <common/fzl_extern.h>
#include <common/fzl_opcodes.h>
#include <common/fzl_types.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
// Call definition
// NOTE: split by call type (builtin/declared/extern)
gen_res_t gen_call(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
// `printline(x)` builtin function
if (strcmp(node->token->value, "printline") == 0)
{
if (node->call.args_count > 0)
for (size_t i = 0; i < node->call.args_count; i++)
if (gen_common(gen, node->call.args[i]).error)
return gen_error;
gen_op(gen, FZL_OPCODE_CALL_BUILTIN);
gen_word(gen, FZL_BUILTIN_PRINTLINE);
if (node->call.args_count < 1)
return gen_error;
return gen_ok_null;
}
// `exit(x?)` builtin function
if (strcmp(node->token->value, "exit") == 0)
{
if (node->call.args_count > 0)
{
for (size_t i = 0; i < node->call.args_count; i++)
if (gen_common(gen, node->call.args[i]).error)
return gen_error;
gen_op(gen, FZL_OPCODE_CALL_BUILTIN);
gen_word(gen, FZL_BUILTIN_EXIT);
if (node->call.args_count < 1)
return gen_error;
}
return gen_ok_null;
}
if (node->call.callee->type == FZL_NODETYPE_IDENTIFIER)
{
if (node->call.args_count > 0)
for (size_t i = 0; i < node->call.args_count; i++)
if (gen_common(gen, node->call.args[i]).error)
return gen_error;
char *name = (char *)node->token->value;
fzl_sym_t sym;
bool found = gen_resolve_name(gen, name, &sym);
if (!found)
return gen_error;
if (sym.node->type == FZL_NODETYPE_EXTERN_FN)
{
size_t fn_n = 0;
fzl_extern_fn_t *fn = NULL;
for (size_t i = 0; i < gen->extern_fns_count; i++)
{
if (strcmp(gen->extern_fns[i].used_name, name) == 0)
{
fn = &gen->extern_fns[i];
fn_n = i;
break;
}
}
if (!fn)
return gen_error;
fzl_type_t rettype;
char *rettypecn = NULL;
if (!fn->has_return)
{
rettype = FZL_TYPE_NULL;
}
else if (fn->ret_type.is_primitive)
{
rettype = fn->ret_type.primitive;
}
else
{
fzl_extern_type_t *type = &gen->extern_types[fn->ret_type.type_slot];
switch (type->kind)
{
case FZL_EXTERN_KIND_REF:
rettype = FZL_TYPE_HANDLE;
rettypecn = type->name;
break;
case FZL_EXTERN_KIND_STRUCT:
rettype = FZL_TYPE_STRUCT;
rettypecn = type->name;
break;
case FZL_EXTERN_KIND_HANDLE:
rettype = FZL_TYPE_HANDLE;
rettypecn = type->name;
break;
case FZL_EXTERN_KIND_ALIAS:
if (type->alias_target.is_primitive)
{
rettype = type->alias_target.primitive;
}
else
{
fzl_extern_type_t *aliased =
&gen->extern_types[type->alias_target.type_slot];
switch (aliased->kind)
{
case FZL_EXTERN_KIND_ALIAS:
return gen_error;
case FZL_EXTERN_KIND_HANDLE:
rettype = FZL_TYPE_HANDLE;
rettypecn = aliased->name;
break;
case FZL_EXTERN_KIND_STRUCT:
rettype = FZL_TYPE_STRUCT;
rettypecn = aliased->name;
break;
case FZL_EXTERN_KIND_REF:
rettype = FZL_TYPE_HANDLE;
rettypecn = aliased->name;
break;
default:
return gen_error;
}
}
break;
default:
return gen_error;
}
}
gen_op(gen, FZL_OPCODE_CALL_EXTERN);
gen_word(gen, fn_n);
return (gen_res_t){
.error = false, .type = rettype, .classname = rettypecn};
}
else
{
if (!sym.ip)
return gen_error;
gen_op(gen, FZL_OPCODE_CALL);
gen_word(gen, sym.ip);
return (gen_res_t){
.error = false, .type = sym.type, .classname = sym.classname};
}
}
if (node->call.callee->type == FZL_NODETYPE_FIELD)
{
fzl_node_t *parent_node = node->call.callee->memb.parent;
fzl_node_t *method_node = node->call.callee->memb.field;
gen_res_t parent_res = gen_common(gen, parent_node);
if (parent_res.error)
return gen_error;
if (parent_res.type != FZL_TYPE_OBJECT || !parent_res.classname)
return gen_error;
char *classname = parent_res.classname;
bool class_exists = false;
for (size_t i = 0; i < gen->classes_count; i++)
{
if (strcmp(classname, gen->classes[i]->name) == 0)
{
class_exists = true;
break;
}
}
if (!class_exists)
return gen_error;
size_t classlen = strlen(classname);
size_t fnlen = strlen(method_node->token->value);
char *methodname = malloc(classlen + fnlen + 2);
strcpy(methodname, classname);
strcpy((methodname + classlen + 1), method_node->token->value);
methodname[classlen] = '_';
methodname[classlen + fnlen + 1] = 0;
fzl_sym_t fn_sym;
bool found_method = false;
for (ssize_t i = gen->syms_top - 1; i >= 0; i--)
if ((found_method = fzl_symt_get(gen->syms[i], methodname, &fn_sym)))
break;
free(methodname);
if (!found_method)
return gen_error;
if (node->call.args_count > 0)
for (size_t i = 0; i < node->call.args_count; i++)
if (gen_common(gen, node->call.args[i]).error)
return gen_error;
gen_op(gen, FZL_OPCODE_CALL);
gen_word(gen, fn_sym.ip);
return (gen_res_t){
.error = false, .type = fn_sym.type, .classname = fn_sym.classname};
}
return gen_error;
}
+79
View File
@@ -0,0 +1,79 @@
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char class_typecn[256];
// Class definition
gen_res_t gen_class(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_gen_ctx_t *ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_CLASS, node);
if (!ctx)
return gen_error;
gen->classes[gen->classes_count] = fzl_mkctable(node->class.name->value);
fzl_ctable_t *class = gen->classes[gen->classes_count++];
class->name = (char *)node->class.name->value;
for (size_t i = 0; i < node->class.fields_count; i++)
{
if (class->fields_remainder <= class->fields_count)
{
class->fields_remainder *= 2;
class->fields = realloc(class->fields, class->fields_remainder *
sizeof(fzl_ctable_field_t));
}
fzl_type_t type;
memset(class_typecn, 0, sizeof(class_typecn));
bool resolved = gen_resolve_type(gen, node->class.fields[i]->var.type,
&type, class_typecn);
if (!resolved)
return gen_error;
class->fields[class->fields_count] = (fzl_ctable_field_t){
.name = node->class.fields[i]->var.identifier->token->value,
.type = type,
.slot_index = class->fields_count++};
}
for (size_t i = 0; i < node->class.methods_count; i++)
{
fzl_node_t *fn = node->class.methods[i];
size_t classname_len = strlen(class->name);
size_t fnname_len = strlen(fn->fn.name->value);
char *method_name = malloc(classname_len + fnname_len + 2);
strcpy(method_name, class->name);
method_name[classname_len] = '_';
strcpy((method_name + classname_len + 1), fn->fn.name->value);
method_name[classname_len + fnname_len + 1] = 0;
if (fn->fn.name->value)
free(fn->fn.name->value);
fn->fn.name->value = method_name;
if (gen_common(gen, fn).error)
{
free(method_name);
fn->fn.name->value = NULL;
return gen_error;
}
}
ctx = gen_fin_ctx(gen);
if (!ctx)
return gen_error;
return gen_ok_null;
}
+154
View File
@@ -0,0 +1,154 @@
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
typedef gen_res_t (*gen_handle_fn)(fzl_gen_t *, fzl_node_t *);
char *null_name = "<null>";
gen_res_t gen_error = (gen_res_t){.error = true};
gen_res_t gen_ok_null =
(gen_res_t){.error = false, .type = FZL_TYPE_NULL, .classname = NULL};
// Common generator entry point
gen_res_t gen_common(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_handle_fn res = NULL;
switch (node->type)
{
case FZL_NODETYPE_ASSIGN:
res = gen_assign;
break;
case FZL_NODETYPE_DECLARATION:
res = gen_declaration;
break;
case FZL_NODETYPE_NOT:
res = gen_unary_logical;
break;
case FZL_NODETYPE_EQUAL:
case FZL_NODETYPE_NEQUAL:
case FZL_NODETYPE_LESS:
case FZL_NODETYPE_LESS_EQUAL:
case FZL_NODETYPE_GREATER:
case FZL_NODETYPE_GREATER_EQUAL:
res = gen_compare;
break;
case FZL_NODETYPE_OR:
case FZL_NODETYPE_AND:
res = gen_logical;
break;
case FZL_NODETYPE_UNARY_PLUS:
case FZL_NODETYPE_UNARY_MINUS:
res = gen_unary_math;
break;
case FZL_NODETYPE_ADD:
case FZL_NODETYPE_SUB:
case FZL_NODETYPE_MUL:
case FZL_NODETYPE_DIV:
case FZL_NODETYPE_POW:
case FZL_NODETYPE_MOD:
res = gen_math;
break;
case FZL_NODETYPE_BREAK:
res = gen_break;
break;
case FZL_NODETYPE_LOOP:
res = gen_loop;
break;
case FZL_NODETYPE_CONSTRUCT:
res = gen_construct;
break;
case FZL_NODETYPE_FIELD:
res = gen_field;
break;
case FZL_NODETYPE_CLASS:
res = gen_class;
break;
case FZL_NODETYPE_CALL:
res = gen_call;
break;
case FZL_NODETYPE_RETURN:
res = gen_return;
break;
case FZL_NODETYPE_FUNCTION:
res = gen_fn;
break;
case FZL_NODETYPE_CONDITIONAL:
res = gen_condition;
break;
case FZL_NODETYPE_IDENTIFIER:
res = gen_identifier;
break;
case FZL_NODETYPE_FMT_STRING:
res = gen_fmtstr;
break;
case FZL_NODETYPE_LITERAL:
res = gen_literal;
break;
case FZL_NODETYPE_BLOCK:
res = gen_block;
break;
case FZL_NODETYPE_EXTERN:
res = gen_extern;
break;
case FZL_NODETYPE_TYPEDEF:
res = gen_typedef;
break;
case FZL_NODETYPE_HANDLE:
res = gen_handle;
break;
case FZL_NODETYPE_ALIAS:
res = gen_alias;
break;
case FZL_NODETYPE_STRUCT:
res = gen_struct;
break;
case FZL_NODETYPE_REFERENCE:
res = gen_reference;
break;
case FZL_NODETYPE_EXTERN_FN:
res = gen_externfn;
break;
}
if (!res)
{
printf("Bruh, you, suka, go fix the generator blyat (%s:%d)\n", __FILE__,
__LINE__);
return gen_error;
}
return res(gen, node);
}
+83
View File
@@ -0,0 +1,83 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdio.h>
// Comparison operations
gen_res_t gen_compare(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_res_t left = gen_common(gen, node->binary_op.left);
if (left.error)
return left;
gen_res_t right = gen_common(gen, node->binary_op.right);
if (right.error)
return right;
if (!gen_is_types_compatible(left.type, right.type, left.classname,
right.classname))
return gen_error;
if (left.type == FZL_TYPE_STRING && right.type == FZL_TYPE_STRING)
{
switch (node->type)
{
case FZL_NODETYPE_EQUAL:
gen_op(gen, FZL_OPCODE_CMP_EQ_STR);
break;
case FZL_NODETYPE_NEQUAL:
gen_op(gen, FZL_OPCODE_CMP_NEQ_STR);
break;
default:
return gen_error;
}
}
else if (left.type == FZL_TYPE_OBJECT && right.type == FZL_TYPE_OBJECT)
{
switch (node->type)
{
case FZL_NODETYPE_EQUAL:
gen_op(gen, FZL_OPCODE_CMP_EQ_OBJ);
break;
case FZL_NODETYPE_NEQUAL:
gen_op(gen, FZL_OPCODE_CMP_NEQ_OBJ);
break;
default:
return gen_error;
}
}
else
{
switch (node->type)
{
case FZL_NODETYPE_EQUAL:
gen_op(gen, FZL_OPCODE_CMP_EQ);
break;
case FZL_NODETYPE_NEQUAL:
gen_op(gen, FZL_OPCODE_CMP_NEQ);
break;
case FZL_NODETYPE_LESS:
gen_op(gen, FZL_OPCODE_CMP_LT);
break;
case FZL_NODETYPE_LESS_EQUAL:
gen_op(gen, FZL_OPCODE_CMP_LTEQ);
break;
case FZL_NODETYPE_GREATER:
gen_op(gen, FZL_OPCODE_CMP_GT);
break;
case FZL_NODETYPE_GREATER_EQUAL:
gen_op(gen, FZL_OPCODE_CMP_GTEQ);
break;
default:
break;
}
}
return (gen_res_t){.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
+37
View File
@@ -0,0 +1,37 @@
#include <compiler/internals/gen.h>
// Conditional operation
gen_res_t gen_condition(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_res_t cres = gen_common(gen, node->cond.condition);
if (cres.error)
return gen_error;
gen_op(gen, FZL_OPCODE_JZ);
size_t jz_if = gen->ops_count;
gen_word(gen, (uint64_t)0);
gen_res_t tblock_res = gen_common(gen, node->cond.true_block);
if (tblock_res.error)
return gen_error;
gen_op(gen, FZL_OPCODE_JMP);
size_t jmp_else = gen->ops_count;
gen_word(gen, (uint64_t)0);
gen->ops[jz_if] = gen->ops_count;
if (node->cond.else_block)
{
gen_res_t fblock_res = gen_common(gen, node->cond.else_block);
if (fblock_res.error)
return gen_error;
}
gen->ops[jmp_else] = gen->ops_count;
return gen_ok_null;
}
+30
View File
@@ -0,0 +1,30 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <string.h>
// Object constructing
gen_res_t gen_construct(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_node_t *classname = node->construct.name;
fzl_ctable_t *ct = NULL;
for (size_t i = 0; i < gen->classes_count; i++)
{
if (strcmp((char *)classname->token->value, gen->classes[i]->name) == 0)
{
ct = gen->classes[i];
break;
}
}
if (!ct)
return gen_error;
gen_op(gen, FZL_OPCODE_ALLOC_OBJECT);
gen_word(gen, ct->fields_count);
return (gen_res_t){
.error = false, .type = FZL_TYPE_OBJECT, .classname = ct->name};
}
+61
View File
@@ -0,0 +1,61 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <string.h>
char dec_typecn[256];
// Variable (or argument) declaration
gen_res_t gen_declaration(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
char *name = (char *)node->var.identifier->token->value;
fzl_type_t type;
memset(dec_typecn, 0, sizeof(dec_typecn));
bool resolved = gen_resolve_type(gen, node->var.type, &type, dec_typecn);
if (!resolved)
return gen_error;
fzl_ctable_t *ct = NULL;
if (type == FZL_TYPE_OBJECT)
{
for (size_t i = 0; i < gen->classes_count; i++)
{
if (strcmp(node->var.type->value, gen->classes[i]->name) == 0)
{
ct = gen->classes[i];
break;
}
}
}
fzl_symtable_res_t res =
fzl_symt_put(gen->syms[gen->syms_top - 1], node, name, type, 0);
if (ct)
fzl_symt_setobjclass(gen->syms[gen->syms_top - 1], name, ct->name);
if (res != FZL_SYMTABLE_RESULT_OK)
return gen_error;
if (fzl_symt_setslot(gen->syms[gen->syms_top - 1], name) < 0)
return gen_error;
fzl_token_t *id_tok = node->var.identifier->token;
size_t const_n =
gen_add_const(gen, (fzl_const_t){.type = FZL_CONSTTYPE_STRING,
.as.string.chars = id_tok->value,
.as.string.length = id_tok->value_sz});
gen_op(gen, FZL_OPCODE_LOADCONST);
gen_word(gen, const_n);
gen_op(gen, FZL_OPCODE_STORE);
gen_op(gen, FZL_OPCODE_LOADCONST);
gen_word(gen, const_n);
return (gen_res_t){.error = false, .type = type, .classname = dec_typecn};
}
+26
View File
@@ -0,0 +1,26 @@
#include <common/fzl_extern.h>
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
// Extern block
gen_res_t gen_extern(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen->extern_libs[gen->extern_libs_count++] =
(fzl_extern_lib_t){.name = (char *)node->ext.libname};
for (size_t i = 0; i < node->ext.typedefs_count; i++)
if (gen_common(gen, node->ext.typedefs[i]).error)
return gen_error;
for (size_t i = 0; i < node->ext.fns_count; i++)
if (gen_common(gen, node->ext.fns[i]).error)
return gen_error;
return gen_ok_null;
}
+135
View File
@@ -0,0 +1,135 @@
#include <common/fzl_extern.h>
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/fzl_parser.h>
#include <compiler/internals/gen.h>
#include <compiler/utils/fzl_symtable.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char ex_argcn[256];
char ex_retcn[256];
// External function definition
gen_res_t gen_externfn(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_gen_ctx_t *ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_FUNCTION, node);
if (!ctx)
return gen_error;
size_t args_remainder = 2;
size_t args_count = 0;
fzl_extern_arg_t *args = malloc(args_remainder * sizeof(fzl_extern_arg_t));
if (!args)
return gen_error;
for (size_t i = 0; i < node->ext_fn.args_count; i++)
{
fzl_node_t *argnode = node->ext_fn.args[i];
if (args_count >= args_remainder)
{
args_remainder *= 2;
fzl_extern_arg_t *newargs =
realloc(args, args_remainder * sizeof(fzl_extern_arg_t));
if (!newargs)
{
free(args);
return gen_error;
}
args = newargs;
}
if (argnode->type != FZL_NODETYPE_DECLARATION)
{
free(args);
return gen_error;
}
fzl_extern_arg_t *arg = &args[args_count++];
fzl_type_t argtype;
memset(ex_argcn, 0, sizeof(ex_argcn));
bool resolved =
gen_resolve_type(gen, argnode->var.type, &argtype, ex_argcn);
if (!resolved)
{
free(args);
return gen_error;
}
ssize_t slot = gen_resolve_extern_type(gen, ex_argcn);
if (slot == -1)
arg->type =
(fzl_extern_type_ref_t){.is_primitive = true, .primitive = argtype};
else
arg->type =
(fzl_extern_type_ref_t){.is_primitive = false, .type_slot = slot};
arg->name = (char *)argnode->var.identifier->token->value;
arg->is_out = argnode->var.is_out;
}
ctx = gen_fin_ctx(gen);
if (!ctx)
{
free(args);
return gen_error;
}
fzl_type_t ret;
memset(ex_retcn, 0, sizeof(ex_retcn));
bool resolved = gen_resolve_type(gen, node->ext_fn.type, &ret, ex_retcn);
if (!resolved)
{
free(args);
return gen_error;
}
fzl_symtable_res_t res =
fzl_symt_put(gen->syms[0], node, node->ext_fn.name, ret, 0);
if (res != FZL_SYMTABLE_RESULT_OK)
{
free(args);
return gen_error;
}
if (ret == FZL_TYPE_OBJECT || ret == FZL_TYPE_STRUCT ||
ret == FZL_TYPE_HANDLE)
{
res = fzl_symt_setobjclass(gen->syms[0], node->ext_fn.name, ex_retcn);
if (res != FZL_SYMTABLE_RESULT_OK)
{
free(args);
return gen_error;
}
}
fzl_extern_fn_t *result = &gen->extern_fns[gen->extern_fns_count++];
ssize_t slot = gen_resolve_extern_type(gen, ex_retcn);
if (slot == -1)
result->ret_type =
(fzl_extern_type_ref_t){.is_primitive = true, .primitive = ret};
else
result->ret_type =
(fzl_extern_type_ref_t){.is_primitive = false, .type_slot = slot};
result->lib_slot = gen->extern_libs_count - 1;
result->args = args;
result->args_count = args_count;
result->has_return = ret != FZL_TYPE_NULL;
result->used_name = node->ext_fn.name;
result->symbol_name = node->ext_fn.original_name ? node->ext_fn.original_name
: node->ext_fn.name;
return gen_ok_null;
}
+49
View File
@@ -0,0 +1,49 @@
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <string.h>
// Field access
gen_res_t gen_field(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_res_t parent_res = gen_common(gen, node->memb.parent);
if (parent_res.error)
return gen_error;
fzl_ctable_t *ct = NULL;
for (size_t i = 0; i < gen->classes_count; i++)
{
if (strcmp(parent_res.classname, gen->classes[i]->name) == 0)
{
ct = gen->classes[i];
break;
}
}
if (!ct)
return gen_error;
fzl_token_t *ftok = node->memb.field->token;
fzl_ctable_field_t ctf;
bool field_exists = false;
for (size_t i = 0; i < ct->fields_count; i++)
{
if (strcmp(ftok->value, ct->fields[i].name) == 0)
{
field_exists = true;
ctf = ct->fields[i];
break;
}
}
if (!field_exists)
return gen_error;
gen_op(gen, FZL_OPCODE_GET_FIELD);
gen_word(gen, ctf.slot_index);
return (gen_res_t){
.error = false, .type = ctf.type, .classname = parent_res.classname};
}
+21
View File
@@ -0,0 +1,21 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
// Format string
gen_res_t gen_fmtstr(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
for (size_t i = 0; i < node->list.entry_count; i++)
if (gen_common(gen, node->list.entries[i]).error)
return gen_error;
gen_op(gen, FZL_OPCODE_BUILD_STR);
gen_word(gen, node->list.entry_count);
return (gen_res_t){
.error = false, .type = FZL_TYPE_STRING, .classname = NULL};
}
+67
View File
@@ -0,0 +1,67 @@
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
char fn_typecn[256];
// Function definition
gen_res_t gen_fn(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_op(gen, FZL_OPCODE_JMP);
size_t skip_ip = gen->ops_count;
gen_word(gen, (uint64_t)0);
fzl_type_t fntype;
memset(fn_typecn, 0, sizeof(fn_typecn));
bool resolved = gen_resolve_type(gen, node->fn.type, &fntype, fn_typecn);
if (!resolved)
return gen_error;
fzl_symtable_res_t putres =
fzl_symt_put(gen->syms[gen->syms_top - 1], node, node->fn.name->value,
fntype, gen->ops_count);
if (putres != FZL_SYMTABLE_RESULT_OK)
return gen_error;
if (fntype == FZL_TYPE_OBJECT)
{
fzl_symtable_res_t updres = fzl_symt_setobjclass(
gen->syms[gen->syms_top - 1], node->fn.name->value, fn_typecn);
if (updres != FZL_SYMTABLE_RESULT_OK)
return gen_error;
}
fzl_gen_ctx_t *ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_FUNCTION, node);
if (!ctx)
return gen_error;
gen_op(gen, FZL_OPCODE_MK_ENVTABLE);
for (ssize_t i = node->fn.args_count - 1; i >= 0; i--)
{
if (gen_common(gen, node->fn.args[i]).error)
return gen_error;
gen_op(gen, FZL_OPCODE_WRITE);
}
if (gen_common(gen, node->fn.body).error)
return gen_error;
gen_op(gen, FZL_OPCODE_RM_ENVTABLE);
gen_op(gen, FZL_OPCODE_RET);
gen->ops[skip_ip] = gen->ops_count;
ctx = gen_fin_ctx(gen);
if (!ctx)
return gen_error;
return (gen_res_t){.error = false, .type = fntype, .classname = fn_typecn};
}
+13
View File
@@ -0,0 +1,13 @@
#include <common/fzl_extern.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
// Opaque pointer
gen_res_t gen_handle(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
type_buf.kind = FZL_EXTERN_KIND_HANDLE;
return gen_ok_null;
}
+29
View File
@@ -0,0 +1,29 @@
#include <compiler/internals/gen.h>
// Identifier lookup
gen_res_t gen_identifier(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_sym_t sym;
bool exists = false;
ssize_t i = gen->syms_top - 1;
for (; i >= 0; i--)
if ((exists = fzl_symt_get(gen->syms[i], node->token->value, &sym)))
break;
if (!exists)
return gen_error;
if (!sym.slot_set)
return gen_error;
size_t depth = gen->syms_top - 1 - i;
gen_op(gen, FZL_OPCODE_LOAD_LOCAL);
gen_word(gen, depth);
gen_word(gen, sym.slot);
return (gen_res_t){
.error = false, .type = sym.type, .classname = sym.classname};
}
+59
View File
@@ -0,0 +1,59 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
gen_res_t gen_literal(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
if (node->token->type == FZL_TOKTYPE_STR_LITERAL)
{
size_t n = gen_add_const(
gen, (fzl_const_t){.type = FZL_CONSTTYPE_STRING,
.as.string.chars = node->token->value,
.as.string.length = node->token->value_sz});
gen_op(gen, FZL_OPCODE_LOADCONST);
gen_word(gen, n);
return (gen_res_t){
.error = false, .type = FZL_TYPE_STRING, .classname = NULL};
}
if (node->token->type == FZL_TOKTYPE_NUM_LITERAL)
{
gen_op(gen, FZL_OPCODE_PUSHNUM);
uint64_t num = strtol(node->token->value, NULL, 10);
gen_word(gen, num);
return (gen_res_t){.error = false, .type = FZL_TYPE_INT, .classname = NULL};
}
if (node->token->type == FZL_TOKTYPE_BOOL_LITERAL)
{
fzl_token_t *tok = node->token;
uint64_t val = strcmp(tok->value, "true") == 0 ? 1 : 0;
gen_op(gen, FZL_OPCODE_PUSHBOOL);
gen_word(gen, val);
return (gen_res_t){
.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
if (node->token->type == FZL_TOKTYPE_NULL_LITERAL)
{
gen_op(gen, FZL_OPCODE_PUSHNUM);
gen_word(gen, 0);
gen_op(gen, FZL_OPCODE_DEREFERENCE);
return (gen_res_t){
.error = false, .type = FZL_TYPE_OBJECT, .classname = null_name};
}
return gen_error;
}
+29
View File
@@ -0,0 +1,29 @@
#include <common/fzl_types.h>
#include <compiler/internals/gen.h>
#include <stdio.h>
// Binary logical operations (and / or)
gen_res_t gen_logical(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
gen_res_t left = gen_common(gen, node->binary_op.left);
if (left.error)
return left;
gen_res_t right = gen_common(gen, node->binary_op.right);
if (right.error)
return right;
if (!gen_is_types_compatible(left.type, right.type, left.classname,
right.classname))
return gen_error;
if (node->type == FZL_NODETYPE_AND)
gen_op(gen, FZL_OPCODE_AND);
else
gen_op(gen, FZL_OPCODE_OR);
return (gen_res_t){.error = false, .type = FZL_TYPE_BOOL, .classname = NULL};
}
+63
View File
@@ -0,0 +1,63 @@
#include <common/fzl_types.h>
#include <compiler/fzl_gen.h>
#include <compiler/internals/gen.h>
#include <stdbool.h>
#include <stdio.h>
// While or for loops
gen_res_t gen_loop(fzl_gen_t *gen, fzl_node_t *node)
{
if (!gen || !node)
return gen_error;
fzl_gen_ctx_t *ctx = gen_ctx(gen, FZL_GEN_CTX_TYPE_LOOP, node);
if (!ctx)
return gen_error;
gen_op(gen, FZL_OPCODE_MK_ENVTABLE);
if (node->loop.init)
if (gen_common(gen, node->loop.init).error)
return gen_error;
size_t start_ip = gen->ops_count;
if (node->loop.cond)
{
if (gen_common(gen, node->loop.cond).error)
return gen_error;
}
else
{
gen_op(gen, FZL_OPCODE_PUSHNUM);
gen_word(gen, 1);
}
gen_op(gen, FZL_OPCODE_JZ);
ctx->loop.breaks[ctx->loop.breaks_count++] = gen->ops_count;
gen_word(gen, 0);
if (gen_common(gen, node->loop.body).error)
return gen_error;
if (node->loop.step)
if (gen_common(gen, node->loop.step).error)
return gen_error;
gen_op(gen, FZL_OPCODE_JMP);
gen_word(gen, start_ip);
// backpatch `break`s
for (size_t i = 0; i < ctx->loop.breaks_count; i++)
gen->ops[ctx->loop.breaks[i]] = gen->ops_count;
gen_op(gen, FZL_OPCODE_RM_ENVTABLE);
for (size_t i = gen->syms_top - 1; i > ctx->level + 1; i--)
fzl_freesymt(gen->syms[--gen->syms_top]);
ctx = gen_fin_ctx(gen);
if (!ctx)
return gen_error;
return gen_ok_null;
}

Some files were not shown because too many files have changed in this diff Show More