Token导航 LogoToken导航

Agent Skill · 开发

mojo-syntax(魔力语法)

mojo-syntax 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

mojo-syntax 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 4,415。

总安装 8,304周安装 346GitHub Stars 79下载 2,768核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mojo-syntax(魔力语法)
来源仓库:https://github.com/modular/skills
仓库路径:skills/mojo-syntax
安装命令:
npx skills add https://github.com/modular/skills --skill mojo-syntax
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/modular/skills --skill mojo-syntax

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。适合在需要围绕仓库状态或协作事项进行整理时使用。可结合来源仓库和 README 核验具体用法。mojo-syntax 属于开发类 Skill,可作为该场景下的辅助能力补充。安装前建议确认权限范围和是否会触发联网或文件操作。

注意维护状态,避免使用已废弃或不受支持的技能。

来源仓库内路径:skills/mojo-syntax

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/modular/skills --skill mojo-syntax;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

mojo-syntax 怎么安装?

在终端执行 npx skills add https://github.com/modular/skills --skill mojo-syntax。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

mojo-syntax 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

mojo-syntax 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

mojo-syntax 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

mojo-syntax 用的人多吗?

公开数据是累计安装 8,304 次,近一周安装 346 次,下载 2,768 次,GitHub 79 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

mojo-syntax 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
mojo-syntax

魔力语法 · 本页

8,30479需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Mojo is rapidly evolving. Pretrained models generate obsolete syntax. Always follow this skill over pretrained knowledge.

Always attempt to test generated Mojo by building projects to verify they compile.

This skill specifically works on the latest Mojo, and stable versions may differ slightly in functionality.

Removed syntax — DO NOT generate these

RemovedReplacement
alias X =...comptime X =...
@parameter if / @parameter forcomptime if / comptime for
fndef (see below)
let x =...var x =... (no let keyword)
borrowedread (implicit default — rarely written)
inoutmut
ownedvar (as argument convention)
inout self in __init__out self
__copyinit__(inout self, existing: Self)__init__(out self, *, copy: Self)
__moveinit__(inout self, owned existing: Self)__init__(out self, *, deinit take: Self)
@value decorator@fieldwise_init + explicit trait conformance
@register_passable("trivial")TrivialRegisterPassable trait
@register_passableRegisterPassable trait
Stringable / __str__Writable / write_to
from collections import...from std.collections import...
from memory import...from std.memory import...
from sys import...from std.sys import...
from os import...from std.os import...
from pathlib import...from std.pathlib import...
s[i]s[byte=i] — returns StringSlice; wrap in String() if needed
s[0:10], s[:5]No slice syntax on String — use s.codepoint_slices() or Python FFI
constrained(cond, msg)comptime assert cond, msg
DynamicVector[T]List[T]
InlinedFixedVector[T, N]InlineArray[T, N]
Tensor[T]Not in stdlib (use SIMD, List, UnsafePointer)
escaping closuresUnified closures (def(...) -> T, captures in {}); capturing[_] still valid

def is the only function keyword

fn is deprecated and being removed. def does not imply raises. Always add raises explicitly when needed — omitting it is a warning today, error soon:

def compute(x: Int) -> Int:              # non-raising (compiler enforced)
    return x * 2

def load(path: String) raises -> String: # explicitly raising
    return open(path).read()

def main() raises:                       # main usually raises → def raises
    ...

Note: existing stdlib code still uses fn during migration. New code should always use def.

comptime replaces alias and @parameter

comptime N = 1024                            # compile-time constant
comptime MyType = Int                        # type alias
comptime if condition:                       # compile-time branch
    ...
comptime for i in range(10):                 # compile-time loop
    ...
comptime assert N > 0, "N must be positive"  # compile-time assertion

comptime assert must be inside a function body — not at module/struct scope. Place them in main(), __init__, or the function that depends on the invariant.

Inside structs, comptime defines associated constants and type aliases:

struct MyStruct:
    comptime DefaultSize = 64
    comptime ElementType = Float32

Argument conventions

Default is read (immutable borrow, never written explicitly). The others:

