stevedlawrence commented on a change in pull request #651: URL: https://github.com/apache/daffodil/pull/651#discussion_r725165734
########## File path: daffodil-runtime1-layers/src/main/resources/META-INF/LICENSE ########## @@ -0,0 +1,284 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +APACHE DAFFODIL SUBCOMPONENTS: + +The Apache Daffodil project contains subcomponents with separate copyright +notices and license terms. Your use of the source code for these subcomponents +is subject to the terms and conditions of the following licenses. + + Review comment: This mentions passera and XML schema files as subcomponents, but they aren't subcomponents of this runtime1-layers jar. I think this whole subcomponents thing can just be dropped, similar to the LICENSE file for the runtime1-unparser. ########## File path: daffodil-core/src/main/scala/org/apache/daffodil/dsom/SequenceGroup.scala ########## @@ -216,29 +214,23 @@ abstract class SequenceGroupTermBase( private val layeredSequenceAllowedProps = Set("ref", "layerTransform", "layerEncoding", "layerLengthKind", "layerLength", "layerLengthUnits", "layerBoundaryMark") - final lazy val maybeLayerTransformerEv: Maybe[LayerTransformerEv] = { - if (maybeLayerTransformEv.isEmpty) Maybe.Nope - else { // need to check that only layering properties are specified - val localProps = this.formatAnnotation.justThisOneProperties - val localKeys = localProps.keySet - val disallowedKeys = localKeys.filterNot(k => layeredSequenceAllowedProps.contains(k)) - if (disallowedKeys.size > 0) - SDE("Sequence has dfdlx:layerTransform specified, so cannot have non-layering properties: %s", disallowedKeys.mkString(", ")) - - val lt = new LayerTransformerEv( - maybeLayerTransformEv.get, - maybeLayerCharsetEv, - Maybe.toMaybe(optionLayerLengthKind), - maybeLayerLengthEv, - Maybe.toMaybe(optionLayerLengthUnits), - maybeLayerBoundaryMarkEv, - sequenceRuntimeData) - lt.compile(tunable) - Maybe.One(lt) + private lazy val optionLayerTransform = findPropertyOption("layerTransform").toOption + + final lazy val optLayerCompiler: Option[LayerCompiler] = { Review comment: Should we make this not an `Option`? This should only be called if `optionLayerTransform` is defined, and if it's defined then we must have a `LayerCompiler`, or else it's an SDE. Maybe just add an `Assert.invariant(optLayerCompiler.isDefined)` and then use `.get` instead of `.map` below? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompilerRegistry.scala ########## @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + + +import org.apache.daffodil.exceptions.ThrowsSDE + +import java.util.ServiceLoader +import scala.collection.JavaConverters.asScalaIteratorConverter +import scala.collection.mutable + +/** + * Transformers have factories. This lets you find the transformer factory + * by the name obtained from dfdlx:layerTransform. + */ +object LayerCompilerRegistry { + + private lazy val fromClassPath: Map[String, LayerCompiler] = + ServiceLoader + .load(classOf[LayerCompiler]) + .iterator() + .asScala + .map(v => v.name -> v) + .toMap + + // TBD: what if there are multiple such on the classpath with the same name? + + private lazy val layerCompilerMap = { + val map = new mutable.HashMap[String, LayerCompiler] + map ++= fromClassPath + map + } + +// def register(layerCompiler: LayerCompiler): Unit = { +// layerCompilerMap.get(layerCompiler.name) match { +// case Some(lc) => +// if (Misc.getNameFromClass(lc) == Misc.getNameFromClass(layerCompiler)) { +// // ok. Already registered same class. +// } else { +// // Attempt to re-register a new different transform using the same name. +// Assert.usageError(s"A layer compiler for name ${lc.name} of class ${Misc.getNameFromClass(lc)} is already registered.") +// } +// case None => +// layerCompilerMap.put(layerCompiler.name, layerCompiler) +// } +// } + + /** + * Given name, finds the factory for the transformer. SDE otherwise. + * + * The state is passed in order to provide diagnostic context if not found. + */ + def find(name: String, context: ThrowsSDE): LayerCompiler = { + val maybeCompiler: Option[LayerCompiler] = layerCompilerMap.get(name) + if (maybeCompiler.isEmpty) { + // + // TODO: Daffodil-2567 + // This is where we would try to dynamically load a layer transform compiler + // for the given layer name. + // Review comment: Remove comment? I think this dynamic loading is all implemented now. ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompilerRegistry.scala ########## @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + + +import org.apache.daffodil.exceptions.ThrowsSDE + +import java.util.ServiceLoader +import scala.collection.JavaConverters.asScalaIteratorConverter +import scala.collection.mutable + +/** + * Transformers have factories. This lets you find the transformer factory + * by the name obtained from dfdlx:layerTransform. + */ +object LayerCompilerRegistry { + + private lazy val fromClassPath: Map[String, LayerCompiler] = + ServiceLoader + .load(classOf[LayerCompiler]) + .iterator() + .asScala + .map(v => v.name -> v) + .toMap + + // TBD: what if there are multiple such on the classpath with the same name? Review comment: Maybe we should detect an log a warning? I think .toMap will silently drop preceeding duplicates. ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -271,15 +212,227 @@ class JavaIOOutputStream(dos: DataOutputStream, finfo: FormatInfo) } abstract class LayerException( - layerSRD: SequenceRuntimeData, - state: PState, + val schemaFileLocation: SchemaFileLocation, + dataLocation: DataLocation, maybeCause: Maybe[Throwable], maybeFormatString: Maybe[String], args: Any*) -extends ThinDiagnostic(One(layerSRD.dpathCompileInfo.schemaFileLocation), One(state.currentLocation), maybeCause, maybeFormatString, args: _*) +extends ThinDiagnostic(One(schemaFileLocation), One(dataLocation), maybeCause, maybeFormatString, args: _*) -case class LayerNotEnoughDataException(layerSRD: SequenceRuntimeData, state: PState, cause: Throwable, nBytesRequired: Int) - extends LayerException(layerSRD, state, One(cause), None, nBytesRequired) { +case class LayerNotEnoughDataException(sfl: SchemaFileLocation, dataLocation: DataLocation, cause: Throwable, nBytesRequired: Int) + extends LayerException(sfl, dataLocation, One(cause), None, nBytesRequired) { override def isError = true override def modeName = "Parse" - } \ No newline at end of file + } + +final class LayerSerializedInfo(val srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +extends Serializable { + + def evaluatables: Seq[Evaluatable[AnyRef]] = + maybeLayerCharsetEv.toScalaOption.toSeq ++ + maybeLayerLengthEv.toScalaOption.toSeq ++ + maybeLayerBoundaryMarkEv.toScalaOption.toSeq + + + def layerRuntimeInfo(state: ParseOrUnparseState): LayerRuntimeInfo = + new LayerRuntimeInfo(state, srd, + maybeLayerCharsetEv, + maybeLayerLengthKind, + maybeLayerLengthEv, + maybeLayerLengthUnits, + maybeLayerBoundaryMarkEv) +} + +/** + * Allows access to all the layer properties, if defined, including + * evaluating expressions if the properties values are defined as expressions. + * Also provides access to variables. + */ + +final class LayerRuntimeInfo(state: ParseOrUnparseState, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +{ + + def SDE(msg: String, args: Any*) = + state.SDE(msg, args) + + /** + * Only needed because unparser suspensions need one, and it is used in too many places + * @return + */ + def runtimeData: RuntimeData = srd + + def optLayerCharset: Option[Charset] = maybeLayerCharsetEv.toScalaOption.map { + _.evaluate(state) + } match { + case Some(bitsCharsetJava: BitsCharsetJava) => Some(bitsCharsetJava.javaCharset) + case None => None + case Some(other) => None // only java charsets are supported. + } + + def optLayerLengthKind: Option[LayerLengthKind] = maybeLayerLengthKind.toScalaOption + + def optLayerLength: Option[Long] = maybeLayerLengthEv.toScalaOption.map{ _.evaluate(state) } + + def optLayerLengthUnits: Option[LayerLengthUnits] = maybeLayerLengthUnits.toScalaOption + + def optLayerBoundaryMark: Option[String] = maybeLayerBoundaryMarkEv.toScalaOption.map{ _.evaluate(state) } + + def getVariable(vrd: VariableRuntimeData): DataValuePrimitive = state.getVariable(vrd, srd) + + def setVariable(vrd: VariableRuntimeData, value: DataValuePrimitive) = + state.setVariable(vrd, value, srd) + + def schemaFileLocation = srd.schemaFileLocation +} + + +abstract class ByteBufferExplicitLengthLayerTransform[T]( + layerInfoArg: LayerRuntimeInfo, + layerName: String, + inputVRDs: Seq[VariableRuntimeData], + outputVRD: VariableRuntimeData) + extends LayerTransformer(layerName, layerInfoArg) { + + val layerRuntimeInfo = layerInfoArg.asInstanceOf[LayerRuntimeInfo] Review comment: Can this be removed and rename layerInfoArg to layerRuntimeInfo? The asInstanceOf no longer does anything. ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -271,15 +212,227 @@ class JavaIOOutputStream(dos: DataOutputStream, finfo: FormatInfo) } abstract class LayerException( - layerSRD: SequenceRuntimeData, - state: PState, + val schemaFileLocation: SchemaFileLocation, + dataLocation: DataLocation, maybeCause: Maybe[Throwable], maybeFormatString: Maybe[String], args: Any*) -extends ThinDiagnostic(One(layerSRD.dpathCompileInfo.schemaFileLocation), One(state.currentLocation), maybeCause, maybeFormatString, args: _*) +extends ThinDiagnostic(One(schemaFileLocation), One(dataLocation), maybeCause, maybeFormatString, args: _*) -case class LayerNotEnoughDataException(layerSRD: SequenceRuntimeData, state: PState, cause: Throwable, nBytesRequired: Int) - extends LayerException(layerSRD, state, One(cause), None, nBytesRequired) { +case class LayerNotEnoughDataException(sfl: SchemaFileLocation, dataLocation: DataLocation, cause: Throwable, nBytesRequired: Int) + extends LayerException(sfl, dataLocation, One(cause), None, nBytesRequired) { override def isError = true override def modeName = "Parse" - } \ No newline at end of file + } + +final class LayerSerializedInfo(val srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +extends Serializable { + + def evaluatables: Seq[Evaluatable[AnyRef]] = + maybeLayerCharsetEv.toScalaOption.toSeq ++ + maybeLayerLengthEv.toScalaOption.toSeq ++ + maybeLayerBoundaryMarkEv.toScalaOption.toSeq + + + def layerRuntimeInfo(state: ParseOrUnparseState): LayerRuntimeInfo = + new LayerRuntimeInfo(state, srd, + maybeLayerCharsetEv, + maybeLayerLengthKind, + maybeLayerLengthEv, + maybeLayerLengthUnits, + maybeLayerBoundaryMarkEv) +} + +/** + * Allows access to all the layer properties, if defined, including + * evaluating expressions if the properties values are defined as expressions. + * Also provides access to variables. + */ + +final class LayerRuntimeInfo(state: ParseOrUnparseState, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +{ + + def SDE(msg: String, args: Any*) = + state.SDE(msg, args) + + /** + * Only needed because unparser suspensions need one, and it is used in too many places + * @return + */ + def runtimeData: RuntimeData = srd + + def optLayerCharset: Option[Charset] = maybeLayerCharsetEv.toScalaOption.map { + _.evaluate(state) + } match { + case Some(bitsCharsetJava: BitsCharsetJava) => Some(bitsCharsetJava.javaCharset) + case None => None + case Some(other) => None // only java charsets are supported. + } + + def optLayerLengthKind: Option[LayerLengthKind] = maybeLayerLengthKind.toScalaOption + + def optLayerLength: Option[Long] = maybeLayerLengthEv.toScalaOption.map{ _.evaluate(state) } + + def optLayerLengthUnits: Option[LayerLengthUnits] = maybeLayerLengthUnits.toScalaOption + + def optLayerBoundaryMark: Option[String] = maybeLayerBoundaryMarkEv.toScalaOption.map{ _.evaluate(state) } + + def getVariable(vrd: VariableRuntimeData): DataValuePrimitive = state.getVariable(vrd, srd) + + def setVariable(vrd: VariableRuntimeData, value: DataValuePrimitive) = + state.setVariable(vrd, value, srd) + Review comment: Mentioned elsewhere, but suggest change get/setVariable to not require VariableRuntimeData but to just work on namespace/localNae strings? ########## File path: build.sbt ########## @@ -58,7 +58,11 @@ lazy val runtime1 = Project("daffodil-runtime1", file("daffodil-runtime1 .settings(commonSettings, usesMacros) lazy val runtime1Unparser = Project("daffodil-runtime1-unparser", file("daffodil-runtime1-unparser")).configs(IntegrationTest) - .dependsOn(runtime1, lib % "test->test", runtime1 % "test->test") + .dependsOn(runtime1, lib % "test->test", runtime1 % "test->test", runtime1Layers) + .settings(commonSettings) + +lazy val runtime1Layers = Project("daffodil-runtime1-layers", file("daffodil-runtime1-layers")).configs(IntegrationTest) + .dependsOn(runtime1, lib % "test->test", runtime1) Review comment: runtime1 is listed twice here ########## File path: daffodil-runtime1-layers/src/main/resources/META-INF/NOTICE ########## @@ -0,0 +1,26 @@ +Apache Daffodil +Copyright 2021 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +Based on source code originally developed by +- The Univerisity of Illinois National Center for Supercomputing Applications (http://www.ncsa.illinois.edu/) +- Tresys Technology (http://www.tresys.com/) +- International Business Machines Corporation (http://www.ibm.com) + +The following NOTICE information applies to components distributed with this project: Review comment: Same here, this is the NOTICE file that goes in the jar, which does not contain these derived works. This can be dropped, same notice can be used from runtime1-unparser. ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompilerRegistry.scala ########## @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + + +import org.apache.daffodil.exceptions.ThrowsSDE + +import java.util.ServiceLoader +import scala.collection.JavaConverters.asScalaIteratorConverter +import scala.collection.mutable + +/** + * Transformers have factories. This lets you find the transformer factory + * by the name obtained from dfdlx:layerTransform. + */ +object LayerCompilerRegistry { + + private lazy val fromClassPath: Map[String, LayerCompiler] = + ServiceLoader + .load(classOf[LayerCompiler]) + .iterator() + .asScala + .map(v => v.name -> v) + .toMap Review comment: I know that it's possible for `iterator.next()` to throw an exception if something went wrong loader a service. We might want to do what UDF loading does, where if one thing fails then it just logs it, ignores it, and moves on. If that layer is never used, then it doesn't matter. Something like this might do? ```scala val iter = loader.iterator() while (iter.hasNext()) { val compilerOpt = try { Some(iter.next()) } catch { case e: ServiceConfigurationError => { Logger.log.warn("Compiler failed to load, ignoring: ${e.getMessage}") None } } // append comilerOpt to map if defined, detect duplicates and warn, etc. } ``` ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompilerRegistry.scala ########## @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + + +import org.apache.daffodil.exceptions.ThrowsSDE + +import java.util.ServiceLoader +import scala.collection.JavaConverters.asScalaIteratorConverter +import scala.collection.mutable + +/** + * Transformers have factories. This lets you find the transformer factory + * by the name obtained from dfdlx:layerTransform. + */ +object LayerCompilerRegistry { + + private lazy val fromClassPath: Map[String, LayerCompiler] = + ServiceLoader + .load(classOf[LayerCompiler]) + .iterator() + .asScala + .map(v => v.name -> v) + .toMap + + // TBD: what if there are multiple such on the classpath with the same name? + + private lazy val layerCompilerMap = { + val map = new mutable.HashMap[String, LayerCompiler] + map ++= fromClassPath + map + } + +// def register(layerCompiler: LayerCompiler): Unit = { +// layerCompilerMap.get(layerCompiler.name) match { +// case Some(lc) => +// if (Misc.getNameFromClass(lc) == Misc.getNameFromClass(layerCompiler)) { +// // ok. Already registered same class. +// } else { +// // Attempt to re-register a new different transform using the same name. +// Assert.usageError(s"A layer compiler for name ${lc.name} of class ${Misc.getNameFromClass(lc)} is already registered.") +// } +// case None => +// layerCompilerMap.put(layerCompiler.name, layerCompiler) +// } +// } Review comment: Remove commented code ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompiler.scala ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + +import org.apache.daffodil.api.WarnID +import org.apache.daffodil.dpath.NodeInfo.PrimType +import org.apache.daffodil.dsom.ImplementsThrowsOrSavesSDE +import org.apache.daffodil.processors.LayerBoundaryMarkEv +import org.apache.daffodil.processors.LayerCharsetEv +import org.apache.daffodil.processors.LayerLengthEv +import org.apache.daffodil.processors.SequenceRuntimeData +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.processors.charset.BitsCharsetJava +import org.apache.daffodil.processors.charset.BitsCharsetNonByteSize +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthKind +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthUnits +import org.apache.daffodil.util.Maybe +import org.apache.daffodil.xml.NS +import org.apache.daffodil.xml.RefQName + +/** + * Must be implemented by all layers. + * + * These are the classes which must be dynamically loaded in order to add a layer implementation + * to Daffodil. + * + * These instances are NOT serialized as part of a saved processor. The compileLayer method + * is called and the resulting LayerTransformerFactory is the serialized object. + */ +abstract class LayerCompiler(val name: String) { + + /** + * Performs all schema-compile-time checking for the layer parameters, and constructs + * a LayerTransfomrmerFactory which is the serialized runtime object that becomes part of the + * processor. + * @param layerCompileInfo Schema-compilation time information about the layer properties. + * @return + */ + def compileLayer(layerCompileInfo: LayerCompileInfo): LayerTransformerFactory + +} + + +/** + * Provides access to DFDL schema compile-time information about the layer properties. + * + * Allows reporting of schema definition errors and warnings at schema compile time. + */ +final class LayerCompileInfo(sequence: ImplementsThrowsOrSavesSDE, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) { Review comment: Should these all be private so external layers must use the helper functions which hide some of the implementation details? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompiler.scala ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + +import org.apache.daffodil.api.WarnID +import org.apache.daffodil.dpath.NodeInfo.PrimType +import org.apache.daffodil.dsom.ImplementsThrowsOrSavesSDE +import org.apache.daffodil.processors.LayerBoundaryMarkEv +import org.apache.daffodil.processors.LayerCharsetEv +import org.apache.daffodil.processors.LayerLengthEv +import org.apache.daffodil.processors.SequenceRuntimeData +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.processors.charset.BitsCharsetJava +import org.apache.daffodil.processors.charset.BitsCharsetNonByteSize +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthKind +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthUnits +import org.apache.daffodil.util.Maybe +import org.apache.daffodil.xml.NS +import org.apache.daffodil.xml.RefQName + +/** + * Must be implemented by all layers. + * + * These are the classes which must be dynamically loaded in order to add a layer implementation + * to Daffodil. + * + * These instances are NOT serialized as part of a saved processor. The compileLayer method + * is called and the resulting LayerTransformerFactory is the serialized object. + */ +abstract class LayerCompiler(val name: String) { + + /** + * Performs all schema-compile-time checking for the layer parameters, and constructs + * a LayerTransfomrmerFactory which is the serialized runtime object that becomes part of the + * processor. + * @param layerCompileInfo Schema-compilation time information about the layer properties. + * @return + */ + def compileLayer(layerCompileInfo: LayerCompileInfo): LayerTransformerFactory + +} + + +/** + * Provides access to DFDL schema compile-time information about the layer properties. + * + * Allows reporting of schema definition errors and warnings at schema compile time. + */ +final class LayerCompileInfo(sequence: ImplementsThrowsOrSavesSDE, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) { + + def getVRD(prefix: String, namespace: String, localName: String, primType: PrimType) : VariableRuntimeData = { Review comment: This gives layers access to the internal `VariableRuntimeData` class. Is this something we want to allow? Would it be possible instead for layers to only deal with variable namespace/localName as Strings. It could pass those strings to get/setVariable, and then those functions lookup the VRD at runtime? And maybe `getVRD` is renamed something like `checkVariableExists`, which does the SDE checks as it does now to make sure the variables exist at compile time with the right types, but doesn't actually return the VRD? Maybe a small performance hit by looking up the VRD at runtime, but that's probably pretty minimal? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompiler.scala ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + +import org.apache.daffodil.api.WarnID +import org.apache.daffodil.dpath.NodeInfo.PrimType +import org.apache.daffodil.dsom.ImplementsThrowsOrSavesSDE +import org.apache.daffodil.processors.LayerBoundaryMarkEv +import org.apache.daffodil.processors.LayerCharsetEv +import org.apache.daffodil.processors.LayerLengthEv +import org.apache.daffodil.processors.SequenceRuntimeData +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.processors.charset.BitsCharsetJava +import org.apache.daffodil.processors.charset.BitsCharsetNonByteSize +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthKind +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthUnits +import org.apache.daffodil.util.Maybe +import org.apache.daffodil.xml.NS +import org.apache.daffodil.xml.RefQName + +/** + * Must be implemented by all layers. + * + * These are the classes which must be dynamically loaded in order to add a layer implementation + * to Daffodil. + * + * These instances are NOT serialized as part of a saved processor. The compileLayer method + * is called and the resulting LayerTransformerFactory is the serialized object. + */ +abstract class LayerCompiler(val name: String) { + + /** + * Performs all schema-compile-time checking for the layer parameters, and constructs + * a LayerTransfomrmerFactory which is the serialized runtime object that becomes part of the + * processor. + * @param layerCompileInfo Schema-compilation time information about the layer properties. + * @return + */ + def compileLayer(layerCompileInfo: LayerCompileInfo): LayerTransformerFactory + +} + + +/** + * Provides access to DFDL schema compile-time information about the layer properties. + * + * Allows reporting of schema definition errors and warnings at schema compile time. + */ +final class LayerCompileInfo(sequence: ImplementsThrowsOrSavesSDE, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) { + + def getVRD(prefix: String, namespace: String, localName: String, primType: PrimType) : VariableRuntimeData = { + val varNamespace = NS(namespace) + val qName = RefQName(Some(prefix), localName, varNamespace).toGlobalQName + val vrd = srd.variableMap.getVariableRuntimeData(qName).getOrElse { + srd.SDE("Variable '%s' is not defined.", qName.toExtendedSyntax) + } + srd.schemaDefinitionUnless(vrd.primType == primType, + "Variable '%s' is not of type '%s'.", qName.toExtendedSyntax, primType) + vrd + } + + /** + * If defined, and the value is a compile-time constant then this will be Some(Some(Charset)) + * If defined, and the value is non-constant or not a regular JVM charset, then this will be Some(None) + * If undefined, the value is None + */ + def optLayerJavaCharsetOptConstantValue: Option[Option[java.nio.charset.Charset]] = { + if (maybeLayerCharsetEv.isEmpty) None + else + maybeLayerCharsetEv.get.optConstant.map { + case java: BitsCharsetJava => Some(java.javaCharset) + case _: BitsCharsetNonByteSize => None + } + } + + def optLayerLengthKind: Option[LayerLengthKind] = { + maybeLayerLengthKind.toScalaOption + } + + def optLayerLengthOptConstantValue: Option[Option[Long]] = { + if (maybeLayerLengthEv.isEmpty) None + else Some(maybeLayerLengthEv.get.optConstant.map { + _.toLong + }) + } + + def optLayerLengthUnits: Option[LayerLengthUnits] = { + maybeLayerLengthUnits.toScalaOption + } + + def optLayerBoundaryMarkOptConstantValue: Option[Option[String]] = { + if (maybeLayerBoundaryMarkEv.isEmpty) None + else Some(maybeLayerBoundaryMarkEv.get.optConstant) + } + + def schemaDefinitionError(message: String, args: Any*): Nothing = { + sequence.schemaDefinitionError(message, args: _*) + } + + def schemaDefinitionWarning(message: String, args: Any*): Unit = { + sequence.SDW(WarnID.LayerCompileWarning, message, args: _*) + } + + /** + * Constructs the LayerSerialziedInfo object, which is a serializable object that contains + * information about the layer parameters for use at runtime. + * @return + */ + def layerSerializedInfo: LayerSerializedInfo = Review comment: Is there a benefit to not allowing a user to create `LayerSerializedInfo`? They never need access to this right? They only need `LayerCompileInfo` and `LayerRuntimeInfo`? If anything, it makes the API a bit smaller and one less thing people have to think about. In `LayeredSequence.scala`, could we just directly create a `LayerSerializedInfo`, rather than getting it from the CompileInfo? In fact, I'm wondering if maybe the `LayerCompileInfo` wants to take a LayerSerializedInfo` as a parameter? The public functions in LayerCompileInfo could reach into the LayerSerializedInfo when needed. That might reduce duplication since the two are so similar?, e.g. ```scala case class LayeredSequence(...) { val layerSerializedInfo = new LayerSerializedInfo(...) val layerCompileInfo = new LayerCompileInfo(sq, layerSerializedInfo) ... } ``` ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerCompilerRegistry.scala ########## @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.daffodil.layers + + +import org.apache.daffodil.exceptions.ThrowsSDE + +import java.util.ServiceLoader +import scala.collection.JavaConverters.asScalaIteratorConverter +import scala.collection.mutable + +/** + * Transformers have factories. This lets you find the transformer factory + * by the name obtained from dfdlx:layerTransform. + */ +object LayerCompilerRegistry { + + private lazy val fromClassPath: Map[String, LayerCompiler] = + ServiceLoader + .load(classOf[LayerCompiler]) + .iterator() + .asScala + .map(v => v.name -> v) + .toMap + + // TBD: what if there are multiple such on the classpath with the same name? + + private lazy val layerCompilerMap = { + val map = new mutable.HashMap[String, LayerCompiler] + map ++= fromClassPath + map + } Review comment: Thoughts on moving the `fromClassPath` logic in here? Is this to just get a mutable HashMap? Do we even need it to be mutable? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -271,15 +212,227 @@ class JavaIOOutputStream(dos: DataOutputStream, finfo: FormatInfo) } abstract class LayerException( - layerSRD: SequenceRuntimeData, - state: PState, + val schemaFileLocation: SchemaFileLocation, + dataLocation: DataLocation, maybeCause: Maybe[Throwable], maybeFormatString: Maybe[String], args: Any*) -extends ThinDiagnostic(One(layerSRD.dpathCompileInfo.schemaFileLocation), One(state.currentLocation), maybeCause, maybeFormatString, args: _*) +extends ThinDiagnostic(One(schemaFileLocation), One(dataLocation), maybeCause, maybeFormatString, args: _*) -case class LayerNotEnoughDataException(layerSRD: SequenceRuntimeData, state: PState, cause: Throwable, nBytesRequired: Int) - extends LayerException(layerSRD, state, One(cause), None, nBytesRequired) { +case class LayerNotEnoughDataException(sfl: SchemaFileLocation, dataLocation: DataLocation, cause: Throwable, nBytesRequired: Int) + extends LayerException(sfl, dataLocation, One(cause), None, nBytesRequired) { override def isError = true override def modeName = "Parse" - } \ No newline at end of file + } + +final class LayerSerializedInfo(val srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +extends Serializable { + + def evaluatables: Seq[Evaluatable[AnyRef]] = + maybeLayerCharsetEv.toScalaOption.toSeq ++ + maybeLayerLengthEv.toScalaOption.toSeq ++ + maybeLayerBoundaryMarkEv.toScalaOption.toSeq + + + def layerRuntimeInfo(state: ParseOrUnparseState): LayerRuntimeInfo = + new LayerRuntimeInfo(state, srd, + maybeLayerCharsetEv, + maybeLayerLengthKind, + maybeLayerLengthEv, + maybeLayerLengthUnits, + maybeLayerBoundaryMarkEv) +} + +/** + * Allows access to all the layer properties, if defined, including + * evaluating expressions if the properties values are defined as expressions. + * Also provides access to variables. + */ + +final class LayerRuntimeInfo(state: ParseOrUnparseState, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) Review comment: Can these parameters be made private? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -271,15 +212,227 @@ class JavaIOOutputStream(dos: DataOutputStream, finfo: FormatInfo) } abstract class LayerException( - layerSRD: SequenceRuntimeData, - state: PState, + val schemaFileLocation: SchemaFileLocation, + dataLocation: DataLocation, maybeCause: Maybe[Throwable], maybeFormatString: Maybe[String], args: Any*) -extends ThinDiagnostic(One(layerSRD.dpathCompileInfo.schemaFileLocation), One(state.currentLocation), maybeCause, maybeFormatString, args: _*) +extends ThinDiagnostic(One(schemaFileLocation), One(dataLocation), maybeCause, maybeFormatString, args: _*) -case class LayerNotEnoughDataException(layerSRD: SequenceRuntimeData, state: PState, cause: Throwable, nBytesRequired: Int) - extends LayerException(layerSRD, state, One(cause), None, nBytesRequired) { +case class LayerNotEnoughDataException(sfl: SchemaFileLocation, dataLocation: DataLocation, cause: Throwable, nBytesRequired: Int) + extends LayerException(sfl, dataLocation, One(cause), None, nBytesRequired) { override def isError = true override def modeName = "Parse" - } \ No newline at end of file + } + +final class LayerSerializedInfo(val srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +extends Serializable { + + def evaluatables: Seq[Evaluatable[AnyRef]] = + maybeLayerCharsetEv.toScalaOption.toSeq ++ + maybeLayerLengthEv.toScalaOption.toSeq ++ + maybeLayerBoundaryMarkEv.toScalaOption.toSeq + + + def layerRuntimeInfo(state: ParseOrUnparseState): LayerRuntimeInfo = + new LayerRuntimeInfo(state, srd, + maybeLayerCharsetEv, + maybeLayerLengthKind, + maybeLayerLengthEv, + maybeLayerLengthUnits, + maybeLayerBoundaryMarkEv) +} + +/** + * Allows access to all the layer properties, if defined, including + * evaluating expressions if the properties values are defined as expressions. + * Also provides access to variables. + */ + +final class LayerRuntimeInfo(state: ParseOrUnparseState, + srd: SequenceRuntimeData, + maybeLayerCharsetEv: Maybe[LayerCharsetEv], + maybeLayerLengthKind: Maybe[LayerLengthKind], + maybeLayerLengthEv: Maybe[LayerLengthEv], + maybeLayerLengthUnits: Maybe[LayerLengthUnits], + maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv]) +{ + + def SDE(msg: String, args: Any*) = + state.SDE(msg, args) + + /** + * Only needed because unparser suspensions need one, and it is used in too many places + * @return + */ + def runtimeData: RuntimeData = srd Review comment: Would be nice if this weren't need, but I gues suspensions make that not possible as mentioned in the comment? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -162,9 +103,9 @@ abstract class LayerTransformer() { // nothing for now Review comment: Any chance this removeLayer function could be implemented and made final? Small concern that we don't want custom layers overriding this and having access to InputSourceDataInputStream ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -40,102 +42,41 @@ import org.apache.daffodil.schema.annotation.props.gen.BitOrder import org.apache.daffodil.processors.parsers.PState import org.apache.daffodil.processors.unparsers.UState import org.apache.daffodil.io.DirectOrBufferedDataOutputStream +import org.apache.daffodil.processors.Evaluatable +import org.apache.daffodil.processors.RuntimeData import passera.unsigned.ULong import org.apache.daffodil.processors.SequenceRuntimeData +import org.apache.daffodil.processors.SuspendableOperation +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.processors.charset.BitsCharsetJava +import org.apache.daffodil.util.ByteBufferOutputStream +import java.io.ByteArrayInputStream +import java.io.EOFException import java.io.InputStream import java.io.OutputStream - -/** - * Factory for a layer transformer. - * - * Responsible for digesting the various args, erroring if the wrong ones - * are specified, and ultimately constructing the LayerTransformer - * of the correct type with the parameters it needs. - */ -abstract class LayerTransformerFactory(nom: String) - extends Serializable { - - val name = nom.toUpperCase() - - def newInstance( - maybeLayerCharsetEv: Maybe[LayerCharsetEv], - maybeLayerLengthKind: Maybe[LayerLengthKind], - maybeLayerLengthEv: Maybe[LayerLengthEv], - maybeLayerLengthUnits: Maybe[LayerLengthUnits], - maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv], - srd: SequenceRuntimeData): LayerTransformer -} - -/** - * Transformers have factories. This lets you find the transformer factory - * by the name obtained from dfdlx:layerTransform. - */ -object LayerTransformerFactory { - - private lazy val transformerMap = new NonAllocatingMap(new HashMap[String, LayerTransformerFactory]) - - def register(factory: LayerTransformerFactory): Unit = { - transformerMap.put(factory.name, factory) - } - /** - * Given name, finds the factory for the transformer. SDE otherwise. - * - * The state is passed in order to provide diagnostic context if not found. - */ - def find(name: String, state: ParseOrUnparseState): LayerTransformerFactory = { - val maybeFactory = transformerMap.get(name) - if (maybeFactory.isEmpty) { - val choices = transformerMap.keySet.mkString(", ") - state.SDE("The dfdlx:layerTransform '%s' was not found. Available choices are: %s", name, choices) - } else { - maybeFactory.get - } - } - - /** - * All transformers must be registered so they are available by name. - * - * It is possible to package a transformer in a separate jar also, but then - * someone has to register it by calling the register method. - * - * Transformers built into the primary Daffodil jars/packages should be - * registered here. - */ - register(Base64MIMETransformerFactory) - register(GZIPTransformerFactory) - register(IMFLineFoldedTransformerFactory) - register(ICalendarLineFoldedTransformerFactory) - - /** - * Arguably the above could be bundled with Daffodil. - * - * The transformers below really should be plugins defined - * outside Daffodil, per DAFFODIL-1927. - */ - register(AISPayloadArmoringTransformerFactory) - register(FourByteSwapTransformerFactory) -} +import java.nio.ByteBuffer +import java.nio.charset.Charset /** * Shared functionality of all LayerTransformers. * * A layer transformer is created at runtime as part of a single parse/unparse call. * Hence, they can be stateful without causing thread-safety issues. */ -abstract class LayerTransformer() { +abstract class LayerTransformer(layerName: String, layerRuntimeInfo: LayerRuntimeInfo) { protected def wrapLayerDecoder(jis: InputStream): InputStream - protected def wrapLimitingStream(jis: InputStream, state: PState): InputStream + protected def wrapLimitingStream(jis: InputStream): InputStream def wrapJavaInputStream(s: InputSourceDataInputStream, fInfo: FormatInfo): InputStream = { new JavaIOInputStream(s, fInfo) } protected def wrapLayerEncoder(jos: OutputStream): OutputStream - protected def wrapLimitingStream(jis: OutputStream, state: UState): OutputStream + protected def wrapLimitingStream(jis: OutputStream): OutputStream def wrapJavaOutputStream(s: DataOutputStream, fInfo: FormatInfo): OutputStream = { Review comment: Same question as above, should this be final due to the `FormatInfo`? ########## File path: daffodil-test/src/test/resources/META-INF/services/org.apache.daffodil.layers.LayerCompiler ########## @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +org.apache.daffodil.layers.AISPayloadArmoringLayerCompiler +org.apache.daffodil.layers.CheckDigitLayerCompiler +org.apache.daffodil.layers.IPv4ChecksumLayerCompiler + Review comment: Why not put these in the src/main? Is the plan to eventually remove them from daffodil and they'll live in their respective repos? ########## File path: daffodil-runtime1/src/main/scala/org/apache/daffodil/layers/LayerTransformer.scala ########## @@ -40,102 +42,41 @@ import org.apache.daffodil.schema.annotation.props.gen.BitOrder import org.apache.daffodil.processors.parsers.PState import org.apache.daffodil.processors.unparsers.UState import org.apache.daffodil.io.DirectOrBufferedDataOutputStream +import org.apache.daffodil.processors.Evaluatable +import org.apache.daffodil.processors.RuntimeData import passera.unsigned.ULong import org.apache.daffodil.processors.SequenceRuntimeData +import org.apache.daffodil.processors.SuspendableOperation +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.processors.charset.BitsCharsetJava +import org.apache.daffodil.util.ByteBufferOutputStream +import java.io.ByteArrayInputStream +import java.io.EOFException import java.io.InputStream import java.io.OutputStream - -/** - * Factory for a layer transformer. - * - * Responsible for digesting the various args, erroring if the wrong ones - * are specified, and ultimately constructing the LayerTransformer - * of the correct type with the parameters it needs. - */ -abstract class LayerTransformerFactory(nom: String) - extends Serializable { - - val name = nom.toUpperCase() - - def newInstance( - maybeLayerCharsetEv: Maybe[LayerCharsetEv], - maybeLayerLengthKind: Maybe[LayerLengthKind], - maybeLayerLengthEv: Maybe[LayerLengthEv], - maybeLayerLengthUnits: Maybe[LayerLengthUnits], - maybeLayerBoundaryMarkEv: Maybe[LayerBoundaryMarkEv], - srd: SequenceRuntimeData): LayerTransformer -} - -/** - * Transformers have factories. This lets you find the transformer factory - * by the name obtained from dfdlx:layerTransform. - */ -object LayerTransformerFactory { - - private lazy val transformerMap = new NonAllocatingMap(new HashMap[String, LayerTransformerFactory]) - - def register(factory: LayerTransformerFactory): Unit = { - transformerMap.put(factory.name, factory) - } - /** - * Given name, finds the factory for the transformer. SDE otherwise. - * - * The state is passed in order to provide diagnostic context if not found. - */ - def find(name: String, state: ParseOrUnparseState): LayerTransformerFactory = { - val maybeFactory = transformerMap.get(name) - if (maybeFactory.isEmpty) { - val choices = transformerMap.keySet.mkString(", ") - state.SDE("The dfdlx:layerTransform '%s' was not found. Available choices are: %s", name, choices) - } else { - maybeFactory.get - } - } - - /** - * All transformers must be registered so they are available by name. - * - * It is possible to package a transformer in a separate jar also, but then - * someone has to register it by calling the register method. - * - * Transformers built into the primary Daffodil jars/packages should be - * registered here. - */ - register(Base64MIMETransformerFactory) - register(GZIPTransformerFactory) - register(IMFLineFoldedTransformerFactory) - register(ICalendarLineFoldedTransformerFactory) - - /** - * Arguably the above could be bundled with Daffodil. - * - * The transformers below really should be plugins defined - * outside Daffodil, per DAFFODIL-1927. - */ - register(AISPayloadArmoringTransformerFactory) - register(FourByteSwapTransformerFactory) -} +import java.nio.ByteBuffer +import java.nio.charset.Charset /** * Shared functionality of all LayerTransformers. * * A layer transformer is created at runtime as part of a single parse/unparse call. * Hence, they can be stateful without causing thread-safety issues. */ -abstract class LayerTransformer() { +abstract class LayerTransformer(layerName: String, layerRuntimeInfo: LayerRuntimeInfo) { protected def wrapLayerDecoder(jis: InputStream): InputStream - protected def wrapLimitingStream(jis: InputStream, state: PState): InputStream + protected def wrapLimitingStream(jis: InputStream): InputStream def wrapJavaInputStream(s: InputSourceDataInputStream, fInfo: FormatInfo): InputStream = { Review comment: Should this be final? Do we want customer layers to be able to override this and access a `FormatInfo`? ########## File path: daffodil-core/src/test/scala/org/apache/daffodil/layers/TestLayers.scala ########## @@ -317,7 +317,7 @@ a few lines of pointless text like this.""".replace("\r\n", "\n").replace("\n", val ipsumLorem4 = s"""Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\r\n tempor incididunt\r\n""" ///////////////////// 123456789012345678901234567890123456789012345678901234567890123456789012 3 4567890123456789012345678901234567890123456789012345678901234567890 ///////////////////// 1 2 3 4 5 6 7 8 - val ipsumLorem4Unfolded = s"""Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt""" + val ipsumLorem4Unfolded = s"""Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt\n""" Review comment: Did you ever track down what caused this? Did we have a bug that was accidentally fixed? ########## File path: daffodil-test/src/test/scala/org/apache/daffodil/layers/IPv4ChecksumLayerTransformerFactory.scala ########## @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.daffodil.layers + +import org.apache.daffodil.dpath.NodeInfo.PrimType +import org.apache.daffodil.processors.VariableRuntimeData +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthKind +import org.apache.daffodil.schema.annotation.props.gen.LayerLengthUnits + +final class IPv4ChecksumLayerCompiler + extends LayerCompiler("IPv4Checksum") { + + + val variablesNamespace = "urn:org.apache.daffodil.layers.IPv4Checksum" + val variablesPreferredNamespacePrefix = "chksum" + val localNameOfVariableToWrite = name + val outputVariableType = PrimType.UnsignedShort + + override def compileLayer(layerCompileInfo: LayerCompileInfo) = { + + val outputVRD = layerCompileInfo.getVRD( + variablesPreferredNamespacePrefix, + variablesNamespace, + localNameOfVariableToWrite, + outputVariableType) + + layerCompileInfo.optLayerLengthKind match { + case Some(LayerLengthKind.Implicit) => // ok + case None => // ok + case Some(other) => layerCompileInfo.SDE(s"The property dfdlx:layerLengthKind must be 'implicit' (or omitted) but was '$other'.") + } + layerCompileInfo.optLayerLengthOptConstantValue match { + case Some(_) => layerCompileInfo.SDE("The dfdlx:layerLength property should not be supplied, as this layer is fixed length (20 bytes).") + case None => // ok + } + layerCompileInfo.optLayerLengthUnits match { + case Some(LayerLengthUnits.Bytes) => // ok + case None => // ok + case Some(other) => layerCompileInfo.SDE("The property dfdlx:layerLengthKind must be 'bytes' but was '$other'.") + } + + new IPv4ChecksumLayerTransformerFactory(name, outputVRD) + } +} + +class IPv4ChecksumLayerTransformerFactory(name: String, outputVRD: VariableRuntimeData) + extends LayerTransformerFactory(name) { + + override def newInstance(layerRuntimeInfo: LayerRuntimeInfo)= { + val xformer = new IPv4Checksum(name, layerRuntimeInfo, outputVRD) Review comment: > We could then specify layers with a LayerCompiler and a LayerTransform, both of which could just be discovered dynamically the way LayerCompilers are now. Are you saying that we never serialize LayerTransforms? And we just use the ServiceLoader to find an create a LayerTransform when needed? One thing to consider is that I think SerivceLoader always returns the same instance. One thing to keep in mind, is I think ServiceLoader always returns the same instance once loaded. But we need unique instances to be thread safe. So I think we still need some kind of factory that creates the actual Transforms. I'm in favor of everything taking a a list of variables if it simplifies things, and things that don't need them would just have an empty list. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
