Skip to content

Commit

Permalink
Merge pull request #134 from unyt-org/0.2
Browse files Browse the repository at this point in the history
Release 0.2
  • Loading branch information
jonasstrehle authored Oct 13, 2024
2 parents a841ab1 + 3ff1ee3 commit 8e8d8b2
Show file tree
Hide file tree
Showing 40 changed files with 1,190 additions and 484 deletions.
8 changes: 4 additions & 4 deletions compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const logger = new Logger("datex compiler");

import { ReadableStream, Runtime } from "../runtime/runtime.ts";
import { Endpoint, IdEndpoint, Target, WildcardTarget, Institution, Person, BROADCAST, target_clause, endpoints, LOCAL_ENDPOINT } from "../types/addressing.ts";
import { Pointer, PointerProperty, Ref } from "../runtime/pointers.ts";
import { Pointer, PointerProperty, ReactiveValue } from "../runtime/pointers.ts";
import { CompilerError, RuntimeError, Error as DatexError, ValueError } from "../types/errors.ts";
import { Function as DatexFunction } from "../types/function.ts";

Expand Down Expand Up @@ -2764,7 +2764,7 @@ export class Compiler {

// make sure normal pointers are collapsed (ignore error if uninitialized pointer is passed in)
try {
value = Ref.collapseValue(value);
value = ReactiveValue.collapseValue(value);
}
catch {}

Expand Down Expand Up @@ -2864,7 +2864,7 @@ export class Compiler {
const skip_first_collapse = !SCOPE.options._first_insert_done&&SCOPE.options.collapse_first_inserted;

const option_collapse = SCOPE.options.collapse_pointers && !(SCOPE.options.keep_external_pointers && value instanceof Pointer && !value.is_origin);
const no_proxify = value instanceof Ref && (((value instanceof Pointer && value.is_anonymous) || option_collapse) || skip_first_collapse);
const no_proxify = value instanceof ReactiveValue && (((value instanceof Pointer && value.is_anonymous) || option_collapse) || skip_first_collapse);

// proxify pointer exceptions:
if (no_proxify) {
Expand Down Expand Up @@ -2903,7 +2903,7 @@ export class Compiler {
// indirect reference pointer
if (indirectReferencePtr) {
SCOPE.options._first_insert_done = true;
Compiler.builder.insert(Ref.collapseValue(value, true), SCOPE, is_root, parents, unassigned_children);
Compiler.builder.insert(ReactiveValue.collapseValue(value, true), SCOPE, is_root, parents, unassigned_children);
return;
}

Expand Down
75 changes: 44 additions & 31 deletions datex_short.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

// shortcut functions
// import { Datex } from "./datex.ts";
import { baseURL, Runtime, PrecompiledDXB, Type, Pointer, Ref, PointerProperty, primitive, Target, IdEndpoint, Markdown, MinimalJSRef, RefOrValue, PartialRefOrValueObject, datex_meta, ObjectWithDatexValues, Compiler, endpoint_by_endpoint_name, endpoint_name, Storage, compiler_scope, datex_scope, DatexResponse, target_clause, ValueError, logger, Class, getUnknownMeta, Endpoint, INSERT_MARK, CollapsedValueAdvanced, CollapsedValue, SmartTransformFunction, compiler_options, activePlugins, METADATA, handleDecoratorArgs, RefOrValueObject, PointerPropertyParent, InferredPointerProperty, RefLike, dc } from "./datex_all.ts";
import { baseURL, Runtime, PrecompiledDXB, Type, Pointer, ReactiveValue, PointerProperty, primitive, Target, IdEndpoint, Markdown, MinimalJSRef, RefOrValue, PartialRefOrValueObject, datex_meta, ObjectWithDatexValues, Compiler, endpoint_by_endpoint_name, endpoint_name, Storage, compiler_scope, datex_scope, DatexResponse, target_clause, ValueError, logger, Class, getUnknownMeta, Endpoint, INSERT_MARK, CollapsedValueAdvanced, CollapsedValue, SmartTransformFunction, compiler_options, activePlugins, METADATA, handleDecoratorArgs, RefOrValueObject, PointerPropertyParent, InferredPointerProperty, RefLike, dc } from "./datex_all.ts";

/** make decorators global */
import { assert as _assert, timeout as _timeout, entrypoint as _entrypoint, ref as _ref, entrypointProperty as _entrypointProperty, property as _property, struct as _struct, endpoint as _endpoint, sync as _sync, allow as _allow} from "./datex_all.ts";
Expand Down Expand Up @@ -41,14 +41,14 @@ declare global {
const selectProperty: typeof _selectProperty;
const not: typeof _not;
const effect: typeof _effect;
const observe: typeof Ref.observe
const observeAndInit: typeof Ref.observeAndInit
const unobserve: typeof Ref.unobserve
const observe: typeof ReactiveValue.observe
const observeAndInit: typeof ReactiveValue.observeAndInit
const unobserve: typeof ReactiveValue.unobserve
/**
* Prevents any values accessed within the callback function from
* being captured by a transform function (e.g. always)
*/
const isolate: typeof Ref.disableCapturing
const isolate: typeof ReactiveValue.disableCapturing

/**
* The local endpoint of the current runtime (alias for Datex.Runtime.endpoint)
Expand Down Expand Up @@ -280,7 +280,7 @@ export function pointer<Key, Parent extends PointerPropertyParent<Key,unknown>>(
*/
export function pointer<T>(value:RefLike<T>): MinimalJSRef<T> // defined 2x with Ref<T> and T for correct type inference
export function pointer<T>(value:T): MinimalJSRef<T>
export function pointer<T>(value:RefOrValue<T>, property?:unknown): unknown {
export function pointer<T>(value:RefOrValue<T>, property?:unknown, callStackIndex = 0): unknown {

// pointer property
if (property !== undefined) {
Expand All @@ -292,7 +292,7 @@ export function pointer<T>(value:RefOrValue<T>, property?:unknown): unknown {
const pointer = <any> Pointer.createOrGet(value).js_value;
// store as eternal?
if (waitingEternals.size) {
const info = getCallerInfo()?.[0];
const info = getCallerInfo()?.[callStackIndex];
if (!info) throw new Error("eternal values are not supported in this runtime environment");
const unique = `${info.file}:${info.row}`;
if (waitingEternals.has(unique)) {
Expand All @@ -301,7 +301,7 @@ export function pointer<T>(value:RefOrValue<T>, property?:unknown): unknown {
}
}
if (waitingLazyEternals.size) {
const info = getCallerInfo()?.[0];
const info = getCallerInfo()?.[callStackIndex];
if (!info) throw new Error("eternal values are not supported in this runtime environment");
const unique = `${info.file}:${info.row}`;
if (waitingLazyEternals.has(unique)) {
Expand All @@ -323,8 +323,13 @@ export function pointer<T>(value:RefOrValue<T>, property?:unknown): unknown {
export function prop<T extends Map<unknown, unknown>>(parent:RefOrValue<T>, propertyKey: T extends Map<infer K, infer V> ? K : unknown): PointerProperty<T extends Map<infer K, infer V> ? V : unknown>|(T extends Map<infer K, infer V> ? V : unknown)
export function prop<T extends Record<PropertyKey, unknown>>(parent:RefOrValue<T>, propertyKey: keyof T): PointerProperty<T[keyof T]>|T[keyof T]
export function prop(parent:Map<unknown, unknown>|Record<PropertyKey, unknown>, propertyKey: unknown): any {
if (Ref.isRef(parent)) return PointerProperty.get(parent, propertyKey);
else if (parent instanceof Map) return parent.get(propertyKey);
// try to get pointer property
if (ReactiveValue.isRef(parent)) {
const prop = PointerProperty.getIfExists(parent, propertyKey);
if (prop !== NOT_EXISTING) return prop;
}

if (parent instanceof Map) return parent.get(propertyKey);
else return parent[propertyKey as keyof typeof parent];
}

Expand Down Expand Up @@ -361,11 +366,10 @@ export function revokeAccess(value: any, endpoint: string|Endpoint) {

export const $$ = pointer;

interface $fn {
<const T>(value:T): MinimalJSRef<T>
}

type $type = (Record<string, Pointer<unknown>|Promise<Pointer<unknown>>>) & $fn;
type $type = (Record<string, Pointer<unknown>|Promise<Pointer<unknown>>>) & {
<T>(value:T): MinimalJSRef<T>
};

/**
* Compiled reactivity syntax ($()) - throws an error when called directly and not compiled to $$() or always()
Expand All @@ -385,10 +389,8 @@ export const $ = new Proxy(function(){} as unknown as $type, {
}
},

apply() {
// TODO: change errors, not UIX specific
if (client_type == "deno") throw new Error("Experimental $() syntax is currently not supported on the backend");
else throw new Error("Experimental $() syntax is not enabled per default. Add \"experimentalFeatures: ['embedded-reactivity']\" to your app.dx to enable this feature.");
apply(_target, _thisArg, args) {
return pointer(args[0], args[1], 1 /* callStackIndex */);
},
})

Expand All @@ -399,31 +401,31 @@ export const $ = new Proxy(function(){} as unknown as $type, {
* @returns
*/
export function val<T>(val: RefOrValue<T>):T { // TODO: return inferred type instead of T (ts resolution error, too deep)
return Ref.collapseValue(val, true, true)
return ReactiveValue.collapseValue(val, true, true)
}


// generate primitive pointers
export function decimal(value:RefOrValue<number|bigint|string> = 0): Pointer<number> {
if (value instanceof Ref) value = value.val; // collapse
if (value instanceof ReactiveValue) value = value.val; // collapse
return Pointer.create(undefined, Number(value)) // adds pointer or returns existing pointer
}
export function integer(value:RefOrValue<bigint|number|string> = 0n): Pointer<bigint> {
if (value instanceof Ref) value = value.val; // collapse
if (value instanceof ReactiveValue) value = value.val; // collapse
return Pointer.create(undefined, BigInt(Math.floor(Number(value)))) // adds pointer or returns existing pointer
}
export function text(string:TemplateStringsArray, ...vars:any[]):Promise<Pointer<string>>
export function text(value?:RefOrValue<any>): Pointer<string>
export function text(value:RefOrValue<string>|TemplateStringsArray = "", ...vars:any[]): Pointer<string>|Promise<Pointer<string>> {
if (value instanceof Ref) value = value.val; // collapse
if (value instanceof ReactiveValue) value = value.val; // collapse
// template transform
if (value instanceof Array) {
return <Promise<Pointer<string>>>_datex(`always '${value.raw.map(s=>s.replace(/\(/g, '\\(').replace(/\'/g, "\\'")).join(INSERT_MARK)}'`, vars)
}
else return Pointer.create(undefined, String(value)) // adds pointer or returns existing pointer
}
export function boolean(value:RefOrValue<boolean> = false): Pointer<boolean> {
if (value instanceof Ref) value = value.val; // collapse
if (value instanceof ReactiveValue) value = value.val; // collapse
return Pointer.create(undefined, Boolean(value)) // adds pointer or returns existing pointer
}

Expand All @@ -433,7 +435,7 @@ export function md(string:TemplateStringsArray, ...vars:any[]):Promise<Markdown>
export function md(value?:RefOrValue<string>): Markdown
export function md(value:RefOrValue<string>|TemplateStringsArray = "", ...vars:any[]): Markdown|Promise<Markdown> {
// transform string reference
if (value instanceof Ref) return <Promise<Markdown>> _datex `always <text/markdown> ${value}`
if (value instanceof ReactiveValue) return <Promise<Markdown>> _datex `always <text/markdown> ${value}`
// template transform
else if (value instanceof Array) return <Promise<Markdown>>_datex(`always <text/markdown>'${value.raw.map(s=>s.replace(/\(/g, '\\(').replace(/\'/g, "\\'")).join(INSERT_MARK)}'`, vars)
// pointer from string
Expand Down Expand Up @@ -485,7 +487,7 @@ export function static_pointer<T>(value:RefOrValue<T>, endpoint:IdEndpoint, uniq
const static_id = Pointer.getStaticPointerId(endpoint, unique_id);
const pointer = Pointer.create(static_id, value)
if (label) pointer.addLabel(typeof label == "string" ? label.replace(/^\$/, '') : label);
return Ref.collapseValue(pointer);
return ReactiveValue.collapseValue(pointer);
}

// similar to pointer(), but also adds a label
Expand Down Expand Up @@ -531,6 +533,9 @@ type revokeAccess = typeof revokeAccess
declare global {
const eternal: undefined
const lazyEternal: undefined
/**
* @deprecated use $()
*/
const $$: typeof pointer
const $: $type

Expand Down Expand Up @@ -619,7 +624,7 @@ export function props<T extends object = object>(parent:RefOrValue<T>, strong_pa
// other DatexValues can also be returned -> check if property already a DatexValue
if (!strong_parent_bounding) {
const property = pointer.getProperty(key);
if (property instanceof Ref) return property;
if (property instanceof ReactiveValue) return property;
}
// create a DatexPointerProperty
return PointerProperty.get(pointer, <keyof Pointer<T>>key);
Expand Down Expand Up @@ -675,23 +680,31 @@ export function translocate<T extends Map<unknown,unknown>|Set<unknown>|Array<un
// value.
// }

export function _$method(value: any, method: string, ...args: unknown[]) {
if (ReactiveValue.isRef(value) && value['$'][method]) {
return value['$'][method](...args);
}
else return value[method](...args);
}


Object.defineProperty(globalThis, 'once', {value:once, configurable:false})
Object.defineProperty(globalThis, 'always', {value:_always, configurable:false})
Object.defineProperty(globalThis, 'asyncAlways', {value:_asyncAlways, configurable:false})
// used internally for reactive $ syntax
Object.defineProperty(globalThis, '_$', {value:(cb:SmartTransformFunction<unknown>)=>_always(cb, {allowStatic: true}), configurable:false})
Object.defineProperty(globalThis, '_$', {value: (cb:SmartTransformFunction<unknown>) => _always(cb, {allowStatic: true, _allowAsync: true, _collapseStatic: true, _returnWrapper: true, _allowAnyType: true}), configurable:false})
Object.defineProperty(globalThis, '_$method', {value: _$method, configurable:false})
Object.defineProperty(globalThis, 'reactiveFn', {value:_reactiveFn, configurable:false})
Object.defineProperty(globalThis, 'toggle', {value:_toggle, configurable:false})
Object.defineProperty(globalThis, 'map', {value:_map, configurable:false})
Object.defineProperty(globalThis, 'equals', {value:_equals, configurable:false})
Object.defineProperty(globalThis, 'selectProperty', {value:_selectProperty, configurable:false})
Object.defineProperty(globalThis, 'not', {value:_not, configurable:false})
Object.defineProperty(globalThis, 'effect', {value:_effect, configurable:false})
Object.defineProperty(globalThis, 'observe', {value:Ref.observe.bind(Ref), configurable:false})
Object.defineProperty(globalThis, 'observeAndInit', {value:Ref.observeAndInit.bind(Ref), configurable:false})
Object.defineProperty(globalThis, 'unobserve', {value:Ref.unobserve.bind(Ref), configurable:false})
Object.defineProperty(globalThis, 'isolate', {value:Ref.disableCapturing.bind(Ref), configurable:false})
Object.defineProperty(globalThis, 'observe', {value:ReactiveValue.observe.bind(ReactiveValue), configurable:false})
Object.defineProperty(globalThis, 'observeAndInit', {value:ReactiveValue.observeAndInit.bind(ReactiveValue), configurable:false})
Object.defineProperty(globalThis, 'unobserve', {value:ReactiveValue.unobserve.bind(ReactiveValue), configurable:false})
Object.defineProperty(globalThis, 'isolate', {value:ReactiveValue.disableCapturing.bind(ReactiveValue), configurable:false})

Object.defineProperty(globalThis, 'grantAccess', {value:grantAccess, configurable:false})
Object.defineProperty(globalThis, 'grantPublicAccess', {value:grantPublicAccess, configurable:false})
Expand Down
Loading

0 comments on commit 8e8d8b2

Please sign in to comment.