Skip to content

Commit

Permalink
Fix display of value node assignments
Browse files Browse the repository at this point in the history
  • Loading branch information
slietar committed Jun 26, 2023
1 parent a89529d commit cbbf55b
Show file tree
Hide file tree
Showing 19 changed files with 147 additions and 68 deletions.
4 changes: 2 additions & 2 deletions client/src/components/block-inspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ export function BlockInspector(props: {

let blockAnalysis = analyzeBlockPath(props.protocol, props.location, props.mark, props.blockPath, globalContext);

console.log(props.mark);
console.log(blockAnalysis);
// console.log(props.mark);
// console.log(blockAnalysis);

let ancestorGroups = blockAnalysis.groups.slice(0, -1);
let leafGroup = blockAnalysis.groups.at(-1)!;
Expand Down
16 changes: 9 additions & 7 deletions client/src/process.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const computeGraph: ProtocolBlockGraphRenderer<ProtocolBlock, ProcessLocation<un
element: (
<GraphNode
activity={location
? (location.mode.type !== 'running')
? (location.mode.type !== 'running') || (location.mode.form === 'paused')
? 'paused'
: 'active'
: 'default'}
Expand Down Expand Up @@ -93,7 +93,6 @@ export interface ProcessBlock<Data> extends ProtocolBlock {

export interface ProcessLocation<Location> extends MasterBlockLocation {
children: {};
date: number;
mode: {
type: 'collecting';
} | {
Expand All @@ -106,7 +105,10 @@ export interface ProcessLocation<Location> extends MasterBlockLocation {
} | {
type: 'running';
pausable: boolean;
processLocation: Location | null;
processInfo: {
date: number;
location: Location;
} | null;
form: 'halting' | 'jumping' | 'normal' | 'paused' | 'pausing';
};
}
Expand Down Expand Up @@ -149,13 +151,13 @@ export function createProcessBlockImpl<Data, Location>(options: {

let Component = options.Component;

if (Component && (mode.type === 'running') && mode.processLocation) {
if (Component && (mode.type === 'running') && mode.processInfo) {
return (
<Component
data={props.block.data}
date={props.location.date}
date={mode.processInfo.date}
context={props.context}
location={mode.processLocation}
location={mode.processInfo.location}
status={(mode.form === 'paused') ? 'paused' : 'normal'} />
);
}
Expand Down Expand Up @@ -197,7 +199,7 @@ export function createProcessBlockImpl<Data, Location>(options: {
},
createFeatures(block, location) {
let processLocation = (location?.mode.type === 'running')
? location.mode.processLocation
? location.mode.processInfo?.location ?? null
: null;

return options.createFeatures?.(block.data, processLocation) ?? [
Expand Down
2 changes: 1 addition & 1 deletion client/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function getCommonBlockPathLength(a: ProtocolBlockPath, b: ProtocolBlockP
return index;
}

export function getRefPaths(block: ProtocolBlock, location: unknown, context: GlobalContext): ProtocolBlockPath[] {
export function getRefPaths(block: ProtocolBlock, location: MasterBlockLocation, context: GlobalContext): ProtocolBlockPath[] {
let blockImpl = getBlockImpl(block, context);
let children = blockImpl.getChildren?.(block, context);

Expand Down
2 changes: 2 additions & 0 deletions host/pr1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from .langservice import *
from .master.analysis import *
from .plugin.manager import *
from .procedure import *
from .rich_text import *
from .staticanalysis.expr import *
from .staticanalysis.expression import *
from .staticanalysis.support import *
Expand Down
2 changes: 1 addition & 1 deletion host/pr1/devices/nodes/value.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def export(self):
"writable": self.writable
}

def export_value(self, value: Optional[T | NullType], /):
def export_value(self, value: Optional[T | NullType], /) -> object:
match value:
case None:
return None
Expand Down
6 changes: 3 additions & 3 deletions host/pr1/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .document import Document

if TYPE_CHECKING:
from .fiber.parser import FiberProtocol
from .fiber.parser import FiberProtocol, GlobalContext
from .input import LanguageServiceAnalysis
from .host import Host

Expand Down Expand Up @@ -64,7 +64,7 @@ class DraftCompilation:
draft_id: str
protocol: 'Optional[FiberProtocol]'

def export(self):
def export(self, context: 'GlobalContext'):
return {
"analysis": {
"completions": [completion.export() for completion in self.analysis.completions],
Expand All @@ -79,6 +79,6 @@ def export(self):
"warnings": [warning.export() for warning in self.analysis.warnings]
},
"missingDocumentPaths": [], # str(path).split("/") for path in self.document_paths],
"protocol": self.protocol and self.protocol.export(),
"protocol": self.protocol and self.protocol.export(context),
"valid": (not self.analysis.errors)
}
20 changes: 19 additions & 1 deletion host/pr1/fiber/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from dataclasses import KW_ONLY, dataclass
from enum import Enum
from types import EllipsisType, NoneType
from typing import Any, Generic, Literal, TypeVar, cast, overload
from typing import Any, Callable, Generic, Literal, TypeVar, cast, overload

from quantops import Quantity

Expand Down Expand Up @@ -238,6 +238,24 @@ def eval(self, context: EvalContext, *, final: bool):
def export(self):
raise NotImplementedError

def export_inner(self, export_inner_value: Callable[[Any], Any], /):
from ..input import EvaluableChain
from ..input.dynamic import EvaluableDynamicValue

match self:
case EvaluableConstantValue(inner_value):
return {
"type": "constant",
"innerValue": export_inner_value(inner_value.value)
}
case EvaluablePythonExpr(contents) | EvaluableChain(EvaluablePythonExpr(contents)) | EvaluableDynamicValue(EvaluablePythonExpr(contents)):
return {
"type": "expression",
"contents": contents.value
}
case _:
raise ValueError


@dataclass
class PythonExprObject:
Expand Down
22 changes: 14 additions & 8 deletions host/pr1/fiber/master2.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from asyncio import Task
import math
from random import random
import time
from uuid import uuid4
Expand All @@ -8,7 +7,6 @@
from dataclasses import dataclass, field
from os import PathLike
from pathlib import Path
from pprint import pprint
from traceback import StackSummary
from typing import IO, TYPE_CHECKING, Any, Optional, Self
import asyncio
Expand All @@ -21,14 +19,14 @@
from ..util.asyncio import wait_all
from ..host import logger
from ..util.decorators import provide_logger
from ..history import TreeAdditionChange, BaseTreeChange, TreeChange, TreeRemovalChange, TreeUpdateChange
from ..history import TreeAdditionChange, TreeChange, TreeRemovalChange, TreeUpdateChange
from ..util.pool import Pool
from ..util.types import SimpleCallbackFunction
from ..util.misc import Exportable, HierarchyNode, IndexCounter
from ..master.analysis import MasterAnalysis, RuntimeAnalysis, RuntimeMasterAnalysisItem
from ..master.analysis import MasterAnalysis, RuntimeAnalysis
from .process import ProgramExecEvent
from .eval import EvalContext, EvalStack
from .parser import BaseBlock, BaseProgramPoint, BaseProgram, FiberProtocol, HeadProgram
from .parser import BaseBlock, BaseProgramPoint, BaseProgram, GlobalContext, HeadProgram
from ..experiment import Experiment
from ..ureg import ureg

Expand Down Expand Up @@ -59,6 +57,7 @@ def __init__(self, compilation: DraftCompilation, /, experiment: Experiment, *,
self._entry_counter = IndexCounter(start=1)
self._events = list[ProgramExecEvent]()
self._file: IO[bytes]
self._location: Any
self._logger: Logger
self._next_analysis_item_id = 0
self._owner: ProgramOwner
Expand Down Expand Up @@ -155,6 +154,8 @@ async def func():
self.experiment.save()

def receive(self, exec_path: list[int], message: Any):
self._logger.critical(f"Received {message!r}")

current_handle = self._handle

for exec_key in exec_path:
Expand All @@ -166,16 +167,16 @@ def study_block(self, block: BaseBlock):
return self._owner.study_block(block)


def export(self):
def export(self) -> object:
if not self._root_entry:
return None

return {
"id": self.id,
"initialAnalysis": self._initial_analysis.export(),
"location": self._root_entry.export(),
"location": self._location,
"masterAnalysis": self._master_analysis.export(),
"protocol": self.protocol.export(),
"protocol": self.protocol.export(GlobalContext(self.host)),
"startDate": (self.start_time * 1000)
}

Expand Down Expand Up @@ -268,7 +269,12 @@ def update_handle(handle: ProgramHandle, parent_entry: Optional[ProgramHandleEnt
update_handle(self._handle)
self._master_analysis += analysis

self._logger.debug(f"Update: {user_significant}")

if self._update_callback and user_significant:
assert self._root_entry
self._location = self._root_entry.export()

self._update_callback()

event = ExperimentReportEvent(
Expand Down
12 changes: 8 additions & 4 deletions host/pr1/fiber/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ def stable(self):
class BaseProgramPoint(ExportableABC):
pass

@dataclass(frozen=True, slots=True)
class GlobalContext:
host: 'Host'

class BaseBlock(ABC, HierarchyNode):
def duration(self):
return DurationTerm.unknown()
Expand All @@ -208,7 +212,7 @@ def import_point(self, data: Any, /) -> BaseProgramPoint:
...

@abstractmethod
def export(self):
def export(self, context: GlobalContext) -> object:
...

# @deprecated
Expand Down Expand Up @@ -481,18 +485,18 @@ def update(self, **kwargs):


@dataclass(kw_only=True)
class FiberProtocol(Exportable):
class FiberProtocol: # (Exportable):
details: ProtocolDetails
draft: Draft
global_symbol: EvalSymbol
name: Optional[str]
root: BaseBlock

def export(self):
def export(self, context: GlobalContext) -> object:
return {
"draft": self.draft.export(),
"name": self.name,
"root": self.root.export()
"root": self.root.export(context)
}


Expand Down
12 changes: 10 additions & 2 deletions host/pr1/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .draft import Draft, DraftCompilation
from .experiment import Experiment, ExperimentId
from .fiber.master2 import Master
from .fiber.parser import AnalysisContext
from .fiber.parser import AnalysisContext, GlobalContext
from .input import (Attribute, BoolType, KVDictType, PrimitiveType, RecordType,
StrType, UnionType)
from .langservice import LanguageServiceAnalysis
Expand Down Expand Up @@ -52,6 +52,14 @@ def find(self, path: NodePath) -> Optional[BaseNode]:

return node

# def find_unchecked(self, path: NodePath) -> BaseNode:
# node = self.find(path)

# if not node:
# raise ValueError(f"Node with path {path!r} not found")

# return node


class PluginConf(Protocol):
development: bool
Expand Down Expand Up @@ -305,7 +313,7 @@ async def process_request(self, request, *, agent) -> Any:
study = None

return {
**compilation.export(),
**compilation.export(GlobalContext(self)),
"study": study and {
"mark": study[1].export(),
"point": study[0].export()
Expand Down
18 changes: 10 additions & 8 deletions host/pr1/procedure.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def create_program(self, handle):
def import_point(self, data, /):
return self._process.import_point(data)

def export(self):
def export(self, context):
return {
"name": self._process.name,
"namespace": self._process.namespace,
Expand Down Expand Up @@ -168,7 +168,7 @@ def send_warning(self, warning: Diagnostic, /):
self._program._handle.send_analysis(RuntimeAnalysis(warnings=[warning]))

def send_location(self, location: T_ProcessLocation, /):
self._mode.process_location = location
self._mode.process_info = (time.time(), location)
self._program._send_location()


Expand Down Expand Up @@ -309,30 +309,33 @@ def export(self):
@dataclass(slots=True)
class Running:
form: ProcessProgramForm.Any
process_location: Optional[Exportable]
process_info: Optional[tuple[float, Exportable]]
pausable: bool
task: Task[None] = field(repr=False)
term: Term

def location(self):
return ProcessProgramMode.RunningLocation(
form=self.form.location,
process_location=self.process_location,
process_info=self.process_info,
pausable=self.pausable
)

@comserde.serializable
@dataclass(frozen=True, slots=True)
class RunningLocation:
form: ProcessProgramFormLocation
process_location: Optional[Exportable]
process_info: Optional[tuple[float, Exportable]]
pausable: bool

def export(self):
return {
"type": "running",
"form": self.form.export(),
"processLocation": self.process_location and self.process_location.export(),
"processInfo": self.process_info and {
"date": (self.process_info[0] * 1000),
"location": self.process_info[1].export()
},
"pausable": self.pausable
}

Expand All @@ -347,7 +350,6 @@ class ProcessProgramLocation:

def export(self):
return {
"date": time.time() * 1000,
"mode": self.mode.export()
}

Expand Down Expand Up @@ -489,7 +491,7 @@ async def run(self, point: Optional[ProcessProgramPoint], stack):

self._mode = ProcessProgramMode.Running(
form=ProcessProgramForm.Normal(),
process_location=None,
process_info=None,
pausable=False,
task=asyncio.create_task(self._block._process(self._context)),
term=DurationTerm.unknown()
Expand Down
2 changes: 1 addition & 1 deletion host/pr1/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ class StackEntry:
class DuplicateKeyError(ReaderError):
def __init__(self, original: LocatedString, duplicate: LocatedString, /):
super().__init__(
"Invalid value, expected expression",
"Duplicate key",
references=[
DiagnosticDocumentReference.from_value(original, id='origin'),
DiagnosticDocumentReference.from_value(duplicate, id='duplicate')
Expand Down
Loading

0 comments on commit cbbf55b

Please sign in to comment.