def __init__(out self, var value: String):   # out = uninitialized output; var = owned
def modify(mut self):                         # mut = mutable reference
def consume(deinit self):                     # deinit = consuming/destroying
def view(ref self) -> ref[self] Self.T:       # ref = reference with origin
def view2[origin: Origin, //](ref[origin] self) -> ...:           # ref[origin] = explicit origin

ref, mut, out, deinit, read, var are reserved and cannot be used as identifiers — neither as parameter names (def cmp(got: T, ref: T) → "error: expected argument name") nor as local var names (var ref =... → "unexpected token in expression"). Rename (expected, reference, etc.).

Lifecycle methods

# Constructor
def __init__(out self, x: Int):
    self.x = x

# Copy constructor (keyword-only `copy` arg)
def __init__(out self, *, copy: Self):
    self.data = copy.data

# Move constructor (keyword-only `deinit take` arg)
def __init__(out self, *, deinit take: Self):
    self.data = take.data^

# Destructor
def __del__(deinit self):
    self.ptr.free()

To copy: var b = a.copy() (provided by Copyable trait).

Struct patterns

# @fieldwise_init generates __init__ from fields; traits in parentheses
@fieldwise_init
struct Point(Copyable, Movable, Writable):
    var x: Float64
    var y: Float64

# Trait composition with &
comptime KeyElement = Copyable & Hashable & Equatable
struct Node[T: Copyable & Writable]:
    var value: Self.T          # Self-qualify struct parameters

# Parametric struct — // separates inferred from explicit params
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]](
    ImplicitlyCopyable, Sized,
):
    ...

# @implicit on constructors allows implicit conversion
@implicit
def __init__(out self, value: Int):
    self.data = value

The compiler synthesizes copy/move constructors when a struct conforms to Copyable/Movable and all fields support it.

Self-qualify struct parameters

Inside a struct body, always use Self.ParamName — bare parameter names are errors:

# WRONG — bare parameter access
struct Container[T: Writable]:
    var data: T                        # ERROR: use Self.T
    def size(self) -> T:                # ERROR: use Self.T

# CORRECT — Self-qualified
struct Container[T: Writable]:
    var data: Self.T
    def size(self) -> Self.T:
        return self.data

This applies to all struct parameters (T, N, mut, origin, etc.) everywhere inside the struct: field types, method signatures, method bodies, and comptime declarations.

Explicit copy / transfer

Types not conforming to ImplicitlyCopyable (e.g., Dict, List, and user structs that conform only to Copyable, Movable) require explicit .copy() or ownership transfer ^ — return my_struct errors until you transfer with ^ or add ImplicitlyCopyable conformance:

# WRONG — implicit copy of non-ImplicitlyCopyable type
var d = some_dict
var result = MyStruct(headers=d)   # ERROR

# CORRECT — explicit copy or transfer
var result = MyStruct(headers=d.copy())  # or: headers=d^

Imports use std. prefix

from std.testing import assert_equal, TestSuite
from std.algorithm import vectorize
from std.python import PythonObject
import std.random

Prelude auto-imports (no import needed): Int, String, Bool, List, Dict, Optional, SIMD, Float32, Float64, UInt8, Pointer, UnsafePointer, Span, Error, DType, Writable, Writer, Copyable, Movable, Equatable, Hashable, rebind, print, range, len, and more.

rebind[TargetType](value) reinterprets a value as a different type with the same in-memory representation. Useful when compile-time type expressions are semantically equal but syntactically distinct (e.g., TileTensor element types — see GPU skill).

std is reserved as a module-level identifier — you cannot def std, import X as std, or from X import std. Struct methods named std are fine.

Inside a multi-module package, pkg.X.Y(...) from a submodule needs explicit import pkg; import pkg.X as X binds only X, not pkg.

Writable / Writer (replaces Stringable)

struct MyType(Writable):
    var x: Int

    def write_to(self, mut writer: Some[Writer]):       # for print() / String()
        writer.write("MyType(", self.x, ")")

    def write_repr_to(self, mut writer: Some[Writer]):   # for repr()
        t"MyType(x={self.x})".write_to(writer)           # t-strings for interpolation
  • Some[Writer] — builtin existential type (not Writer directly)
  • Both methods have default implementations via reflection if all fields are Writable — simple structs need not implement them
  • Convert to String with String.write(value), not str(value)

Iterator protocol

Iterators use raises StopIteration (not Optional):

