enum과 셀 타입
기본 플러그인은 직접 만든 enum과 셀 타입을 Core에 등록합니다. 이 쪽은 기본 플러그인부터 직접 만든 셀 타입과 래퍼 타입까지 차례로 다룹니다.
enum과 파서 등록하기
ISheetForgePlugin을 구현하세요. 이 인터페이스를 구현한 클래스가 플러그인의 이름을 밝히고 enum과 셀 파서를 등록합니다.
using SheetForge.Core.Model;
using SheetForge.Core.Plugins;
public sealed class SkillsPlugin : ISheetForgePlugin
{
public string Name => "Skills"; // for diagnostics / duplicate-conflict reports
public void RegisterEnums(EnumRegistry enums)
{
// Any Enum<ActionType> / Enum<EffectType> cell in a sheet now resolves,
// and codegen emits the real CLR enum type on the generated field.
enums.Register<ActionType>();
enums.Register<EffectType>();
}
public void RegisterCellParsers(CellParserRegistry parsers)
{
// A custom cell type joins parsing, validation, codegen, bake and
// round-trip by registration alone (open-closed — zero pipeline edits).
parsers.Register(new ModifierCellParser());
}
}| 멤버 | 하는 일 |
|---|---|
Name | 진단과 중복 충돌 리포트에서 이 플러그인을 가리키는 이름 |
RegisterEnums | enum 셀을 직접 만든 CLR enum과 잇습니다 |
RegisterCellParsers | 직접 만든 셀 타입을 더합니다 |
enums.Register<ActionType>() 호출 뒤에는 시트의 모든 Enum<ActionType> 셀이 그 enum으로 풀립니다. 코드 생성은 생성 필드에 실제 CLR enum 타입을 씁니다.
등록한 셀 타입은 등록만으로 파싱, 검증, 코드 생성, 베이크, 왕복에 참여합니다. 파이프라인에서 고칠 곳은 없습니다.
직접 만든 셀 타입 더하기
직접 만든 셀 타입은 셀의 글을 직접 정의한 타입의 값으로 바꿉니다. 구현하는 인터페이스는 두 개까지입니다.
| 인터페이스 | 바꾸는 것 | 필요한 때 |
|---|---|---|
ICellValueParser | 문자열을 값으로 | 직접 만든 셀 타입이면 언제나 |
ICustomCellType | CLR 타입을 알려 주고 값을 정규 문자열로 | 강타입 베이크와 Export·Push의 왕복 |
예제는 Modifier라는 작은 문법을 구현합니다. 셀에는 stat:op:value 꼴로 씁니다. 예를 들면 attack:add:10입니다.
using System;
using SheetForge.Core.Model;
using SheetForge.Core.Unparse;
public sealed class ModifierCellParser : ICellValueParser, ICustomCellType
{
// The @type cell text: a column declares "Modifier" or "List<Modifier>".
public string TypeName => "Modifier";
// ICustomCellType: the CLR value type codegen emits ([Serializable] struct).
public Type ValueType => typeof(Modifier);
public bool TryParse(CellParseContext context, string text, out object value)
{
value = null;
string[] parts = text.Split(':');
if (parts.Length != 3)
{
// Failure = collect a structured error and return false. Never throw.
context.Errors.Add(new ImportError(
ImportErrorCode.CustomTypeParseFailed, context.Coordinate,
text, "'stat:op:value' form (e.g. attack:add:10)", null));
return false;
}
// ... parse the three parts (InvariantCulture; reject NaN/Infinity) ...
value = new Modifier(parts[0].Trim(), /*op*/ default, /*value*/ 0f);
return true;
}
// ICustomCellType: value → canonical cell string (the exact inverse of TryParse).
public bool TryRender(object value, out string text, out string reason)
{
reason = null;
if (!(value is Modifier m)) { text = null; reason = "Not a Modifier."; return false; }
// Use CanonicalValueRenderer.RenderFloat for floats — round-trip-safe on Mono.
text = m.stat + ":" + "add" + ":" + CanonicalValueRenderer.RenderFloat(m.value);
return true;
}
}완성본은 Assets/SheetForge.PluginDemo/ModifierCellParser.cs 파일이고 플러그인 데모 패키지가 이 파일을 되살립니다. 완성본에는 op 토큰 검증과 가장 가까운 이름 제안이 더 들어 있습니다.
파서 규칙
TypeName은@type셀의 글입니다. 컬럼은Modifier나List<Modifier>로 선언합니다.ValueType은 코드 생성이 만드는 CLR 값 타입입니다. 예제에서는[Serializable]구조체입니다.- 실패하면
context.Errors에 구조화된 오류를 더하고false를 반환하세요. 예외를 던지지 마세요. - 예제는 세 부분을
InvariantCulture로 파싱하고 NaN과 Infinity는 거절합니다. TryRender는 정규 셀 문자열을 반환합니다.TryParse를 정확히 거꾸로 되짚는 동작입니다.- 실수는
CanonicalValueRenderer.RenderFloat로 문자열로 바꾸세요. Mono에서도 왕복한 값이 그대로 남습니다.
대상이 있는 직접 만든 타입
직접 만든 타입에 붙인 @target도 등록만으로 동작합니다. 컬럼을 Modifier@Stats로 선언하면 파서가 읽는 context.Type.TargetName의 값은 "Stats"입니다.
그 대상이 온전한지는 도메인 검증기가 검사합니다. 그 탭이 있는지와 id가 실제 데이터로 풀리는지를 검증기가 답합니다. RecordId@Tab과 같은 역할 분담입니다.
@ 붙은 이름이라도 등록하지 않은 타입이면 제안이 붙은 오류가 납니다. 오타는 계속 잡힙니다.
예약된 타입 이름
Core는 어느 플러그인보다 먼저 내장 타입 이름을 등록합니다. 그 이름은 int, float, bool, string, Enum, RecordId, AssetRef, ResourceRef, DirectRef, IntId, LocRef, Color, AnimationCurve, Gradient입니다.
이 가운데 하나를 다시 쓰는 파서는 PluginRegistrationConflict 오류로 등록에 실패합니다. 그때 일어나는 일은 셋입니다.
- 내장 타입이 그대로 남습니다.
- 그
RegisterCellParsers호출은 충돌한 파서에서 멈춥니다. - 플러그인의 다른 슬롯은 그대로 로드됩니다.
Color나 Gradient 타입을 따로 만들어 배포한 플러그인은 그 타입의 이름을 바꿔야 합니다. 변경 기록의 업그레이드 안내를 보세요.
색, 커브, 그라디언트 값
타입에 색이나 커브, 그라디언트를 담는다면 표기를 다시 구현하지 않아도 됩니다. Core가 필요한 부품을 제공합니다.
| 부품 | 타입 | 얻는 것 |
|---|---|---|
| 값 모델 | ColorValue, CurveValue, GradientValue | TryParse(text, out value, out error)와 Render() |
| 평가기 | CurveEvaluator와 GradientEvaluator | Unity와 똑같은 샘플링 |
| 편집기 힌트 | StudioCellEditorHint | 두 호스트 모두에서 그 타입에 맞는 기본 편집기 |
StudioCellEditorHint에는 ColorPicker, CurveEditor, GradientEditor 원형 가운데 하나를 주세요. 힌트는 셀 편집기 원형에서 설명합니다.
래퍼 타입 더하기
래퍼는 MyWrapper<T>처럼 쓰는 제네릭 값 모양입니다. 안쪽 T 값 여러 개를 셀 하나에 담습니다. 예를 들어 Pair<int> 셀에는 1~2가 들어갑니다.
직접 정하는 것은 바깥 문법, 곧 구분자와 조각 수뿐입니다. 안쪽 T는 Core가 재귀로 파싱합니다. 그래서 Pair<RecordId@Effects>, Pair<Enum<DamageType>>, 중첩한 Box<Pair<int>>도 코드를 더 쓰지 않고 파싱과 검증을 거칩니다. 안에 든 참조도 빠짐없이 검증합니다.
ICellWrapperType을 구현하세요. 등록은 같은 RegisterCellParsers 훅에서 parsers.RegisterWrapper(...)로 합니다.
// A [Serializable] generic value type — codegen emits Pair<int>, Pair<RecordRef>, ...
[Serializable] public struct Pair<T> { public T First; public T Second; public Pair(T a, T b){First=a;Second=b;} }
public sealed class PairWrapper : ICellWrapperType
{
public string Name => "Pair"; // the @type token: Pair<Inner>
public Type OpenClrType => typeof(Pair<>); // generic open type — exactly one type parameter
// Outer syntax only: split "1~2" into ["1","2"]. Use a delimiter OTHER than ';'
// so List<Pair<T>> doesn't clash with the list separator.
public bool TrySplit(string cell, out IReadOnlyList<string> pieces, out string reason)
{
reason = null;
var parts = (cell ?? "").Split('~');
if (parts.Length != 2) { pieces = null; reason = "'a~b' form (two parts)."; return false; }
pieces = new[] { parts[0], parts[1] };
return true; // the Core parses each piece as the inner type
}
public string JoinCanonical(IReadOnlyList<string> inner) => inner[0] + "~" + inner[1]; // inverse of TrySplit
public object Assemble(IReadOnlyList<object> inner, Type closed) =>
Activator.CreateInstance(closed, inner[0], inner[1]); // bake: build Pair<TInner>
public bool TryDisassemble(object v, out IReadOnlyList<object> inner, out string reason)
{
reason = null;
var t = v.GetType();
inner = new[] { t.GetField("First").GetValue(v), t.GetField("Second").GetValue(v) };
return true; // Export: read the values back out (inverse of Assemble)
}
}
// In your ISheetForgePlugin.RegisterCellParsers:
public void RegisterCellParsers(CellParserRegistry parsers) => parsers.RegisterWrapper(new PairWrapper());래퍼 멤버
| 멤버 | 역할 |
|---|---|
Name | Pair<Inner>처럼 쓰는 @type 토큰 |
OpenClrType | 타입 매개변수가 정확히 하나인 열린 제네릭 타입 |
TrySplit | 셀을 조각으로 나눕니다. 바깥 문법만 다룹니다 |
JoinCanonical | 조각을 다시 잇습니다. TrySplit의 역연산입니다 |
Assemble | 베이크할 때 Pair<TInner> 같은 닫힌 타입을 만듭니다 |
TryDisassemble | Export할 때 값을 다시 꺼냅니다. Assemble의 역연산입니다 |
TrySplit이 나눈 조각은 Core가 하나씩 안쪽 타입으로 파싱합니다.
구분자로는 ; 말고 다른 문자를 쓰세요. ; 문자를 쓰면 List<Pair<T>> 컬럼에서 목록 구분자와 부딪힙니다.
등록 한 번으로 얻는 것
등록 한 번으로 다음을 모두 얻습니다.
- 재귀적인
@type해석 Pair<RecordRef> First;같은 강타입 코드 생성- 베이크
- Export와 Push의 왕복
- 래퍼 안에 든
RecordId@Tab의 참조 통과
참조 통과는 세 가지를 뜻합니다. 안쪽 참조는 무결성 검사를 받습니다. 키 이름을 바꾸면 그 변경이 전파되고 탭 이름을 바꾸면 새 이름으로 다시 쓰입니다.
거절되는 표기와 ; 구분자의 주의점은 래퍼를 거부하는 규칙에 있습니다.