10 Commits

Author SHA1 Message Date
21641f888e 恢复原来的构建逻辑 2026-01-19 17:33:52 +08:00
def69e031f qswl x3 2026-01-19 17:26:46 +08:00
009a70fc64 气死我了x2 2026-01-19 17:24:29 +08:00
e01b4e9849 气死我了 2026-01-19 17:19:12 +08:00
da262a4cf1 尝试修复 build.yml 版本构建 2026-01-19 17:09:44 +08:00
f76e28ee8d 修改 build action 2026-01-19 16:57:57 +08:00
a324cf17f6 尝试修复windows构建版本获取问题,代码是ds写的。我不会actions 2026-01-19 16:27:14 +08:00
caf058dd55 [VER] v0.4.1-alpha
[Fix] 修复struct定义创建instanceCtx时拷贝类方法错误的Bug,表现在同一类的2个不同实例内置函数一样的问题
      (即 addr A != addr B, addr A.method == addr B.method)
      修复后为 (addr A != addr B, addr A.method != addr B.method)
      方法的closureContext指向instance的Context
      修复后 std.time可以正常使用
2026-01-19 16:10:12 +08:00
9e3f17711f [VER] 0.4.0-alpha
[Fix] 修复恶性Bug: Parser: parseExpression没有正确解析二元表达式,没有用到 right binding power的问题,表现在生成类似 a * b * c时,结果为 a * (b * c) 的Bug
[Impl][Fix] 修复跨文件(如import)报错信息错误的问题,现在Ast跟踪保存文件信息,报错统一从Error父类获取
[...] 忘了,好困不管了
2026-01-19 04:13:55 +08:00
d398d457b5 [VER] v0.3.9-alpha
[Feat] is 操作符现在可以直接判断内置数据类型, 如 10 is Int
[Fix] evalMemberExpr的lhs可以为右值,修复原来限制为左值的BUG,如调用一个函数返回结果为struct且访问member触发此bug
[Impl] 可更换的std::dynamic_pointer_cast更换为static版本,更快!
[Feat] 增加标准库 std.time,以及用到的builtin: __ftime_now_ns,但目前 Time类有点BUG
[...] 剩下的忘了
2026-01-15 17:51:01 +08:00
18 changed files with 384 additions and 152 deletions

View File

@@ -100,6 +100,8 @@ namespace Fig::Ast
struct AstAddressInfo
{
size_t line, column;
std::shared_ptr<FString> sourcePath;
std::shared_ptr<std::vector<FString>> sourceLines;
};
class _AstBase

View File

@@ -4,7 +4,7 @@
#include <cstdint>
#include <string_view>
#define __FCORE_VERSION "0.3.8-alpha"
#define __FCORE_VERSION "0.4.1-alpha"
#if defined(_WIN32)
#define __FCORE_PLATFORM "Windows"

18
src/Core/runtimeTime.cpp Normal file
View File

@@ -0,0 +1,18 @@
#include <Core/runtimeTime.hpp>
#include <cassert>
namespace Fig::Time
{
Clock::time_point start_time;
void init()
{
static bool flag = false;
if (flag)
{
assert(false);
}
start_time = Clock::now();
flag = true;
}
};

10
src/Core/runtimeTime.hpp Normal file
View File

@@ -0,0 +1,10 @@
#pragma once
#include <chrono>
namespace Fig::Time
{
using Clock = std::chrono::steady_clock;
extern Clock::time_point start_time; // since process start
void init();
};

View File

@@ -6,6 +6,7 @@
#include <format>
#include <source_location>
#include <string>
#include <vector>
namespace Fig
{
@@ -16,8 +17,10 @@ namespace Fig
explicit AddressableError(FString _msg,
size_t _line,
size_t _column,
FString _sourcePath,
std::vector<FString> _sourceLines,
std::source_location loc = std::source_location::current()) :
src_loc(loc), line(_line), column(_column)
src_loc(loc), line(_line), column(_column), sourcePath(std::move(_sourcePath)), sourceLines(std::move(_sourceLines))
{
message = _msg;
}
@@ -33,9 +36,11 @@ namespace Fig
}
std::source_location src_loc;
size_t getLine() const { return line; }
size_t getColumn() const { return column; }
virtual size_t getLine() const { return line; }
virtual size_t getColumn() const { return column; }
FString getMessage() const { return message; }
FString getSourcePath() const { return sourcePath; }
std::vector<FString> getSourceLines() const { return sourceLines; }
virtual FString getErrorType() const
{
@@ -45,6 +50,9 @@ namespace Fig
protected:
size_t line, column;
FString message;
FString sourcePath;
std::vector<FString> sourceLines;
};
class UnaddressableError : public std::exception
@@ -84,14 +92,6 @@ namespace Fig
public:
using AddressableError::AddressableError;
explicit SyntaxError(FString _msg,
size_t _line,
size_t _column,
std::source_location loc = std::source_location::current()) :
AddressableError(_msg, _line, _column, loc)
{
}
virtual FString toString() const override
{
std::string msg = std::format("[SyntaxError] {} in [{}] {}", this->message.toBasicString(), this->src_loc.file_name(), this->src_loc.function_name());

View File

@@ -98,8 +98,11 @@ namespace Fig
}
inline void logAddressableError(const AddressableError &err, FString fileName, std::vector<FString> sourceLines)
inline void logAddressableError(const AddressableError &err)
{
const FString &fileName = err.getSourcePath();
const std::vector<FString> &sourceLines = err.getSourceLines();
std::print("\n");
namespace TC = TerminalColors;
coloredPrint(TC::LightWhite, "An error occurred! ");

View File

@@ -2,6 +2,7 @@
#include <Core/fig_string.hpp>
#include <unordered_set>
#include <variant>
#include <map>
@@ -75,6 +76,28 @@ namespace Fig
using BoolClass = bool;
using NullClass = std::monostate;
using StringClass = FString;
static const std::unordered_set<TypeInfo, TypeInfoHash> builtinTypes
{
Any,
Null,
Int,
String,
Bool,
Double,
Function,
StructType,
StructInstance,
List,
Map,
Module,
InterfaceType
};
inline bool isTypeBuiltin(const TypeInfo &type)
{
return builtinTypes.contains(type);
}
}; // namespace ValueType
}; // namespace Fig

View File

@@ -22,6 +22,11 @@
#include <filesystem>
#include <fstream>
#include <memory>
#include <unordered_map>
#ifndef SourceInfo
#define SourceInfo(ptr) (ptr->sourcePath), (ptr->sourceLines)
#endif
namespace Fig
{
@@ -40,8 +45,8 @@ namespace Fig
}
LvObject Evaluator::evalMemberExpr(Ast::MemberExpr me, ContextPtr ctx)
{
LvObject base = evalLv(me->base, ctx);
RvObject baseVal = base.get();
// LvObject base = evalLv(me->base, ctx);
RvObject baseVal = eval(me->base, ctx);
const FString &member = me->member;
if (baseVal->getTypeInfo() == ValueType::Module)
{
@@ -194,17 +199,17 @@ namespace Fig
switch (exp->getType())
{
case AstType::VarExpr: {
Ast::VarExpr var = std::dynamic_pointer_cast<Ast::VarExprAst>(exp);
Ast::VarExpr var = std::static_pointer_cast<Ast::VarExprAst>(exp);
assert(var != nullptr);
return evalVarExpr(var, ctx);
}
case AstType::MemberExpr: {
Ast::MemberExpr me = std::dynamic_pointer_cast<Ast::MemberExprAst>(exp);
Ast::MemberExpr me = std::static_pointer_cast<Ast::MemberExprAst>(exp);
assert(me != nullptr);
return evalMemberExpr(me, ctx);
}
case AstType::IndexExpr: {
Ast::IndexExpr ie = std::dynamic_pointer_cast<Ast::IndexExprAst>(exp);
Ast::IndexExpr ie = std::static_pointer_cast<Ast::IndexExprAst>(exp);
assert(ie != nullptr);
return evalIndexExpr(ie, ctx);
}
@@ -298,6 +303,9 @@ namespace Fig
ObjectPtr lhs = eval(lexp, ctx);
ObjectPtr rhs = eval(rexp, ctx);
const TypeInfo &lhsType = lhs->getTypeInfo();
const TypeInfo &rhsType = rhs->getTypeInfo();
if (lhs->is<StructInstance>() && rhs->is<StructType>())
{
const StructInstance &si = lhs->as<StructInstance>();
@@ -310,10 +318,33 @@ namespace Fig
const InterfaceType &it = rhs->as<InterfaceType>();
return std::make_shared<Object>(implements(si.parentType, it.type, ctx));
}
throw EvaluatorError(
u8"TypeError",
std::format("Operator `is` requires an struct instance on left-hand side, got '{}'",
lhs->getTypeInfo().toString().toBasicString()),
if (ValueType::isTypeBuiltin(lhsType) && rhsType == ValueType::StructType)
{
const StructType &st = rhs->as<StructType>();
const TypeInfo &type = st.type;
/*
如果是内置类型(e.g. Int, String)
那么 eval出来String这个字出来的是StructType
而出来的StructType.type就不会是一个独立的TypeInfo,而是内置的ValueType::String
依次我们可以判断内置类型
e.g:
"123" is String
L OP R
其中 L 类型为 String
而 R 类型为 StructType (builtins.hpp) 中注册
拿到 R 的 StructType, 其中的 type 为 String
*/
if (lhs->getTypeInfo() == type) { return Object::getTrueInstance(); }
return Object::getFalseInstance();
}
throw EvaluatorError(u8"TypeError",
std::format("Unsupported operator `is` for '{}' && '{}'",
lhsType.toString().toBasicString(),
rhsType.toString().toBasicString()),
bin->lexp);
}
@@ -606,27 +637,27 @@ namespace Fig
switch (type)
{
case AstType::ValueExpr: {
auto val = std::dynamic_pointer_cast<Ast::ValueExprAst>(exp);
auto val = std::static_pointer_cast<Ast::ValueExprAst>(exp);
assert(val != nullptr);
return val->val;
}
case AstType::VarExpr: {
auto varExpr = std::dynamic_pointer_cast<Ast::VarExprAst>(exp);
auto varExpr = std::static_pointer_cast<Ast::VarExprAst>(exp);
assert(varExpr != nullptr);
return evalVarExpr(varExpr, ctx).get(); // LvObject -> RvObject
}
case AstType::BinaryExpr: {
auto bin = std::dynamic_pointer_cast<Ast::BinaryExprAst>(exp);
auto bin = std::static_pointer_cast<Ast::BinaryExprAst>(exp);
assert(bin != nullptr);
return evalBinary(bin, ctx);
}
case AstType::UnaryExpr: {
auto un = std::dynamic_pointer_cast<Ast::UnaryExprAst>(exp);
auto un = std::static_pointer_cast<Ast::UnaryExprAst>(exp);
assert(un != nullptr);
return evalUnary(un, ctx);
}
case AstType::TernaryExpr: {
auto te = std::dynamic_pointer_cast<Ast::TernaryExprAst>(exp);
auto te = std::static_pointer_cast<Ast::TernaryExprAst>(exp);
assert(te != nullptr);
return evalTernary(te, ctx);
}
@@ -634,7 +665,7 @@ namespace Fig
case AstType::IndexExpr: return evalLv(exp, ctx).get();
case AstType::FunctionCall: {
auto fnCall = std::dynamic_pointer_cast<Ast::FunctionCallExpr>(exp);
auto fnCall = std::static_pointer_cast<Ast::FunctionCallExpr>(exp);
assert(fnCall != nullptr);
Ast::Expression callee = fnCall->callee;
@@ -659,7 +690,7 @@ namespace Fig
return evalFunctionCall(fn, fnCall->arg, fnName, ctx);
}
case AstType::FunctionLiteralExpr: {
auto fnLiteral = std::dynamic_pointer_cast<Ast::FunctionLiteralExprAst>(exp);
auto fnLiteral = std::static_pointer_cast<Ast::FunctionLiteralExprAst>(exp);
assert(fnLiteral != nullptr);
Ast::BlockStatement body = nullptr;
@@ -689,7 +720,7 @@ namespace Fig
return std::make_shared<Object>(std::move(fn));
}
case AstType::InitExpr: {
auto initExpr = std::dynamic_pointer_cast<Ast::InitExprAst>(exp);
auto initExpr = std::static_pointer_cast<Ast::InitExprAst>(exp);
LvObject structeLv = evalLv(initExpr->structe, ctx);
ObjectPtr structTypeVal = structeLv.get();
const FString &structName = structeLv.name();
@@ -953,22 +984,47 @@ namespace Fig
}
}
}
instanceCtx->merge(*structT.defContext);
for (auto &[id, fn] : instanceCtx->getFunctions())
// instanceCtx->merge(*structT.defContext);
// for (auto &[id, fn] : instanceCtx->getFunctions())
// {
// instanceCtx->_update(*instanceCtx->getFunctionName(id),
// std::make_shared<Object>(Function(fn.paras,
// fn.retType,
// fn.body,
// instanceCtx) // change its closureContext to
// // struct instance's context
// ));
// }
ContextPtr stDefCtx = structT.defContext;
// load struct method
for (auto &[id, fn] : stDefCtx->getFunctions())
{
instanceCtx->_update(*instanceCtx->getFunctionName(id),
std::make_shared<Object>(Function(fn.paras,
auto funcNameOpt = stDefCtx->getFunctionName(id);
assert(funcNameOpt.has_value());
const FString &funcName = *funcNameOpt;
auto funcSlot = stDefCtx->get(funcName);
instanceCtx->def(
funcName,
ValueType::Function,
funcSlot->am,
std::make_shared<Object>(Function(
fn.paras,
fn.retType,
fn.body,
instanceCtx) // change its closureContext to
// struct instance's context
));
instanceCtx
))
);
}
return std::make_shared<Object>(StructInstance(structT.type, instanceCtx));
}
case AstType::ListExpr: {
auto lstExpr = std::dynamic_pointer_cast<Ast::ListExprAst>(exp);
auto lstExpr = std::static_pointer_cast<Ast::ListExprAst>(exp);
assert(lstExpr != nullptr);
List list;
@@ -977,7 +1033,7 @@ namespace Fig
}
case AstType::MapExpr: {
auto mapExpr = std::dynamic_pointer_cast<Ast::MapExprAst>(exp);
auto mapExpr = std::static_pointer_cast<Ast::MapExprAst>(exp);
assert(mapExpr != nullptr);
Map map;
@@ -985,7 +1041,9 @@ namespace Fig
return std::make_shared<Object>(std::move(map));
}
default: assert(false);
default: {
throw RuntimeError(FString(std::format("err type of expr: {}", magic_enum::enum_name(type))));
}
}
return Object::getNullInstance(); // ignore warning
}
@@ -1005,12 +1063,12 @@ namespace Fig
switch (stmt->getType())
{
case ImportSt: {
auto i = std::dynamic_pointer_cast<Ast::ImportSt>(stmt);
auto i = std::static_pointer_cast<Ast::ImportSt>(stmt);
assert(i != nullptr);
return evalImportSt(i, ctx);
}
case VarDefSt: {
auto varDef = std::dynamic_pointer_cast<Ast::VarDefAst>(stmt);
auto varDef = std::static_pointer_cast<Ast::VarDefAst>(stmt);
assert(varDef != nullptr);
if (ctx->containsInThisScope(varDef->name))
@@ -1051,7 +1109,7 @@ namespace Fig
}
case FunctionDefSt: {
auto fnDef = std::dynamic_pointer_cast<Ast::FunctionDefSt>(stmt);
auto fnDef = std::static_pointer_cast<Ast::FunctionDefSt>(stmt);
assert(fnDef != nullptr);
const FString &fnName = fnDef->name;
@@ -1071,7 +1129,7 @@ namespace Fig
}
case StructSt: {
auto stDef = std::dynamic_pointer_cast<Ast::StructDefSt>(stmt);
auto stDef = std::static_pointer_cast<Ast::StructDefSt>(stmt);
assert(stDef != nullptr);
if (ctx->containsInThisScope(stDef->name))
@@ -1123,7 +1181,7 @@ namespace Fig
}
case InterfaceDefSt: {
auto ifd = std::dynamic_pointer_cast<Ast::InterfaceDefAst>(stmt);
auto ifd = std::static_pointer_cast<Ast::InterfaceDefAst>(stmt);
assert(ifd != nullptr);
const FString &interfaceName = ifd->name;
@@ -1144,7 +1202,7 @@ namespace Fig
}
case ImplementSt: {
auto ip = std::dynamic_pointer_cast<Ast::ImplementAst>(stmt);
auto ip = std::static_pointer_cast<Ast::ImplementAst>(stmt);
assert(ip != nullptr);
TypeInfo structType(ip->structName);
@@ -1288,7 +1346,7 @@ namespace Fig
}
case IfSt: {
auto ifSt = std::dynamic_pointer_cast<Ast::IfSt>(stmt);
auto ifSt = std::static_pointer_cast<Ast::IfSt>(stmt);
ObjectPtr condVal = eval(ifSt->condition, ctx);
if (condVal->getTypeInfo() != ValueType::Bool)
{
@@ -1315,7 +1373,7 @@ namespace Fig
return StatementResult::normal();
};
case WhileSt: {
auto whileSt = std::dynamic_pointer_cast<Ast::WhileSt>(stmt);
auto whileSt = std::static_pointer_cast<Ast::WhileSt>(stmt);
while (true)
{
ObjectPtr condVal = eval(whileSt->condition, ctx);
@@ -1338,7 +1396,7 @@ namespace Fig
return StatementResult::normal();
};
case ForSt: {
auto forSt = std::dynamic_pointer_cast<Ast::ForSt>(stmt);
auto forSt = std::static_pointer_cast<Ast::ForSt>(stmt);
ContextPtr loopContext = std::make_shared<Context>(
FString(std::format("<For {}:{}>", forSt->getAAI().line, forSt->getAAI().column)),
ctx); // for loop has its own context
@@ -1379,7 +1437,7 @@ namespace Fig
}
case TrySt: {
auto tryst = std::dynamic_pointer_cast<Ast::TrySt>(stmt);
auto tryst = std::static_pointer_cast<Ast::TrySt>(stmt);
assert(tryst != nullptr);
ContextPtr tryCtx = std::make_shared<Context>(
@@ -1418,7 +1476,7 @@ namespace Fig
}
case ThrowSt: {
auto ts = std::dynamic_pointer_cast<Ast::ThrowSt>(stmt);
auto ts = std::static_pointer_cast<Ast::ThrowSt>(stmt);
assert(ts != nullptr);
ObjectPtr value = eval(ts->value, ctx);
@@ -1430,7 +1488,7 @@ namespace Fig
}
case ReturnSt: {
auto returnSt = std::dynamic_pointer_cast<Ast::ReturnSt>(stmt);
auto returnSt = std::static_pointer_cast<Ast::ReturnSt>(stmt);
assert(returnSt != nullptr);
ObjectPtr returnValue = Object::getNullInstance(); // default is null
@@ -1441,11 +1499,13 @@ namespace Fig
case BreakSt: {
if (!ctx->parent)
{
throw EvaluatorError(u8"BreakOutsideLoopError", u8"`break` statement outside loop", stmt);
throw EvaluatorError(
u8"BreakOutsideLoopError", u8"`break` statement outside loop", stmt);
}
if (!ctx->isInLoopContext())
{
throw EvaluatorError(u8"BreakOutsideLoopError", u8"`break` statement outside loop", stmt);
throw EvaluatorError(
u8"BreakOutsideLoopError", u8"`break` statement outside loop", stmt);
}
return StatementResult::breakFlow();
}
@@ -1453,17 +1513,19 @@ namespace Fig
case ContinueSt: {
if (!ctx->parent)
{
throw EvaluatorError(u8"ContinueOutsideLoopError", u8"`continue` statement outside loop", stmt);
throw EvaluatorError(
u8"ContinueOutsideLoopError", u8"`continue` statement outside loop", stmt);
}
if (!ctx->isInLoopContext())
{
throw EvaluatorError(u8"ContinueOutsideLoopError", u8"`continue` statement outside loop", stmt);
throw EvaluatorError(
u8"ContinueOutsideLoopError", u8"`continue` statement outside loop", stmt);
}
return StatementResult::continueFlow();
}
case ExpressionStmt: {
auto exprStmt = std::dynamic_pointer_cast<Ast::ExpressionStmtAst>(stmt);
auto exprStmt = std::static_pointer_cast<Ast::ExpressionStmtAst>(stmt);
assert(exprStmt != nullptr);
return StatementResult::normal(eval(exprStmt->exp, ctx));
@@ -1583,28 +1645,30 @@ namespace Fig
ContextPtr Evaluator::loadModule(const std::filesystem::path &path)
{
FString modSourcePath(path.string());
std::ifstream file(path);
assert(file.is_open());
std::string source((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
Lexer lexer((FString(source)));
Parser parser(lexer);
std::vector<Ast::AstBase> asts;
std::vector<FString> modSourceLines = Utils::splitSource(FString(source));
std::vector<FString> sourceLines = Utils::splitSource(FString(source));
Lexer lexer((FString(source)), modSourcePath, modSourceLines);
Parser parser(lexer, modSourcePath, modSourceLines);
std::vector<Ast::AstBase> asts;
asts = parser.parseAll();
Evaluator evaluator;
evaluator.SetSourcePath(FString(path.string()));
evaluator.SetSourcePath(modSourcePath);
evaluator.SetSourceLines(modSourceLines);
ContextPtr modctx = std::make_shared<Context>(FString(std::format("<Module at {}>", path.string())), nullptr);
evaluator.SetGlobalContext(modctx);
evaluator.RegisterBuiltinsValue();
evaluator.Run(asts);
evaluator.Run(asts); // error upward pass-by, log outside, we have already keep info in evaluator error
return evaluator.global;
}
@@ -1626,8 +1690,9 @@ namespace Fig
if (ctx->containsInThisScope(modName))
{
throw EvaluatorError(
u8"RedeclarationError", std::format("{} has already been declared.", modName.toBasicString()), i);
throw EvaluatorError(u8"RedeclarationError",
std::format("{} has already been declared.", modName.toBasicString()),
i);
}
ctx->def(
modName, ValueType::Module, AccessModifier::PublicConst, std::make_shared<Object>(Module(modName, modCtx)));
@@ -1641,14 +1706,14 @@ namespace Fig
for (auto &ast : asts)
{
Ast::Expression exp;
if ((exp = std::dynamic_pointer_cast<Ast::ExpressionAst>(ast)))
if ((exp = std::dynamic_pointer_cast<Ast::ExpressionAst>(ast))) // 保持 dynamic_pointer_cast !
{
sr = StatementResult::normal(eval(exp, global));
}
else
{
// statement
Ast::Statement stmt = std::dynamic_pointer_cast<Ast::StatementAst>(ast);
Ast::Statement stmt = std::static_pointer_cast<Ast::StatementAst>(ast);
assert(stmt != nullptr);
sr = evalStatement(stmt, global);
if (sr.isError())

View File

@@ -1,6 +1,6 @@
#include "Ast/Statements/ImplementSt.hpp"
#include "Ast/Statements/InterfaceDefSt.hpp"
#include "Value/Type.hpp"
#include <Ast/Statements/ImplementSt.hpp>
#include <Ast/Statements/InterfaceDefSt.hpp>
#include <Value/Type.hpp>
#include <Ast/ast.hpp>
#include <Context/context.hpp>
@@ -63,12 +63,18 @@ namespace Fig
public:
FString sourcePath;
std::vector<FString> sourceLines;
void SetSourcePath(const FString &sp)
{
sourcePath = sp;
}
void SetSourceLines(const std::vector<FString> &sl)
{
sourceLines = sl;
}
void SetGlobalContext(ContextPtr ctx)
{
assert(ctx != nullptr);

View File

@@ -10,7 +10,10 @@ namespace Fig
public:
FString typeName;
using AddressableError::AddressableError;
EvaluatorError(FString _typeName, FString msg, Ast::AstBase ast, std::source_location loc = std::source_location::current())
EvaluatorError(FString _typeName,
FString msg,
Ast::AstBase ast,
std::source_location loc = std::source_location::current())
{
message = msg;
line = ast->getAAI().line;
@@ -20,8 +23,13 @@ namespace Fig
typeName = std::move(_typeName);
sourcePath = *ast->getAAI().sourcePath;
sourceLines = *ast->getAAI().sourceLines;
}
EvaluatorError(FString _typeName, std::string_view msg, Ast::AstBase ast, std::source_location loc = std::source_location::current())
EvaluatorError(FString _typeName,
std::string_view msg,
Ast::AstBase ast,
std::source_location loc = std::source_location::current())
{
message = FString::fromBasicString(std::string(msg.data()));
line = ast->getAAI().line;
@@ -30,13 +38,11 @@ namespace Fig
src_loc = std::move(loc);
typeName = std::move(_typeName);
sourcePath = *ast->getAAI().sourcePath;
sourceLines = *ast->getAAI().sourceLines;
}
virtual FString getErrorType() const override
{
return typeName;
}
};
virtual FString getErrorType() const override { return typeName; }
};
}; // namespace Fig

View File

@@ -28,7 +28,7 @@ This software is licensed under the MIT License. See LICENSE.txt for details.
*/
#include <Utils/argparse/argparse.hpp>
#include <print>
// #include <print>
#include <fstream>
#include <Core/core.hpp>
@@ -38,6 +38,7 @@ This software is licensed under the MIT License. See LICENSE.txt for details.
#include <Utils/AstPrinter.hpp>
#include <Utils/utils.hpp>
#include <Error/errorLog.hpp>
#include <Core/runtimeTime.hpp>
static size_t addressableErrorCount = 0;
static size_t unaddressableErrorCount = 0;
@@ -45,6 +46,10 @@ static size_t unaddressableErrorCount = 0;
int main(int argc, char **argv)
{
Time::init();
// init, set start_time (std::chrono::time_point)
argparse::ArgumentParser program("Fig Interpreter", Fig::Core::VERSION.data());
program.add_argument("source")
.help("source file to be interpreted")
@@ -84,7 +89,9 @@ int main(int argc, char **argv)
std::string source((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
Fig::Lexer lexer((Fig::FString(source)));
std::vector<FString> sourceLines = Fig::Utils::splitSource(Fig::FString(source));
Fig::Lexer lexer((Fig::FString(source)), sourcePath, sourceLines);
// Token tok;
// while ((tok = lexer.nextToken()).getType() != TokenType::EndOfFile)
@@ -92,11 +99,9 @@ int main(int argc, char **argv)
// std::println("{}", tok.toString().toBasicString());
// }
Fig::Parser parser(lexer);
Fig::Parser parser(lexer, sourcePath, sourceLines);
std::vector<Fig::Ast::AstBase> asts;
std::vector<FString> sourceLines = Fig::Utils::splitSource(Fig::FString(source));
try
{
asts = parser.parseAll();
@@ -104,7 +109,7 @@ int main(int argc, char **argv)
catch (const Fig::AddressableError &e)
{
addressableErrorCount++;
ErrorLog::logAddressableError(e, sourcePath, sourceLines);
ErrorLog::logAddressableError(e);
return 1;
}
catch (const Fig::UnaddressableError &e)
@@ -129,6 +134,7 @@ int main(int argc, char **argv)
Fig::Evaluator evaluator;
evaluator.SetSourcePath(sourcePath);
evaluator.SetSourceLines(sourceLines);
evaluator.CreateGlobalContext();
evaluator.RegisterBuiltinsValue();
@@ -139,7 +145,7 @@ int main(int argc, char **argv)
catch (const Fig::AddressableError &e)
{
addressableErrorCount++;
ErrorLog::logAddressableError(e, sourcePath, sourceLines);
ErrorLog::logAddressableError(e);
evaluator.printStackTrace();
return 1;
}

View File

@@ -10,6 +10,10 @@
#include <iostream> // debug
#endif
#ifndef SourceInfo
#define SourceInfo(ptr) (ptr->sourcePath), (ptr->sourceLines)
#endif
namespace Fig
{
@@ -163,7 +167,7 @@ namespace Fig
{
if (it.isEnd())
{
error = SyntaxError(u8"Unterminated FString", this->line, it.column());
error = SyntaxError(u8"Unterminated FString", this->line, it.column(), SourceInfo(this));
return IllegalTok;
}
next();
@@ -200,12 +204,11 @@ namespace Fig
}
else
{
error = SyntaxError(FString(
std::format(
"Unsupported escape character: {}",
error = SyntaxError(FString(std::format("Unsupported escape character: {}",
FString(ec.getString()).toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
}
@@ -217,7 +220,7 @@ namespace Fig
}
if (unterminated)
{
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col);
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col, SourceInfo(this));
return IllegalTok;
}
return Token(str, TokenType::LiteralString);
@@ -244,7 +247,7 @@ namespace Fig
}
if (unterminated)
{
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col);
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col, SourceInfo(this));
return IllegalTok;
}
return Token(str, TokenType::LiteralString);
@@ -275,7 +278,7 @@ namespace Fig
{
if (it.isEnd())
{
error = SyntaxError(u8"Unterminated FString", this->line, it.column());
error = SyntaxError(u8"Unterminated FString", this->line, it.column(), SourceInfo(this));
return IllegalTok;
}
next();
@@ -317,12 +320,11 @@ namespace Fig
}
else
{
error = SyntaxError(FString(
std::format(
"Unsupported escape character: {}",
error = SyntaxError(FString(std::format("Unsupported escape character: {}",
FString(ec.getString()).toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
}
@@ -334,7 +336,7 @@ namespace Fig
}
if (unterminated)
{
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col);
error = SyntaxError(u8"Unterminated FString", this->line, str_start_col, SourceInfo(this));
return IllegalTok;
}
return Token(str, TokenType::LiteralString);
@@ -378,8 +380,10 @@ namespace Fig
if (numStr.ends_with(U'e'))
{
error = SyntaxError(
FString(std::format("Illegal number literal: {}", numStr.toBasicString())), this->line, it.column());
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column(),
SourceInfo(this));
return IllegalTok;
}
@@ -395,8 +399,10 @@ namespace Fig
if (!hasDigit)
{
error = SyntaxError(
FString(std::format("Illegal number literal: {}", numStr.toBasicString())), this->line, it.column());
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column(),
SourceInfo(this));
return IllegalTok;
}
@@ -407,14 +413,16 @@ namespace Fig
{
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
if (ePos + 1 >= numStr.length())
{
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
bool hasDigitAfterE = false;
@@ -427,7 +435,8 @@ namespace Fig
{
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
continue;
@@ -438,7 +447,8 @@ namespace Fig
{
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
}
@@ -447,7 +457,8 @@ namespace Fig
{
error = SyntaxError(FString(std::format("Illegal number literal: {}", numStr.toBasicString())),
this->line,
it.column());
it.column(),
SourceInfo(this));
return IllegalTok;
}
}
@@ -472,9 +483,10 @@ namespace Fig
if (!startsWith(sym))
{
error = SyntaxError(
FString(std::format("No such operator: {}", sym.toBasicString())),
this->line, it.column());
error = SyntaxError(FString(std::format("No such operator: {}", sym.toBasicString())),
this->line,
it.column(),
SourceInfo(this));
next();
return IllegalTok;
}
@@ -500,9 +512,10 @@ namespace Fig
if (!symbol_map.contains(sym))
{
error = SyntaxError(
FString(std::format("No such operator: {}", sym.toBasicString())),
this->line, it.column());
error = SyntaxError(FString(std::format("No such operator: {}", sym.toBasicString())),
this->line,
it.column(),
SourceInfo(this));
next();
return IllegalTok;
}
@@ -562,7 +575,8 @@ namespace Fig
if (!terminated)
{
error = SyntaxError(FString(u8"Unterminated multiline comment"), this->line, it.column());
error =
SyntaxError(FString(u8"Unterminated multiline comment"), this->line, it.column(), SourceInfo(this));
next();
return IllegalTok;
}
@@ -633,9 +647,11 @@ namespace Fig
}
else
{
error = SyntaxError(FString(
std::format("Cannot tokenize char: '{}'", FString(ch.getString()).toBasicString())),
this->line, it.column());
error =
SyntaxError(FString(std::format("Cannot tokenize char: '{}'", FString(ch.getString()).toBasicString())),
this->line,
it.column(),
SourceInfo(this));
if (hasNext())
{
next();

View File

@@ -23,6 +23,9 @@ namespace Fig
SyntaxError error;
UTF8Iterator it;
FString sourcePath;
std::vector<FString> sourceLines;
std::vector<Warning> warnings;
size_t last_line, last_column, column = 1;
@@ -60,8 +63,8 @@ namespace Fig
static const std::unordered_map<FString, TokenType> symbol_map;
static const std::unordered_map<FString, TokenType> keyword_map;
inline Lexer(const FString &_source) :
source(_source), it(source)
inline Lexer(const FString &_source, const FString &_sourcePath, const std::vector<FString> &_sourceLines) :
source(_source), it(source), sourcePath(_sourcePath), sourceLines(_sourceLines)
{
line = 1;
}

View File

@@ -0,0 +1,51 @@
/*
Official Module `time`
Library/time/time.fig
Copyright © 2026 PuqiAR. All rights reserved.
*/
import _builtins; // provides __ftime_now_ns (int64_t)
public struct Time
{
ns: Int; // int64_t, private
public func toNanos() -> Int
{
return ns;
}
public func toMicros() -> Int
{
return __fvalue_int_from(ns / 1000); // convert double to int
}
public func toMillis() -> Double
{
return ns / 1000 / 1000;
}
public func toSeconds() -> Double
{
return ns / 1000 / 1000 / 1000;
}
public func since(other: Time) -> Int
{
const time_ns := other.toNanos();
const result := ns - time_ns;
if result < 0
{
throw "time has been reversed! 😢";
}
return result;
}
// TODO: support `-` operator when Fig supports overload
}
public func now() -> Time
{
return Time{__ftime_now_ns()};
}

View File

@@ -1,10 +1,12 @@
#pragma once
#include "Ast/Statements/InterfaceDefSt.hpp"
#include "Ast/functionParameters.hpp"
#include <Ast/Statements/InterfaceDefSt.hpp>
#include <Ast/functionParameters.hpp>
#include <Core/fig_string.hpp>
#include <Value/value.hpp>
#include <Core/runtimeTime.hpp>
#include <chrono>
#include <numeric>
#include <unordered_map>
#include <functional>
@@ -65,6 +67,7 @@ namespace Fig
{u8"__fvalue_double_parse", 1},
{u8"__fvalue_double_from", 1},
{u8"__fvalue_string_from", 1},
{u8"__ftime_now_ns", 0},
/* math start */
{u8"__fmath_acos", 1},
{u8"__fmath_acosh", 1},
@@ -194,6 +197,15 @@ namespace Fig
ObjectPtr val = args[0];
return std::make_shared<Object>(val->toStringIO());
}},
{u8"__ftime_now_ns",
[](const std::vector<ObjectPtr> &args) -> ObjectPtr {
// returns nanoseconds
using namespace Fig::Time;
auto now = Clock::now();
return std::make_shared<Object>(static_cast<ValueType::IntClass>(
std::chrono::duration_cast<std::chrono::nanoseconds>(now - start_time).count()));
}},
/* math start */
{u8"__fmath_acos",
[](const std::vector<ObjectPtr> &args) -> ObjectPtr {

View File

@@ -22,7 +22,7 @@ namespace Fig
// 逻辑
{Ast::Operator::And, {5, 6}},
{Ast::Operator::Or, {4, 5}},
{Ast::Operator::Not, {30, 31}}, // 一元
// {Ast::Operator::Not, {30, 31}}, // 一元
// 比较
{Ast::Operator::Equal, {7, 8}},
@@ -37,7 +37,7 @@ namespace Fig
{Ast::Operator::BitAnd, {6, 7}},
{Ast::Operator::BitOr, {4, 5}},
{Ast::Operator::BitXor, {5, 6}},
{Ast::Operator::BitNot, {30, 31}}, // 一元
// {Ast::Operator::BitNot, {30, 31}}, // 一元
{Ast::Operator::ShiftLeft, {15, 16}},
{Ast::Operator::ShiftRight, {15, 16}},
@@ -214,7 +214,7 @@ namespace Fig
variaPara = pname;
next(); // skip `...`
if (!isThis(TokenType::RightParen))
throw SyntaxError(
throwAddressableError<SyntaxError>(
u8"Expects right paren, variable parameter function can only have one parameter",
currentAAI.line,
currentAAI.column);
@@ -433,7 +433,7 @@ namespace Fig
}
else
{
throw SyntaxError(FString(u8"Invalid syntax"), currentAAI.line, currentAAI.column);
throwAddressableError<SyntaxError>(FString(u8"Invalid syntax"), currentAAI.line, currentAAI.column);
}
}
return makeAst<Ast::InterfaceDefAst>(interfaceName, methods, isPublic);
@@ -480,7 +480,7 @@ namespace Fig
}
else
{
throw SyntaxError(FString(u8"Invalid syntax"), currentAAI.line, currentAAI.column);
throwAddressableError<SyntaxError>(FString(u8"Invalid syntax"), currentAAI.line, currentAAI.column);
}
}
@@ -556,7 +556,8 @@ namespace Fig
{
if (finallyBlock != nullptr)
{
throw SyntaxError(u8"Duplicate try finally-block", currentAAI.line, currentAAI.column);
throwAddressableError<SyntaxError>(
u8"Duplicate try finally-block", currentAAI.line, currentAAI.column);
}
next(); // consume `finally`
expect(TokenType::LeftBrace);
@@ -592,6 +593,7 @@ namespace Fig
}
else if (isThis(TokenType::Struct))
{
next();
stmt = __parseStructDef(true);
}
else if (isThis(TokenType::Interface))
@@ -677,11 +679,7 @@ namespace Fig
}
else
{
throw SyntaxError(
u8"invalid syntax",
currentAAI.line,
currentAAI.column
);
throwAddressableError<SyntaxError>(u8"invalid syntax", currentAAI.line, currentAAI.column);
}
return stmt;
}
@@ -1207,11 +1205,11 @@ namespace Fig
if (!isTokenOp(tok)) break;
op = Ast::TokenToOp.at(tok.getType());
Precedence lbp = getLeftBindingPower(op);
auto [lbp, rbp] = getBindingPower(op);
if (bp >= lbp) break;
next(); // consume op
lhs = makeAst<Ast::BinaryExprAst>(lhs, op, parseExpression(bp, stop, stop2));
lhs = makeAst<Ast::BinaryExprAst>(lhs, op, parseExpression(rbp, stop, stop2));
}
return lhs;
@@ -1231,10 +1229,8 @@ namespace Fig
auto stmt = __parseStatement();
if (!output.empty() && stmt->getType() == Ast::AstType::PackageSt)
{
throw SyntaxError(
u8"Package must be at the beginning of the file",
currentAAI.line,
currentAAI.column);
throwAddressableError<SyntaxError>(
u8"Package must be at the beginning of the file", currentAAI.line, currentAAI.column);
}
pushNode(stmt);
}

View File

@@ -6,6 +6,7 @@
#include <Core/fig_string.hpp>
#include <Error/error.hpp>
#include <memory>
#include <print>
#include <source_location>
#include <unordered_map>
@@ -22,6 +23,9 @@ namespace Fig
std::vector<Ast::AstBase> output;
std::vector<Token> previousTokens;
std::shared_ptr<FString> sourcePathPtr;
std::shared_ptr<std::vector<FString>> sourceLinesPtr;
size_t tokenPruduced = 0;
size_t currentTokenIndex = 0;
@@ -72,7 +76,11 @@ namespace Fig
static const std::unordered_map<Ast::Operator, std::pair<Precedence, Precedence>> opPrecedence;
static const std::unordered_map<Ast::Operator, Precedence> unaryOpPrecedence;
Parser(const Lexer &_lexer) : lexer(_lexer) {}
Parser(const Lexer &_lexer, FString _sourcePath, std::vector<FString> _sourceLines) : lexer(_lexer)
{
sourcePathPtr = std::make_shared<FString>(_sourcePath);
sourceLinesPtr = std::make_shared<std::vector<FString>>(_sourceLines);
}
AddressableError *getError() const { return error.get(); }
@@ -83,7 +91,7 @@ namespace Fig
std::source_location loc = std::source_location::current())
{
static_assert(std::is_base_of_v<AddressableError, _ErrT>, "_ErrT must derive from AddressableError");
_ErrT spError(msg, line, column, loc);
_ErrT spError(msg, line, column, *sourcePathPtr, *sourceLinesPtr, loc);
error = std::make_unique<_ErrT>(spError);
throw spError;
}
@@ -92,7 +100,7 @@ namespace Fig
{
static_assert(std::is_base_of_v<AddressableError, _ErrT>, "_ErrT must derive from AddressableError");
// line, column provide by `currentAAI`
_ErrT spError(msg, currentAAI.line, currentAAI.column, loc);
_ErrT spError(msg, currentAAI.line, currentAAI.column, *sourcePathPtr, *sourceLinesPtr, loc);
error = std::make_unique<_ErrT>(spError);
throw spError;
}
@@ -135,7 +143,10 @@ namespace Fig
CTI也需要显示转换否则转换完的pruduced又会被转回去变为 int64_t max
*/
currentTokenIndex++;
setCurrentAAI(Ast::AstAddressInfo{.line = currentToken().line, .column = currentToken().column});
setCurrentAAI(Ast::AstAddressInfo{.line = currentToken().line,
.column = currentToken().column,
.sourcePath = sourcePathPtr,
.sourceLines = sourceLinesPtr});
return;
}
if (isEOF()) return;
@@ -143,7 +154,11 @@ namespace Fig
tokenPruduced++;
if (tok == IllegalTok) throw lexer.getError();
currentTokenIndex = tokenPruduced - 1;
setCurrentAAI(Ast::AstAddressInfo{.line = tok.line, .column = tok.column});
setCurrentAAI(Ast::AstAddressInfo{.line = tok.line,
.column = tok.column,
.sourcePath = sourcePathPtr,
.sourceLines = sourceLinesPtr});
previousTokens.push_back(tok);
}
inline const Token &currentToken()
@@ -298,8 +313,7 @@ namespace Fig
Ast::ListExpr __parseListExpr(); // entry: current is `[`
Ast::MapExpr __parseMapExpr(); // entry: current is `{`
Ast::InitExpr __parseInitExpr(
Ast::Expression); // entry: current is `{`, ahead is struct type exp.
Ast::InitExpr __parseInitExpr(Ast::Expression); // entry: current is `{`, ahead is struct type exp.
Ast::Expression __parseTupleOrParenExpr(); // entry: current is `(`
Ast::FunctionLiteralExpr __parseFunctionLiteralExpr(); // entry: current is Token::LParen after Token::Function

View File

@@ -28,6 +28,7 @@ target("Fig")
add_files("src/Evaluator/main.cpp")
add_files("src/Core/warning.cpp")
add_files("src/Core/runtimeTime.cpp")
add_files("src/Evaluator/evaluator.cpp")
add_files("src/Evaluator/Value/value.cpp")
add_files("src/Lexer/lexer.cpp")