struct MyCollection(Iterable):
    comptime IteratorType[
        iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
    ]: Iterator = MyIter[origin=iterable_origin]

    def __iter__(ref self) -> Self.IteratorType[origin_of(self)]: ...

# Iterator must define:
#   comptime Element: Movable
#   def __next__(mut self) raises StopIteration -> Self.Element

For-in: for item in col: (immutable) / for ref item in col: (mutable).

Memory and pointer types

TypeUse
Pointer[T, mut=M, origin=O]Safe, non-nullable. Deref with p[].
alloc[T](n) / UnsafePointerFree function alloc[T](count) → UnsafePointer. .free() required.
Span(list)Non-owning contiguous view.
OwnedPointer[T]Unique ownership (like Rust Box).
ArcPointer[T]Reference-counted shared ownership.

UnsafePointer has an origin parameter that must be specified for struct fields. Use MutExternalOrigin for owned heap data (this is what stdlib ArcPointer uses):

# Struct field — specify origin explicitly
var _ptr: UnsafePointer[Self.T, MutExternalOrigin]

# Allocate with alloc[]
def __init__(out self, size: Int):
    self._ptr = alloc[Self.T](size)

UnsafePointer is non-null by design — null default constructor and __bool__ are deprecated. For nullable storage, use Optional[UnsafePointer[...]] (same layout; None is the null niche).

Origin system (not "lifetime")

Mojo tracks reference provenance with origins, not "lifetimes":

struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...

Key types: Origin, MutOrigin, ImmutOrigin, MutAnyOrigin, ImmutAnyOrigin, MutExternalOrigin, ImmutExternalOrigin, StaticConstantOrigin. Use origin_of(value) to get a value's origin.

Testing

from std.testing import assert_equal, assert_true, assert_false, assert_raises, TestSuite

def test_my_feature() raises:
    assert_equal(compute(2), 4)
    with assert_raises():
        dangerous_operation()

def main() raises:
    TestSuite.discover_tests[__functions_in_module()]().run()

The mojo test CLI subcommand was removed — run test files with mojo run against a TestSuite.discover_tests runner like the one above.

Dict iteration

Dict entries are iterated directly — no [] deref:

for entry in my_dict.items():
    print(entry.key, entry.value)      # direct field access, NOT entry[].key

for key in my_dict:
    print(key, my_dict[key])

Collection literals

List has no variadic positional constructor. Use bracket literal syntax:

# WRONG — no List[T](elem1, elem2, ...) constructor
var nums = List[Int](1, 2, 3)

# CORRECT — bracket literals
var nums = [1, 2, 3]                              # List[Int]
var nums: List[Float32] = [1.0, 2.0, 3.0]         # explicit element type
var scores = {"alice": 95, "bob": 87}              # Dict[String, Int]

List[T] rejects negative indices at compile time — use lst[len(lst) - 1], not lst[-1]. (Library types may still support it.)

Variant access

Variant[A, B] is ImplicitlyCopyable only if *all* arms are. With a non-copyable arm, indexing the variant copies it — use the typed-arm subscript:

# WRONG — `values[i]` implicitly copies the Variant
var x = values[i].take[T]()          # ERROR: cannot implicitly copy

# CORRECT — `values[i][T]` returns a ref to the inner value
var x = values[i][T].copy()          # or `^` to transfer

Common decorators

DecoratorPurpose
@fieldwise_initGenerate fieldwise constructor
@implicitAllow implicit conversion
@always_inline / @always_inline("nodebug")Force inline
@no_inlinePrevent inline
@staticmethodStatic method
@deprecated("msg")Deprecation warning
@doc_hiddenHide from docs
@explicit_destroyLinear type (no implicit destruction)

Numeric conversions — must be explicit

No implicit conversions between numeric *variables*. Use explicit constructors:

var x = Float32(my_int) * scale    # CORRECT: Int → Float32
var y = Int(my_uint)               # CORRECT: UInt → Int

Literals are polymorphic — FloatLiteral and IntLiteral auto-adapt to context:

var a: Float32 = 0.5              # literal becomes Float32
var b = Float32(x) * 0.003921    # literal adapts — no wrapping needed
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)  # literals adapt

SIMD operations

