经 AI Skill Hub 精选评估,红龙代码执行引擎 获评「推荐使用」。这款AI工具在功能完整性、社区活跃度和易用性方面表现出色,AI 评分 7.0 分,适合有一定技术背景的用户使用。
红龙代码执行引擎 是一款基于 Python 开发的开源工具,专注于 多语言执行、虚拟机、LLM集成 等核心功能。作为 GitHub 开源项目,它拥有活跃的社区支持和持续的版本迭代,代码完全透明可审计,支持本地部署以保护数据隐私。无论是个人使用还是集成到企业工作流,都能提供稳定可靠的解决方案。
红龙代码执行引擎 是一款基于 Python 开发的开源工具,专注于 多语言执行、虚拟机、LLM集成 等核心功能。作为 GitHub 开源项目,它拥有活跃的社区支持和持续的版本迭代,代码完全透明可审计,支持本地部署以保护数据隐私。无论是个人使用还是集成到企业工作流,都能提供稳定可靠的解决方案。
# 方式一:pip 安装(推荐)
pip install red-dragon
# 方式二:虚拟环境安装(推荐生产环境)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install red-dragon
# 方式三:从源码安装(获取最新功能)
git clone https://github.com/avishek-sen-gupta/red-dragon
cd red-dragon
pip install -e .
# 验证安装
python -c "import red_dragon; print('安装成功')"
# 命令行使用
red-dragon --help
# 基本用法
red-dragon input_file -o output_file
# Python 代码中调用
import red_dragon
# 示例
result = red_dragon.process("input")
print(result)
# red-dragon 配置文件示例(config.yml) app: name: "red-dragon" debug: false log_level: "INFO" # 运行时指定配置文件 red-dragon --config config.yml # 或通过环境变量配置 export RED_DRAGON_API_KEY="your-key" export RED_DRAGON_OUTPUT_DIR="./output"
<p align="center"> <img src="banner.svg" alt="RedDragon — Multi-language code analysis and execution" width="900"> </p>
The VM executes programs deterministically, tracking data flow through incomplete programs with missing imports or unknown externals entirely without LLM calls.
| Feature | Summary |
|---|---|
| **Write-time type coercion** | Register values coerced to statically-inferred types at write time (e.g. Float→Int for array indices) |
| **Class inheritance** | 10 OOP frontends extract parent chains; executor walks inheritance hierarchy on method miss; multi-level dispatch, overrides, overload accumulation |
| **Static method dispatch** | Class.method(args) dispatches directly via ClassRef across Java, C#, C++, PHP, Ruby |
| **Overload resolution** | Composable OverloadResolver: arity distance + type compatibility scoring with TypeGraph.is_subtype_expr() for inheritance-aware dispatch |
| **Field initializers** | Instance field initializers prepended to constructor bodies (matching javac/Roslyn/kotlinc); synthetic constructors for classes without explicit ones |
| **Implicit this** | Java, C#, C++ — bare field reads/writes in methods rewritten to LOAD_FIELD this/STORE_FIELD this when identifier matches a declared class field |
| **Property accessors** | Kotlin/Pascal custom getters/setters lowered as synthetic methods; navigation expressions intercepted; common infrastructure reusable across frontends |
| **Default parameters** | Shared __resolve_default__ IR helper; wired for 10 frontends (Python, JS, TS, Ruby, C#, C++, Kotlin, Scala, PHP, Pascal) |
| **Symbol extraction** | All 15 frontends run pre-lowering symbol extraction building SymbolTable of classes, fields, methods, inheritance; used for field resolution, type seeding, constructor generation |
| **Pattern matching** | 13-type Pattern ADT; 7 language consumers (Python, C#, Java, Rust, Ruby, Kotlin, Scala); compiles to existing IR primitives; guards supported |
| **Builtins** | len, range, print, str, slice, etc. Method builtins (length/size/Length, subList, substring, toString) via METHOD_TABLE. All return BuiltinResult — no direct heap mutation |
| **Byte-addressed memory** | ALLOC_REGION/WRITE_REGION/LOAD_REGION for COBOL-style REDEFINES overlays |
| **Named continuations** | SET_CONTINUATION/RESUME_CONTINUATION for COBOL PERFORM return semantics |
| **Closures** | Shared mutable environments (capture-by-reference); mutations persist across calls and are visible to sibling closures |
| **LLM resolver** | Optionally replaces symbolic placeholders with concrete values for unresolved function/method calls |
<details> <summary><strong>VM feature implementation details</strong> (click to expand)</summary>
list[str]. C++ Util::square(5) is lowered by a dedicated lower_cpp_call pass. Ruby singleton methods (def self.method) are registered under the bare method name. C++ static methods skip implicit this emission.ArityThenTypeStrategy ranks candidates by arity distance then type compatibility score (exact=2, coercion/subtype=1, neutral=0, mismatch=-1). DefaultTypeCompatibility uses TypeGraph.is_subtype_expr() for inheritance-aware dispatch (e.g. foo(Dog) beats foo(Animal) when passing a Dog), with _COMPATIBLE_PAIRS handling primitive coercion (Int↔Float, Bool→Int) separately from subtyping.__init__ (or __construct for PHP). Lua table-based OOP uses a different mechanism: dotted function declarations emit STORE_FIELD, dotted calls emit LOAD_FIELD + CALL_UNKNOWN (ADR-104).x = v assignments where x is a declared class field are rewritten to LOAD_VAR this + STORE_FIELD at lowering time. Implicit-this field reads — resolve_field walks the class hierarchy; _method_declared_names tracks local variables to avoid shadowing. reset_method_scope() called at method entry.get() = field + 1 lowered as __get_<prop>__ with field resolved to raw LOAD_FIELD/STORE_FIELD. Pascal: property Name: string read FName write SetName supports field-targeted and method-targeted accessors. Common infrastructure in common/property_accessors.py.declSection > declField. COBOL uses from_data_layout. resolve_field returns NULL_FIELD sentinel (not None).__match_args__), Or, As, Value, Deref, Relational, And, Negated. CPython linear chain model with two-pass test-before-bind. Seven consumers: Python, C#, Java, Rust, Ruby, Kotlin, Scala. Decomposes into BINOP ==, CALL_FUNCTION isinstance/len, LOAD_INDEX, LOAD_FIELD, STORE_VAR, BRANCH_IF.</details>
The execution engine is split into focused modules under interpreter/vm/: vm_types.py (state model with domain-typed keys), vm.py (apply_update, operators, register resolution), executor.py (34 opcode handlers dispatched by instruction type), builtins.py (built-in function table), unresolved_call.py (symbolic/LLM call resolution), and field_fallback.py (field access chain). Supporting modules: cfg_types.py, run_types.py, registry.py, and cobol/ (COBOL type system, EBCDIC tables, IR encoder/decoder builders). All 34 IR opcodes are defined as frozen dataclasses in interpreter/instructions.py, with domain-typed fields (Register, CodeLabel, VarName, FieldName, FuncName, BinopKind/UnopKind) and reads()/writes() methods for dataflow analysis.
poetry install
cd proleap-bridge && ./build.sh && cd ..
```
a = 1
b = 2
c = a + b
d = a * b
e = c + d
f = e - a
def square(x):
return x * x
g = square(c)
h = g + f
total = h + e + b
Diamond dependencies (c and d both depend on a and b), function calls (g = square(c)), and multi-operand expressions (total = h + e + b). The direct dependency graph (docs/graph.md):
total directly depends on h, e, and b. The transitive closure adds a, c, d, f, and g. See scripts/demo_dataflow.py for the full pipeline (lowering → CFG → reaching definitions → dependency graph → Mermaid visualisation).
poetry run python -m viz project tests/fixtures/projects/python_basic -l python poetry run python -m viz project /path/to/java/project -l java -s 500 ```
Six synchronized panels: Source (span-highlighted), AST (collapsible tree, toggle a), IR (grouped by CFG block), VM State (heap/stack/registers with diff highlighting), CFG (box-drawing graph, toggle g), and Step (delta summary). Arrow keys step forward/backward, space toggles auto-play, d toggles Dataflow mode (replaces AST/VM/CFG with call-graph summaries and whole-program dependency graph, cross-highlights source and IR on function selection), q quits.
The project mode (viz project) compiles an entire directory via compile_directory() and presents a two-phase experience. Phase 1 (Project Overview) shows a box-drawing import DAG and an entry-point picker grouped by module. Select a function or top-level execution to proceed. Phase 2 (Execution) reuses all standard panels with module-aware source switching: as execution crosses module boundaries, the Source and AST panels automatically swap to the active module's content, and the Source title updates to show the current file path. Press p to return to the project overview.
The pipeline result also includes interprocedural analysis (call graph, function summaries, and whole-program dependency graph) when the source contains function definitions. The Dataflow Summary panel (viz/panels/dataflow_summary_panel.py) renders this as a collapsible tree: each function shows its callers, callees, and merged data-flow summaries across call contexts. The Dataflow Graph panel (viz/panels/dataflow_graph_panel.py) renders interprocedural data flow as a collapsible call-chain tree. Top-level call sites are discovered via find_top_level_call_sites, then build_call_chain recursively constructs a per-parameter flow tree for each callee: each parameter's data flows to return endpoints, field writes, or through inner call sites (with argument mapping) into recursive subtrees, with cycle detection via immutable visited sets. The tree widget replaces the previous flat edge list, making multi-level call chains navigable. The legacy annotate_endpoint and render_graph_lines functions remain available for programmatic use.
The lowering trace mode shows four panels: source with highlighted spans, a collapsible tree of handler invocations (which handler processed which AST node), handler details (emitted IR, dispatch type, module), and the full IR output. Click any node in the trace tree to see its handler, emitted instructions, and source location.
The coverage matrix mode displays a cross-language grid showing which AST node types each frontend handles, distinguishing language-specific handlers (✓) from shared/common handlers (✓*). Supports filtering by node type name.
```bash git clone --recurse-submodules https://github.com/avishek-sen-gupta/red-dragon.git cd red-dragon
git clone https://github.com/avishek-sen-gupta/red-dragon.git
cd red-dragon
poetry install
poetry run python -m pytest tests/unit/ -x -q
All 15 tree-sitter frontends and the LLM frontends work without JDK/Maven. COBOL integration tests skip gracefully when the ProLeap JAR is not present.
cfg = build_cfg_from_source(source, function_name="factorial")
cat myprogram.cbl | java -jar proleap-bridge/target/proleap-bridge-0.1.0-shaded.jar
java -jar proleap-bridge/target/proleap-bridge-0.1.0-shaded.jar myprogram.cbl
java -jar proleap-bridge/target/proleap-bridge-0.1.0-shaded.jar -format TANDEM myprogram.cbl
poetry run python interpreter.py myfile.py -v # run on a file
poetry run python interpreter.py myfile.py --ir-only # inspect IR only
poetry run python interpreter.py myfile.py --cfg-only # inspect CFG only
poetry run python interpreter.py example.js -l javascript # non-Python source
poetry run python interpreter.py myfile.py -f llm -v # LLM frontend
poetry run python interpreter.py myfile.py -f chunked_llm # chunked LLM frontend
poetry run python interpreter.py example.cob -l cobol # COBOL via ProLeap bridge
export PROLEAP_BRIDGE_JAR=/path/to/bridge.jar # optional: custom bridge JAR path
poetry run python interpreter.py myfile.py --mermaid # output CFG as Mermaid flowchart
poetry run python interpreter.py myfile.py --mermaid --function foo # CFG for a single function
| Flag | Description |
|---|---|
-v | Print IR, CFG, and step-by-step execution |
-l | Source language (default: python) |
-b | LLM backend: claude, openai, ollama, huggingface (default: claude) |
-n | Maximum interpretation steps (default: 100) |
-f | Frontend: deterministic, llm, chunked_llm, cobol (default: deterministic) |
--ir-only | Print the IR and exit |
--cfg-only | Print the CFG and exit |
--mermaid | Output CFG as a Mermaid flowchart diagram and exit |
--function | Extract CFG for a single function (use with --mermaid or --cfg-only) |
def classify(x):
if x > 0:
label = "positive"
else:
label = "negative"
return label
Function bodies appear as subgraphs with dashed call edges (-.->|"call"|) connecting CALL_FUNCTION sites to function entry blocks. Blocks with more than 6 instructions are collapsed to show the first 4 lines, an ... (N more) placeholder, and the terminator — keeping CFG diagrams readable without hiding critical branch/return instructions. All 15 frontends produce the same CFG shape for equivalent logic.
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
[step 4] call factorial(5) → dispatch to func_factorial_0
[step 53] binop 1 <= 1 = True ← base case
[step 56] return 1 ← unwind begins
[step 57] 2 * 1 = 2 → 3 * 2 = 6 → 4 * 6 = 24 → 5 * 24 = 120
[step 65] store_var result 120
Final state: result = 120 (67 steps, 0 LLM calls)
The VM also handles — all deterministically:
Pointer(base, offset) with parameterized types (Pointer[ClassName], Pointer[ElementType]), method dispatch with overload resolution (arity + type + subtype-aware scoring via TypeGraph), field accessALLOC_REGION/WRITE_REGION/LOAD_REGION for COBOL-style REDEFINES overlaysSET_CONTINUATION/RESUME_CONTINUATION for COBOL PERFORM return semanticsVMState.data_layout after executionlen, range, print, int, str, slice, arrayOf/listOf, byte-manipulation primitives, etc. Method builtins (subList, substring, slice, length/size/Length, toString) dispatch through METHOD_TABLE for cross-language collection and string operations. All builtins return a BuiltinResult(value, new_objects, heap_writes) (defined in vm_types.py) instead of raw values — no builtin directly mutates vm.heap. Heap mutations are expressed as data in the result and applied uniformly via StateUpdate, keeping builtins pure and side-effect-free.The execution engine is split into focused modules under interpreter/vm/: vm_types.py, vm.py, executor.py (34 opcode handlers), builtins.py, unresolved_call.py, and field_fallback.py. Supporting modules: cfg_types.py, run_types.py, registry.py, and cobol/ (COBOL type system, EBCDIC tables, IR encoder/decoder builders).
Only needed for --frontend llm or when execution encounters symbolic values:
```bash export ANTHROPIC_API_KEY=sk-... # for Claude (default) export OPENAI_API_KEY=sk-... # for OpenAI export HUGGING_FACE_API_TOKEN=hf_... # for HuggingFace Inference Endpoints
When the VM encounters a call to an unresolved function (e.g., math.sqrt(16)), the default behavior creates symbolic values that propagate through subsequent computation. The UnresolvedCallStrategy enum controls this:
SYMBOLIC (default) — creates symbolic placeholders: math.sqrt(16) → sym_N, subsequent sym_N + 1 → sym_M (precision death)LLM — makes a lightweight LLM call to get a plausible concrete value: math.sqrt(16) → 4.0, subsequent 4.0 + 1 = 5.0 (precision preserved), with support for side effects via heap_writes/var_writesfrom interpreter.run import run
from interpreter.run_types import UnresolvedCallStrategy
vm = run(source, language="python", unresolved_call_strategy=UnresolvedCallStrategy.LLM)
All CLI pipelines are available as composable functions — no argparse required.
```python from interpreter import lower_source, lower_and_infer, dump_ir, build_cfg_from_source, dump_cfg, dump_mermaid, extract_function_source, ir_stats, run from interpreter.constants import Language
source = """ def factorial(n): if n <= 1: return n return n * factorial(n - 1) result = factorial(6) """

An interactive TUI for stepping through the full pipeline (source → AST → IR → CFG → execution) is included in viz/:
```bash
vm = run(source, language=Language.PYTHON, verbose=True) frame = vm.call_stack[0] print(frame.local_vars["result"]) # 720
#### With LLM calls
python from interpreter import lower_source, run from interpreter.constants import Language from interpreter import constants from interpreter.run_types import UnresolvedCallStrategy
The Exercism suite (tests/unit/exercism/) pulls canonical test data from Exercism's problem-specifications and runs solutions in all 15 languages. Each exercise is parametrized across all canonical test cases.
<details> <summary><strong>Exercism exercise breakdown</strong> (click to expand)</summary>
| Exercise | Constructs tested | Cases | Execution |
|---|---|---|---|
| **leap** | modulo, boolean logic, short-circuit eval | 9 | 270 |
| **collatz-conjecture** | while loop, conditional, integer division | 4 | 120 |
| **difference-of-squares** | while loop, accumulator, function composition | 9 | 270 |
| **two-fer** | string concatenation, string literals | 3 | 90 |
| **hamming** | string indexing, character comparison, while loop | 5 | 150 |
| **reverse-string** | backward iteration, string building | 5 | 150 |
| **rna-transcription** | multi-branch if, char mapping | 6 | 180 |
| **perfect-numbers** | divisor loop, three-way return | 9 | 270 |
| **triangle** | nested ifs, validity guards, float sides | 21 | 630 |
| **space-age** | float division, string-to-number mapping | 8 | 240 |
| **grains** | exponentiation, large integers (2^63) | 8 | 240 |
| **isogram** | nested while loops, case-insensitive comparison | 14 | 420 |
| **nth-prime** | nested loops, trial division, primality testing | 3 | 90 |
| **resistor-color** | string-to-integer mapping, string equality | 3 | 90 |
| **pangram** | nested loops, letter search, toLowerChar helper | 11 | 330 |
| **bob** | string classification, multi-branch return | 22 | 616 |
| **luhn** | charToDigit helper, right-to-left traversal, modulo | 22 | 660 |
poetry run python -m viz compare c:viz/examples/pointer_demo.c rust:viz/examples/pointer_demo.rs
创新的IR+VM架构解决LLM代码执行的确定性问题,但项目初期阶段,需���多社区验证和文档完善。
AI Skill Hub 为第三方内容聚合平台,本页面信息基于公开数据整理,不对工具功能和质量作任何法律背书。
建议在沙箱或测试环境中充分验证后,再部署至生产环境,并做好必要的安全评估。
✅ MIT 协议 — 最宽松的开源协议之一,可自由商用、修改、分发,仅需保留版权声明。
AI Skill Hub 点评:红龙代码执行引擎 的核心功能完整,质量良好。对于AI 技术爱好者来说,这是一个值得纳入个人工具库的选择。建议先在非生产环境试用,再逐步推广。
| 原始名称 | red-dragon |
| 原始描述 | 开源AI工具:Multi-language code execution through a simple IR and deterministic VM with LLM 。⭐10 · Python |
| Topics | 多语言执行虚拟机LLM集成代码解释 |
| GitHub | https://github.com/avishek-sen-gupta/red-dragon |
| License | MIT |
| 语言 | Python |
收录时间:2026-06-08 · 更新时间:2026-06-11 · License:MIT · AI Skill Hub 不对第三方内容的准确性作法律背书。