Compare commits

...

39 Commits

Author SHA1 Message Date
Username404-59 bd87e9a93b
ParseComponents.hpp: Add two helper functions for ParseTree.parent
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-19 19:17:50 +01:00
Username404-59 a3e2427017
ParseComponents.hpp: Add a parent reference wrapper to ParseTree
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-19 18:32:24 +01:00
Username404-59 76cc701dd7
Py.hpp, GodotScript.hpp: Add missing pass after empty else branches
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-01 04:30:12 +01:00
Username404-59 2758a2e95a
SemanticAnalysis.hpp: Re-add checking for redefinitions of constants
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-01 04:21:20 +01:00
Username404-59 af9f76ee72
Retain line numbers for semantic analysis and fix checking redefinitions
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-01 02:21:57 +01:00
Username404-59 91c1ae0611
GodotScript.hpp: Add a TODO
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-01 01:09:07 +01:00
Username404-59 fa874ef0d2
Don't try to find duplicate references, this is stupid
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2025-01-01 01:06:51 +01:00
Username404-59 888c75a31e
Share the Reference analysis task with the Define one
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-12-31 23:11:15 +01:00
Username404-59 2c0cec16d6
Move redefinition checking to SemanticAnalysis.hpp
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-12-31 19:59:02 +01:00
Username404-59 7fb9ca37a7
Move task macros to Tasking.hpp
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-08-07 14:28:14 +02:00
Username404-59 d4df3aa4ea
Add boilerplate for semantic analysis
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-08-07 03:05:55 +02:00
Username404-59 ea8902a3cc
Target.hpp: Fix the shitty Yerbacon::fail call in Target::forName
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-07-31 21:45:26 +02:00
Username404-59 d3248c04a0
GodotScript.hpp: Add missing namespace usage
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-07-31 20:29:41 +02:00
Username404-59 b528811d7c
README.md: Fix the path to Yerbacon.svg
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-06-22 21:29:15 +02:00
Username404-59 023af39a22
CMakeLists.txt: Support emscripten 3.1.58 SINGLE_FILE without a worker.js file
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-05-10 03:29:12 +02:00
Username404-59 d4c854d8ef
Jenkinsfile: Add another ldid fork link to the documentation
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-03-31 22:03:33 +02:00
Username404-59 1f319e9697
Jenkinsfile: Fix documentation
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2024-03-31 19:58:17 +02:00
Username404-59 3d97955d41
CMakeLists.txt: Replace the deprecated vercel_pkg with yao_pkg
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2024-03-31 19:52:38 +02:00
Username404-59 5d43854e6d
CMakeLists.txt: Support emscripten 3.1.54 and higher
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-03-27 20:54:50 +01:00
Username404-59 8f92674387
lexer.cpp: Remove commented test code
Signed-off-by: Username404-59 <w.iron.zombie@gmail.com>
2024-03-13 18:02:54 +01:00
Username404 7a4549dafb
main.cpp: Remove useless optional usage
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-10-18 10:36:01 +02:00
Username404 7d5abdf9b5
Jenkinsfile: Add Android targets
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-17 12:00:32 +02:00
Username404 2b22029e77
Jenkinsfile: Make RPM packages for i686 instead of i386
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-16 22:06:37 +02:00
Username404 1a9b549f9b
CMakeLists.txt: Link OpenMP statically on Android
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-16 21:01:43 +02:00
Username404 8a7f556520
CMakeLists.txt: Allow PIE with UPX since it now seems to work with it
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-16 20:36:05 +02:00
Username404 8706db23b3
Yerbacon.hpp: Make sure the OpenMP headers are included when they are present
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-16 19:12:57 +02:00
Username404 3476d3c642
lexer.cpp: Rename isString to isStringDelimiter
Add a few comments in other files

Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-12 13:02:36 +02:00
Username404 a8d1e6b09a
main.cpp: Add a newline to code that is given by the "--text" argument
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-08 03:14:45 +02:00
Username404 ddaf3a44d1
Parser.hpp: Prioritize missing conditions over missing body code
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-08 03:01:38 +02:00
Username404 c37f91caf3
Lua.hpp: Fix an extra space being added
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-07 00:34:27 +02:00
Username404 85a3582612
Parser.hpp: Add basic parsing of if/elseif/else statements
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-06 19:49:35 +02:00
Username404 164e5c5da3
Parser.hpp: Fix an indentation mistake
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-08-04 16:45:10 +02:00
Username404 4f99cd6cae
Jenkinsfile: Specify that emscripten 3.1.30 is known to work
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-07-27 03:53:34 +02:00
Username404 fe5de82208
Parser.hpp: Parse all references instead of properties only
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-06-21 16:57:54 +02:00
Username404 ade66e8343
main.cpp: Add emscripten support to the "--output" argument
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-06-16 12:08:54 +02:00
Username404 c1b0184b64
filefuncs.cpp: Simplify the outputFileContent function
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-06-13 00:35:09 +02:00
Username404 d41d492686
main.cpp: Add a '-o'/'--output' argument
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-06-12 21:31:46 +02:00
Username404 e20e7dabdc
Parser.hpp: Add a TODO comment
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-05-07 21:58:04 +02:00
Username404 5b04eb37b0
ParseComponents.hpp: Add two missing iterator functions
Signed-off-by: Username404 <w.iron.zombie@gmail.com>
2023-04-30 16:38:41 +02:00
23 changed files with 398 additions and 126 deletions

View File

@ -67,6 +67,9 @@ if (${IS_GNU} OR ${IS_CLANG})
include(FindOpenMP)
if (OpenMP_CXX_FOUND)
set(CMAKE_CXX_FLAGS "${OpenMP_CXX_FLAGS} ${CMAKE_CXX_FLAGS}")
if (ANDROID)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-openmp")
endif()
add_definitions(-D_GLIBCXX_PARALLEL)
endif()
endif()
@ -78,7 +81,15 @@ if (${IS_GNU} OR ${IS_CLANG})
else()
set(IS_HOST_NOT_ANDROID 0)
endif()
set(CMAKE_EXE_LINKER_FLAGS "--closure 1 --closure-args=\"--compilation_level SIMPLE\" -lnodefs.js -lembind -sDYNAMIC_EXECUTION=0 -sFORCE_FILESYSTEM=1 -sWASM=0 --memory-init-file 0 -sEXPORTED_FUNCTIONS=_main -sEXIT_RUNTIME=1 -sSINGLE_FILE=1 -sSAFE_HEAP=${IS_HOST_NOT_ANDROID} -sMALLOC='emmalloc' -sABORTING_MALLOC=0 -sJS_MATH=1 -sENVIRONMENT='web,webview,worker,node,shell' -sNODEJS_CATCH_EXIT=0 -sSTRICT=1 -sMINIMAL_RUNTIME=0 -sDISABLE_EXCEPTION_CATCHING=0 -sSTACK_SIZE=8MB -sALLOW_MEMORY_GROWTH=1 -Wno-pthreads-mem-growth -sMEMORY_GROWTH_GEOMETRIC_STEP=0 -sDECLARE_ASM_MODULE_EXPORTS=1 -sDEMANGLE_SUPPORT=1 ${CMAKE_EXE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "--closure 1 --closure-args=\"--compilation_level SIMPLE\" -lnodefs.js -lembind -sDYNAMIC_EXECUTION=0 -sFORCE_FILESYSTEM=1 -sWASM=0 -sEXPORTED_FUNCTIONS=_main -sEXIT_RUNTIME=1 -sSINGLE_FILE=1 -sSAFE_HEAP=${IS_HOST_NOT_ANDROID} -sMALLOC='emmalloc' -sABORTING_MALLOC=0 -sJS_MATH=1 -sENVIRONMENT='web,webview,worker,node,shell' -sNODEJS_CATCH_EXIT=0 -sMINIMAL_RUNTIME=0 -sDISABLE_EXCEPTION_CATCHING=0 -sSTACK_SIZE=8MB -sALLOW_MEMORY_GROWTH=1 -Wno-pthreads-mem-growth -sMEMORY_GROWTH_GEOMETRIC_STEP=0 -sDECLARE_ASM_MODULE_EXPORTS=1 ${CMAKE_EXE_LINKER_FLAGS}")
if (EMSCRIPTEN_VERSION VERSION_LESS 3.1.58)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sSTRICT=1")
endif ()
if (EMSCRIPTEN_VERSION VERSION_LESS 3.1.54)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -sDEMANGLE_SUPPORT=1")
elseif (EMSCRIPTEN_VERSION VERSION_LESS 3.1.55)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --memory-init-file 0")
endif()
if (CMAKE_USE_PTHREADS_INIT)
set(CMAKE_CXX_FLAGS "-pthread ${CMAKE_CXX_FLAGS}") # Emscripten requires the -pthread flag
set(CMAKE_EXE_LINKER_FLAGS "-sPROXY_TO_PTHREAD=0 -sPTHREAD_POOL_SIZE=3 ${CMAKE_EXE_LINKER_FLAGS}") # See https://github.com/emscripten-core/emscripten/issues/16706
@ -175,7 +186,13 @@ set(CPACK_PACKAGE_INSTALL_DIRECTORY "${PROJECT_NAME} ${CMAKE_PROJECT_VERSION_MAJ
set(CPACK_PACKAGE_FILE_NAME "${LOWERCASE_PROJECT_NAME}-${PROJECT_VERSION}-${TIME}.${CMAKE_SYSTEM_PROCESSOR}")
include_directories(${CMAKE_CURRENT_LIST_DIR})
add_executable(${EXENAME} src/main.cpp ${CMAKE_CURRENT_BINARY_DIR}/processed/${PROJECT_NAME}.rc src/etc/filefuncs.cpp src/etc/lexer.cpp src/headers/lex.hpp src/headers/misc.hpp src/headers/parsing/ParseComponents.hpp src/headers/transpiler/Target.hpp src/headers/transpiler/implementations/Lua.hpp src/headers/transpiler/implementations/Js.hpp src/headers/transpiler/implementations/Py.hpp src/headers/parsing/Parser.hpp src/headers/arguments.hpp src/headers/parsing/ReservedIdentifiers.hpp)
add_executable(${EXENAME} src/main.cpp ${CMAKE_CURRENT_BINARY_DIR}/processed/${PROJECT_NAME}.rc src/etc/filefuncs.cpp
src/etc/lexer.cpp src/headers/lex.hpp src/headers/misc.hpp
src/headers/parsing/ParseComponents.hpp src/headers/transpiler/Target.hpp
src/headers/transpiler/implementations/Lua.hpp src/headers/transpiler/implementations/Js.hpp src/headers/transpiler/implementations/Py.hpp
src/headers/parsing/Parser.hpp src/headers/arguments.hpp src/headers/parsing/ReservedIdentifiers.hpp src/headers/emscripten_compatibility.h
src/headers/Tasking.hpp
src/headers/SemanticAnalysis.hpp)
target_compile_definitions(${EXENAME} PRIVATE YBCON_VERSION="${CODENAME} ${PROJECT_VERSION}")
target_precompile_headers(${EXENAME} PRIVATE src/headers/Yerbacon.hpp)
if (Threads_FOUND)
@ -186,17 +203,7 @@ option(NO_SELF_PACKER "Disables usage of a self-packer")
if (NOT (UPPERCASE_BUILD_TYPE STREQUAL "DEBUG" OR UPPERCASE_BUILD_TYPE STREQUAL "RELWITHDEBINFO" OR NO_SELF_PACKER OR DEFINED EMSCRIPTEN))
include(FindSelfPackers)
if (SELF_PACKER_FOR_EXECUTABLE MATCHES upx) # UPX version d61edc9 or higher is required when using a cross-compiler to target the musl C library
if (CMAKE_CXX_LINK_NO_PIE_SUPPORTED OR MINGW) # MINGW does not support PIE, yet the variable is set to NO.
set(SELF_PACKER_FOR_EXECUTABLE_FLAGS ${SELF_PACKER_FOR_EXECUTABLE_FLAGS} --ultra-brute --best)
if (USER_DEFINED_PIE AND CMAKE_POSITION_INDEPENDENT_CODE)
message(NOTICE "-- Could NOT manually enable PIE (UPX is in use)")
endif()
set(CMAKE_POSITION_INDEPENDENT_CODE FALSE)
set_target_properties(${EXENAME} PROPERTIES POSITION_INDEPENDENT_CODE ${CMAKE_POSITION_INDEPENDENT_CODE})
else()
set(SELF_PACKER_FOR_EXECUTABLE "SELF_PACKER_FOR_EXECUTABLE-NOTFOUND")
message(NOTICE "UPX usage has been disabled because position-dependent executables are unsupported by the current compiler")
endif()
set(SELF_PACKER_FOR_EXECUTABLE_FLAGS ${SELF_PACKER_FOR_EXECUTABLE_FLAGS} --ultra-brute --best)
endif()
if (NOT SELF_PACKER_FOR_EXECUTABLE STREQUAL "SELF_PACKER_FOR_EXECUTABLE-NOTFOUND")
add_custom_command(TARGET ${EXENAME} POST_BUILD COMMAND "${SELF_PACKER_FOR_EXECUTABLE}" ${SELF_PACKER_FOR_EXECUTABLE_FLAGS} $<TARGET_FILE:${EXENAME}> VERBATIM)
@ -212,13 +219,16 @@ if (EMSCRIPTEN)
set(NODE_PACKAGE_PROGRAM "${NPM_PRESENT}")
endif()
if (DEFINED NODE_PACKAGE_PROGRAM)
if (EMSCRIPTEN_VERSION VERSION_LESS 3.1.58)
set(YAO_ASSETS "\n \"assets\": \"../${EXENAME}.worker.js\",")
endif()
configure_file("resources/package.json" "processed/package.json" @ONLY)
file(COPY "${CMAKE_CURRENT_BINARY_DIR}/processed/package.json" DESTINATION ".")
file(COPY "resources/.npmrc" DESTINATION ".")
add_custom_target(vercel_pkg COMMAND ${NODE_PACKAGE_PROGRAM} install)
add_dependencies(vercel_pkg ${EXENAME})
add_custom_target(yao_pkg COMMAND ${NODE_PACKAGE_PROGRAM} install)
add_dependencies(yao_pkg ${EXENAME})
# Warning: https://github.com/sbingner/ldid has to be on the PATH, before packaging, for the arm64 macOS executable to work
add_custom_command(TARGET vercel_pkg POST_BUILD COMMAND node_modules/.bin/pkg --config processed/package.json -C Brotli $<TARGET_FILE:${EXENAME}> --no-bytecode --public-packages "\"*\"" --public --output "${EXENAME}-mac" VERBATIM)
add_custom_command(TARGET yao_pkg POST_BUILD COMMAND node_modules/.bin/pkg --config processed/package.json -C Brotli $<TARGET_FILE:${EXENAME}> --no-bytecode --public-packages "\"*\"" --public --output "${EXENAME}-mac" VERBATIM)
endif()
endif()

22
Jenkinsfile vendored
View File

@ -3,18 +3,19 @@ def clean_workspace() { cleanWs(cleanWhenNotBuilt: false, deleteDirs: true, disa
boolean use_yarn_or_npm() { return fileExists('/usr/bin/yarn') || fileExists('/usr/bin/npm') }
/* Required Plugins:
- CMake
- CMake 3.21 or higher
- Sidebar Link
- Workspace Cleanup
Required Compilers:
- Musl cross-compiling toolchains (archives ending in "-cross" from https://musl.cc/#binaries) for x86_64, i686, armel, armhf, aarch64 and riscv64, unzipped into /usr/, along with soft links from /usr/bin/ to the binaries
- Emscripten Clang (https://github.com/emscripten-core/emsdk) in /usr/share/
- Emscripten Clang (https://github.com/emscripten-core/emsdk; the 3.1.30 version is known to work) in /usr/share/
- MinGW32 G++/Clang (https://github.com/mstorsjo/llvm-mingw) for x86_64, i686, armhf and aarch64, (unzip the content of the folder in the tar.xz file) in /usr/, along with soft links from /usr/bin/ to the binaries
- Android NDK Clang (https://ci.android.com/builds/submitted/10493228/linux/latest/android-ndk-10493228-linux-x86_64.zip) unzipped as /usr/android-ndk
Optional Tools:
- Ninja
- UPX (d61edc9 or higher)
- Vercel PKG (https://github.com/vercel/pkg)
- LDID (https://github.com/sbingner/ldid)
- NPM/Yarn to enable Yao PKG (https://github.com/yao-pkg/pkg)
- LDID (https://github.com/ProcursusTeam/ldid or https://github.com/sbingner/ldid)
*/
pipeline {
@ -39,7 +40,7 @@ pipeline {
name 'TARGET'
values(
'x86_64-linux-musl (RPM=x86_64, DEB=amd64)',
'i686-linux-musl (RPM=i386, DEB=i386)',
'i686-linux-musl (RPM=i686, DEB=i386)',
'armel-linux-musleabi (RPM=armv4l, DEB=armel)',
'armv7l-linux-musleabihf (RPM=armv7hl, DEB=armhf)',
'aarch64-linux-musl (RPM=aarch64, DEB=arm64)',
@ -48,6 +49,10 @@ pipeline {
'i686-w64-mingw32 (RPM=i386, DEB=i386)',
'armv7-w64-mingw32 (RPM=armv7hl, DEB=armhf)',
'aarch64-w64-mingw32 (RPM=aarch64, DEB=arm64)',
'x86_64-linux-android21 (RPM=x86_64, DEB=amd64) -> x86_64',
'i686-linux-android21 (RPM=i686, DEB=i386) -> x86',
'armv7a-linux-android21 (RPM=armv7, DEB=armhf) -> armeabi-v7a',
'aarch64-linux-android21 (RPM=aarch64, DEB=arm64) -> arm64-v8a',
'/usr/share/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake'
)
}
@ -60,16 +65,15 @@ pipeline {
final String path = use_toolchain ? "${TARGET}" : "${TARGET}".substring(0, "${TARGET}".indexOf(' ('))
final String rpmArch = use_toolchain ? 'noarch' : "${TARGET}".substring("${TARGET}".indexOf('(RPM=') + 5, "${TARGET}".indexOf(','))
final String debArch = use_toolchain ? 'noarch' : "${TARGET}".substring("${TARGET}".indexOf('DEB=') + 4, "${TARGET}".indexOf(')'))
final String system_name = !path.contains('mingw') ? sh(returnStdout: true, script: 'uname -s').trim() : 'Windows'
final String system_name = path.contains('mingw') ? 'Windows' : (path.contains('android') ? 'Android' : sh(returnStdout: true, script: 'uname -s').trim())
final String linker = "/usr/bin/${path}-ld"
final boolean not_packer_compatible = path.contains('riscv') || ((path.contains('aarch64') || path.contains('arm')) && path.contains('mingw'))
final String build_directory = "cmake-build-${use_toolchain ? path.substring(path.lastIndexOf('/') + 1, path.length() - 6) : path}".toLowerCase()
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
// Note: CMake 3.20 or higher is needed
cmakeBuild buildDir: build_directory, buildType: 'release', cleanBuild: true, installation: 'Latest',
cmakeArgs: "--no-warn-unused-cli ${use_toolchain ? "-DCMAKE_TOOLCHAIN_FILE=${path}" : "-DCMAKE_SYSTEM_NAME=\"${system_name}\" -DCXX_TARGET=\"${use_toolchain ? 'noarch' : debArch}\" -DCPACK_RPM_PACKAGE_ARCHITECTURE=${rpmArch} -DCPACK_DEBIAN_PACKAGE_ARCHITECTURE=${debArch} -DCMAKE_SYSTEM_PROCESSOR=\"${path.substring(0, path.indexOf('-'))}\" -DCMAKE_C_COMPILER=/usr/bin/${path}-gcc -DCMAKE_CXX_COMPILER=/usr/bin/${path}-g++ -DCMAKE_LINKER=${fileExists("${linker}.gold") ? "${linker}.gold" : linker} -DCMAKE_AR=/usr/bin/${path}-ar -DCMAKE_RC_COMPILER=/usr/bin/${path}-windres -DCMAKE_EXE_LINKER_FLAGS=-static"} -DNO_SELF_PACKER=${!(not_packer_compatible || use_toolchain) ? "OFF" : "ON"} -DIGNORE_MINIMAL_COMPILER_VERSION=ON -DNO_CCACHE=ON -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON${path.endsWith('armv7-w64-mingw32') ? ' -DCMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE=NO' : ''}",
cmakeArgs: "--no-warn-unused-cli ${use_toolchain ? "-DCMAKE_TOOLCHAIN_FILE=${path}" : "-DCMAKE_SYSTEM_NAME=\"${system_name}\" -DCXX_TARGET=\"${use_toolchain ? 'noarch' : debArch}\" -DCPACK_RPM_PACKAGE_ARCHITECTURE=${rpmArch} -DCPACK_DEBIAN_PACKAGE_ARCHITECTURE=${debArch} -DCMAKE_C_COMPILER=/usr/bin/${path}-gcc -DCMAKE_CXX_COMPILER=/usr/bin/${path}-g++ ${system_name == 'Android' ? "-DCMAKE_SYSTEM_VERSION=21 -DCMAKE_ANDROID_STL_TYPE=c++_static -DCMAKE_CXX_FLAGS=-static-openmp -DCMAKE_ANDROID_NDK=/usr/android-ndk -DCMAKE_ANDROID_ARCH_ABI=${"${TARGET}".substring("${TARGET}".indexOf(' -> ') + 4)}" : "-DCMAKE_SYSTEM_PROCESSOR=${path.substring(0, path.indexOf('-'))}"} -DCMAKE_LINKER=${fileExists("${linker}.gold") ? "${linker}.gold" : linker} -DCMAKE_AR=/usr/bin/${path}-ar -DCMAKE_RC_COMPILER=/usr/bin/${path}-windres -DCMAKE_EXE_LINKER_FLAGS=-static"} -DNO_SELF_PACKER=${!(not_packer_compatible || use_toolchain) ? "OFF" : "ON"} -DIGNORE_MINIMAL_COMPILER_VERSION=ON -DNO_CCACHE=ON -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON${path.endsWith('armv7-w64-mingw32') ? ' -DCMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE=NO' : ''}",
generator: cmake_generator()
cmake arguments: "--build ./$build_directory --target ${!("${TARGET}".endsWith('Emscripten.cmake') && use_yarn_or_npm()) ? 'ybcon' : 'vercel_pkg'}", installation: 'Latest'
cmake arguments: "--build ./$build_directory --target ${!("${TARGET}".endsWith('Emscripten.cmake') && use_yarn_or_npm()) ? 'ybcon' : 'yao_pkg'}", installation: 'Latest'
}
}
}

View File

@ -1,6 +1,6 @@
# Yerbacon
<img title="Yer &#129363;" align="left" src="/Username404-59/Yerbacon/raw/branch/stable/resources/Yerbacon.svg" alt="Yerbacon logo" width="192" height="192">
<img title="Yer &#129363;" align="left" src="resources/Yerbacon.svg" alt="Yerbacon logo" width="192" height="192">
### &#9658; A language that transpiles into another programming language, like Lua, JavaScript (ES6) or Python.
```

View File

@ -2,9 +2,8 @@
"name": "@EXENAME@",
"bin": "@EXENAME@.js",
"license": "@CPACK_RPM_PACKAGE_LICENSE@",
"devDependencies": { "pkg": "^5.8.0" },
"pkg": {
"assets": "../@EXENAME@.worker.js",
"devDependencies": { "@yao-pkg/pkg": "^5.9.0" },
"pkg": {@YAO_ASSETS@
"targets": [
"latest-macos-x64",
"latest-macos-arm64"

View File

@ -8,7 +8,7 @@ _ybconAutoComplete() {
COMPREPLY=()
current="${COMP_WORDS[COMP_CWORD]}"
previous="${COMP_WORDS[COMP_CWORD-1]}"
options='-h -p -t --help --parallel --target= --newlines= --printresult --text --version --buildInfo'
options='-h -p -t -o --help --parallel --target= --newlines= --printresult --text --output --version --buildInfo'
if [[ "${current}" == -* ]]; then
YCompReply "$(compgen -W "$options" -- "$current")"
return 0

View File

@ -8,4 +8,5 @@ complete -c ybcon -l parallel -k -d "Transpile files in parallel mode"
complete -c ybcon -l target -k -f -a 'lua js py' -d "Set the transpilation target"
complete -c ybcon -l newlines -k -f -a 'on off' -d "Enable or disable new lines"
complete -c ybcon -s p -l printresult -d "Enable printing the transpilation result to stdout"
complete -c ybcon -x -s t -l text -d "Transpile text provided after this argument (implies -p)"
complete -c ybcon -x -s t -l text -d "Transpile text provided after this argument (implies -p)"
complete -c ybcon -x -s o -l output -a '(__fish_complete_directories)' -d 'Output the transpiled file(s) to the specified directory'

View File

@ -10,6 +10,7 @@ _ybcon() {
--newlines='[Enable or disable new lines]:state:(on off)' \
{-p,--printresult}'[Enable printing the transpilation result to stdout]' \
{-t,--text}'[Transpile text provided after this argument (implies -p)]' \
{-o,--output}'[Output the transpiled file(s) to the specified directory]' \
"*:$completeyfile"
return 0
}

View File

@ -21,6 +21,7 @@ usage() {
echo " --newlines=on/off Enable or disable new lines"
echo " -p or --printresult Enable printing the transpilation result to stdout"
echo " -t or --text Transpile text provided after this argument (implies -p)"
echo " -o or --output Output the transpiled file(s) to the specified directory"
printf "\n"
fi
}

View File

@ -17,7 +17,4 @@ string getFileContent(const string& file)
} else throw Yerbacon::Exception("Could not open \"" + file + "\" : " + generic_category().message(errno));
}
void outputFileContent(const string& file, const string_view content) {
ofstream outputFile (file, ofstream::out);
outputFile << content;
}
void outputFileContent(const string& file, const string_view content) { ofstream(file, ofstream::out) << content;}

View File

@ -64,9 +64,9 @@ vector<tok> lex(const string_view& in)
string formedString;
for (;i < in.size(); ++i) {
const tok::type currentCharType = getIdentifierCharType(in[i]);
const bool isString = currentCharType == STRING;
if (isTypeString && (i == in.size() - 1 && not isString)) throw tok::LexerException("A never ending string was found", lineNumber);
if ((currentCharType == type || isTypeString) && !isString) {
const bool isStringDelimiter = currentCharType == STRING;
if (isTypeString && (i == in.size() - 1 && not isStringDelimiter)) throw tok::LexerException("A never ending string was found", lineNumber);
if ((currentCharType == type || isTypeString) && !isStringDelimiter) {
formedString += in[i];
} else {
if (not isTypeString) --i;
@ -81,10 +81,5 @@ vector<tok> lex(const string_view& in)
}
}
}
/* Test
for (const auto& it : resVal) {
cout << it << ' ' << it.toktype << '\n';
}
*/
return resVal;
}

View File

@ -0,0 +1,58 @@
#ifndef YERBACON_SEMANTICANALYSIS_HPP
#define YERBACON_SEMANTICANALYSIS_HPP
#include "parsing/ParseComponents.hpp"
#include "Tasking.hpp"
using namespace StandardComponents;
struct SemanticAnalyser final: public Tasking {
typedef Yerbacon::Exception SemanticException;
static void error(const string_view& text, unsigned long line = 0) {
throw SemanticException(text, line);
}
const auto& analyseTree(const ParseTree& tree) {
const auto& task_map = getTaskMapInstance();
for (unsigned int i = 0; i < tree.size(); ++i) {
try {
task_map.at(tree[i]->getId())(tree, i);
} catch (const out_of_range&) {}
}
return tree;
}
private:
unordered_task_map getTaskMapInstance() final {
using namespace StandardComponents;
return {
make_nonlocal_task(Function,
if (index > 0 and any_of(parsedTree.cbegin(), parsedTree.cbegin() + index, [&parseComponent](const component_ptr& pointer){
if (pointer->getId() != typeid(Reference)) {
string_view ptr_name;
try {
ptr_name = dynamic_cast<NamedIdentifier<true>&>(*pointer).name;
} catch (const bad_cast&) {
try {
ptr_name = dynamic_cast<NamedIdentifier<false>&>(*pointer).name;
} catch (const bad_cast&) {
return false;
}
};
if (ptr_name == parseComponent.name) {
return true;
}
}
return false;
})) { error(parseComponent.name + " has already been defined previously", parseComponent.line); }
),
share_task(Function, Class),
share_task(Function, Define<true>),
make_nonlocal_task(Define<false>,
if (parsedTree.findReferenceByName<Define<true>>(parseComponent.name).has_value()) {
error(parseComponent.name + string(" cannot be redefined as it is final"), parseComponent.line);
}
)
};
};
};
#endif //YERBACON_SEMANTICANALYSIS_HPP

24
src/headers/Tasking.hpp Normal file
View File

@ -0,0 +1,24 @@
#ifndef YERBACON_TASKING_HPP
#define YERBACON_TASKING_HPP
#include <typeindex>
#include <unordered_map>
#include "parsing/ParseComponents.hpp"
#define make_task_base(start, type, captures, function_body) make_pair(type_index(typeid(type)), [captures](const ParseTree& parsedTree, unsigned int& index) { start; function_body })
#define make_task_base_R(T, C, F) make_task_base(const T& parseComponent = reinterpret_cast<T&>(*parsedTree[index]), T, C, F)
#define make_task(T, F) make_task_base_R(T, this, F)
#define make_task_noR(T, F) make_task_base(,T, this, F)
#define make_nonlocal_task(T, F) make_task_base_R(T, , F)
#define share_task(T, T2) make_task_noR(T2, this->getTaskMapInstance()[typeid(T)](parsedTree, index);)
class Tasking {
protected:
typedef function<void (const ParseTree& parsedTree, unsigned int& index)> task;
typedef unordered_map<type_index, task> unordered_task_map;
public:
virtual unordered_task_map getTaskMapInstance() = 0;
virtual ~Tasking() = default;
};
#endif //YERBACON_TASKING_HPP

View File

@ -23,6 +23,10 @@
#error "The current standard library is incomplete"
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
#define token_expansion(X) #X
#define make_string(X) token_expansion(X)

View File

@ -0,0 +1,36 @@
#ifndef YERBACON_EMSCRIPTEN_COMPATIBILITY_H
#define YERBACON_EMSCRIPTEN_COMPATIBILITY_H
#include <string_view>
#include <string>
#include <filesystem>
filesystem::path mount(const std::string_view& element_path) {
filesystem::path file_path = element_path;
#ifdef EMSCRIPTEN
if (element_path.size() >= 2 and element_path[1] == ':') {
auto path = string(element_path.begin() + 2, element_path.end());
replace(path.begin(), path.end(), '\\', '/');
file_path = path;
}
const string directory = filesystem::path(file_path).remove_filename();
cout << "Directory: " << directory << endl;
for (unsigned int character = 1; character < directory.size(); ++character) {
const string sub_directory = directory.substr(0, character);
if (is_node and (directory[character] == '/') and not filesystem::is_directory(sub_directory)) {
MAIN_THREAD_EM_ASM({
const sub_directory = UTF8ToString($0);
if (!FS.isMountpoint(sub_directory)) {
try {
FS.mkdir(sub_directory);
FS.mount(NODEFS, {root: sub_directory}, sub_directory);
} catch (exception) {}
};
}, sub_directory.c_str());
}
}
#endif
return file_path;
}
#endif //YERBACON_EMSCRIPTEN_COMPATIBILITY_H

View File

@ -24,6 +24,7 @@ template<bool disallow_reserved>
struct NamedIdentifier: virtual ParseComponent {
struct identifier_reserved_exception: exception {};
const string name;
unsigned long line = 0;
explicit NamedIdentifier(const string_view nameText): name(nameText) {
if (disallow_reserved and reserved(name)) {
throw identifier_reserved_exception();
@ -41,6 +42,7 @@ class ParseTree: public virtual ParseComponent {
using array_type = decltype(subComponents);
using iterator = array_type::iterator;
using constant_iterator = array_type::const_iterator;
mutable optional<reference_wrapper<const ParseTree>> parent;
protected:
IS_PARSECOMPONENT
void addComponent(const T& component) const {
@ -50,6 +52,9 @@ protected:
static_assert(is_move_constructible_v<T>, "T is not copy-constructible or move-constructible");
subComponents.emplace_back(new T(move(const_cast<T&>(component))));
}
if constexpr(is_base_of_v<ParseTree, T>) {
reinterpret_cast<const ParseTree&>(*subComponents.back()).parent = cref(*this);
}
};
IS_PARSECOMPONENT
void addAllComponents(
@ -62,9 +67,19 @@ public:
inline size_t size() const { return subComponents.size(); }
inline bool empty() const { return size() == 0; }
inline iterator begin() noexcept { return subComponents.begin(); }
inline constant_iterator begin() const noexcept { return cbegin(); }
inline constant_iterator cbegin() const noexcept { return subComponents.cbegin(); }
inline iterator end() noexcept { return subComponents.end(); }
inline constant_iterator end() const noexcept { return cend(); }
inline constant_iterator cend() const noexcept { return subComponents.cend(); }
const decltype(parent)& getParent() const { return parent; }
void traverse_parent(const auto& lambda) const
{ if (parent.has_value()) for_each(parent.value().get().begin(), parent.value().get().end(), lambda); }
bool any_parent(const auto& lambda) const
{ return parent.has_value() and any_of(parent.value().get().begin(), parent.value().get().end(), lambda); }
IS_PARSECOMPONENT
vector<T*> findById() const {
vector<T*> filteredComponents;
@ -103,12 +118,12 @@ public:
#undef IS_PARSECOMPONENT
namespace StandardComponents {
template<bool BOOL>
struct Define: NamedIdentifier<true> {
const bool final;
const bool final = BOOL;
ParseTree content;
explicit Define(const bool& isFinal, string_view nameText, ParseTree&& content): NamedIdentifier(nameText), final(isFinal), content(move(content)) {}
explicit Define(string_view nameText, ParseTree&& content): Define(false, nameText, move(content)) {}
Define(Define&& define) noexcept: Define(define.final, define.name, move(define.content)) {}
explicit Define(string_view nameText, ParseTree&& content): NamedIdentifier(nameText), content(move(content)) {}
Define(Define&& define) noexcept: Define(define.name, move(define.content)) {}
};
struct Reference: NamedIdentifier<false> {
using NamedIdentifier::NamedIdentifier;
@ -128,6 +143,42 @@ namespace StandardComponents {
struct Call: ParseTree, Reference {
using Reference::Reference;
};
struct Operator: ParseComponent { // TODO Parse operators in Parser.hpp
tok::type operator_type;
Operator(const convertible_to<tok::type> auto& operator_token): operator_type() {
using enum tok::type;
static_assert((operator_token == PLUS or operator_token == HYPHEN or operator_token == ASTERISK or operator_token == DIVIDE or operator_token == LCOMP or operator_token == RCOMP));
operator_type = operator_token;
}
};
struct Condition: ParseTree {
Condition(const ParseTree left, const ParseTree right, const Operator& operator_token) {
*this << left << operator_token << right;
}
explicit Condition(const derived_from<ParseComponent> auto condition) { *this << condition; }
struct Statement;
protected:
Condition() = default;
};
struct Condition::Statement: ParseTree {
struct Branch;
Condition condition;
ParseTree else_branches;
bool is_last_branch_conditional() const;
Statement(Condition _condition): ParseTree(), condition(move(_condition)), else_branches() {}
protected:
Statement(): condition(), else_branches() {}
};
struct Condition::Statement::Branch: Condition::Statement {
inline bool is_conditional() const { return not condition.empty(); };
using Condition::Statement::Statement; Branch(): Condition::Statement() {};
private:
using Condition::Statement::is_last_branch_conditional;
};
bool Condition::Statement::is_last_branch_conditional() const {
const auto* last = (not else_branches.empty()) ? dynamic_cast<const Branch*>(else_branches[else_branches.size() - 1].get()) : nullptr;
return (last == nullptr and (not this->condition.empty())) or (last != nullptr and not last->condition.empty());
}
struct Function: NamedIdentifier<true>, ParseTree {
ParseTree parameters;

View File

@ -88,14 +88,48 @@ namespace Parser {
} else {
unsigned int parametersDistance = 0;
if (next.toktype == LPAR) {
const auto closing = find_if(lexed.begin() + i, lexed.end(), [](const tok& token){ return token.toktype == RPAR; });
const auto closing = find_corresponding(lexed.begin() + i + 2, lexed.end(), LPAR, RPAR);
parametersDistance = distance(lexed.begin() + i, closing);
i += parametersDistance;
}
if (nextAre({LCOMP, LCOMP, LBRACE})) {
const bool is_branch = current.toktext == ID(CONDITION_STATEMENT_BRANCH);
const bool is_conditional_branch = (not is_branch) and current.toktext == ID(CONDITION_STATEMENT_CONDITIONAL_BRANCH);
if (current.toktext == ID(CONDITION_STATEMENT) or is_branch or is_conditional_branch) {
if (is_branch or is_conditional_branch) {
const auto& last_id = parseTree.at(parseTree.size() - 1)->getId();
if (last_id != typeid(Condition::Statement)) {
parsingError(current, "unexpected \"" + current.toktext + "\" without preceding if statement");
}
}
const bool has_condition = next.toktype == LPAR and ((lexed.begin() + i - parametersDistance) + 2) < lexed.begin() + i;
if (not has_condition and not is_branch) parsingError(current, "missing condition after an \"" + current.toktext + "\" statement");
if (*(lexed.begin() + i + 1) != tok::LBRACE) parsingError(*(lexed.begin() + i), "missing statement body");
const auto body_end = find_corresponding(lexed.begin() + i + 2, lexed.end(), LBRACE, RBRACE);
auto* statement = (is_branch or is_conditional_branch) ? dynamic_cast<Condition::Statement*>(parseTree[parseTree.size() - 1].get()) : nullptr;
auto& else_branches = statement->else_branches;
if ((is_conditional_branch or is_branch) and not statement->is_last_branch_conditional())
parsingError(current, "<- unexpected branch", true);
Condition condition ((ParseTree()));
// TODO Check that the condition is valid
if (has_condition)
condition = Condition(parse((lexed.begin() + i - parametersDistance) + 2, lexed.begin() + i));
if (has_condition or is_branch) {
if (is_conditional_branch or is_branch) {
auto branch = (has_condition ? (Condition::Statement::Branch(move(condition))) : Condition::Statement::Branch());
branch.ParseTree::operator=(parse(lexed.begin() + i + 2, body_end));
else_branches << branch;
} else {
Condition::Statement new_statement (move(condition));
new_statement.ParseTree::operator=(parse(lexed.begin() + i + 2, body_end));
parseTree << new_statement;
}
i += distance(lexed.begin() + i, body_end);
}
continue;
} else if (nextAre({LCOMP, LCOMP, LBRACE})) {
Function function(current.toktext);
if (parametersDistance > 2)
function.parameters = parse(filter_comma_list(lexed.begin() + ((i + 2) - parametersDistance), lexed.begin() + i));
function.parameters = parse(filter_comma_list(lexed.begin() + ((i + 2) - parametersDistance), lexed.begin() + i)); // TODO Parse parameters correctly
parseTree << function;
i += 2;
break;
@ -103,15 +137,16 @@ namespace Parser {
bool isFinalDefine = nextAre({TAG, DEFINE});
if (isFinalDefine || next.toktype == DEFINE) {
const optional previousDefinition = parseTree.template findReferenceByName<Define>(current.toktext);
if (previousDefinition.has_value() && (previousDefinition.value().get().final || isFinalDefine))
parsingError(current, previousDefinition->get().final ? " cannot be redefined as it is final" : " cannot be made final after it has been declared", true);
const unsigned increment = 2 + isFinalDefine;
const auto beginning = lexed.begin() + i + increment;
const auto end = find_if(beginning, lexed.end(), [&current](const tok& it){
return it.toktype == SEMICOLON || it.line != current.line;
});
parseTree << Define(isFinalDefine, current.toktext, parse(beginning, end));
auto&& body = parse(beginning, end);
if (isFinalDefine)
parseTree << Define<true>(current.toktext, move(body));
else
parseTree << Define<false>(current.toktext, move(body));
i += 1 + isFinalDefine + distance(beginning, end);
} else {
const bool method = nextAre({DOT, IDENTIFIER, LPAR});
@ -119,7 +154,7 @@ namespace Parser {
const string name = property or method ? current.toktext + '.' + lexed[i + 2].toktext : current.toktext;
if (method or next.toktype == LPAR) {
parseTree << Call(name);
} else if (property) {
} else {
parseTree << Reference(name);
}
if (property or method) i += 2;
@ -149,20 +184,14 @@ namespace Parser {
} catch (const NamedIdentifier<true>::identifier_reserved_exception&) {
parsingError(current, " is a reserved identifier", true);
}
if (not parseTree.empty()) {
const auto& last = parseTree.cend() - 1;
const type_info& lastId = last->get()->getId();
const auto* last_identifier = dynamic_cast<NamedIdentifier<true>*>(last->get());
if (last_identifier != nullptr) {
if (lastId != typeid(Define) and
any_of(parseTree.cbegin(), last, [&last_identifier](const component_ptr& pointer){
try {
return dynamic_cast<NamedIdentifier<true>&>(*pointer).name == last_identifier->name;
} catch (const bad_cast&) {
return false;
}
}))
{ parsingError(current, " has already been defined previously", true); }
if (!parseTree.empty()) {
const component_ptr& last = parseTree[parseTree.size() - 1];
try {
dynamic_cast<NamedIdentifier<true>&>(*last).line = current.line;
} catch (const bad_cast&) {
try {
dynamic_cast<NamedIdentifier<false>&>(*last).line = current.line;
} catch (const bad_cast&) {}
}
}
}

View File

@ -7,11 +7,11 @@
#include <string_view>
static constinit const array identifiers {
"class", "structure", "print", "print_line"
"class", "structure", "print", "print_line", "if", "else", "elseif"
};
enum class ReservedIdentifier: size_t {
CLASS, STRUCT, PRINT_FUNCTION, PRINT_LINE_FUNCTION
CLASS, STRUCT, PRINT_FUNCTION, PRINT_LINE_FUNCTION, CONDITION_STATEMENT, CONDITION_STATEMENT_BRANCH, CONDITION_STATEMENT_CONDITIONAL_BRANCH
};
inline const char* ID(const ReservedIdentifier& identifier) {

View File

@ -15,8 +15,9 @@
#endif
#include "../parsing/ParseComponents.hpp"
#include "../Tasking.hpp"
class Target {
class Target: protected Tasking {
constexpr static const char* const interpolationString = "${";
constexpr static const char* const interpolationCloseString = "}";
protected:
@ -65,13 +66,6 @@ protected:
}
} else output << openCharacters << view << closeCharacters;
}
typedef function<void (const ParseTree& parsedTree, unsigned int& index)> task;
#define make_task_base(start, type, captures, function_body) make_pair(type_index(typeid(type)), [captures](const ParseTree& parsedTree, unsigned int& index) { start; function_body })
#define make_task_base_R(T, C, F) make_task_base(const T& parseComponent = reinterpret_cast<T&>(*parsedTree[index]), T, C, F)
#define make_task(T, F) make_task_base_R(T, this, F)
#define make_task_noR(T, F) make_task_base(,T, this, F)
#define make_nonlocal_task(T, F) make_task_base_R(T, , F)
typedef unordered_map<type_index, task> unordered_task_map;
typedef pair<const char*, const char*> print_functions_pair;
virtual unordered_task_map getTaskMap() = 0;
virtual print_functions_pair printFunctions() = 0;
@ -93,7 +87,7 @@ protected:
} catch (const out_of_range&) {
throw Yerbacon::Exception(string(
#ifndef __GNUC__
id.name()
id.name() // This is undefined behaviour but most other compilers should output the name
#else
abi::__cxa_demangle(id.name(), nullptr, nullptr, nullptr)
#endif
@ -108,13 +102,13 @@ protected:
void separate_transpileTree(const T& parseTree, const unsigned short& indentationLevel = 0) {
transpileTree(parseTree, indentationLevel, [this, &parseTree](const auto& iterator){
if ((newLines || iterator + 1 == parseTree.cend()) && use_uniqueLineSeparator()) output << uniqueLineSeparator().value();
if (iterator + 1 != parseTree.cend()) output << separator;
if (iterator + 1 < parseTree.cend()) output << separator;
});
}
IS(ParseTree)
void separate_transpileTree(const T& parseTree, const string_view separation_characters) {
transpileTree(parseTree, 0, [this, &parseTree, &separation_characters](const auto& iterator){
if (iterator + 1 != parseTree.cend()) { output << separation_characters; }
if (iterator + 1 < parseTree.cend()) { output << separation_characters; }
});
}
typedef optional<const char*> optional_string;
@ -124,7 +118,7 @@ protected:
string separator;
static constexpr const char* indentation = " ";
public:
unordered_task_map getTaskMapInstance() {
unordered_task_map getTaskMapInstance() final {
unordered_task_map fullMap = getTaskMap();
// Default / Shared tasks:
fullMap.merge(unordered_task_map({
@ -137,7 +131,9 @@ public:
separate_transpileTree(parseComponent, ", ");
output << ')';
),
make_task(StandardComponents::types::Integer, output << setprecision(parseComponent.precision) << fixed << parseComponent.value;)
make_task(StandardComponents::types::Integer, output << setprecision(parseComponent.precision) << fixed << parseComponent.value;),
make_task(StandardComponents::Condition, output << '('; transpileTree(parseComponent); output << ')';),
share_task(StandardComponents::Define<false>, StandardComponents::Define<true>)
}));
return fullMap;
};
@ -150,7 +146,7 @@ public:
};
explicit Target(const bool& newLines): output(), newLines(newLines), separator() {};
Target() = delete;
virtual ~Target() = default;
~Target() override = default;
};
#include "implementations/Lua.hpp"
@ -165,12 +161,7 @@ unique_ptr<Target> Target::forName(string_view name, const bool newLines = true)
ADDTARGET("py", PyTarget);
ADDTARGET("gd", GsTarget);
#undef ADDTARGET
#undef make_nonlocal_task
#undef make_task_noR
#undef make_task
#undef make_task_base_R
#undef make_task_base
Yerbacon::fail({"\"", string(1, (char) toupper(name.at(1))).data(), name.substr(2).data(), "\" is not a valid target."});
Yerbacon::fail({"\"", name.data(), "\" is not a valid target."});
return nullptr;
}

View File

@ -1,12 +1,13 @@
#ifndef GODOTSCRIPT_HPP
#define GODOTSCRIPT_HPP
using namespace StandardComponents;
struct GsTarget: Target {
print_functions_pair printFunctions() final { return make_pair("printraw", "print"); }
unordered_task_map getTaskMap() final {
return {
make_task(Define,
output << (parseComponent.final ? "const " : "var ") << parseComponent.name << " = ";
make_task(Define<false>,
output << (parseComponent.final ? "const " : "var ") << parseComponent.name << " = "; // TODO Handle redefining GodotScript variables
transpileTree(parseComponent.content);
),
make_task(types::String, stringInterpolation(R"(""")", parseComponent.content);),
@ -16,6 +17,23 @@ struct GsTarget: Target {
output << "):" << separator << indentation;
if (parseComponent.empty()) output << "pass";
separate_transpileTree(parseComponent, 1);
),
make_task(Condition::Statement,
output << "if ("; transpileTree(parseComponent.condition); output << "):" << separator << indentation;
if (parseComponent.empty()) output << "pass";
separate_transpileTree(parseComponent, 1);
if (not parseComponent.else_branches.empty()) {
output << separator;
separate_transpileTree(parseComponent.else_branches);
}
),
make_task(Condition::Statement::Branch,
if (parseComponent.is_conditional()) {
output << "elif ("; transpileTree(parseComponent.condition); output << ")";
} else output << "else";
output << ':' << separator << indentation;
separate_transpileTree(parseComponent, 1);
if (parseComponent.empty()) output << "pass";
)
};
}

View File

@ -7,7 +7,7 @@ struct JsTarget: Target {
bool use_uniqueLineSeparator() final { return true; }
unordered_task_map getTaskMap() final {
return {
make_task(Define,
make_task(Define<false>,
output << (parseComponent.final ? "const " : "let ") << parseComponent.name << " = ";
transpileTree(parseComponent.content);
),
@ -20,6 +20,27 @@ struct JsTarget: Target {
separate_transpileTree(parseComponent, 1);
if (newLines and not parseComponent.empty()) output << separator;
output << '}';
),
make_task(Condition::Statement,
output << "if ("; transpileTree(parseComponent.condition); output << ") {";
if (not parseComponent.empty()) {
if (newLines) output << separator << indentation; }
separate_transpileTree(parseComponent, 1);
if (not parseComponent.else_branches.empty()) {
if (newLines) output << separator;
output << '}';
separate_transpileTree(parseComponent.else_branches, string((newLines) ? separator : "") + '}');
}
if (newLines) output << separator;
output << '}';
),
make_task(Condition::Statement::Branch,
if (parseComponent.is_conditional()) {
output << " else if ("; transpileTree(parseComponent.condition); output << ')';
} else output << " else";
output << " {";
if (newLines) output << separator << indentation;
separate_transpileTree(parseComponent, 1);
)
};
}

View File

@ -7,7 +7,7 @@ struct LuaTarget: Target {
optional_string uniqueLineSeparator() final { return " "; }
unordered_task_map getTaskMap() final {
return {
make_task(Define,
make_task(Define<false>,
if (parseComponent.final) output << "local ";
output << parseComponent.name;
if (parseComponent.final) output << " <const>"; // TODO Find an alternative to <const> for lua <5.4
@ -26,6 +26,25 @@ struct LuaTarget: Target {
separate_transpileTree(parseComponent, 1);
if (not parseComponent.empty()) output << separator;
output << "end";
),
make_task(Condition::Statement,
output << "if ("; transpileTree(parseComponent.condition); output << ") then";
if (not parseComponent.empty()) {
output << separator; if (newLines) output << indentation; }
separate_transpileTree(parseComponent, 1);
if (not parseComponent.else_branches.empty()) {
output << separator;
separate_transpileTree(parseComponent.else_branches);
}
output << separator << "end";
),
make_task(Condition::Statement::Branch,
if (parseComponent.is_conditional()) {
output << "elseif ("; transpileTree(parseComponent.condition); output << ") then";
} else output << "else";
output << separator;
if (newLines) output << indentation;
separate_transpileTree(parseComponent, 1);
)
};
}

View File

@ -7,7 +7,7 @@ struct PyTarget: Target {
optional_string uniqueLineSeparator() final { return {}; }
unordered_task_map getTaskMap() final {
return {
make_task(Define, output << parseComponent.name << " = "; transpileTree(parseComponent.content);),
make_task(Define<false>, output << parseComponent.name << " = "; transpileTree(parseComponent.content);),
make_task(types::String, stringInterpolation(R"(""")", parseComponent.content);),
make_task(Function,
output << "def " << parseComponent.name << '(';
@ -16,6 +16,28 @@ struct PyTarget: Target {
if (parseComponent.empty()) output << "pass";
separate_transpileTree(parseComponent, 1);
),
make_task(Condition::Statement,
output << "if ("; transpileTree(parseComponent.condition); output << "):" << separator << indentation;
if (parseComponent.empty()) output << "pass";
separate_transpileTree(parseComponent, 1);
if (not parseComponent.else_branches.empty()) {
output << separator;
separate_transpileTree(parseComponent.else_branches);
}
),
make_task(Condition::Statement::Branch,
if (parseComponent.is_conditional()) {
output << "elif ("; transpileTree(parseComponent.condition); output << ")";
} else output << "else";
output << ':' << separator << indentation;
separate_transpileTree(parseComponent, 1);
if (parseComponent.empty()) output << "pass";
),
make_task(StandardComponents::Reference,
if (parseComponent.name == "true" or parseComponent.name == "false") {
output << (char) toupper(parseComponent.name.front()) << parseComponent.name.substr(1);
} else output << parseComponent.name;
)
};
}
using Target::Target;

View File

@ -7,7 +7,9 @@ using namespace std;
#include "headers/misc.hpp"
#include "headers/arguments.hpp"
#include "headers/SemanticAnalysis.hpp"
#include "headers/transpiler/Target.hpp"
#include "headers/emscripten_compatibility.h"
int main(int argc, char* argv[]) {
setlocale(LC_ALL, "");
@ -19,6 +21,7 @@ int main(int argc, char* argv[]) {
using unit_result = pair<string, optional<Yerbacon::Exception>>;
using unit = future<unit_result>;
map<string_view, unit> Units;
optional<filesystem::path> output_directory;
#ifdef EMSCRIPTEN
is_node = MAIN_THREAD_EM_ASM_INT({ return ENVIRONMENT_IS_NODE; });
#endif
@ -41,45 +44,33 @@ int main(int argc, char* argv[]) {
} else goto invalid_argument;
}
else if (currentArgument == ArgumentShort("text")) printResult = text_provided = true;
else if (currentArgument == ArgumentShort("output"))
if ((not output_directory.has_value()) and Units.empty() and (i + 1) != argc) {
mount(argv[i + 1]);
output_directory = argv[i + 1]; ++i;
} else goto invalid_argument;
else if (text_provided || currentArgument.ends_with(".ybcon")) {
#ifdef _OPENMP
if (not parallel) omp_set_num_threads(1);
#endif
optional file_path = make_optional<filesystem::path>();
if (not text_provided) {
file_path = filesystem::path(currentArgument);
#ifdef EMSCRIPTEN
if (currentArgument.size() >= 2 and currentArgument[1] == ':') {
auto path = string(currentArgument).erase(0, 2);
replace(path.begin(), path.end(), '\\', '/');
file_path = path;
}
const string directory = filesystem::path(file_path.value()).remove_filename();
for (unsigned int character = 1; character < directory.size(); ++character) {
const string sub_directory = directory.substr(0, character);
if (is_node and (directory[character] == '/') and not filesystem::is_directory(sub_directory)) {
MAIN_THREAD_EM_ASM({
const sub_directory = UTF8ToString($0);
if (!FS.isMountpoint(sub_directory)) {
try {
FS.mkdir(sub_directory);
FS.mount(NODEFS, {root: sub_directory}, sub_directory);
} catch (exception) {}
};
}, sub_directory.c_str());
}
}
#endif
}
Units.insert_or_assign(currentArgument, async(not parallel ? launch::deferred : launch::async, [&, currentArgument, file_path]() {
filesystem::path file_path;
if (not text_provided) file_path = mount(currentArgument);
Units.insert_or_assign(currentArgument, async(not parallel ? launch::deferred : launch::async, [&, currentArgument, file_path, index = Units.size() + 1]() {
unit_result resultingPair;
try {
resultingPair.first = Target::forName(target, newLines)->transpileWithTree(
parseString(text_provided ? currentArgument : getFileContent(file_path->string()))
SemanticAnalyser().analyseTree(
parseString(text_provided ? string(currentArgument) + '\n' : getFileContent(file_path.string(/* NOTE: This string is expected to finish with a line ending */)))
)
);
if (not text_provided) outputFileContent(filesystem::path(file_path.value()).replace_extension(target).string(), resultingPair.first);
if (!text_provided or output_directory.has_value())
outputFileContent(
(not output_directory.has_value() ? filesystem::path(file_path)
: output_directory->append(
(not text_provided) ? file_path.filename().string() : to_string(index))
).replace_extension(target).string(), resultingPair.first);
} catch (const Yerbacon::Exception& error) {
resultingPair.first = file_path.has_value() ? file_path->filename().string() : string();
resultingPair.first = not text_provided ? file_path.filename().string() : string();
resultingPair.second.emplace(error);
}
return resultingPair;