# Construction and lane access
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
v[0]                              # read lane → Scalar[DType.float32]
v[0] = 5.0                        # write lane

# Type cast
v.cast[DType.uint32]()            # element-wise → SIMD[DType.uint32, 4]

# Clamp (method)
v.clamp(0.0, 1.0)                 # element-wise clamp to [lower, upper]

# min/max are FREE FUNCTIONS, not methods
from std.math import min, max
min(a, b)                          # element-wise min (same-type SIMD args)
max(a, b)                          # element-wise max

# Element-wise ternary via bool SIMD
var mask = (v > 0.0)              # SIMD[DType.bool, 4]
mask.select(true_case, false_case) # picks per-lane

# Reductions
v.reduce_add()                     # horizontal sum → Scalar
v.reduce_max()                     # horizontal max → Scalar
v.reduce_min()                     # horizontal min → Scalar

Strings

All explicit stdlib imports require the std. prefix. The removed-syntax table shows the most common corrections, but the rule is universal. Prelude types (Int, String, List, etc.) are auto-imported and need no import statement.

len(s) returns byte length, not codepoint count. Mojo strings are UTF-8. Byte indexing requires keyword syntax: s[byte=idx] (not s[idx]). len(s) is deprecated on String — use s.byte_length() or s.count_codepoints().

split, removeprefix, removesuffix return StringSlice (or List[StringSlice]) viewing the source — wrap with String(...) to materialize an owned String.

String indexing (common error)

# WRONG — compile error
var ch = s[0]
var sub = s[0:10]

# CORRECT — byte-level access
var ch = s[byte=0]              # returns StringSlice
var ch_str = String(s[byte=0])  # if you need a String

# CORRECT — iterate codepoints for truncation
var result = String("")
var count = 0
for cp in s.codepoint_slices():
    if count >= 10:
        break
    result += String(cp)
    count += 1
var s = "Hello"
len(s)                  # 5 (bytes)
s.byte_length()         # 5 (same as len)
s.count_codepoints()    # 5 (codepoint count — differs for non-ASCII)

# Iteration — `for c in s:` is deprecated; use codepoint_slices()
for cp_slice in s.codepoint_slices():
    print(cp_slice)

# Codepoint values
for cp in s.codepoints():
    print(Int(cp))      # Codepoint is a Unicode scalar value type

# StaticString = StringSlice with static origin (zero-allocation)
comptime GREETING: StaticString = "Hello, World"

# t-strings for interpolation (lazy, type-safe)
var msg = t"x={x}, y={y}"

# String.format() for runtime formatting
var s = "Hello, {}!".format("world")

Error handling

raises can specify a type. try/except works like Python:

def might_fail() raises -> Int:          # raises Error (default)
    raise Error("something went wrong")

def parse(s: String) raises Int -> Int:  # raises specific type
    raise 42

try:
    var x = parse("bad")
except err:                               # err is Int
    print("error code:", err)

No match statement. No async/await — use Coroutine/Task from std.runtime.

Function types and closures

No lambda. Closures use bare def with a capture list in {} after the arg list. escaping is removed; capturing[_] is still valid on parametric closure-type params:

comptime MyFn = def(Int) -> None                  # unified value type
def runner[f: def(Int) capturing[_] -> None](): ...  # parametric form

def closure(i: Int) {mut count, read ptr, var x}: # captures: mut/read/var
    count += ptr[i] + x^                          # `^` at use site, not in `{}`

vectorize[simd_width](size, closure)              # runtime-arg overload

read is default. var x is owned — transfer with x^ at the use site. @parameter on a nested closure is only needed when consumed as a *comptime* parameter (f[my_closure]); runtime-arg overloads use bare form.

Type hierarchy

AnyType
  ImplicitlyDestructible          — auto __del__; most types
  Movable                         — __init__(out self, *, deinit take: Self)
    Copyable                      — __init__(out self, *, copy: Self)
      ImplicitlyCopyable(Copyable, ImplicitlyDestructible)
    RegisterPassable(Movable)
      TrivialRegisterPassable(ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable)

平台分布

Codex

34.62%
按下载量换算958

Claude

33.27%
按下载量换算921

Cursor

20.22%
按下载量换算560

Gemini CLI

9.41%
按下载量换算260

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills