From 1bf3c1f46ccb83570a33ca18754e5f66355b4f6e Mon Sep 17 00:00:00 2001 From: Trevor Robinson Date: Mon, 19 May 2014 13:53:00 -0500 Subject: [PATCH] Import Juno 1.0.1 source from juno-xlat.sf.net --- LICENSE-afl-2.0.txt | 46 + LICENSE-javacc.txt | 13 + LICENSE-lgpl.txt | 504 ++ LICENSE-osl-2.0.txt | 49 + bin/juno | 60 + bin/juno.bat | 16 + docs/api/allclasses-frame.html | 88 + docs/api/allclasses-noframe.html | 88 + .../juno/runtime/AbstractMethodCallError.html | 254 + .../com/newisys/juno/runtime/AssocArray.html | 586 +++ .../newisys/juno/runtime/BitAssocArray.html | 508 ++ .../juno/runtime/BitBitAssocArray.html | 341 ++ .../juno/runtime/BitObjectAssocArray.html | 355 ++ docs/api/com/newisys/juno/runtime/BitOp.html | 612 +++ .../com/newisys/juno/runtime/BitVectorOp.html | 731 +++ .../com/newisys/juno/runtime/BooleanOp.html | 385 ++ .../juno/runtime/ImmutableValueFactory.html | 291 + docs/api/com/newisys/juno/runtime/IntOp.html | 580 ++ .../com/newisys/juno/runtime/IntegerOp.html | 1266 +++++ docs/api/com/newisys/juno/runtime/Juno.html | 3224 ++++++++++++ .../com/newisys/juno/runtime/JunoEnum.html | 462 ++ .../newisys/juno/runtime/JunoEnumUtil.html | 322 ++ .../com/newisys/juno/runtime/JunoEvent.html | 263 + .../juno/runtime/JunoEventValueFactory.html | 324 ++ .../runtime/JunoObject.PackingPosition.html | 312 ++ .../com/newisys/juno/runtime/JunoObject.html | 1128 ++++ .../juno/runtime/JunoRuntimeException.html | 285 + .../com/newisys/juno/runtime/JunoString.html | 1438 +++++ .../juno/runtime/JunoStringValueFactory.html | 323 ++ .../newisys/juno/runtime/LongWrapperOp.html | 1285 +++++ .../com/newisys/juno/runtime/OVAAssert.html | 434 ++ .../com/newisys/juno/runtime/OVAEngine.html | 829 +++ .../com/newisys/juno/runtime/OVAEvent.html | 375 ++ .../juno/runtime/StringAssocArray.html | 332 ++ .../juno/runtime/StringObjectAssocArray.html | 328 ++ .../com/newisys/juno/runtime/StringOp.html | 894 ++++ .../juno/runtime/TestbenchFactory.html | 309 ++ .../newisys/juno/runtime/ValueFactory.html | 235 + .../class-use/AbstractMethodCallError.html | 138 + .../juno/runtime/class-use/AssocArray.html | 276 + .../juno/runtime/class-use/BitAssocArray.html | 199 + .../runtime/class-use/BitBitAssocArray.html | 201 + .../class-use/BitObjectAssocArray.html | 175 + .../newisys/juno/runtime/class-use/BitOp.html | 138 + .../juno/runtime/class-use/BitVectorOp.html | 138 + .../juno/runtime/class-use/BooleanOp.html | 138 + .../class-use/ImmutableValueFactory.html | 138 + .../newisys/juno/runtime/class-use/IntOp.html | 138 + .../juno/runtime/class-use/IntegerOp.html | 138 + .../newisys/juno/runtime/class-use/Juno.html | 138 + .../juno/runtime/class-use/JunoEnum.html | 223 + .../juno/runtime/class-use/JunoEnumUtil.html | 138 + .../juno/runtime/class-use/JunoEvent.html | 235 + .../class-use/JunoEventValueFactory.html | 161 + .../class-use/JunoObject.PackingPosition.html | 171 + .../juno/runtime/class-use/JunoObject.html | 219 + .../class-use/JunoRuntimeException.html | 138 + .../juno/runtime/class-use/JunoString.html | 354 ++ .../class-use/JunoStringValueFactory.html | 161 + .../juno/runtime/class-use/LongWrapperOp.html | 138 + .../juno/runtime/class-use/OVAAssert.html | 177 + .../juno/runtime/class-use/OVAEngine.html | 138 + .../juno/runtime/class-use/OVAEvent.html | 189 + .../runtime/class-use/StringAssocArray.html | 191 + .../class-use/StringObjectAssocArray.html | 161 + .../juno/runtime/class-use/StringOp.html | 138 + .../runtime/class-use/TestbenchFactory.html | 138 + .../juno/runtime/class-use/ValueFactory.html | 260 + .../newisys/juno/runtime/package-frame.html | 117 + .../newisys/juno/runtime/package-summary.html | 321 ++ .../newisys/juno/runtime/package-tree.html | 176 + .../com/newisys/juno/runtime/package-use.html | 241 + docs/api/constant-values.html | 528 ++ docs/api/deprecated-list.html | 140 + docs/api/help-doc.html | 211 + docs/api/index-files/index-1.html | 221 + docs/api/index-files/index-10.html | 189 + docs/api/index-files/index-11.html | 202 + docs/api/index-files/index-12.html | 181 + docs/api/index-files/index-13.html | 194 + docs/api/index-files/index-14.html | 245 + docs/api/index-files/index-15.html | 231 + docs/api/index-files/index-16.html | 270 + docs/api/index-files/index-17.html | 244 + docs/api/index-files/index-18.html | 376 ++ docs/api/index-files/index-19.html | 163 + docs/api/index-files/index-2.html | 256 + docs/api/index-files/index-20.html | 175 + docs/api/index-files/index-21.html | 167 + docs/api/index-files/index-3.html | 241 + docs/api/index-files/index-4.html | 184 + docs/api/index-files/index-5.html | 196 + docs/api/index-files/index-6.html | 199 + docs/api/index-files/index-7.html | 245 + docs/api/index-files/index-8.html | 157 + docs/api/index-files/index-9.html | 192 + docs/api/index.html | 34 + docs/api/overview-tree.html | 178 + docs/api/package-list | 1 + docs/api/resources/inherit.gif | Bin 0 -> 57 bytes docs/api/serialized-form.html | 174 + docs/api/stylesheet.css | 29 + docs/index.html | 17 + docs/juno-logo.png | Bin 0 -> 10512 bytes docs/juno-quick-start/index.html | 123 + docs/juno-runtime-quickref/index.html | 911 ++++ java/build.xml | 74 + java/juno-runtime/build.xml | 49 + java/juno-runtime/manifest.mf | 2 + .../juno/runtime/AbstractMethodCallError.java | 40 + .../com/newisys/juno/runtime/AssocArray.java | 299 ++ .../newisys/juno/runtime/BitAssocArray.java | 166 + .../juno/runtime/BitBitAssocArray.java | 72 + .../juno/runtime/BitObjectAssocArray.java | 76 + .../src/com/newisys/juno/runtime/BitOp.java | 182 + .../com/newisys/juno/runtime/BitVectorOp.java | 319 ++ .../com/newisys/juno/runtime/BooleanOp.java | 122 + .../juno/runtime/ImmutableValueFactory.java | 61 + .../src/com/newisys/juno/runtime/IntOp.java | 218 + .../com/newisys/juno/runtime/IntegerOp.java | 393 ++ .../src/com/newisys/juno/runtime/Juno.java | 3914 ++++++++++++++ .../com/newisys/juno/runtime/JunoEnum.java | 131 + .../newisys/juno/runtime/JunoEnumUtil.java | 69 + .../com/newisys/juno/runtime/JunoEvent.java | 88 + .../juno/runtime/JunoEventValueFactory.java | 54 + .../com/newisys/juno/runtime/JunoObject.java | 828 +++ .../juno/runtime/JunoRuntimeException.java | 50 + .../com/newisys/juno/runtime/JunoString.java | 813 +++ .../juno/runtime/JunoStringValueFactory.java | 53 + .../juno/runtime/JunoThreadContext.java | 55 + .../newisys/juno/runtime/LongWrapperOp.java | 401 ++ .../com/newisys/juno/runtime/OVAAssert.java | 174 + .../com/newisys/juno/runtime/OVAEngine.java | 281 + .../com/newisys/juno/runtime/OVAEvent.java | 90 + .../juno/runtime/StringAssocArray.java | 77 + .../juno/runtime/StringObjectAssocArray.java | 76 + .../com/newisys/juno/runtime/StringOp.java | 431 ++ .../juno/runtime/TestbenchFactory.java | 175 + .../newisys/juno/runtime/ValueFactory.java | 42 + .../newisys/juno/runtime/package-info.java | 8 + .../com/newisys/printf/StringUnescaper.java | 120 + .../com/newisys/printf/VeraBaseFormatter.java | 35 + .../VeraInvalidConversionFormatter.java | 47 + .../newisys/printf/VeraNoArgFormatter.java | 131 + .../newisys/printf/VeraNumericFormatter.java | 481 ++ .../newisys/printf/VeraPrintfFormatter.java | 255 + .../newisys/printf/VeraStringFormatter.java | 148 + java/juno-samples/build.xml | 61 + java/juno-samples/changesimulator.sh | 35 + java/juno-samples/floptest/dut.if.vrh | 16 + java/juno-samples/floptest/dut.test_top.v | 32 + java/juno-samples/floptest/dut.v | 20 + java/juno-samples/floptest/floptest.dat | 11 + java/juno-samples/floptest/floptest.vr | 299 ++ java/juno-samples/floptest/makefile | 18 + java/juno-samples/makefile | 149 + java/juno-samples/xmlreader/makefile | 38 + .../src/collections/arraylist_tmpl.vr | 249 + .../src/collections/assocarraymap_tmpl.vr | 817 +++ .../src/collections/assocarrayset_tmpl.vr | 97 + .../src/collections/collection_tmpl.vr | 249 + .../xmlreader/src/collections/collections.mak | 2 + .../collectionstest/collectionstest.mak | 2 + .../collectionstest/collectionstest.vr | 664 +++ .../src/collections/comparator_tmpl.vr | 25 + .../xmlreader/src/collections/hashmap_tmpl.vr | 568 ++ .../xmlreader/src/collections/hashset_tmpl.vr | 98 + .../intcollections/elem_int_defines.vr | 46 + .../intcollections/intarraylist.vr | 22 + .../intcollections/intassocarraymap.vr | 22 + .../intcollections/intassocarrayset.vr | 23 + .../intcollections/intcollection.vr | 22 + .../intcollections/intcollections.dot | 54 + .../intcollections/intcollections.mak | 14 + .../intcollections/intcomparator.vr | 47 + .../intcollections/intlinkedlist.vr | 22 + .../src/collections/intcollections/intlist.vr | 22 + .../src/collections/intcollections/intmap.vr | 25 + .../src/collections/intcollections/intset.vr | 22 + .../intcollections/intsortedmap.vr | 23 + .../intcollections/intsortedset.vr | 23 + .../intcollections/kv_int_obj_defines.vr | 68 + .../src/collections/linkedhashmap_tmpl.vr | 584 ++ .../src/collections/linkedlist_tmpl.vr | 401 ++ .../xmlreader/src/collections/list_tmpl.vr | 191 + .../xmlreader/src/collections/map_tmpl.vr | 533 ++ .../collections/objcollections/arraylist.vr | 22 + .../collections/objcollections/collection.vr | 22 + .../objcollections/collectionsbase.vr | 40 + .../collections/objcollections/comparator.vr | 47 + .../objcollections/elem_obj_defines.vr | 49 + .../src/collections/objcollections/hashmap.vr | 22 + .../src/collections/objcollections/hashset.vr | 23 + .../objcollections/kv_obj_obj_defines.vr | 85 + .../objcollections/linkedhashmap.vr | 22 + .../collections/objcollections/linkedlist.vr | 22 + .../src/collections/objcollections/list.vr | 22 + .../src/collections/objcollections/map.vr | 24 + .../objcollections/objcollections.dot | 63 + .../objcollections/objcollections.mak | 18 + .../src/collections/objcollections/set.vr | 22 + .../collections/objcollections/sortedmap.vr | 23 + .../collections/objcollections/sortedset.vr | 23 + .../src/collections/objcollections/treemap.vr | 22 + .../src/collections/objcollections/treeset.vr | 23 + .../xmlreader/src/collections/set_tmpl.vr | 66 + .../src/collections/sortedmap_tmpl.vr | 31 + .../src/collections/sortedset_tmpl.vr | 26 + .../strcollections/elem_str_defines.vr | 49 + .../strcollections/kv_str_obj_defines.vr | 85 + .../strcollections/kv_str_str_defines.vr | 85 + .../strcollections/strarraylist.vr | 22 + .../strcollections/strcollection.vr | 22 + .../strcollections/strcollections.mak | 23 + .../strcollections/strcomparator.vr | 60 + .../collections/strcollections/strhashmap.vr | 22 + .../collections/strcollections/strhashset.vr | 23 + .../strcollections/strlinkedhashmap.vr | 22 + .../strcollections/strlinkedlist.vr | 22 + .../src/collections/strcollections/strlist.vr | 22 + .../src/collections/strcollections/strmap.vr | 25 + .../src/collections/strcollections/strset.vr | 22 + .../strcollections/strsortedmap.vr | 23 + .../strcollections/strsortedset.vr | 23 + .../strcollections/strstrhashmap.vr | 22 + .../strcollections/strstrlinkedhashmap.vr | 22 + .../collections/strcollections/strstrmap.vr | 25 + .../strcollections/strstrsortedmap.vr | 23 + .../strcollections/strstrtreemap.vr | 22 + .../collections/strcollections/strtreemap.vr | 22 + .../collections/strcollections/strtreeset.vr | 23 + .../strintcollections/kv_str_int_defines.vr | 61 + .../strintcollections/strintcollections.mak | 5 + .../strintcollections/strinthashmap.vr | 22 + .../strintcollections/strintmap.vr | 25 + .../xmlreader/src/collections/treemap_tmpl.vr | 1206 +++++ .../xmlreader/src/collections/treeset_tmpl.vr | 106 + .../xmlreader/src/common/common.mak | 8 + .../xmlreader/src/common/common.vri | 36 + .../xmlreader/src/common/listparser.vr | 60 + java/juno-samples/xmlreader/src/common/log.vr | 626 +++ .../xmlreader/src/common/logtest/logtest.mak | 3 + .../xmlreader/src/common/logtest/logtest.vr | 58 + .../xmlreader/src/common/miscutil.vr | 118 + .../xmlreader/src/common/object.vr | 122 + .../xmlreader/src/common/property.vr | 48 + .../xmlreader/src/common/randutil.vr | 171 + .../src/common/randutiltest/randutiltest.mak | 2 + .../src/common/randutiltest/randutiltest.vr | 78 + .../xmlreader/src/common/rangeparser.vr | 59 + java/juno-samples/xmlreader/src/sax/sax.mak | 2 + java/juno-samples/xmlreader/src/sax/sax.vr | 240 + .../xmlreader/src/streams/filestreams.vr | 151 + .../xmlreader/src/streams/lineposstreams.vr | 130 + .../xmlreader/src/streams/parsestream.vr | 300 ++ .../xmlreader/src/streams/streams.mak | 7 + .../xmlreader/src/streams/streams.vr | 89 + .../xmlreader/src/streams/stringstreams.vr | 85 + .../xmlreader/src/xmlreader/uri.vr | 82 + .../xmlreader/src/xmlreader/xincludefilter.vr | 243 + .../xmlreader/src/xmlreader/xml-grammar.txt | 83 + .../xmlreader/src/xmlreader/xmlattributes.vr | 211 + .../xmlreader/src/xmlreader/xmldoctypeinfo.vr | 159 + .../xmlreader/src/xmlreader/xmlerror.vr | 115 + .../xmlreader/src/xmlreader/xmlinputsource.vr | 122 + .../xmlreader/src/xmlreader/xmllocator.vr | 116 + .../xmlreader/src/xmlreader/xmlnamescope.vr | 63 + .../xmlreader/src/xmlreader/xmlreader.mak | 11 + .../xmlreader/src/xmlreader/xmlreader.vr | 2213 ++++++++ .../src/xmlreader/xmlreadertest/test.xml | 18 + .../src/xmlreader/xmlreadertest/test2.xml | 4 + .../xmlreader/xmlreadertest/xmlreadertest.mak | 2 + .../xmlreader/xmlreadertest/xmlreadertest.vr | 149 + java/juno/build.xml | 49 + java/juno/manifest.mf | 2 + .../src/com/newisys/juno/JunoPPHandler.java | 357 ++ .../src/com/newisys/juno/JunoTranslator.java | 682 +++ .../juno/NewisysComponentMapBuilder.java | 330 ++ .../com/newisys/juno/VeraAbsComponent.java | 187 + .../src/com/newisys/juno/VeraComponent.java | 253 + .../com/newisys/juno/VeraComponentGroup.java | 34 + .../com/newisys/juno/VeraComponentMap.java | 77 + .../newisys/juno/VeraComponentProcessor.java | 133 + .../com/newisys/juno/VeraFileProcessor.java | 294 ++ .../schemaanalyzer/juno/AccessType.java | 75 + .../schemaanalyzer/juno/AnalyzerModule.java | 523 ++ .../schemaanalyzer/juno/BlockAnalysis.java | 103 + .../juno/BlockMemberAnalyzer.java | 991 ++++ .../schemaanalyzer/juno/ClassAnalysis.java | 54 + .../juno/ClassMemberAnalyzer.java | 232 + .../juno/CompUnitMemberAnalyzer.java | 182 + .../schemaanalyzer/juno/DADUAllocator.java | 95 + .../schemaanalyzer/juno/DADUAnalysis.java | 165 + .../schemaanalyzer/juno/DADUState.java | 112 + .../juno/ExpressionAnalysis.java | 118 + .../juno/ExpressionAnalyzer.java | 904 ++++ .../schemaanalyzer/juno/FunctionAnalysis.java | 138 + .../juno/SchemaMemberAnalyzer.java | 58 + .../schemaanalyzer/juno/VariableAnalysis.java | 762 +++ .../juno/VeraSchemaAnalyzer.java | 428 ++ .../schemaanalyzer/juno/XZSourceType.java | 90 + .../juno/ArithmeticOperationBuilder.java | 68 + .../juno/ArrayLHSTranslator.java | 347 ++ .../schemabuilder/juno/BaseLHSTranslator.java | 107 + .../juno/BitOperationBuilder.java | 180 + .../juno/BitSliceLHSTranslator.java | 302 ++ .../juno/BitVectorOperationBuilder.java | 253 + .../juno/BlockMemberTranslator.java | 1408 +++++ .../juno/BooleanOperationBuilder.java | 149 + .../juno/BuiltinFunctionTranslator.java | 38 + .../juno/BuiltinFunctionTranslatorMap.java | 970 ++++ .../juno/ClassMemberTranslator.java | 142 + .../juno/CompUnitMemberTranslator.java | 260 + .../juno/ConcatLHSTranslator.java | 265 + .../juno/ConsExpressionPrinter.java | 635 +++ .../juno/ConsExpressionTranslator.java | 664 +++ .../juno/ConvertedExpression.java | 450 ++ .../juno/DefaultFactoryCallBuilder.java | 154 + .../juno/EqualityOperationBuilder.java | 40 + .../juno/EqualsEqualityOperationBuilder.java | 84 + .../juno/EvalOnceExprBuilder.java | 156 + .../juno/ExpressionConverter.java | 1197 +++++ .../juno/ExpressionTranslator.java | 2995 +++++++++++ .../juno/FactoryCallBuilder.java | 49 + .../juno/FactoryTranslationMap.java | 46 + .../juno/IntOperationBuilder.java | 172 + .../juno/IntegerOperationBuilder.java | 211 + .../schemabuilder/juno/JavaKeywords.java | 97 + .../schemabuilder/juno/JavaRefType.java | 67 + .../schemabuilder/juno/JunoSchemaBuilder.java | 133 + .../schemabuilder/juno/LHSTranslator.java | 38 + .../juno/ManualTranslationMap.java | 76 + .../schemabuilder/juno/PackageNamer.java | 143 + .../PrimitiveEqualityOperationBuilder.java | 67 + .../juno/RelationalOperationBuilder.java | 36 + .../juno/SchemaMemberTranslator.java | 62 + .../schemabuilder/juno/SchemaTypes.java | 206 + .../juno/ShiftOperationBuilder.java | 32 + .../juno/SimpleLHSTranslator.java | 105 + .../schemabuilder/juno/TempBlockScope.java | 72 + .../schemabuilder/juno/TranslatedClass.java | 53 + .../juno/TranslatedObjectMap.java | 74 + .../schemabuilder/juno/TranslatorModule.java | 3517 +++++++++++++ .../juno/TypeConversionException.java | 49 + .../schemabuilder/juno/TypeTranslator.java | 231 + .../schemabuilder/juno/VarBuilder.java | 79 + .../newisys/schemabuilder/juno/VarInfo.java | 85 + .../schemabuilder/juno/VarInfoMap.java | 77 + .../schemabuilder/juno/VerilogImporter.java | 185 + java/juno/test/test.vr | 119 + java/juno/test/testpp.vr | 148 + java/juno/test/testpp2.vr | 1 + java/langschema-vera/build.xml | 40 + java/langschema-vera/manifest.mf | 2 + .../com/newisys/langschema/vera/VeraAdd.java | 67 + .../langschema/vera/VeraAddSubAssignment.java | 43 + .../langschema/vera/VeraAndReduction.java | 61 + .../vera/VeraArithmeticAssignment.java | 43 + .../vera/VeraArithmeticNegative.java | 61 + .../langschema/vera/VeraArrayAccess.java | 85 + .../langschema/vera/VeraArrayCreation.java | 82 + .../langschema/vera/VeraArrayInitializer.java | 63 + .../langschema/vera/VeraArrayType.java | 90 + .../newisys/langschema/vera/VeraAssign.java | 45 + .../langschema/vera/VeraAssignAdd.java | 39 + .../langschema/vera/VeraAssignAnd.java | 39 + .../langschema/vera/VeraAssignAndNot.java | 39 + .../langschema/vera/VeraAssignDivide.java | 39 + .../langschema/vera/VeraAssignLeftShift.java | 39 + .../langschema/vera/VeraAssignModulo.java | 39 + .../langschema/vera/VeraAssignMultiply.java | 39 + .../newisys/langschema/vera/VeraAssignOr.java | 39 + .../langschema/vera/VeraAssignOrNot.java | 39 + .../langschema/vera/VeraAssignRightShift.java | 39 + .../langschema/vera/VeraAssignSubtract.java | 39 + .../langschema/vera/VeraAssignXor.java | 39 + .../langschema/vera/VeraAssignXorNot.java | 39 + .../langschema/vera/VeraAssignment.java | 52 + .../langschema/vera/VeraAssocArrayType.java | 44 + .../vera/VeraBinaryArithmeticOperation.java | 39 + .../vera/VeraBinaryLogicalOperation.java | 39 + .../langschema/vera/VeraBinaryOperation.java | 49 + .../langschema/vera/VeraBindMember.java | 61 + .../langschema/vera/VeraBindVariable.java | 85 + .../langschema/vera/VeraBitSliceAccess.java | 68 + .../newisys/langschema/vera/VeraBitType.java | 65 + .../langschema/vera/VeraBitVectorLiteral.java | 73 + .../langschema/vera/VeraBitVectorType.java | 65 + .../langschema/vera/VeraBitwiseAnd.java | 67 + .../langschema/vera/VeraBitwiseAndNot.java | 67 + .../langschema/vera/VeraBitwiseNegative.java | 61 + .../langschema/vera/VeraBitwiseOr.java | 67 + .../langschema/vera/VeraBitwiseOrNot.java | 67 + .../langschema/vera/VeraBitwiseReverse.java | 61 + .../langschema/vera/VeraBitwiseXor.java | 67 + .../langschema/vera/VeraBitwiseXorNot.java | 67 + .../newisys/langschema/vera/VeraBlock.java | 77 + .../langschema/vera/VeraBlockMember.java | 33 + .../vera/VeraBlockMemberVisitor.java | 29 + .../langschema/vera/VeraBreakStatement.java | 54 + .../vera/VeraBreakpointStatement.java | 44 + .../newisys/langschema/vera/VeraCaseKind.java | 28 + .../newisys/langschema/vera/VeraClass.java | 117 + .../langschema/vera/VeraClassConstraint.java | 77 + .../langschema/vera/VeraClassMember.java | 33 + .../vera/VeraClassMemberVisitor.java | 36 + .../langschema/vera/VeraClassModifier.java | 30 + .../vera/VeraComparisonOperation.java | 72 + .../langschema/vera/VeraCompilationUnit.java | 119 + .../vera/VeraCompilationUnitMember.java | 38 + .../VeraCompilationUnitMemberVisitor.java | 56 + .../langschema/vera/VeraComplexType.java | 61 + .../langschema/vera/VeraConcatenation.java | 154 + .../langschema/vera/VeraConditional.java | 82 + .../langschema/vera/VeraConstraintSet.java | 72 + .../vera/VeraContinueStatement.java | 54 + .../langschema/vera/VeraCopyCreation.java | 64 + .../newisys/langschema/vera/VeraDefine.java | 111 + .../langschema/vera/VeraDefineArgument.java | 45 + .../langschema/vera/VeraDefineReference.java | 69 + .../langschema/vera/VeraDefineReferrer.java | 31 + .../langschema/vera/VeraDepthAccess.java | 67 + .../newisys/langschema/vera/VeraDistSet.java | 39 + .../newisys/langschema/vera/VeraDivide.java | 71 + .../vera/VeraDriveSampleStatement.java | 105 + .../langschema/vera/VeraDynamicArrayType.java | 44 + .../vera/VeraEnumValueReference.java | 61 + .../langschema/vera/VeraEnumeration.java | 131 + .../vera/VeraEnumerationElement.java | 109 + .../newisys/langschema/vera/VeraEqual.java | 44 + .../langschema/vera/VeraEqualOperation.java | 118 + .../langschema/vera/VeraEventType.java | 51 + .../langschema/vera/VeraExactEqual.java | 46 + .../langschema/vera/VeraExactNotEqual.java | 46 + .../langschema/vera/VeraExpectKind.java | 28 + .../langschema/vera/VeraExpectStatement.java | 121 + .../langschema/vera/VeraExpectTerm.java | 60 + .../langschema/vera/VeraExpression.java | 308 ++ .../langschema/vera/VeraExpressionDefine.java | 51 + .../vera/VeraExpressionStatement.java | 55 + .../vera/VeraExpressionVisitor.java | 194 + .../langschema/vera/VeraFixedArrayType.java | 116 + .../vera/VeraFixedBitVectorType.java | 68 + .../langschema/vera/VeraForStatement.java | 99 + .../langschema/vera/VeraForkStatement.java | 71 + .../newisys/langschema/vera/VeraFunction.java | 108 + .../langschema/vera/VeraFunctionArgument.java | 108 + .../vera/VeraFunctionArgumentModifier.java | 30 + .../vera/VeraFunctionInvocation.java | 88 + .../langschema/vera/VeraFunctionModifier.java | 30 + .../vera/VeraFunctionReference.java | 56 + .../langschema/vera/VeraFunctionType.java | 164 + .../langschema/vera/VeraGlobalFunction.java | 73 + .../langschema/vera/VeraGlobalVariable.java | 73 + .../newisys/langschema/vera/VeraGreater.java | 87 + .../langschema/vera/VeraGreaterOrEqual.java | 87 + .../langschema/vera/VeraHDLFunction.java | 51 + .../langschema/vera/VeraIfElseConstraint.java | 74 + .../langschema/vera/VeraIfStatement.java | 77 + .../vera/VeraImplicationConstraint.java | 64 + .../newisys/langschema/vera/VeraInSet.java | 39 + .../langschema/vera/VeraIncDecOperation.java | 44 + .../langschema/vera/VeraInstanceCreation.java | 71 + .../langschema/vera/VeraIntegerLiteral.java | 61 + .../langschema/vera/VeraIntegerType.java | 64 + .../vera/VeraInterfaceReference.java | 53 + .../langschema/vera/VeraInterfaceSignal.java | 213 + .../langschema/vera/VeraInterfaceType.java | 75 + .../langschema/vera/VeraLeftShift.java | 67 + .../com/newisys/langschema/vera/VeraLess.java | 87 + .../langschema/vera/VeraLessOrEqual.java | 87 + .../langschema/vera/VeraLocalVariable.java | 57 + .../langschema/vera/VeraLogicalAnd.java | 46 + .../langschema/vera/VeraLogicalNegative.java | 70 + .../langschema/vera/VeraLogicalOr.java | 46 + .../langschema/vera/VeraMagicType.java | 57 + .../langschema/vera/VeraMemberAccess.java | 95 + .../langschema/vera/VeraMemberFunction.java | 126 + .../langschema/vera/VeraMemberVariable.java | 92 + .../newisys/langschema/vera/VeraModulo.java | 71 + .../newisys/langschema/vera/VeraMultiply.java | 67 + .../com/newisys/langschema/vera/VeraName.java | 89 + .../newisys/langschema/vera/VeraNameKind.java | 35 + .../langschema/vera/VeraNaryOperation.java | 46 + .../langschema/vera/VeraNotAndReduction.java | 61 + .../newisys/langschema/vera/VeraNotEqual.java | 44 + .../newisys/langschema/vera/VeraNotInSet.java | 39 + .../langschema/vera/VeraNotOrReduction.java | 61 + .../langschema/vera/VeraNotXorReduction.java | 61 + .../langschema/vera/VeraNullLiteral.java | 53 + .../newisys/langschema/vera/VeraNullType.java | 53 + .../langschema/vera/VeraOperation.java | 60 + .../langschema/vera/VeraOrReduction.java | 61 + .../langschema/vera/VeraPortSignal.java | 76 + .../newisys/langschema/vera/VeraPortType.java | 75 + .../langschema/vera/VeraPostDecrement.java | 39 + .../langschema/vera/VeraPostIncrement.java | 39 + .../langschema/vera/VeraPreDecrement.java | 39 + .../langschema/vera/VeraPreIncrement.java | 39 + .../langschema/vera/VeraPrimitiveKind.java | 28 + .../langschema/vera/VeraPrimitiveType.java | 35 + .../newisys/langschema/vera/VeraProgram.java | 98 + .../newisys/langschema/vera/VeraRandCase.java | 50 + .../vera/VeraRandCaseStatement.java | 60 + .../newisys/langschema/vera/VeraRange.java | 79 + .../langschema/vera/VeraRangeDefine.java | 51 + .../langschema/vera/VeraReduction.java | 39 + .../langschema/vera/VeraRepeatStatement.java | 60 + .../langschema/vera/VeraReplication.java | 101 + .../langschema/vera/VeraReturnStatement.java | 53 + .../langschema/vera/VeraRightShift.java | 67 + .../langschema/vera/VeraRootClass.java | 109 + .../newisys/langschema/vera/VeraSchema.java | 111 + .../langschema/vera/VeraSchemaMember.java | 31 + .../vera/VeraSchemaMemberVisitor.java | 30 + .../langschema/vera/VeraSchemaObject.java | 38 + .../langschema/vera/VeraSchemaObjectImpl.java | 85 + .../vera/VeraSchemaObjectVisitor.java | 43 + .../langschema/vera/VeraSetMember.java | 57 + .../langschema/vera/VeraSetOperation.java | 64 + .../newisys/langschema/vera/VeraSetRange.java | 53 + .../newisys/langschema/vera/VeraSetValue.java | 46 + .../langschema/vera/VeraShiftOperation.java | 78 + .../langschema/vera/VeraSignalDirection.java | 28 + .../langschema/vera/VeraSignalKind.java | 28 + .../langschema/vera/VeraSignalReference.java | 58 + .../langschema/vera/VeraStatement.java | 31 + .../langschema/vera/VeraStatementDefine.java | 51 + .../langschema/vera/VeraStatementImpl.java | 66 + .../langschema/vera/VeraStatementVisitor.java | 60 + .../langschema/vera/VeraStringLiteral.java | 89 + .../langschema/vera/VeraStringType.java | 123 + .../langschema/vera/VeraStructuredType.java | 67 + .../vera/VeraStructuredTypeMember.java | 34 + .../newisys/langschema/vera/VeraSubtract.java | 67 + .../langschema/vera/VeraSuperReference.java | 58 + .../langschema/vera/VeraSurrXParams.java | 66 + .../langschema/vera/VeraSurrXTransition.java | 40 + .../langschema/vera/VeraSwitchCase.java | 56 + .../vera/VeraSwitchDefaultCase.java | 37 + .../langschema/vera/VeraSwitchStatement.java | 88 + .../langschema/vera/VeraSwitchValueCase.java | 52 + .../langschema/vera/VeraSyncStatement.java | 59 + .../newisys/langschema/vera/VeraSyncTerm.java | 59 + .../langschema/vera/VeraSystemClass.java | 97 + .../vera/VeraSystemClockReference.java | 44 + .../vera/VeraTerminateStatement.java | 44 + .../langschema/vera/VeraTernaryOperation.java | 50 + .../langschema/vera/VeraThisReference.java | 56 + .../com/newisys/langschema/vera/VeraType.java | 88 + .../langschema/vera/VeraTypeDefine.java | 51 + .../langschema/vera/VeraTypeVisitor.java | 62 + .../langschema/vera/VeraUDFFunction.java | 51 + .../vera/VeraUnaryArithmeticOperation.java | 39 + .../langschema/vera/VeraUnaryOperation.java | 41 + .../vera/VeraUnsizedBitVectorType.java | 41 + .../langschema/vera/VeraUserClass.java | 99 + .../newisys/langschema/vera/VeraVCAKind.java | 28 + .../langschema/vera/VeraVCAQValue.java | 28 + .../newisys/langschema/vera/VeraVariable.java | 87 + .../langschema/vera/VeraVariableModifier.java | 30 + .../vera/VeraVariableReference.java | 61 + .../langschema/vera/VeraVisibility.java | 30 + .../langschema/vera/VeraVoidLiteral.java | 53 + .../newisys/langschema/vera/VeraVoidType.java | 54 + .../langschema/vera/VeraWhileStatement.java | 63 + .../langschema/vera/VeraWildEqual.java | 46 + .../langschema/vera/VeraWildNotEqual.java | 46 + .../langschema/vera/VeraXorReduction.java | 61 + .../vera/BlockMemberPrinter.java | 530 ++ .../vera/ClassMemberPrinter.java | 120 + .../vera/CompilationUnitMemberPrinter.java | 257 + .../schemaprinter/vera/ExpressionPrinter.java | 726 +++ .../vera/SchemaMemberPrinter.java | 67 + .../vera/SchemaObjectPrinter.java | 784 +++ .../schemaprinter/vera/VeraSchemaPrinter.java | 99 + .../vera/VeraSchemaPrinterModule.java | 661 +++ java/langsource/build.xml | 38 + java/langsource/manifest.mf | 2 + .../com/newisys/langsource/SourceObject.java | 59 + .../newisys/langsource/SourceObjectImpl.java | 303 ++ .../newisys/parser/util/FunctionMacro.java | 33 + .../newisys/parser/util/IncludeLocation.java | 62 + .../src/com/newisys/parser/util/Macro.java | 29 + .../src/com/newisys/parser/util/MacroRef.java | 29 + .../com/newisys/parser/util/MacroRefUtil.java | 98 + .../newisys/parser/util/ParseException.java | 221 + .../parser/util/PreprocessedToken.java | 69 + .../src/com/newisys/parser/util/Token.java | 90 + .../com/newisys/parser/util/TokenManager.java | 25 + .../newisys/parser/util/TokenMgrError.java | 170 + java/make-parser/build.xml | 37 + java/make-parser/manifest.mf | 2 + .../parser/make/AbstractTokenizer.java | 104 + .../newisys/parser/make/BlankTokenizer.java | 53 + .../com/newisys/parser/make/FileGlobber.java | 167 + .../com/newisys/parser/make/MakeDatabase.java | 552 ++ .../com/newisys/parser/make/MakeFileInfo.java | 87 + .../com/newisys/parser/make/MakeFunction.java | 958 ++++ .../parser/make/MakeParseException.java | 94 + .../com/newisys/parser/make/MakeParser.java | 1515 ++++++ .../newisys/parser/make/MakeParserTest.java | 108 + .../com/newisys/parser/make/MakePattern.java | 156 + .../newisys/parser/make/MakePatternRule.java | 65 + .../src/com/newisys/parser/make/MakeRule.java | 58 + .../newisys/parser/make/MakeStaticRule.java | 98 + .../src/com/newisys/parser/make/MakeUtil.java | 220 + .../com/newisys/parser/make/MakeVariable.java | 93 + .../parser/make/MakeVariableOrigin.java | 61 + .../parser/make/MakeVariableScope.java | 64 + .../newisys/parser/make/PathTokenizer.java | 110 + .../newisys/parser/make/RuleTokenType.java | 37 + .../newisys/parser/make/RuleTokenizer.java | 161 + .../com/newisys/parser/make/VPathEntry.java | 54 + java/vera-parser/build-token-xlat-table.pl | 100 + java/vera-parser/build.xml | 101 + java/vera-parser/manifest.mf | 2 + .../newisys/langsource/vera/AbsFuncDecl.java | 88 + .../newisys/langsource/vera/AbsVarDecl.java | 63 + .../langsource/vera/ArrayAccessDecl.java | 79 + .../langsource/vera/ArrayInitDecl.java | 47 + .../newisys/langsource/vera/ArrayKind.java | 45 + .../newisys/langsource/vera/ArrayTypeRef.java | 70 + .../com/newisys/langsource/vera/BindDecl.java | 70 + .../langsource/vera/BindSignalDecl.java | 58 + .../langsource/vera/BitSliceAccessDecl.java | 66 + .../langsource/vera/BitVectorLiteralDecl.java | 96 + .../langsource/vera/BitVectorTypeRef.java | 52 + .../newisys/langsource/vera/BlockDecl.java | 86 + .../newisys/langsource/vera/BreakDecl.java | 37 + .../langsource/vera/BreakpointDecl.java | 37 + .../com/newisys/langsource/vera/CaseDecl.java | 82 + .../langsource/vera/CaseMemberDecl.java | 58 + .../langsource/vera/ClassConstraintDecl.java | 45 + .../newisys/langsource/vera/ClassDecl.java | 160 + .../langsource/vera/ClassDeclMember.java | 29 + .../langsource/vera/ClassFuncDecl.java | 64 + .../langsource/vera/ClassModifier.java | 40 + .../newisys/langsource/vera/ClassVarDecl.java | 123 + .../langsource/vera/CompilationUnitDecl.java | 60 + .../vera/CompilationUnitDeclMember.java | 29 + .../langsource/vera/ConstraintDecl.java | 69 + .../newisys/langsource/vera/ContinueDecl.java | 37 + .../langsource/vera/DefaultValueDecl.java | 37 + .../newisys/langsource/vera/DefineDecl.java | 74 + .../langsource/vera/DepthAccessDecl.java | 71 + .../langsource/vera/DriveSampleDecl.java | 99 + .../newisys/langsource/vera/DummyDecl.java | 33 + .../com/newisys/langsource/vera/EnumDecl.java | 59 + .../langsource/vera/EnumElementDecl.java | 77 + .../newisys/langsource/vera/ExpectDecl.java | 115 + .../langsource/vera/ExpectExprDecl.java | 67 + .../langsource/vera/ExpressionDecl.java | 55 + .../vera/ExpressionStatementDecl.java | 49 + .../langsource/vera/ExtConstraintDecl.java | 45 + .../langsource/vera/ExternVarDecl.java | 33 + .../langsource/vera/FixedArrayTypeRef.java | 67 + .../com/newisys/langsource/vera/ForDecl.java | 54 + .../newisys/langsource/vera/ForkJoinDecl.java | 82 + .../newisys/langsource/vera/FuncCallDecl.java | 84 + .../com/newisys/langsource/vera/FuncDecl.java | 56 + .../langsource/vera/GlobalVarDecl.java | 32 + .../newisys/langsource/vera/HDLTaskDecl.java | 49 + .../langsource/vera/IfElseConstraintDecl.java | 80 + .../newisys/langsource/vera/IfElseDecl.java | 81 + .../vera/ImplicationConstraintDecl.java | 58 + .../langsource/vera/IntegerLiteralDecl.java | 82 + .../langsource/vera/InterfaceDecl.java | 59 + .../newisys/langsource/vera/LiteralDecl.java | 44 + .../newisys/langsource/vera/LiteralKind.java | 44 + .../newisys/langsource/vera/LocalVarDecl.java | 52 + .../langsource/vera/LocalVarModifier.java | 41 + .../com/newisys/langsource/vera/LoopDecl.java | 50 + .../newisys/langsource/vera/MacroDecl.java | 35 + .../langsource/vera/MemberAccessDecl.java | 71 + .../langsource/vera/NamedConstraintDecl.java | 39 + .../newisys/langsource/vera/NewArrayDecl.java | 70 + .../newisys/langsource/vera/NewCopyDecl.java | 58 + .../com/newisys/langsource/vera/NewDecl.java | 65 + .../langsource/vera/NullLiteralDecl.java | 37 + .../langsource/vera/OperationDecl.java | 154 + .../com/newisys/langsource/vera/Operator.java | 122 + .../langsource/vera/OperatorPosition.java | 43 + .../newisys/langsource/vera/ParamDecl.java | 66 + .../com/newisys/langsource/vera/PortDecl.java | 59 + .../newisys/langsource/vera/PragmaDecl.java | 45 + .../langsource/vera/PrimitiveTypeRef.java | 52 + .../newisys/langsource/vera/ProgramDecl.java | 70 + .../newisys/langsource/vera/RandCaseDecl.java | 52 + .../langsource/vera/RandCaseMemberDecl.java | 55 + .../com/newisys/langsource/vera/RandMode.java | 42 + .../newisys/langsource/vera/RangeDecl.java | 81 + .../langsource/vera/RangeListDecl.java | 70 + .../newisys/langsource/vera/RepeatDecl.java | 32 + .../newisys/langsource/vera/ReturnDecl.java | 37 + .../langsource/vera/SetOperationDecl.java | 82 + .../newisys/langsource/vera/SignalDecl.java | 163 + .../langsource/vera/SignalRangeDecl.java | 66 + .../langsource/vera/SignalSkewDecl.java | 69 + .../langsource/vera/StatementDecl.java | 49 + .../langsource/vera/StringLiteralDecl.java | 175 + .../newisys/langsource/vera/SuperRefDecl.java | 37 + .../com/newisys/langsource/vera/SyncDecl.java | 51 + .../com/newisys/langsource/vera/SyncEdge.java | 42 + .../com/newisys/langsource/vera/SyncTerm.java | 79 + .../langsource/vera/TerminateDecl.java | 37 + .../newisys/langsource/vera/ThisRefDecl.java | 37 + .../com/newisys/langsource/vera/TypeRef.java | 60 + .../newisys/langsource/vera/TypeRefKind.java | 42 + .../newisys/langsource/vera/TypedefDecl.java | 45 + .../newisys/langsource/vera/UDFFuncDecl.java | 61 + .../newisys/langsource/vera/UserTypeRef.java | 54 + .../com/newisys/langsource/vera/VarDecl.java | 39 + .../newisys/langsource/vera/VarRefDecl.java | 73 + .../newisys/langsource/vera/VeraFuncDecl.java | 39 + .../langsource/vera/VeraSourceObject.java | 46 + .../langsource/vera/VeraSourceObjectImpl.java | 146 + .../langsource/vera/VeraSourceVisitor.java | 174 + .../langsource/vera/VoidLiteralDecl.java | 37 + .../langsource/vera/WeightedRangeDecl.java | 55 + .../newisys/langsource/vera/WhileDecl.java | 32 + .../src/com/newisys/parser/vera/VeraParser.jj | 3302 ++++++++++++ .../parser/vera/VeraParserBasePPHandler.java | 78 + .../vera/VeraParserBoundedTokenManager.java | 111 + .../parser/vera/VeraParserPPHandler.java | 315 ++ .../vera/VeraParserReusableTokenManager.java | 70 + .../parser/vera/VeraParserTokenManager.java | 32 + .../com/newisys/parser/vera/VeraToken.java | 54 + .../newisys/parser/verapp/PathResolver.java | 106 + .../parser/verapp/VeraPPBaseHandler.java | 489 ++ .../parser/verapp/VeraPPCallbacks.java | 133 + .../parser/verapp/VeraPPCharStream.java | 610 +++ .../parser/verapp/VeraPPFunctionMacro.java | 265 + .../parser/verapp/VeraPPFunctionMacroRef.java | 77 + .../newisys/parser/verapp/VeraPPHandler.java | 131 + .../newisys/parser/verapp/VeraPPMacro.java | 46 + .../parser/verapp/VeraPPMacroArgRef.java | 64 + .../parser/verapp/VeraPPObjectMacro.java | 34 + .../com/newisys/parser/verapp/VeraPPParser.jj | 1067 ++++ .../parser/verapp/VeraPPParserTest.java | 62 + .../parser/verapp/VeraPPSimpleMacroRef.java | 54 + .../parser/verapp/VeraPPStaticMacro.java | 40 + .../parser/verapp/VeraPPUserMacro.java | 114 + .../vera/SourceSemanticException.java | 91 + .../vera/VeraAnonymousScope.java | 64 + .../schemabuilder/vera/VeraClassScope.java | 114 + .../vera/VeraCompilationUnitScope.java | 145 + .../vera/VeraPreprocessorInfo.java | 61 + .../schemabuilder/vera/VeraSchemaBuilder.java | 4688 +++++++++++++++++ .../schemabuilder/vera/VeraScopeDelegate.java | 37 + .../schemabuilder/vera/VeraSimpleScope.java | 55 + java/vlogdef/build.xml | 43 + java/vlogdef/manifest.mf | 2 + .../src/com/newisys/dv/vlogdef/Defines.java | 329 ++ .../dv/vlogdef/VerilogDefineException.java | 50 + 755 files changed, 125889 insertions(+) create mode 100644 LICENSE-afl-2.0.txt create mode 100644 LICENSE-javacc.txt create mode 100644 LICENSE-lgpl.txt create mode 100644 LICENSE-osl-2.0.txt create mode 100644 bin/juno create mode 100644 bin/juno.bat create mode 100644 docs/api/allclasses-frame.html create mode 100644 docs/api/allclasses-noframe.html create mode 100644 docs/api/com/newisys/juno/runtime/AbstractMethodCallError.html create mode 100644 docs/api/com/newisys/juno/runtime/AssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/BitAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/BitBitAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/BitObjectAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/BitOp.html create mode 100644 docs/api/com/newisys/juno/runtime/BitVectorOp.html create mode 100644 docs/api/com/newisys/juno/runtime/BooleanOp.html create mode 100644 docs/api/com/newisys/juno/runtime/ImmutableValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/IntOp.html create mode 100644 docs/api/com/newisys/juno/runtime/IntegerOp.html create mode 100644 docs/api/com/newisys/juno/runtime/Juno.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoEnum.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoEnumUtil.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoEvent.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoEventValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoObject.PackingPosition.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoObject.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoRuntimeException.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoString.html create mode 100644 docs/api/com/newisys/juno/runtime/JunoStringValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/LongWrapperOp.html create mode 100644 docs/api/com/newisys/juno/runtime/OVAAssert.html create mode 100644 docs/api/com/newisys/juno/runtime/OVAEngine.html create mode 100644 docs/api/com/newisys/juno/runtime/OVAEvent.html create mode 100644 docs/api/com/newisys/juno/runtime/StringAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/StringObjectAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/StringOp.html create mode 100644 docs/api/com/newisys/juno/runtime/TestbenchFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/ValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/AbstractMethodCallError.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/AssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BitAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BitBitAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BitObjectAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BitOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BitVectorOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/BooleanOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/ImmutableValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/IntOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/IntegerOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/Juno.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoEnum.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoEnumUtil.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoEvent.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoEventValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoObject.PackingPosition.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoObject.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoRuntimeException.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoString.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/JunoStringValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/LongWrapperOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/OVAAssert.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/OVAEngine.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/OVAEvent.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/StringAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/StringObjectAssocArray.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/StringOp.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/TestbenchFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/class-use/ValueFactory.html create mode 100644 docs/api/com/newisys/juno/runtime/package-frame.html create mode 100644 docs/api/com/newisys/juno/runtime/package-summary.html create mode 100644 docs/api/com/newisys/juno/runtime/package-tree.html create mode 100644 docs/api/com/newisys/juno/runtime/package-use.html create mode 100644 docs/api/constant-values.html create mode 100644 docs/api/deprecated-list.html create mode 100644 docs/api/help-doc.html create mode 100644 docs/api/index-files/index-1.html create mode 100644 docs/api/index-files/index-10.html create mode 100644 docs/api/index-files/index-11.html create mode 100644 docs/api/index-files/index-12.html create mode 100644 docs/api/index-files/index-13.html create mode 100644 docs/api/index-files/index-14.html create mode 100644 docs/api/index-files/index-15.html create mode 100644 docs/api/index-files/index-16.html create mode 100644 docs/api/index-files/index-17.html create mode 100644 docs/api/index-files/index-18.html create mode 100644 docs/api/index-files/index-19.html create mode 100644 docs/api/index-files/index-2.html create mode 100644 docs/api/index-files/index-20.html create mode 100644 docs/api/index-files/index-21.html create mode 100644 docs/api/index-files/index-3.html create mode 100644 docs/api/index-files/index-4.html create mode 100644 docs/api/index-files/index-5.html create mode 100644 docs/api/index-files/index-6.html create mode 100644 docs/api/index-files/index-7.html create mode 100644 docs/api/index-files/index-8.html create mode 100644 docs/api/index-files/index-9.html create mode 100644 docs/api/index.html create mode 100644 docs/api/overview-tree.html create mode 100644 docs/api/package-list create mode 100644 docs/api/resources/inherit.gif create mode 100644 docs/api/serialized-form.html create mode 100644 docs/api/stylesheet.css create mode 100644 docs/index.html create mode 100644 docs/juno-logo.png create mode 100644 docs/juno-quick-start/index.html create mode 100644 docs/juno-runtime-quickref/index.html create mode 100644 java/build.xml create mode 100644 java/juno-runtime/build.xml create mode 100644 java/juno-runtime/manifest.mf create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/AbstractMethodCallError.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/AssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BitAssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BitBitAssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BitObjectAssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BitOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BitVectorOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/BooleanOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/ImmutableValueFactory.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/IntOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/IntegerOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/Juno.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoEnum.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoEnumUtil.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoEvent.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoEventValueFactory.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoObject.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoRuntimeException.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoString.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoStringValueFactory.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/JunoThreadContext.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/LongWrapperOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/OVAAssert.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/OVAEngine.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/OVAEvent.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/StringAssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/StringObjectAssocArray.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/StringOp.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/TestbenchFactory.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/ValueFactory.java create mode 100644 java/juno-runtime/src/com/newisys/juno/runtime/package-info.java create mode 100644 java/juno-runtime/src/com/newisys/printf/StringUnescaper.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraBaseFormatter.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraInvalidConversionFormatter.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraNoArgFormatter.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraNumericFormatter.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraPrintfFormatter.java create mode 100644 java/juno-runtime/src/com/newisys/printf/VeraStringFormatter.java create mode 100644 java/juno-samples/build.xml create mode 100644 java/juno-samples/changesimulator.sh create mode 100644 java/juno-samples/floptest/dut.if.vrh create mode 100644 java/juno-samples/floptest/dut.test_top.v create mode 100644 java/juno-samples/floptest/dut.v create mode 100644 java/juno-samples/floptest/floptest.dat create mode 100644 java/juno-samples/floptest/floptest.vr create mode 100644 java/juno-samples/floptest/makefile create mode 100644 java/juno-samples/makefile create mode 100644 java/juno-samples/xmlreader/makefile create mode 100644 java/juno-samples/xmlreader/src/collections/arraylist_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/assocarraymap_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/assocarrayset_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/collection_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/collections.mak create mode 100644 java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.mak create mode 100644 java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.vr create mode 100644 java/juno-samples/xmlreader/src/collections/comparator_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/hashmap_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/hashset_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/elem_int_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intarraylist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intassocarraymap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intassocarrayset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intcollection.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intcollections.dot create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intcollections.mak create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intcomparator.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intlinkedlist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intlist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intsortedmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/intsortedset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/intcollections/kv_int_obj_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/linkedhashmap_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/linkedlist_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/list_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/map_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/arraylist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/collection.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/collectionsbase.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/comparator.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/elem_obj_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/hashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/hashset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/kv_obj_obj_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/linkedhashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/linkedlist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/list.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/map.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/objcollections.dot create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/objcollections.mak create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/set.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/sortedmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/sortedset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/treemap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/objcollections/treeset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/set_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/sortedmap_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/sortedset_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/elem_str_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/kv_str_obj_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/kv_str_str_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strarraylist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strcollection.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strcollections.mak create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strcomparator.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strhashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strhashset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strlinkedhashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strlinkedlist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strlist.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strsortedmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strsortedset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strstrhashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strstrlinkedhashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strstrmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strstrsortedmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strstrtreemap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strtreemap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strcollections/strtreeset.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strintcollections/kv_str_int_defines.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strintcollections/strintcollections.mak create mode 100644 java/juno-samples/xmlreader/src/collections/strintcollections/strinthashmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/strintcollections/strintmap.vr create mode 100644 java/juno-samples/xmlreader/src/collections/treemap_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/collections/treeset_tmpl.vr create mode 100644 java/juno-samples/xmlreader/src/common/common.mak create mode 100644 java/juno-samples/xmlreader/src/common/common.vri create mode 100644 java/juno-samples/xmlreader/src/common/listparser.vr create mode 100644 java/juno-samples/xmlreader/src/common/log.vr create mode 100644 java/juno-samples/xmlreader/src/common/logtest/logtest.mak create mode 100644 java/juno-samples/xmlreader/src/common/logtest/logtest.vr create mode 100644 java/juno-samples/xmlreader/src/common/miscutil.vr create mode 100644 java/juno-samples/xmlreader/src/common/object.vr create mode 100644 java/juno-samples/xmlreader/src/common/property.vr create mode 100644 java/juno-samples/xmlreader/src/common/randutil.vr create mode 100644 java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.mak create mode 100644 java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.vr create mode 100644 java/juno-samples/xmlreader/src/common/rangeparser.vr create mode 100644 java/juno-samples/xmlreader/src/sax/sax.mak create mode 100644 java/juno-samples/xmlreader/src/sax/sax.vr create mode 100644 java/juno-samples/xmlreader/src/streams/filestreams.vr create mode 100644 java/juno-samples/xmlreader/src/streams/lineposstreams.vr create mode 100644 java/juno-samples/xmlreader/src/streams/parsestream.vr create mode 100644 java/juno-samples/xmlreader/src/streams/streams.mak create mode 100644 java/juno-samples/xmlreader/src/streams/streams.vr create mode 100644 java/juno-samples/xmlreader/src/streams/stringstreams.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/uri.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xincludefilter.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xml-grammar.txt create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlattributes.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmldoctypeinfo.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlerror.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlinputsource.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmllocator.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlnamescope.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreader.mak create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreader.vr create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/test.xml create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/test2.xml create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.mak create mode 100644 java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.vr create mode 100644 java/juno/build.xml create mode 100644 java/juno/manifest.mf create mode 100644 java/juno/src/com/newisys/juno/JunoPPHandler.java create mode 100644 java/juno/src/com/newisys/juno/JunoTranslator.java create mode 100644 java/juno/src/com/newisys/juno/NewisysComponentMapBuilder.java create mode 100644 java/juno/src/com/newisys/juno/VeraAbsComponent.java create mode 100644 java/juno/src/com/newisys/juno/VeraComponent.java create mode 100644 java/juno/src/com/newisys/juno/VeraComponentGroup.java create mode 100644 java/juno/src/com/newisys/juno/VeraComponentMap.java create mode 100644 java/juno/src/com/newisys/juno/VeraComponentProcessor.java create mode 100644 java/juno/src/com/newisys/juno/VeraFileProcessor.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/AccessType.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/AnalyzerModule.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/BlockAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/BlockMemberAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/ClassAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/ClassMemberAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/CompUnitMemberAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/DADUAllocator.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/DADUAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/DADUState.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/FunctionAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/SchemaMemberAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/VariableAnalysis.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/VeraSchemaAnalyzer.java create mode 100644 java/juno/src/com/newisys/schemaanalyzer/juno/XZSourceType.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ArithmeticOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ArrayLHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BaseLHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BitOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BitSliceLHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BitVectorOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BlockMemberTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BooleanOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslatorMap.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ClassMemberTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/CompUnitMemberTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ConcatLHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionPrinter.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ConvertedExpression.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/DefaultFactoryCallBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/EqualityOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/EqualsEqualityOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/EvalOnceExprBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ExpressionConverter.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ExpressionTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/FactoryCallBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/FactoryTranslationMap.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/IntOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/IntegerOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/JavaKeywords.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/JavaRefType.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/JunoSchemaBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/LHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ManualTranslationMap.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/PackageNamer.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/PrimitiveEqualityOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/RelationalOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/SchemaMemberTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/SchemaTypes.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/ShiftOperationBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/SimpleLHSTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TempBlockScope.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TranslatedClass.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TranslatedObjectMap.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TranslatorModule.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TypeConversionException.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/TypeTranslator.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/VarBuilder.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/VarInfo.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/VarInfoMap.java create mode 100644 java/juno/src/com/newisys/schemabuilder/juno/VerilogImporter.java create mode 100644 java/juno/test/test.vr create mode 100644 java/juno/test/testpp.vr create mode 100644 java/juno/test/testpp2.vr create mode 100644 java/langschema-vera/build.xml create mode 100644 java/langschema-vera/manifest.mf create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAdd.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAddSubAssignment.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAndReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticAssignment.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticNegative.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayAccess.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayCreation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayInitializer.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssign.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAdd.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAnd.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAndNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignDivide.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignLeftShift.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignModulo.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignMultiply.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOr.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOrNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignRightShift.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignSubtract.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXorNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignment.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraAssocArrayType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryArithmeticOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryLogicalOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBindMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBindVariable.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitSliceAccess.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorLiteral.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAnd.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAndNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseNegative.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOr.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOrNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseReverse.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXorNot.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBlock.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMemberVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakpointStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraCaseKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraClass.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraClassConstraint.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMemberVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraClassModifier.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraComparisonOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnit.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMemberVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraComplexType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraConcatenation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraConditional.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraConstraintSet.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraContinueStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraCopyCreation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDefine.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineArgument.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReferrer.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDepthAccess.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDistSet.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDivide.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDriveSampleStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraDynamicArrayType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumValueReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumeration.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumerationElement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEqualOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraEventType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExactEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExactNotEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectTerm.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpression.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionDefine.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedArrayType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedBitVectorType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraForStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraForkStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgument.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgumentModifier.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionInvocation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionModifier.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalFunction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalVariable.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraGreater.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraGreaterOrEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraHDLFunction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraIfElseConstraint.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraIfStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraImplicationConstraint.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraInSet.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraIncDecOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraInstanceCreation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerLiteral.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceSignal.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLeftShift.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLess.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLessOrEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLocalVariable.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalAnd.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalNegative.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalOr.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraMagicType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberAccess.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberFunction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberVariable.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraModulo.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraMultiply.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraName.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNameKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNaryOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNotAndReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNotEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNotInSet.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNotOrReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNotXorReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNullLiteral.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraNullType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraOrReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPortSignal.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPortType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPostDecrement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPostIncrement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPreDecrement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPreIncrement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraProgram.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCase.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCaseStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRange.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRangeDefine.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraReduction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRepeatStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraReplication.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraReturnStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRightShift.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraRootClass.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchema.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMemberVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObject.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectImpl.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSetMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSetOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSetRange.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSetValue.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraShiftOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalDirection.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementDefine.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementImpl.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStringLiteral.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStringType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredTypeMember.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSubtract.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSuperReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXParams.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXTransition.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchCase.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchDefaultCase.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchValueCase.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncTerm.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClass.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClockReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraTerminateStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraTernaryOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraThisReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeDefine.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeVisitor.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraUDFFunction.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryArithmeticOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryOperation.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraUnsizedBitVectorType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraUserClass.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAKind.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAQValue.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVariable.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableModifier.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableReference.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVisibility.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidLiteral.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidType.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraWhileStatement.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraWildEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraWildNotEqual.java create mode 100644 java/langschema-vera/src/com/newisys/langschema/vera/VeraXorReduction.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/BlockMemberPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/ClassMemberPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/CompilationUnitMemberPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/ExpressionPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaMemberPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaObjectPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinter.java create mode 100644 java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinterModule.java create mode 100644 java/langsource/build.xml create mode 100644 java/langsource/manifest.mf create mode 100644 java/langsource/src/com/newisys/langsource/SourceObject.java create mode 100644 java/langsource/src/com/newisys/langsource/SourceObjectImpl.java create mode 100644 java/langsource/src/com/newisys/parser/util/FunctionMacro.java create mode 100644 java/langsource/src/com/newisys/parser/util/IncludeLocation.java create mode 100644 java/langsource/src/com/newisys/parser/util/Macro.java create mode 100644 java/langsource/src/com/newisys/parser/util/MacroRef.java create mode 100644 java/langsource/src/com/newisys/parser/util/MacroRefUtil.java create mode 100644 java/langsource/src/com/newisys/parser/util/ParseException.java create mode 100644 java/langsource/src/com/newisys/parser/util/PreprocessedToken.java create mode 100644 java/langsource/src/com/newisys/parser/util/Token.java create mode 100644 java/langsource/src/com/newisys/parser/util/TokenManager.java create mode 100644 java/langsource/src/com/newisys/parser/util/TokenMgrError.java create mode 100644 java/make-parser/build.xml create mode 100644 java/make-parser/manifest.mf create mode 100644 java/make-parser/src/com/newisys/parser/make/AbstractTokenizer.java create mode 100644 java/make-parser/src/com/newisys/parser/make/BlankTokenizer.java create mode 100644 java/make-parser/src/com/newisys/parser/make/FileGlobber.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeDatabase.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeFileInfo.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeFunction.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeParseException.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeParser.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeParserTest.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakePattern.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakePatternRule.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeRule.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeStaticRule.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeUtil.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeVariable.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeVariableOrigin.java create mode 100644 java/make-parser/src/com/newisys/parser/make/MakeVariableScope.java create mode 100644 java/make-parser/src/com/newisys/parser/make/PathTokenizer.java create mode 100644 java/make-parser/src/com/newisys/parser/make/RuleTokenType.java create mode 100644 java/make-parser/src/com/newisys/parser/make/RuleTokenizer.java create mode 100644 java/make-parser/src/com/newisys/parser/make/VPathEntry.java create mode 100644 java/vera-parser/build-token-xlat-table.pl create mode 100644 java/vera-parser/build.xml create mode 100644 java/vera-parser/manifest.mf create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/AbsFuncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/AbsVarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ArrayAccessDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ArrayInitDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ArrayKind.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ArrayTypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BindDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BindSignalDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BitSliceAccessDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BitVectorLiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BitVectorTypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BlockDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BreakDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/BreakpointDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/CaseDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/CaseMemberDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassDeclMember.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassFuncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassModifier.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ClassVarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDeclMember.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ContinueDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/DefaultValueDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/DefineDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/DepthAccessDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/DriveSampleDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/DummyDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/EnumDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/EnumElementDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExpectDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExpectExprDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExpressionDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExpressionStatementDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExtConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ExternVarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/FixedArrayTypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ForDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ForkJoinDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/FuncCallDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/FuncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/GlobalVarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/HDLTaskDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/IfElseConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/IfElseDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ImplicationConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/IntegerLiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/InterfaceDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/LiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/LiteralKind.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/LocalVarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/LocalVarModifier.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/LoopDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/MacroDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/MemberAccessDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/NamedConstraintDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/NewArrayDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/NewCopyDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/NewDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/NullLiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/OperationDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/Operator.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/OperatorPosition.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ParamDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/PortDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/PragmaDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/PrimitiveTypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ProgramDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RandCaseDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RandCaseMemberDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RandMode.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RangeDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RangeListDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/RepeatDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ReturnDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SetOperationDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SignalDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SignalRangeDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SignalSkewDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/StatementDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/StringLiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SuperRefDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SyncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SyncEdge.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/SyncTerm.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/TerminateDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/ThisRefDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/TypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/TypeRefKind.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/TypedefDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/UDFFuncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/UserTypeRef.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VarDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VarRefDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VeraFuncDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObject.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObjectImpl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VeraSourceVisitor.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/VoidLiteralDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/WeightedRangeDecl.java create mode 100644 java/vera-parser/src/com/newisys/langsource/vera/WhileDecl.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParser.jj create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParserBasePPHandler.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParserBoundedTokenManager.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParserPPHandler.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParserReusableTokenManager.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraParserTokenManager.java create mode 100644 java/vera-parser/src/com/newisys/parser/vera/VeraToken.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/PathResolver.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPBaseHandler.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPCallbacks.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPCharStream.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacro.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacroRef.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPHandler.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacro.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacroArgRef.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPObjectMacro.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPParser.jj create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPParserTest.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPSimpleMacroRef.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPStaticMacro.java create mode 100644 java/vera-parser/src/com/newisys/parser/verapp/VeraPPUserMacro.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/SourceSemanticException.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraAnonymousScope.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraClassScope.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraCompilationUnitScope.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraPreprocessorInfo.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSchemaBuilder.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraScopeDelegate.java create mode 100644 java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSimpleScope.java create mode 100644 java/vlogdef/build.xml create mode 100644 java/vlogdef/manifest.mf create mode 100644 java/vlogdef/src/com/newisys/dv/vlogdef/Defines.java create mode 100644 java/vlogdef/src/com/newisys/dv/vlogdef/VerilogDefineException.java diff --git a/LICENSE-afl-2.0.txt b/LICENSE-afl-2.0.txt new file mode 100644 index 0000000..6cb40a9 --- /dev/null +++ b/LICENSE-afl-2.0.txt @@ -0,0 +1,46 @@ +The Academic Free License + v. 2.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: +Licensed under the Academic Free License version 2.0 + +1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: +a) to reproduce the Original Work in copies; + +b) to prepare derivative works ("Derivative Works") based upon the Original Work; + +c) to distribute copies of the Original Work and Derivative Works to the public; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. + +2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. + +5) This section intentionally omitted. + +6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. + +9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. + +10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, for patent infringement (i) against Licensor with respect to a patent applicable to software or (ii) against any entity with respect to a patent applicable to the Original Work (but excluding combinations of the Original Work with other software or hardware). + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. ¤ 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. + +12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For 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. + +15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +This license is Copyright (C) 2003 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. \ No newline at end of file diff --git a/LICENSE-javacc.txt b/LICENSE-javacc.txt new file mode 100644 index 0000000..e9748f7 --- /dev/null +++ b/LICENSE-javacc.txt @@ -0,0 +1,13 @@ +Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +-Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +-Redistribution in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +You acknowledge that this software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility. diff --git a/LICENSE-lgpl.txt b/LICENSE-lgpl.txt new file mode 100644 index 0000000..8add30a --- /dev/null +++ b/LICENSE-lgpl.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/LICENSE-osl-2.0.txt b/LICENSE-osl-2.0.txt new file mode 100644 index 0000000..38f7957 --- /dev/null +++ b/LICENSE-osl-2.0.txt @@ -0,0 +1,49 @@ +Open Software License + v. 2.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: +Licensed under the Open Software License version 2.0 + +1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: +a) to reproduce the Original Work in copies; + +b) to prepare derivative works ("Derivative Works") based upon the Original Work; + +c) to distribute copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute shall be licensed under the Open Software License; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. + + + + +2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. + +5) External Deployment. The term "External Deployment" means the use or distribution of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether the Original Work or Derivative Works are distributed to those persons or made available as an application intended for use over a computer network. As an express condition for the grants of license hereunder, You agree that any External Deployment by You of a Derivative Work shall be deemed a distribution and shall be licensed to all under the terms of this License, as prescribed in section 1(c) herein. + +6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. + +9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. This License shall terminate immediately and you may no longer exercise any of the rights granted to You by this License upon Your failure to honor the proviso in Section 1(c) herein. + +10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, for patent infringement (i) against Licensor with respect to a patent applicable to software or (ii) against any entity with respect to a patent applicable to the Original Work (but excluding combinations of the Original Work with other software or hardware). + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. + +12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For 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. + +15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +This license is Copyright (C) 2003 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. \ No newline at end of file diff --git a/bin/juno b/bin/juno new file mode 100644 index 0000000..b5a177d --- /dev/null +++ b/bin/juno @@ -0,0 +1,60 @@ +#!/bin/sh +# Utility script to setup the correct classpath and run juno + +############################################################################# +# Check that environment variables are set # +# JOVE_HOME should point to the base of a Jove installation (src or binary) # +# JUNO_HOME should point to the base of a Juno installation # +# JAVA_HOME should point to the base of a Java installation # +############################################################################# +if [ ! -e "${JOVE_HOME}/bin" -a ! -e "${JOVE_HOME}/java/jove" ]; then + echo "JOVE_HOME must point to a valid Jove installation" + exit 1 +fi +if [ ! -e "${JUNO_HOME}/java/juno" ]; then + echo "JUNO_HOME must point to a valid Juno installation" + exit 1 +fi +if [ ! -e "${JAVA_HOME}/bin/java" ]; then + echo "JAVA_HOME must point to a valid Java installation" + exit 1 +fi + +############################ +# Construct Jove Classpath # +############################ +JOVE_PKGS="jove jove-ifgen langschema langschema-java langschema-jove newisys-utils randsolver" +JOVE_CLASSPATH="" +if [ -e "${JOVE_HOME}/bin" ]; then + # Found Jove binary install + for PKG in ${JOVE_PKGS} + do + JOVE_CLASSPATH=${JOVE_CLASSPATH}:${JOVE_HOME}/bin/${PKG}.jar + done +else + # Must be Jove src install + for PKG in ${JOVE_PKGS} + do + JOVE_CLASSPATH=${JOVE_CLASSPATH}:${JOVE_HOME}/java/${PKG}/bin + done +fi + +#################################### +# Construct Juno Classpath # +# Juno only comes as a source dist # +#################################### +JUNO_PKGS="juno juno-runtime langschema-vera langsource make-parser vera-parser vlogdef" +JUNO_CLASSPATH="" +for PKG in ${JUNO_PKGS} +do + JUNO_CLASSPATH=${JUNO_CLASSPATH}:${JUNO_HOME}/java/${PKG}/bin +done + +######################################################### +# Set Java options, create final classpath and run Juno # +######################################################### +JAVA_OPTS="-Xms128M -Xmx256M -ea" +CLASSPATH=${CLASSPATH}:${JOVE_CLASSPATH}:${JUNO_CLASSPATH} + +${JAVA_HOME}/bin/java ${JAVA_OPTS} -cp ${CLASSPATH} com.newisys.juno.JunoTranslator "$@" + diff --git a/bin/juno.bat b/bin/juno.bat new file mode 100644 index 0000000..e9abc4e --- /dev/null +++ b/bin/juno.bat @@ -0,0 +1,16 @@ +@echo off + +rem support both source and binary jove distributions +if EXIST %JOVE_HOME%\bin ( + set JOVE_CLASSPATH=%JOVE_HOME%\bin\jove-ifgen.jar;%JOVE_HOME%\bin\newisys-utils.jar;%JOVE_HOME%\bin\langschema.jar;%JOVE_HOME%\bin\langschema-java.jar;%JOVE_HOME%\bin\langschema-jove.jar;%JOVE_HOME%\bin\jove.jar;%JOVE_HOME%\bin\randsolver.jar +) ELSE ( + set JOVE_CLASSPATH=%JOVE_HOME%\java\jove-ifgen\bin;%JOVE_HOME%\java\newisys-utils\bin;%JOVE_HOME%\java\langschema\bin;%JOVE_HOME%\java\langschema-java\bin;%JOVE_HOME%\java\langschema-jove\bin;%JOVE_HOME%\java\jove\bin;%JOVE_HOME%\java\randsolver\bin +) + +set JUNO_CLASSPATH=%JUNO_HOME%\java\juno\bin;%JUNO_HOME%\java\juno-runtime\bin;%JUNO_HOME%\java\langschema-vera\bin;%JUNO_HOME%\java\langsource\bin;%JUNO_HOME%\java\make-parser\bin;%JUNO_HOME%\java\vera-parser\bin;%JUNO_HOME%\java\vlogdef\bin; + +set CLASSPATH=%JOVE_CLASSPATH%;%JUNO_CLASSPATH%;%CLASSPATH% + +set JAVA_OPTS="-ea" + +java %JAVA_OPTS% -cp %CLASSPATH% com.newisys.juno.JunoTranslator %* diff --git a/docs/api/allclasses-frame.html b/docs/api/allclasses-frame.html new file mode 100644 index 0000000..380ac22 --- /dev/null +++ b/docs/api/allclasses-frame.html @@ -0,0 +1,88 @@ + + + + + + +All Classes (Jove API) + + + + + + + + + + +All Classes +
+ + + + + +
AbstractMethodCallError +
+AssocArray +
+BitAssocArray +
+BitBitAssocArray +
+BitObjectAssocArray +
+BitOp +
+BitVectorOp +
+BooleanOp +
+ImmutableValueFactory +
+IntegerOp +
+IntOp +
+Juno +
+JunoEnum +
+JunoEnumUtil +
+JunoEvent +
+JunoEventValueFactory +
+JunoObject +
+JunoObject.PackingPosition +
+JunoRuntimeException +
+JunoString +
+JunoStringValueFactory +
+LongWrapperOp +
+OVAAssert +
+OVAEngine +
+OVAEvent +
+StringAssocArray +
+StringObjectAssocArray +
+StringOp +
+TestbenchFactory +
+ValueFactory +
+
+ + + diff --git a/docs/api/allclasses-noframe.html b/docs/api/allclasses-noframe.html new file mode 100644 index 0000000..0fe94b7 --- /dev/null +++ b/docs/api/allclasses-noframe.html @@ -0,0 +1,88 @@ + + + + + + +All Classes (Jove API) + + + + + + + + + + +All Classes +
+ + + + + +
AbstractMethodCallError +
+AssocArray +
+BitAssocArray +
+BitBitAssocArray +
+BitObjectAssocArray +
+BitOp +
+BitVectorOp +
+BooleanOp +
+ImmutableValueFactory +
+IntegerOp +
+IntOp +
+Juno +
+JunoEnum +
+JunoEnumUtil +
+JunoEvent +
+JunoEventValueFactory +
+JunoObject +
+JunoObject.PackingPosition +
+JunoRuntimeException +
+JunoString +
+JunoStringValueFactory +
+LongWrapperOp +
+OVAAssert +
+OVAEngine +
+OVAEvent +
+StringAssocArray +
+StringObjectAssocArray +
+StringOp +
+TestbenchFactory +
+ValueFactory +
+
+ + + diff --git a/docs/api/com/newisys/juno/runtime/AbstractMethodCallError.html b/docs/api/com/newisys/juno/runtime/AbstractMethodCallError.html new file mode 100644 index 0000000..36762b9 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/AbstractMethodCallError.html @@ -0,0 +1,254 @@ + + + + + + +AbstractMethodCallError (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class AbstractMethodCallError

+
+java.lang.Object
+  extended by java.lang.Throwable
+      extended by java.lang.Error
+          extended by com.newisys.juno.runtime.AbstractMethodCallError
+
+
+
All Implemented Interfaces:
java.io.Serializable
+
+
+
+
public class AbstractMethodCallError
extends java.lang.Error
+ + +

+Exception thrown by translator-generated stub methods in non-abstract classes + when an abstract method is unimplemented. +

+ +

+

+
See Also:
Serialized Form
+
+ +

+ + + + + + + + + + + + + + +
+Constructor Summary
AbstractMethodCallError() + +
+           
AbstractMethodCallError(java.lang.String message) + +
+           
+  + + + + + + + +
+Method Summary
+ + + + + + + +
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+AbstractMethodCallError

+
+public AbstractMethodCallError()
+
+
+
+ +

+AbstractMethodCallError

+
+public AbstractMethodCallError(java.lang.String message)
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/AssocArray.html b/docs/api/com/newisys/juno/runtime/AssocArray.html new file mode 100644 index 0000000..10e8048 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/AssocArray.html @@ -0,0 +1,586 @@ + + + + + + +AssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class AssocArray<K,V>

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<K,V>
+
+
+
Type Parameters:
K - key type
V - value type
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
Direct Known Subclasses:
BitAssocArray, StringAssocArray
+
+
+
+
public class AssocArray<K,V>
extends java.lang.Object
implements java.lang.Cloneable
+ + +

+Base implementation of associative arrays. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
AssocArray() + +
+          Creates an AssocArray with a default value of null.
AssocArray(AssocArray<? extends K,? extends V> other) + +
+          Creates a new AssocArray which is a copy of the specified array.
AssocArray(V nullValue) + +
+          Creates an AssocArray with the specified default value.
AssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates an AssocArray with the specified default value factory.
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ intcheck() + +
+          Checks if there are any entries in this associative array.
+ intcheck(K key) + +
+          Checks if there is a mapping in this associative array for the specified + key.
+ AssocArray<K,V>clone() + +
+           
+ intdelete() + +
+          Remove all entries from this associative array.
+ intdelete(K key) + +
+          Deletes the entry in this associative array for the specified key (if + one exists).
+ Kfirst() + +
+          Returns the first key in this associative array.
+ Vget(K key) + +
+          Gets the value for the specified key from this associative array.
+ VgetOrCreate(K key) + +
+          Gets the value for the specified key from this associative array.
+ Knext(K prevKey) + +
+          Returns the key following the given key in this associative array.
+ voidput(K key, + V value) + +
+          Associates the specified value with the specified key in this + associative array.
+ java.lang.StringtoString() + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+AssocArray

+
+public AssocArray()
+
+
Creates an AssocArray with a default value of null. +

+

+
+ +

+AssocArray

+
+public AssocArray(V nullValue)
+
+
Creates an AssocArray with the specified default value. If a key is + requested that does not exist in this array, the default value will be + returned. +

+

+
Parameters:
nullValue - the default value for this array
+
+
+ +

+AssocArray

+
+public AssocArray(ValueFactory<? extends V> nullValueFactory)
+
+
Creates an AssocArray with the specified default value factory. If a key + is requested that does not exist in this array, the factory will be used + to instantiate the default value. +

+

+
Parameters:
nullValueFactory - the value factory used to create default values
+
+
+ +

+AssocArray

+
+public AssocArray(AssocArray<? extends K,? extends V> other)
+
+
Creates a new AssocArray which is a copy of the specified array. +

+

+
Parameters:
other - the array to copy
+
+ + + + + + + + +
+Method Detail
+ +

+get

+
+public V get(K key)
+
+
Gets the value for the specified key from this associative array. +

+

+
+
+
+
Parameters:
key - the key whose associated value is to be returned +
Returns:
the value which maps to the specified key, or the default value + if this associative array contains no mapping for this key
+
+
+
+ +

+getOrCreate

+
+public V getOrCreate(K key)
+
+
Gets the value for the specified key from this associative array. If the + array contains no mapping for the key, a mapping is added to the default + value. +

+

+
+
+
+
Parameters:
key - the key whose associated value is to be returned +
Returns:
the value which maps to the specified key, or the default value + if this associative array contains no mapping for this key
+
+
+
+ +

+put

+
+public void put(K key,
+                V value)
+
+
Associates the specified value with the specified key in this + associative array. +

+

+
+
+
+
Parameters:
key - the key with which the specified value is to be associated
value - the value to be associated with the specified key
+
+
+
+ +

+check

+
+public int check()
+
+
Checks if there are any entries in this associative array. +

+

+
+
+
+ +
Returns:
the number of entries in this associative array
+
+
+
+ +

+check

+
+public int check(K key)
+
+
Checks if there is a mapping in this associative array for the specified + key. +

+

+
+
+
+
Parameters:
key - the key to check for a mapping +
Returns:
1 if there is an entry in this associative array for + key, 0 otherwise
+
+
+
+ +

+delete

+
+public int delete()
+
+
Remove all entries from this associative array. +

+

+
+
+
+ +
Returns:
1
+
+
+
+ +

+delete

+
+public int delete(K key)
+
+
Deletes the entry in this associative array for the specified key (if + one exists). +

+

+
+
+
+
Parameters:
key - the key to delete the mapping of +
Returns:
1 if the key exists in this associative array and + was deleted, 0 otherwise
+
+
+
+ +

+first

+
+public K first()
+
+
Returns the first key in this associative array. This method can be used + with next(K) to iterate all keys in the array. +

+

+
+
+
+ +
Returns:
the first key in this associative array, or null if this array + is empty
+
+
+
+ +

+next

+
+public K next(K prevKey)
+
+
Returns the key following the given key in this associative array. This + method can be used with first() to iterate all keys in the array. +

+

+
+
+
+
Parameters:
prevKey - a previously returned key +
Returns:
the key following prevKey in this associative + array, or null if there are no more keys
+
+
+
+ +

+clone

+
+public AssocArray<K,V> clone()
+
+
+
Overrides:
clone in class java.lang.Object
+
+
+
+
+
+
+ +

+toString

+
+public java.lang.String toString()
+
+
+
Overrides:
toString in class java.lang.Object
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BitAssocArray.html b/docs/api/com/newisys/juno/runtime/BitAssocArray.html new file mode 100644 index 0000000..b39d692 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BitAssocArray.html @@ -0,0 +1,508 @@ + + + + + + +BitAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BitAssocArray<V>

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<com.newisys.verilog.util.BitVector,V>
+      extended by com.newisys.juno.runtime.BitAssocArray<V>
+
+
+
Type Parameters:
V - value type
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
Direct Known Subclasses:
BitBitAssocArray, BitObjectAssocArray
+
+
+
+
public class BitAssocArray<V>
extends AssocArray<com.newisys.verilog.util.BitVector,V>
+ + +

+BitVector-keyed associative array. +

+ +

+


+ +

+ + + + + + + + + + + +
+Field Summary
+static com.newisys.verilog.util.BitVectorNULL_KEY + +
+           
+  + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
BitAssocArray() + +
+          Creates a BitAssocArray with a default value of null.
BitAssocArray(BitAssocArray<? extends V> other) + +
+          Creates a BitAssocArray which is a copy of the specified array.
BitAssocArray(V nullValue) + +
+          Creates a BitAssocArray with the specified default value.
BitAssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates a BitAssocArray with the specified default value factory.
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ BitAssocArray<V>clone() + +
+           
+ com.newisys.verilog.util.BitVectorfirst() + +
+          Returns the first key in this associative array.
+ Vget(com.newisys.verilog.util.BitVector key) + +
+          Gets the value for the specified key from this associative array.
+ VgetOrCreate(com.newisys.verilog.util.BitVector key) + +
+          Gets the value for the specified key from this associative array.
+ com.newisys.verilog.util.BitVectornext(com.newisys.verilog.util.BitVector prevKey) + +
+          Returns the key following the given key in this associative array.
+ voidput(com.newisys.verilog.util.BitVector key, + V value) + +
+          Associates the specified value with the specified key in this + associative array.
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.AssocArray
check, check, delete, delete, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+NULL_KEY

+
+public static final com.newisys.verilog.util.BitVector NULL_KEY
+
+
+
+
+ + + + + + + + +
+Constructor Detail
+ +

+BitAssocArray

+
+public BitAssocArray()
+
+
Creates a BitAssocArray with a default value of null. +

+

+
+ +

+BitAssocArray

+
+public BitAssocArray(V nullValue)
+
+
Creates a BitAssocArray with the specified default value. If a key is + requested that does not exist in this array, the default value will be + returned. +

+

+
Parameters:
nullValue - the default value for this array
+
+
+ +

+BitAssocArray

+
+public BitAssocArray(ValueFactory<? extends V> nullValueFactory)
+
+
Creates a BitAssocArray with the specified default value factory. If a + key is requested that does not exist in this array, the factory will be + used to instantiate the default value. +

+

+
Parameters:
nullValueFactory - the value factory used to create default values
+
+
+ +

+BitAssocArray

+
+public BitAssocArray(BitAssocArray<? extends V> other)
+
+
Creates a BitAssocArray which is a copy of the specified array. +

+

+
Parameters:
other - the array to copy
+
+ + + + + + + + +
+Method Detail
+ +

+get

+
+public V get(com.newisys.verilog.util.BitVector key)
+
+
Gets the value for the specified key from this associative array. +

+

+
Overrides:
get in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+
Parameters:
key - the key whose associated value is to be returned +
Returns:
the value which maps to the specified key, or the default value + if this associative array contains no mapping for this key +
Throws: +
java.lang.RuntimeException - if key contains X/Z
+
+
+
+ +

+getOrCreate

+
+public V getOrCreate(com.newisys.verilog.util.BitVector key)
+
+
Gets the value for the specified key from this associative array. If the + array contains no mapping for the key, a mapping is added to the default + value. +

+

+
Overrides:
getOrCreate in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+
Parameters:
key - the key whose associated value is to be returned +
Returns:
the value which maps to the specified key, or the default value + if this associative array contains no mapping for this key +
Throws: +
java.lang.RuntimeException - if key contains X/Z
+
+
+
+ +

+put

+
+public void put(com.newisys.verilog.util.BitVector key,
+                V value)
+
+
Associates the specified value with the specified key in this + associative array. +

+

+
Overrides:
put in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+
Parameters:
key - the key with which the specified value is to be associated
value - the value to be associated with the specified key
+
+
+
+ +

+first

+
+public com.newisys.verilog.util.BitVector first()
+
+
Returns the first key in this associative array. This method can be used + with next(com.newisys.verilog.util.BitVector) to iterate all keys in the array. +

+

+
Overrides:
first in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+ +
Returns:
the first key in this associative array, or X if this array is + empty
+
+
+
+ +

+next

+
+public com.newisys.verilog.util.BitVector next(com.newisys.verilog.util.BitVector prevKey)
+
+
Returns the key following the given key in this associative array. This + method can be used with first() to iterate all keys in the array. +

+

+
Overrides:
next in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+
Parameters:
prevKey - a previously returned key +
Returns:
the key following prevKey in this associative + array, or X if there are no more keys
+
+
+
+ +

+clone

+
+public BitAssocArray<V> clone()
+
+
+
Overrides:
clone in class AssocArray<com.newisys.verilog.util.BitVector,V>
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BitBitAssocArray.html b/docs/api/com/newisys/juno/runtime/BitBitAssocArray.html new file mode 100644 index 0000000..29468c7 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BitBitAssocArray.html @@ -0,0 +1,341 @@ + + + + + + +BitBitAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BitBitAssocArray

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<com.newisys.verilog.util.BitVector,V>
+      extended by com.newisys.juno.runtime.BitAssocArray<com.newisys.verilog.util.BitVector>
+          extended by com.newisys.juno.runtime.BitBitAssocArray
+
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
+
public final class BitBitAssocArray
extends BitAssocArray<com.newisys.verilog.util.BitVector>
+ + +

+BitVector-to-BitVector associative array. +

+ +

+


+ +

+ + + + + + + +
+Field Summary
+ + + + + + + +
Fields inherited from class com.newisys.juno.runtime.BitAssocArray
NULL_KEY
+  + + + + + + + + + + + + + +
+Constructor Summary
BitBitAssocArray(BitBitAssocArray other) + +
+          Creates a BitBitAssocArray that is a copy of the specified array.
BitBitAssocArray(int valueLength) + +
+          Creates a BitBitAssocArray which has a default value of X with the + specified number of bits.
+  + + + + + + + + + + + + + + + +
+Method Summary
+ BitBitAssocArrayclone() + +
+           
+ intgetValueLength() + +
+          Returns the length in bits of the default value
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.BitAssocArray
first, get, getOrCreate, next, put
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.AssocArray
check, check, delete, delete, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+BitBitAssocArray

+
+public BitBitAssocArray(int valueLength)
+
+
Creates a BitBitAssocArray which has a default value of X with the + specified number of bits. +

+

+
Parameters:
valueLength - the length of the default value
+
+
+ +

+BitBitAssocArray

+
+public BitBitAssocArray(BitBitAssocArray other)
+
+
Creates a BitBitAssocArray that is a copy of the specified array. +

+

+
Parameters:
other - the array to copy
+
+ + + + + + + + +
+Method Detail
+ +

+getValueLength

+
+public int getValueLength()
+
+
Returns the length in bits of the default value +

+

+ +
Returns:
the length of the default value
+
+
+
+ +

+clone

+
+public BitBitAssocArray clone()
+
+
+
Overrides:
clone in class BitAssocArray<com.newisys.verilog.util.BitVector>
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BitObjectAssocArray.html b/docs/api/com/newisys/juno/runtime/BitObjectAssocArray.html new file mode 100644 index 0000000..3ba2782 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BitObjectAssocArray.html @@ -0,0 +1,355 @@ + + + + + + +BitObjectAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BitObjectAssocArray

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<com.newisys.verilog.util.BitVector,V>
+      extended by com.newisys.juno.runtime.BitAssocArray<java.lang.Object>
+          extended by com.newisys.juno.runtime.BitObjectAssocArray
+
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
+
public final class BitObjectAssocArray
extends BitAssocArray<java.lang.Object>
+ + +

+BitVector-to-Object associative array. +

+ +

+


+ +

+ + + + + + + +
+Field Summary
+ + + + + + + +
Fields inherited from class com.newisys.juno.runtime.BitAssocArray
NULL_KEY
+  + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
BitObjectAssocArray() + +
+          Creates a BitObjectAssocArray.
BitObjectAssocArray(BitObjectAssocArray other) + +
+          Creates a BitObjectAssocArray which is a copy of the specified array.
BitObjectAssocArray(java.lang.Object nullValue) + +
+          Creates a BitObjectAssocArray with the specified default value.
BitObjectAssocArray(ValueFactory<?> nullValueFactory) + +
+          Creates a BitObjectAssocArray with the specified default value factory.
+  + + + + + + + + + + + +
+Method Summary
+ BitObjectAssocArrayclone() + +
+           
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.BitAssocArray
first, get, getOrCreate, next, put
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.AssocArray
check, check, delete, delete, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+BitObjectAssocArray

+
+public BitObjectAssocArray()
+
+
Creates a BitObjectAssocArray. +

+

+
+ +

+BitObjectAssocArray

+
+public BitObjectAssocArray(java.lang.Object nullValue)
+
+
Creates a BitObjectAssocArray with the specified default value. If a key + is requested that does not exist in this array, the default value will + be returned. +

+

+
Parameters:
nullValue - the default value for this array
+
+
+ +

+BitObjectAssocArray

+
+public BitObjectAssocArray(ValueFactory<?> nullValueFactory)
+
+
Creates a BitObjectAssocArray with the specified default value factory. + If a key is requested that does not exist in this array, the factory + will be used to instantiate the default value. +

+

+
Parameters:
nullValueFactory - the value factory used to create default values
+
+
+ +

+BitObjectAssocArray

+
+public BitObjectAssocArray(BitObjectAssocArray other)
+
+
Creates a BitObjectAssocArray which is a copy of the specified array. +

+

+
Parameters:
other - the array to copy
+
+ + + + + + + + +
+Method Detail
+ +

+clone

+
+public BitObjectAssocArray clone()
+
+
+
Overrides:
clone in class BitAssocArray<java.lang.Object>
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BitOp.html b/docs/api/com/newisys/juno/runtime/BitOp.html new file mode 100644 index 0000000..65ad1e6 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BitOp.html @@ -0,0 +1,612 @@ + + + + + + +BitOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BitOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.BitOp
+
+
+
+
public final class BitOp
extends java.lang.Object
+ + +

+Bit conversion and operation methods referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static com.newisys.verilog.util.Bitdivide(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+static com.newisys.verilog.util.Bitequal(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+static com.newisys.verilog.util.Bitmod(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+static com.newisys.verilog.util.BitnotEqual(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+static com.newisys.verilog.util.BittoBit(com.newisys.verilog.util.BitVector bv) + +
+           
+static com.newisys.verilog.util.BittoBit(int i) + +
+           
+static com.newisys.verilog.util.BittoBit(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BittoBit(long l) + +
+           
+static com.newisys.verilog.util.BittoBit(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BittoBit(java.lang.Object o) + +
+           
+static com.newisys.verilog.util.BittoBit(java.lang.String s) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(int len, + com.newisys.verilog.util.Bit b) + +
+           
+static inttoInt(com.newisys.verilog.util.Bit b) + +
+           
+static com.newisys.verilog.util.BittoLogicalBit(com.newisys.verilog.util.BitVector bv) + +
+           
+static com.newisys.verilog.util.BittoLogicalBit(int i) + +
+           
+static com.newisys.verilog.util.BittoLogicalBit(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BittoLogicalBit(long l) + +
+           
+static com.newisys.verilog.util.BittoLogicalBit(java.lang.Long l) + +
+           
+static inttoShiftCount(com.newisys.verilog.util.Bit b) + +
+           
+static com.newisys.verilog.util.BitwildEqual(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+static com.newisys.verilog.util.BitwildNotEqual(com.newisys.verilog.util.Bit b1, + com.newisys.verilog.util.Bit b2) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(int i)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(long l)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(java.lang.Long l)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(java.lang.String s)
+
+
+
+
+
+
+ +

+toBit

+
+public static com.newisys.verilog.util.Bit toBit(java.lang.Object o)
+
+
+
+
+
+
+ +

+toLogicalBit

+
+public static com.newisys.verilog.util.Bit toLogicalBit(int i)
+
+
+
+
+
+
+ +

+toLogicalBit

+
+public static com.newisys.verilog.util.Bit toLogicalBit(long l)
+
+
+
+
+
+
+ +

+toLogicalBit

+
+public static com.newisys.verilog.util.Bit toLogicalBit(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toLogicalBit

+
+public static com.newisys.verilog.util.Bit toLogicalBit(java.lang.Long l)
+
+
+
+
+
+
+ +

+toLogicalBit

+
+public static com.newisys.verilog.util.Bit toLogicalBit(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(int len,
+                                                             com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+toInt

+
+public static int toInt(com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+divide

+
+public static com.newisys.verilog.util.Bit divide(com.newisys.verilog.util.Bit b1,
+                                                  com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+
+ +

+mod

+
+public static com.newisys.verilog.util.Bit mod(com.newisys.verilog.util.Bit b1,
+                                               com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+
+ +

+equal

+
+public static com.newisys.verilog.util.Bit equal(com.newisys.verilog.util.Bit b1,
+                                                 com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+
+ +

+notEqual

+
+public static com.newisys.verilog.util.Bit notEqual(com.newisys.verilog.util.Bit b1,
+                                                    com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+
+ +

+wildEqual

+
+public static com.newisys.verilog.util.Bit wildEqual(com.newisys.verilog.util.Bit b1,
+                                                     com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+
+ +

+wildNotEqual

+
+public static com.newisys.verilog.util.Bit wildNotEqual(com.newisys.verilog.util.Bit b1,
+                                                        com.newisys.verilog.util.Bit b2)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BitVectorOp.html b/docs/api/com/newisys/juno/runtime/BitVectorOp.html new file mode 100644 index 0000000..37c37ff --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BitVectorOp.html @@ -0,0 +1,731 @@ + + + + + + +BitVectorOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BitVectorOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.BitVectorOp
+
+
+
+
public final class BitVectorOp
extends java.lang.Object
+ + +

+BitVector conversion and operation methods referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + +
+Field Summary
+static com.newisys.verilog.util.BitVectorBIT_0 + +
+           
+static com.newisys.verilog.util.BitVectorBIT_1 + +
+           
+static com.newisys.verilog.util.BitVectorBIT_X + +
+           
+static com.newisys.verilog.util.BitVectorBIT_Z + +
+           
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static com.newisys.verilog.util.BitVectorconcat(com.newisys.verilog.util.BitVector... bvs) + +
+           
+static com.newisys.verilog.util.Bitequal(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.BitVectorgetBits(com.newisys.verilog.util.BitVector bv, + int high, + int low) + +
+          Wrapper for BitVector.getBits() that allows high and low indices to be + swapped.
+static com.newisys.verilog.util.BitVectorgetBitsChecked(com.newisys.verilog.util.BitVector bv, + int high, + int low) + +
+          Wrapper for BitVector.getBits() that allows high and low indices to be + swapped, and allows the indices to extend beyond the length of the + BitVector.
+static com.newisys.verilog.util.BitVectorgetMask(int index) + +
+          Generates a bit mask of index+1 bits with the index bit set to ONE, and + any lower-order bits set to ZERO.
+static com.newisys.verilog.util.BitVectorgetMask(int high, + int low) + +
+          Generates a bit mask of high+1 bits with each bit between high and low + (inclusive) set to ONE, and any lower-order bits set to ZERO.
+static com.newisys.verilog.util.Bitgreater(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.BitgreaterOrEqual(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.Bitless(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.BitlessOrEqual(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.BitnotEqual(com.newisys.verilog.util.BitVector bv1, + com.newisys.verilog.util.BitVector bv2) + +
+           
+static com.newisys.verilog.util.BitVectorpromote(com.newisys.verilog.util.BitVector bv, + int minLen) + +
+           
+static com.newisys.verilog.util.BitVectorreplicate(int count, + com.newisys.verilog.util.BitVector bv) + +
+           
+static com.newisys.verilog.util.BitVectorsetBits(com.newisys.verilog.util.BitVector bv, + int high, + int low, + com.newisys.verilog.util.BitVector value) + +
+          Wrapper for BitVector.setBits() that allows high and low indices to be + swapped.
+static com.newisys.verilog.util.BitVectortoBitVector(com.newisys.verilog.util.Bit b) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(boolean[] ba) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Object value) + +
+           
+static inttoInt(com.newisys.verilog.util.BitVector bv) + +
+           
+static inttoShiftCount(com.newisys.verilog.util.BitVector bv) + +
+           
+static inttoShiftCount(com.newisys.verilog.util.BitVector bv, + int max) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+BIT_0

+
+public static final com.newisys.verilog.util.BitVector BIT_0
+
+
+
+
+
+ +

+BIT_1

+
+public static final com.newisys.verilog.util.BitVector BIT_1
+
+
+
+
+
+ +

+BIT_Z

+
+public static final com.newisys.verilog.util.BitVector BIT_Z
+
+
+
+
+
+ +

+BIT_X

+
+public static final com.newisys.verilog.util.BitVector BIT_X
+
+
+
+
+ + + + + + + + +
+Method Detail
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(boolean[] ba)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Object value)
+
+
+
+
+
+
+ +

+toInt

+
+public static int toInt(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(com.newisys.verilog.util.BitVector bv,
+                               int max)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+equal

+
+public static com.newisys.verilog.util.Bit equal(com.newisys.verilog.util.BitVector bv1,
+                                                 com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+notEqual

+
+public static com.newisys.verilog.util.Bit notEqual(com.newisys.verilog.util.BitVector bv1,
+                                                    com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+greater

+
+public static com.newisys.verilog.util.Bit greater(com.newisys.verilog.util.BitVector bv1,
+                                                   com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+greaterOrEqual

+
+public static com.newisys.verilog.util.Bit greaterOrEqual(com.newisys.verilog.util.BitVector bv1,
+                                                          com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+less

+
+public static com.newisys.verilog.util.Bit less(com.newisys.verilog.util.BitVector bv1,
+                                                com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+lessOrEqual

+
+public static com.newisys.verilog.util.Bit lessOrEqual(com.newisys.verilog.util.BitVector bv1,
+                                                       com.newisys.verilog.util.BitVector bv2)
+
+
+
+
+
+
+ +

+concat

+
+public static com.newisys.verilog.util.BitVector concat(com.newisys.verilog.util.BitVector... bvs)
+
+
+
+
+
+
+ +

+replicate

+
+public static com.newisys.verilog.util.BitVector replicate(int count,
+                                                           com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+getBits

+
+public static com.newisys.verilog.util.BitVector getBits(com.newisys.verilog.util.BitVector bv,
+                                                         int high,
+                                                         int low)
+
+
Wrapper for BitVector.getBits() that allows high and low indices to be + swapped. +

+

+
Parameters:
bv - the BitVector to get the bit slice from
high - the "high" index
low - the "low" index +
Returns:
the bit slice
+
+
+
+ +

+getBitsChecked

+
+public static com.newisys.verilog.util.BitVector getBitsChecked(com.newisys.verilog.util.BitVector bv,
+                                                                int high,
+                                                                int low)
+
+
Wrapper for BitVector.getBits() that allows high and low indices to be + swapped, and allows the indices to extend beyond the length of the + BitVector. Any bits requested beyond the length of the BitVector are + returned as 0. +

+

+
Parameters:
bv - the BitVector to get the bit slice from
high - the "high" index
low - the "low" index +
Returns:
the bit slice
+
+
+
+ +

+setBits

+
+public static com.newisys.verilog.util.BitVector setBits(com.newisys.verilog.util.BitVector bv,
+                                                         int high,
+                                                         int low,
+                                                         com.newisys.verilog.util.BitVector value)
+
+
Wrapper for BitVector.setBits() that allows high and low indices to be + swapped. +

+

+
Parameters:
bv - the BitVector to set the bit slice in
high - the "high" index
low - the "low" index
value - the bit slice to store +
Returns:
the new BitVector with the bit slice written
+
+
+
+ +

+getMask

+
+public static com.newisys.verilog.util.BitVector getMask(int index)
+
+
Generates a bit mask of index+1 bits with the index bit set to ONE, and + any lower-order bits set to ZERO. +

+

+
Parameters:
index - the index of the bit to set to ONE +
Returns:
a bit vector representing a mask containing the given bit
+
+
+
+ +

+getMask

+
+public static com.newisys.verilog.util.BitVector getMask(int high,
+                                                         int low)
+
+
Generates a bit mask of high+1 bits with each bit between high and low + (inclusive) set to ONE, and any lower-order bits set to ZERO. +

+

+
Parameters:
high - the index of the highest bit to set to ONE
low - the index of the lowest bit to set to ONE +
Returns:
a bit vector representing a mask containing the given bit range
+
+
+
+ +

+promote

+
+public static com.newisys.verilog.util.BitVector promote(com.newisys.verilog.util.BitVector bv,
+                                                         int minLen)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/BooleanOp.html b/docs/api/com/newisys/juno/runtime/BooleanOp.html new file mode 100644 index 0000000..88e8256 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/BooleanOp.html @@ -0,0 +1,385 @@ + + + + + + +BooleanOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class BooleanOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.BooleanOp
+
+
+
+
public final class BooleanOp
extends java.lang.Object
+ + +

+boolean conversion and operation methods referenced by + translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static booleandivide(boolean b1, + boolean b2) + +
+           
+static booleanmod(boolean b1, + boolean b2) + +
+           
+static booleantoBoolean(com.newisys.verilog.util.Bit b, + boolean xzTrue) + +
+           
+static booleantoBoolean(com.newisys.verilog.util.BitVector bv) + +
+           
+static booleantoBoolean(com.newisys.verilog.util.BitVector bv, + boolean lowBitOnly, + boolean xzTrue) + +
+           
+static booleantoBoolean(java.lang.Object o) + +
+           
+static booleantoBoolean(java.lang.Object o, + boolean lowBitOnly, + boolean xzTrue) + +
+           
+static booleantoBoolean(java.lang.String s) + +
+           
+static booleantoBooleanXZTrue(com.newisys.verilog.util.BitVector bv) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+toBoolean

+
+public static boolean toBoolean(com.newisys.verilog.util.Bit b,
+                                boolean xzTrue)
+
+
+
+
+
+
+ +

+toBoolean

+
+public static boolean toBoolean(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toBooleanXZTrue

+
+public static boolean toBooleanXZTrue(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toBoolean

+
+public static boolean toBoolean(com.newisys.verilog.util.BitVector bv,
+                                boolean lowBitOnly,
+                                boolean xzTrue)
+
+
+
+
+
+
+ +

+toBoolean

+
+public static boolean toBoolean(java.lang.Object o)
+
+
+
+
+
+
+ +

+toBoolean

+
+public static boolean toBoolean(java.lang.Object o,
+                                boolean lowBitOnly,
+                                boolean xzTrue)
+
+
+
+
+
+
+ +

+toBoolean

+
+public static boolean toBoolean(java.lang.String s)
+
+
+
+
+
+
+ +

+divide

+
+public static boolean divide(boolean b1,
+                             boolean b2)
+
+
+
+
+
+
+ +

+mod

+
+public static boolean mod(boolean b1,
+                          boolean b2)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/ImmutableValueFactory.html b/docs/api/com/newisys/juno/runtime/ImmutableValueFactory.html new file mode 100644 index 0000000..5380696 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/ImmutableValueFactory.html @@ -0,0 +1,291 @@ + + + + + + +ImmutableValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class ImmutableValueFactory<T>

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.ImmutableValueFactory<T>
+
+
+
Type Parameters:
T - object type produced by factory
+
+
All Implemented Interfaces:
ValueFactory<T>
+
+
+
+
public final class ImmutableValueFactory<T>
extends java.lang.Object
implements ValueFactory<T>
+ + +

+Implementation of ValueFactory for immutable objects. +

+ +

+


+ +

+ + + + + + + + + + + +
+Constructor Summary
ImmutableValueFactory(T value) + +
+          Create an ImmutableValueFactory with the specified immutable object.
+  + + + + + + + + + + + + + + + +
+Method Summary
+ TcopyInstance(T other) + +
+          Returns the immutable object passed as an argument.
+ TnewInstance() + +
+          Returns the immutable object for this factory.
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+ImmutableValueFactory

+
+public ImmutableValueFactory(T value)
+
+
Create an ImmutableValueFactory with the specified immutable object. +

+

+
Parameters:
value - the immutable Object to use in this factory
+
+ + + + + + + + +
+Method Detail
+ +

+newInstance

+
+public T newInstance()
+
+
Returns the immutable object for this factory. +

+

+
Specified by:
newInstance in interface ValueFactory<T>
+
+
+ +
Returns:
this factory's immutable object
+
+
+
+ +

+copyInstance

+
+public T copyInstance(T other)
+
+
Returns the immutable object passed as an argument. +

+

+
Specified by:
copyInstance in interface ValueFactory<T>
+
+
+
Parameters:
other - the Object to copy +
Returns:
other
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/IntOp.html b/docs/api/com/newisys/juno/runtime/IntOp.html new file mode 100644 index 0000000..b35f6fe --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/IntOp.html @@ -0,0 +1,580 @@ + + + + + + +IntOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class IntOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.IntOp
+
+
+
+
public final class IntOp
extends java.lang.Object
+ + +

+int/long conversion and operation methods + referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static intbitCount(int i) + +
+           
+static intbitCount(long l) + +
+           
+static intbitwiseReverse(int i) + +
+           
+static longbitwiseReverse(long l) + +
+           
+static booleanreductiveAnd(int i) + +
+           
+static booleanreductiveAnd(long l) + +
+           
+static booleanreductiveAndNot(int i) + +
+           
+static booleanreductiveAndNot(long l) + +
+           
+static booleanreductiveOr(int i) + +
+           
+static booleanreductiveOr(long l) + +
+           
+static booleanreductiveOrNot(int i) + +
+           
+static booleanreductiveOrNot(long l) + +
+           
+static booleanreductiveXor(int i) + +
+           
+static booleanreductiveXor(long l) + +
+           
+static booleanreductiveXorNot(int i) + +
+           
+static booleanreductiveXorNot(long l) + +
+           
+static inttoInt(java.lang.Object o) + +
+           
+static inttoInt(java.lang.String s) + +
+           
+static longtoLong(java.lang.Object o) + +
+           
+static longtoLong(java.lang.String s) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+toInt

+
+public static int toInt(java.lang.Object o)
+
+
+
+
+
+
+ +

+toInt

+
+public static int toInt(java.lang.String s)
+
+
+
+
+
+
+ +

+toLong

+
+public static long toLong(java.lang.Object o)
+
+
+
+
+
+
+ +

+toLong

+
+public static long toLong(java.lang.String s)
+
+
+
+
+
+
+ +

+bitwiseReverse

+
+public static int bitwiseReverse(int i)
+
+
+
+
+
+
+ +

+bitwiseReverse

+
+public static long bitwiseReverse(long l)
+
+
+
+
+
+
+ +

+reductiveAnd

+
+public static boolean reductiveAnd(int i)
+
+
+
+
+
+
+ +

+reductiveAnd

+
+public static boolean reductiveAnd(long l)
+
+
+
+
+
+
+ +

+reductiveAndNot

+
+public static boolean reductiveAndNot(int i)
+
+
+
+
+
+
+ +

+reductiveAndNot

+
+public static boolean reductiveAndNot(long l)
+
+
+
+
+
+
+ +

+reductiveOr

+
+public static boolean reductiveOr(int i)
+
+
+
+
+
+
+ +

+reductiveOr

+
+public static boolean reductiveOr(long l)
+
+
+
+
+
+
+ +

+reductiveOrNot

+
+public static boolean reductiveOrNot(int i)
+
+
+
+
+
+
+ +

+reductiveOrNot

+
+public static boolean reductiveOrNot(long l)
+
+
+
+
+
+
+ +

+reductiveXor

+
+public static boolean reductiveXor(int i)
+
+
+
+
+
+
+ +

+reductiveXor

+
+public static boolean reductiveXor(long l)
+
+
+
+
+
+
+ +

+reductiveXorNot

+
+public static boolean reductiveXorNot(int i)
+
+
+
+
+
+
+ +

+reductiveXorNot

+
+public static boolean reductiveXorNot(long l)
+
+
+
+
+
+
+ +

+bitCount

+
+public static int bitCount(int i)
+
+
+
+
+
+
+ +

+bitCount

+
+public static int bitCount(long l)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/IntegerOp.html b/docs/api/com/newisys/juno/runtime/IntegerOp.html new file mode 100644 index 0000000..d7ab1e5 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/IntegerOp.html @@ -0,0 +1,1266 @@ + + + + + + +IntegerOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class IntegerOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.IntegerOp
+
+
+
+
public final class IntegerOp
extends java.lang.Object
+ + +

+Integer conversion and operation methods referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static java.lang.Integeradd(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseAnd(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseAndNot(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseNot(java.lang.Integer i) + +
+           
+static java.lang.IntegerbitwiseOr(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseOrNot(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseReverse(java.lang.Integer i) + +
+           
+static java.lang.IntegerbitwiseXor(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerbitwiseXorNot(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.Integerdec(java.lang.Integer i) + +
+           
+static java.lang.Integerdivide(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.Bitequal(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitexactEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitexactNotEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.Bitgreater(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitgreaterOrEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.Integerinc(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.Bitless(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitlessOrEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerlogicalAnd(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegerlogicalNegative(java.lang.Integer i) + +
+           
+static java.lang.IntegerlogicalOr(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static booleanlowBitToBoolean(java.lang.Integer i) + +
+           
+static booleanlowBitToBooleanXZTrue(java.lang.Integer i) + +
+           
+static java.lang.Integermod(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.Integermultiply(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.Integernegate(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitnotEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitreductiveAnd(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitreductiveAndNot(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitreductiveOr(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitreductiveOrNot(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitreductiveXor(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitreductiveXorNot(java.lang.Integer i) + +
+           
+static java.lang.IntegershiftLeft(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.IntegershiftRight(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static java.lang.Integersubtract(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Integer i) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Integer i, + int len) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Integer i, + int len, + boolean signExtend) + +
+           
+static booleantoBoolean(java.lang.Integer i) + +
+           
+static booleantoBooleanXZTrue(java.lang.Integer i) + +
+           
+static inttoInt(java.lang.Integer i) + +
+           
+static java.lang.IntegertoInteger(com.newisys.verilog.util.Bit b) + +
+           
+static java.lang.IntegertoInteger(com.newisys.verilog.util.BitVector bv) + +
+           
+static java.lang.IntegertoInteger(com.newisys.verilog.util.BitVector bv, + boolean signed) + +
+           
+static java.lang.IntegertoInteger(java.lang.Long l) + +
+           
+static java.lang.IntegertoInteger(java.lang.Object o) + +
+           
+static java.lang.IntegertoInteger(java.lang.String s) + +
+           
+static inttoShiftCount(java.lang.Integer i) + +
+           
+static inttoShiftCount(java.lang.Integer i, + int max) + +
+           
+static com.newisys.verilog.util.BitwildEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+static com.newisys.verilog.util.BitwildNotEqual(java.lang.Integer i1, + java.lang.Integer i2) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+toBoolean

+
+public static boolean toBoolean(java.lang.Integer i)
+
+
+
+
+
+
+ +

+lowBitToBoolean

+
+public static boolean lowBitToBoolean(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toBooleanXZTrue

+
+public static boolean toBooleanXZTrue(java.lang.Integer i)
+
+
+
+
+
+
+ +

+lowBitToBooleanXZTrue

+
+public static boolean lowBitToBooleanXZTrue(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Integer i,
+                                                             int len)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Integer i,
+                                                             int len,
+                                                             boolean signExtend)
+
+
+
+
+
+
+ +

+toInt

+
+public static int toInt(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(java.lang.Integer i,
+                               int max)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(com.newisys.verilog.util.BitVector bv,
+                                          boolean signed)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(java.lang.Long l)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(java.lang.String s)
+
+
+
+
+
+
+ +

+toInteger

+
+public static java.lang.Integer toInteger(java.lang.Object o)
+
+
+
+
+
+
+ +

+add

+
+public static java.lang.Integer add(java.lang.Integer i1,
+                                    java.lang.Integer i2)
+
+
+
+
+
+
+ +

+subtract

+
+public static java.lang.Integer subtract(java.lang.Integer i1,
+                                         java.lang.Integer i2)
+
+
+
+
+
+
+ +

+multiply

+
+public static java.lang.Integer multiply(java.lang.Integer i1,
+                                         java.lang.Integer i2)
+
+
+
+
+
+
+ +

+divide

+
+public static java.lang.Integer divide(java.lang.Integer i1,
+                                       java.lang.Integer i2)
+
+
+
+
+
+
+ +

+mod

+
+public static java.lang.Integer mod(java.lang.Integer i1,
+                                    java.lang.Integer i2)
+
+
+
+
+
+
+ +

+negate

+
+public static java.lang.Integer negate(java.lang.Integer i)
+
+
+
+
+
+
+ +

+inc

+
+public static java.lang.Integer inc(java.lang.Integer i)
+
+
+
+
+
+
+ +

+dec

+
+public static java.lang.Integer dec(java.lang.Integer i)
+
+
+
+
+
+
+ +

+bitwiseAnd

+
+public static java.lang.Integer bitwiseAnd(java.lang.Integer i1,
+                                           java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseAndNot

+
+public static java.lang.Integer bitwiseAndNot(java.lang.Integer i1,
+                                              java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseOr

+
+public static java.lang.Integer bitwiseOr(java.lang.Integer i1,
+                                          java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseOrNot

+
+public static java.lang.Integer bitwiseOrNot(java.lang.Integer i1,
+                                             java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseXor

+
+public static java.lang.Integer bitwiseXor(java.lang.Integer i1,
+                                           java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseXorNot

+
+public static java.lang.Integer bitwiseXorNot(java.lang.Integer i1,
+                                              java.lang.Integer i2)
+
+
+
+
+
+
+ +

+bitwiseNot

+
+public static java.lang.Integer bitwiseNot(java.lang.Integer i)
+
+
+
+
+
+
+ +

+bitwiseReverse

+
+public static java.lang.Integer bitwiseReverse(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveAnd

+
+public static com.newisys.verilog.util.Bit reductiveAnd(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveAndNot

+
+public static com.newisys.verilog.util.Bit reductiveAndNot(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveOr

+
+public static com.newisys.verilog.util.Bit reductiveOr(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveOrNot

+
+public static com.newisys.verilog.util.Bit reductiveOrNot(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveXor

+
+public static com.newisys.verilog.util.Bit reductiveXor(java.lang.Integer i)
+
+
+
+
+
+
+ +

+reductiveXorNot

+
+public static com.newisys.verilog.util.Bit reductiveXorNot(java.lang.Integer i)
+
+
+
+
+
+
+ +

+logicalAnd

+
+public static java.lang.Integer logicalAnd(java.lang.Integer i1,
+                                           java.lang.Integer i2)
+
+
+
+
+
+
+ +

+logicalOr

+
+public static java.lang.Integer logicalOr(java.lang.Integer i1,
+                                          java.lang.Integer i2)
+
+
+
+
+
+
+ +

+logicalNegative

+
+public static java.lang.Integer logicalNegative(java.lang.Integer i)
+
+
+
+
+
+
+ +

+equal

+
+public static com.newisys.verilog.util.Bit equal(java.lang.Integer i1,
+                                                 java.lang.Integer i2)
+
+
+
+
+
+
+ +

+notEqual

+
+public static com.newisys.verilog.util.Bit notEqual(java.lang.Integer i1,
+                                                    java.lang.Integer i2)
+
+
+
+
+
+
+ +

+exactEqual

+
+public static com.newisys.verilog.util.Bit exactEqual(java.lang.Integer i1,
+                                                      java.lang.Integer i2)
+
+
+
+
+
+
+ +

+exactNotEqual

+
+public static com.newisys.verilog.util.Bit exactNotEqual(java.lang.Integer i1,
+                                                         java.lang.Integer i2)
+
+
+
+
+
+
+ +

+wildEqual

+
+public static com.newisys.verilog.util.Bit wildEqual(java.lang.Integer i1,
+                                                     java.lang.Integer i2)
+
+
+
+
+
+
+ +

+wildNotEqual

+
+public static com.newisys.verilog.util.Bit wildNotEqual(java.lang.Integer i1,
+                                                        java.lang.Integer i2)
+
+
+
+
+
+
+ +

+greater

+
+public static com.newisys.verilog.util.Bit greater(java.lang.Integer i1,
+                                                   java.lang.Integer i2)
+
+
+
+
+
+
+ +

+greaterOrEqual

+
+public static com.newisys.verilog.util.Bit greaterOrEqual(java.lang.Integer i1,
+                                                          java.lang.Integer i2)
+
+
+
+
+
+
+ +

+less

+
+public static com.newisys.verilog.util.Bit less(java.lang.Integer i1,
+                                                java.lang.Integer i2)
+
+
+
+
+
+
+ +

+lessOrEqual

+
+public static com.newisys.verilog.util.Bit lessOrEqual(java.lang.Integer i1,
+                                                       java.lang.Integer i2)
+
+
+
+
+
+
+ +

+shiftLeft

+
+public static java.lang.Integer shiftLeft(java.lang.Integer i1,
+                                          java.lang.Integer i2)
+
+
+
+
+
+
+ +

+shiftRight

+
+public static java.lang.Integer shiftRight(java.lang.Integer i1,
+                                           java.lang.Integer i2)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/Juno.html b/docs/api/com/newisys/juno/runtime/Juno.html new file mode 100644 index 0000000..2c535e3 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/Juno.html @@ -0,0 +1,3224 @@ + + + + + + +Juno (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class Juno

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.Juno
+
+
+
+
public final class Juno
extends java.lang.Object
+ + +

+Implementations of Vera's built-in functions for use by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Field Summary
+static intALL + +
+           
+static intANY + +
+           
+static intCHECK + +
+           
+static intCOPY_NO_WAIT + +
+           
+static intCOPY_WAIT + +
+           
+static intDELETE + +
+           
+static intFIRST + +
+           
+static intHAND_SHAKE + +
+           
+static intHI + +
+           
+static intHNUM + +
+           
+static intLO + +
+           
+static intMAILBOX + +
+           
+static intNEXT + +
+           
+static intNO_WAIT + +
+           
+static intNUM + +
+           
+static intOFF + +
+           
+static intON + +
+           
+static intONE_BLAST + +
+           
+static intONE_SHOT + +
+           
+static intORDER + +
+           
+static intRAWIN + +
+           
+static intREGION + +
+           
+static intSEMAPHORE + +
+           
+static intSILENT + +
+           
+static intSTR + +
+           
+static com.newisys.dv.ClockSignalsystemClock + +
+          Represents the system clock, "CLOCK".
+static intVERBOSE + +
+           
+static intWAIT + +
+           
+  + + + + + + + + + + +
+Constructor Summary
Juno() + +
+           
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static intalloc(int type, + int id, + int count) + +
+          alloc built-in function for allocating a REGION or a MAILBOX.
+static intalloc(int type, + int id, + int count, + int keyCount) + +
+          alloc built-in function for allocating a REGION or a MAILBOX.
+static intassoc_index(int op, + AssocArray<?,?> array) + +
+          assoc_index built-in function for dealing with entire arrays.
+static intassoc_index(int op, + AssocArray array, + int[] index_ref) + +
+          See assoc_index(int, AssocArray, Object[]).
+static intassoc_index(int op, + AssocArray array, + java.lang.Object index) + +
+          assoc_index built-in function for dealing with array elements.
+static intassoc_index(int op, + AssocArray array, + java.lang.Object[] index_ref) + +
+          assoc_index built-in function for dealing with array elements.
+static voidbadCast() + +
+           
+static + + + + +
+<T> T[]
+
copyArray(T[] dstArray, + T[] srcArray, + T initExtra) + +
+          Copies the given source array into the given destination array, and + initializes any extra elements in the destination array with the given + value.
+static + + + + +
+<T> T[]
+
copyArray(T[] dstArray, + T[] srcArray, + ValueFactory<T> factory) + +
+          Clones the elements in the given source array into the given destination + array, and initializes any extra elements in the destination array, using + the given value factory.
+static voiddelay(int ticks) + +
+          Block the current thread until the specified number of ticks have occurred.
+static voiddumpStack(java.io.OutputStream oStream) + +
+           
+static voidenter_context() + +
+          Enter a new thread context.
+static booleanequals(java.lang.Object o1, + java.lang.Object o2) + +
+           
+static voiderror_mode(int enable, + int ec) + +
+          NOTE: error_mode is currently unsupported.
+static voiderror(java.lang.String format, + java.lang.Object... args) + +
+          error built-in function.
+static voidexit(int status) + +
+          Exit the DV.simulation with the given exit status.
+static voidfclose(int fd) + +
+          fclose built-in function.
+static booleanfeof(int fd) + +
+          feof built-in function.
+static booleanferror(int fd) + +
+          ferror built-in function
+static voidfflush(int fd) + +
+          fflush built-in function.
+static intflag() + +
+          Returns the status of the internal flag variable.
+static intflag(int enable) + +
+          Sets and gets the status of the internal flag variable.
+static intfopen(java.lang.String filename, + java.lang.String mode) + +
+          fopen built-in function
+static intfopen(java.lang.String filename, + java.lang.String mode, + int verbose) + +
+          fopen built-in function
+static com.newisys.eventsim.SimulationThreadfork(java.lang.Runnable r) + +
+          Fork a new thread of execution.
+static com.newisys.eventsim.SimulationThreadfork(java.lang.String name, + java.lang.Runnable r) + +
+          Fork a new thread of execution.
+static voidfprintf(int fd, + java.lang.String format, + java.lang.Object... args) + +
+          fprintf built-in function.
+static com.newisys.verilog.util.BitVectorfreadb(int fd, + int mode) + +
+          Reads a binary value from a file and returns the corresponding BitVector.
+static com.newisys.verilog.util.BitVectorfreadh(int fd, + int mode) + +
+          Reads a hexadecimal value from a file and returns the corresponding BitVector.
+static java.lang.Stringfreadstr(int fd) + +
+          freadstr built-in function.
+static java.lang.Stringfreadstr(int fd, + int mode) + +
+          freadstr built-in function.
+static com.newisys.verilog.util.BitVectorget_plus_arg(int op, + java.lang.String name) + +
+          Returns a plusarg value as defined in jove.ini or on the command line.
+static intget_systime() + +
+          Returns the current DV.simulation wall-clock time in seconds.
+static intget_time(int part) + +
+          Get the current DV.simulation time in ticks.
+static java.util.PropertiesgetProperties() + +
+          Returns a clone of the Properties from jove.ini and command line.
+static + + + + +
+<T> T[]
+
initArray(T[] array, + T value, + int start) + +
+          Initializes the given Object array with the given value, starting at the + given index and continuing to the end of the array.
+static + + + + +
+<T> T[]
+
initArray(T[] array, + ValueFactory<T> factory, + int start) + +
+          Initializes the given Object array with values from the given factory, + starting at the given index and continuing to the end of the array.
+static voidinitialize() + +
+           
+static voidleave_context() + +
+          Leave a thread context.
+static booleanlock_file(java.lang.String filename, + int timeout) + +
+          lock_file built-in function.
+static intmailbox_get(int op, + int mailbox_id) + +
+          Returns the size of the given mailbox.
+static intmailbox_get(int op, + int mailbox_id, + java.lang.Object[] data_ref) + +
+          Retrieve an object from a given mailbox.
+static intmailbox_get(int op, + int mailbox_id, + java.lang.Object[] data_ref, + int check) + +
+          Retrieve an object from a given mailbox.
+static voidmailbox_put(int mailbox_id, + java.lang.Object data) + +
+          Put an object into a given mailbox.
+static intos_command(java.lang.String command) + +
+          Run a command outside of the Jove environment.
+static voidprintf(java.lang.String format, + java.lang.Object... args) + +
+          printf built-in function.
+static java.lang.Stringpsprintf(java.lang.String format, + java.lang.Object... args) + +
+          psprintf built-in function.
+static intrand48() + +
+          Returns a 32 bit signed random value generated using a 48 bit linear + congruential algorithm.
+static intrand48(int seed) + +
+          Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit signed rand value generated from it.
+static intrandcase(int... weights) + +
+          Choose a value based on a weighted randomization.
+static intrandom() + +
+          Return a 32 bit signed random value.
+static intrandom(int seed) + +
+          Seeds the random number generator and then returns a 32 bit signed rand + value.
+static intregion_enter(int op, + int region_id, + java.lang.Object[] values) + +
+          NOTE: region_enter is currently unsupported.
+static voidregion_exit(int region_id, + java.lang.Object[] values) + +
+          NOTE: region_exit is currently unsupported.
+static voidrewind(int fd) + +
+          rewind built-in function.
+static intsemaphore_get(int op, + int semaphore_id, + int keyCount) + +
+          Acquire one or more keys from a given semaphore.
+static voidsemaphore_put(int semaphore_id, + int keyCount) + +
+          Release the specified number of keys to the specified semaphore.
+static voidsprintf(JunoString str, + java.lang.String format, + java.lang.Object... args) + +
+          sprintf built-in function.
+static voidsrandom(int seed) + +
+          Creates a new random number generator for the DV.simulation and seeds it with + the given value.
+static voidsrandom(int seed, + JunoObject obj) + +
+          Creates a new random number generator for the DV.simulation and seeds it with + the given value.
+static voidsscanf(java.lang.String str, + java.lang.String format, + java.lang.Object[] args, + java.lang.Class[] types) + +
+          built-in sscanf function.
+static intsync(int op, + JunoEvent... events) + +
+          Wait on a given set of JunoEvents to occur.
+static voidtrigger(int op, + JunoEvent... events) + +
+          Triggers one or more JunoEvents.
+static voidtrigger(JunoEvent... events) + +
+          Triggers one or more JunoEvents in ONE_SHOT mode.
+static voidunlock_file(java.lang.String filename) + +
+          unlock_file built-in function
+static com.newisys.verilog.util.BitVectorurand48() + +
+          Returns a 32 bit unsigned random value generated using a 48 bit linear + congruential algorithm.
+static com.newisys.verilog.util.BitVectorurand48(int seed) + +
+          Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit unsigned rand value generated from it.
+static com.newisys.verilog.util.BitVectorurandom_range(com.newisys.verilog.util.BitVector maxval) + +
+          Returns a 32 bit unsigned random value between 0 and maxval, inclusive.
+static com.newisys.verilog.util.BitVectorurandom_range(com.newisys.verilog.util.BitVector maxval, + com.newisys.verilog.util.BitVector minval) + +
+          Returns a 32 bit unsigned random value between minval and maxval, inclusive.
+static com.newisys.verilog.util.BitVectorurandom() + +
+          Returns a 32 bit unsigned random value.
+static com.newisys.verilog.util.BitVectorurandom(int seed) + +
+          Seeds the random number generator and then returns a 32 bit unsigned rand + value.
+static java.lang.Stringvera_get_clk_name(com.newisys.dv.Signal signal) + +
+          Return the name of the clock associated with the given signal.
+static intvera_get_dir(com.newisys.dv.Signal signal) + +
+          Returns the direction of the given signal.
+static java.lang.Stringvera_get_ifc_name(com.newisys.dv.Signal signal) + +
+          NOTE: vera_get_ifc_name is currently unsupported.
+static intvera_get_in_depth(com.newisys.dv.Signal signal) + +
+          Returns the input depth of the given signal.
+static intvera_get_in_skew(com.newisys.dv.Signal signal) + +
+          Returns the input skew of the given signal.
+static intvera_get_in_type(com.newisys.dv.Signal signal) + +
+          Returns the type of input signal is represented by the given signal.
+static java.lang.Stringvera_get_name(com.newisys.dv.Signal signal) + +
+          Return a signal's name.
+static intvera_get_out_skew(com.newisys.dv.Signal signal) + +
+          Returns the output skew of the given signal.
+static intvera_get_out_type(com.newisys.dv.Signal signal) + +
+          Returns the type of output signal is represented by the given signal.
+static intvera_get_width(com.newisys.dv.Signal signal) + +
+          Returns the width of the given signal.
+static booleanvera_is_bound(com.newisys.dv.Signal signal) + +
+          Check if a signal is bound to the design.
+static voidvera_report_profile(int type, + java.lang.String filename) + +
+          NOTE: vera_report_profile is currently unsupported
+static voidwait_child() + +
+          Block until all threads marked as children of the current thread have + exited.
+static voidwarning(java.lang.String warning) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+systemClock

+
+public static com.newisys.dv.ClockSignal systemClock
+
+
Represents the system clock, "CLOCK". It must be initialized before + any classes generated by the translator are loaded. +

+

+
+
+
+ +

+CHECK

+
+public static final int CHECK
+
+
+
See Also:
Constant Field Values
+
+
+ +

+FIRST

+
+public static final int FIRST
+
+
+
See Also:
Constant Field Values
+
+
+ +

+NEXT

+
+public static final int NEXT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+DELETE

+
+public static final int DELETE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+NUM

+
+public static final int NUM
+
+
+
See Also:
Constant Field Values
+
+
+ +

+STR

+
+public static final int STR
+
+
+
See Also:
Constant Field Values
+
+
+ +

+HNUM

+
+public static final int HNUM
+
+
+
See Also:
Constant Field Values
+
+
+ +

+SEMAPHORE

+
+public static final int SEMAPHORE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+REGION

+
+public static final int REGION
+
+
+
See Also:
Constant Field Values
+
+
+ +

+MAILBOX

+
+public static final int MAILBOX
+
+
+
See Also:
Constant Field Values
+
+
+ +

+NO_WAIT

+
+public static final int NO_WAIT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+WAIT

+
+public static final int WAIT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+COPY_NO_WAIT

+
+public static final int COPY_NO_WAIT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+COPY_WAIT

+
+public static final int COPY_WAIT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OFF

+
+public static final int OFF
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ON

+
+public static final int ON
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ONE_SHOT

+
+public static final int ONE_SHOT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ONE_BLAST

+
+public static final int ONE_BLAST
+
+
+
See Also:
Constant Field Values
+
+
+ +

+HAND_SHAKE

+
+public static final int HAND_SHAKE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ALL

+
+public static final int ALL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ANY

+
+public static final int ANY
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ORDER

+
+public static final int ORDER
+
+
+
See Also:
Constant Field Values
+
+
+ +

+VERBOSE

+
+public static final int VERBOSE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+SILENT

+
+public static final int SILENT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+RAWIN

+
+public static final int RAWIN
+
+
+
See Also:
Constant Field Values
+
+
+ +

+LO

+
+public static final int LO
+
+
+
See Also:
Constant Field Values
+
+
+ +

+HI

+
+public static final int HI
+
+
+
See Also:
Constant Field Values
+
+ + + + + + + + +
+Constructor Detail
+ +

+Juno

+
+public Juno()
+
+
+ + + + + + + + +
+Method Detail
+ +

+initialize

+
+public static void initialize()
+
+
+
+
+
+
+ +

+initArray

+
+public static <T> T[] initArray(T[] array,
+                                T value,
+                                int start)
+
+
Initializes the given Object array with the given value, starting at the + given index and continuing to the end of the array. +

+

+
Type Parameters:
T - the array element type
Parameters:
array - the array to initialize
value - the initial value
start - the starting index +
Returns:
the given array
+
+
+
+ +

+initArray

+
+public static <T> T[] initArray(T[] array,
+                                ValueFactory<T> factory,
+                                int start)
+
+
Initializes the given Object array with values from the given factory, + starting at the given index and continuing to the end of the array. +

+

+
Type Parameters:
T - the array element type
Parameters:
array - the array to initialize
factory - the factory providing initial values
start - the starting index +
Returns:
the given array
+
+
+
+ +

+copyArray

+
+public static <T> T[] copyArray(T[] dstArray,
+                                T[] srcArray,
+                                T initExtra)
+
+
Copies the given source array into the given destination array, and + initializes any extra elements in the destination array with the given + value. +

+

+
Type Parameters:
T - the array element type
Parameters:
dstArray - the array to copy into
srcArray - the array to copy from
initExtra - value used to initialize the rest of the destination + array, if the source array is shorter +
Returns:
the destination array
+
+
+
+ +

+copyArray

+
+public static <T> T[] copyArray(T[] dstArray,
+                                T[] srcArray,
+                                ValueFactory<T> factory)
+
+
Clones the elements in the given source array into the given destination + array, and initializes any extra elements in the destination array, using + the given value factory. +

+

+
Type Parameters:
T - the array element type
Parameters:
dstArray - the array to copy into
srcArray - the array to copy from
factory - the value factory used to copy and initialize values +
Returns:
the destination array
+
+
+
+ +

+badCast

+
+public static void badCast()
+
+
+
+
+
+
+ +

+equals

+
+public static boolean equals(java.lang.Object o1,
+                             java.lang.Object o2)
+
+
+
+
+
+
+ +

+assoc_index

+
+public static int assoc_index(int op,
+                              AssocArray<?,?> array)
+
+
assoc_index built-in function for dealing with entire arrays. +

+ If op == CHECK, this method returns the number of elements in array. +

+ If op == DELETE, this method deletes all elements in array. +

+

+

+
Parameters:
op - Either CHECKor DELETE
array - the array on which to perform the operation +
Returns:
the size of the array if op == CHECK or a 1 if op == DELETE
See Also:
assoc_index(int, AssocArray, Object), +assoc_index(int, AssocArray, Object[])
+
+
+
+ +

+assoc_index

+
+public static int assoc_index(int op,
+                              AssocArray array,
+                              java.lang.Object index)
+
+
assoc_index built-in function for dealing with array elements. +

+ If op == CHECK, return whether or not array[index] is valid. +

+ If op == DELETE, invalidate array[index] if it exists. +

+

+

+
Parameters:
op - Either CHECKor DELETE
array - the array on which to perform the operation
index - the index of array on which to perform op +
Returns:
if op == CHECK, return 0 if index in array is valid, 0 if it is + not valid. if op == DELETE, return 1 if the element at index was + removed from the array, and 0 if the element was not found in the + array. +
Throws: +
java.lang.IllegalArgumentException - if index is null, or is a BitVector + containing an X/Z value, or index is not either a BitVector, + String or JunoString object
See Also:
assoc_index(int, AssocArray), +assoc_index(int, AssocArray, Object[])
+
+
+
+ +

+assoc_index

+
+public static int assoc_index(int op,
+                              AssocArray array,
+                              int[] index_ref)
+
+
See assoc_index(int, AssocArray, Object[]). This method is + identical except the type of index_ref is + int[]. +

+

+
Parameters:
op - Either FIRSTor NEXTor CHECK or + DELETE
array - the array on which to perform the operation
index_ref - an array holding a reference to the index of + array on which to perform op +
Returns:
see assoc_index(int, AssocArray, Object[]) +
Throws: +
java.lang.IllegalArgumentException - if index_ref is null or contains more + than 1 element
+
+
+
+ +

+assoc_index

+
+public static int assoc_index(int op,
+                              AssocArray array,
+                              java.lang.Object[] index_ref)
+
+
assoc_index built-in function for dealing with array elements. +

+ If op == FIRST, index_ref[0] is set to the first valid index of the + array. If a valid first element is found, a 1 is returned and + index_ref[0] is set to that element. If not, a 0 is returned and + index_ref[0] is left unchanged. +

+ If op == NEXT, index_ref[0] is set to the next valid index of the array. + If a valid next element is found, a 1 is returned and index_ref[0] is set + to that element. If not, a 0 is returned and index_ref[0] is left + unchanged. +

+ If op == CHECK, return whether or not array[index] exists. If it does, a + 1 is returned. If not, a 0 is returned. +

+ If op == DELETE, invalidate array[index] if it exists. If it is + successful, a 1 is returned. If the element did not exist, a 0 is + returned. +

+

+

+
Parameters:
op - Either FIRSTor NEXTor CHECK or + DELETE
array - the array on which to perform the operation
index_ref - an array holding a reference to the index of + array on which to perform op +
Returns:
see above +
Throws: +
java.lang.IllegalArgumentException - if index_ref is null or contains more + than 1 element, or if index_ref[0] is a BitVector containing + an X/Z value, or index_ref[0] is not either a BitVector, + String or JunoString object
See Also:
assoc_index(int, AssocArray)
+
+
+
+ +

+getProperties

+
+public static java.util.Properties getProperties()
+
+
Returns a clone of the Properties from jove.ini and command line. +

+

+ +
Returns:
a clone of the Properties.
+
+
+
+ +

+get_plus_arg

+
+public static com.newisys.verilog.util.BitVector get_plus_arg(int op,
+                                                              java.lang.String name)
+
+
Returns a plusarg value as defined in jove.ini or on the command line. +

+

+
Parameters:
op - one of CHECK, NUM, STR, or + HNUM which determines how the value associated with a given + plusarg is interpreted.
name - A String containing the name of the property to be queried. A + good practice is end this String with '=' (e.g. "txns="). +
Returns:
A BitVector containing the user-specified value for the plusarg + described by name interpreted as described by op. If name was not + specified by the user, a BitVector of value 32'h0 is returned.
+
+
+
+ +

+alloc

+
+public static int alloc(int type,
+                        int id,
+                        int count)
+
+
alloc built-in function for allocating a REGION or a MAILBOX. +

+ This method allocates either a region or a mailbox, based on type. If id + is 0, the next available id is used. This method attempts to allocate + count region/mailboxes. +

+ If successful, the return value is the id of the first object. If id was + 0, this will be a non-zero value. If id was non-zero, this will be + identical to id. The objects are allocated contiguously so allocating N + objects will result in N valid contiguous values, starting at the id + returned. +

+ When the allocation cannot be performed (e.g. there are no more + regions/mailboxes or count is greater than the maximum number of + regions/mailboxes available) a RuntimeException will occur. +

+

+
Parameters:
type - one of either MAILBOXor REGION
id - the base id to use. If 0, use the next available id.
count - the number of objects to create. +
Returns:
the id of the first object created. +
Throws: +
java.lang.IllegalArgumentException - if count <= 0
+
+
+
+ +

+alloc

+
+public static int alloc(int type,
+                        int id,
+                        int count,
+                        int keyCount)
+
+
alloc built-in function for allocating a REGION or a MAILBOX. +

+ This method allocates a semaphore. If id is 0, the next available id is + used. This method attempts to allocate count semaphores. +

+ If successful, the return value is the id of the first semaphore. If id + was 0, this will be a non-zero value. If id was non-zero, this will be + identical to id. The semaphore are allocated contiguously so allocating N + semaphores will result in N valid contiguous values, starting at the id + returned. +

+ When the allocation cannot be performed (e.g. there are no more + semaphores or count is greater than the maximum number of semaphores + available) a RuntimeException will occur. +

+

+
Parameters:
type - should be SEMAPHORE
id - the base id to use. If 0, use the next available id.
count - the number of semaphores to create.
keyCount - the number of keys initially available in each semaphore +
Returns:
the id of the first semaphore created. +
Throws: +
java.lang.IllegalArgumentException - if count <= 0
+
+
+
+ +

+semaphore_put

+
+public static void semaphore_put(int semaphore_id,
+                                 int keyCount)
+
+
Release the specified number of keys to the specified semaphore. +

+

+
Parameters:
semaphore_id - the semaphore to which the keys should be released
keyCount - the number of keys to release
+
+
+
+ +

+semaphore_get

+
+public static int semaphore_get(int op,
+                                int semaphore_id,
+                                int keyCount)
+
+
Acquire one or more keys from a given semaphore. +

+

+
Parameters:
op - One of WAIT or NO_WAIT. If op == WAIT, the + thread will block until keyCount keys can be acquired from the semaphore. + If op == NO_WAIT, the thread will not block and the return value can be + examined to check for success.
semaphore_id - The Semaphore ID on which to operate.
keyCount - The number of keys that should be acquired from the + semaphore. +
Returns:
1 if keyCount keys were successfully acquired from the semaphore, + 0 otherwise.
+
+
+
+ +

+region_enter

+
+public static int region_enter(int op,
+                               int region_id,
+                               java.lang.Object[] values)
+
+
NOTE: region_enter is currently unsupported. +

+

+
Parameters:
op - One of WAIT or NO_WAIT. If op == WAIT, the + thread will block until the region can be entered. If op == NO_WAIT, the + thread will not block and the return value can be examined to check for + success.
region_id - The Region ID on which to operate.
values - An array of values to acquire. +
Returns:
1 if the region was successfully entered, 0 otherwise.
+
+
+
+ +

+region_exit

+
+public static void region_exit(int region_id,
+                               java.lang.Object[] values)
+
+
NOTE: region_exit is currently unsupported. +

+

+
Parameters:
region_id - The Region ID on which to operate.
values - An array of values to release.
+
+
+
+ +

+mailbox_put

+
+public static void mailbox_put(int mailbox_id,
+                               java.lang.Object data)
+
+
Put an object into a given mailbox. +

+

+
Parameters:
mailbox_id - The Mailbox ID in which to put the object.
data - The object to put into the mailbox.
+
+
+
+ +

+mailbox_get

+
+public static int mailbox_get(int op,
+                              int mailbox_id)
+
+
Returns the size of the given mailbox. +

+ This is equivalent to calling mailbox_get(op, mailbox_id, null, 1); +

+

+
Parameters:
op - One of WAIT, NO_WAIT COPY_WAIT, or + COPY_NO_WAIT. If op is WAIT or COPY_WAIT and the mailbox is + empty, the thread will block until the mailbox is non-empty. At that time + the number of elements in the mailbox is returned. If NO_WAIT or COPY_NO_WAIT + is specified, the number of elements in the mailbox is returned and the + thread will not block.
mailbox_id - The Mailbox ID on which to operate. +
Returns:
the size of the given mailbox.
+
+
+
+ +

+mailbox_get

+
+public static int mailbox_get(int op,
+                              int mailbox_id,
+                              java.lang.Object[] data_ref)
+
+
Retrieve an object from a given mailbox. +

+ This is equivalent to calling mailbox_get(op, mailbox_id, data_ref, 1); +

+

+
Parameters:
op - One of WAIT, NO_WAIT COPY_WAIT, or + COPY_NO_WAIT. If op is WAIT or COPY_WAIT, the thread will block + until data is available in the mailbox. Otherwise, the thread will not + block and the return value can be examined to check for success. If op + is COPY_WAIT or COPY_NO_WAIT and there is data in the mailbox, the data + will be copied to data_ref[0], but will not be removed from the mailbox. + The next request will get the same object. However, op == WAIT or NO_WAIT, + the data will be removed from the mailbox.
mailbox_id - The Mailbox ID on which to operate.
data_ref - An array into which the returned object will be placed. If + this value is null, op is ignored and the current size of the mailbox is + returned. +
Returns:
Returns the number of entries in the mailbox, or -1 if there is + a type mismatch.
+
+
+
+ +

+mailbox_get

+
+public static int mailbox_get(int op,
+                              int mailbox_id,
+                              java.lang.Object[] data_ref,
+                              int check)
+
+
Retrieve an object from a given mailbox. +

+

+

+
Parameters:
op - One of WAIT, NO_WAIT COPY_WAIT, or + COPY_NO_WAIT. If op is WAIT or COPY_WAIT, the thread will block + until data is available in the mailbox. Otherwise, the thread will not + block and the return value can be examined to check for success. If op + is COPY_WAIT or COPY_NO_WAIT and there is data in the mailbox, the data + will be copied to data_ref[0], but will not be removed from the mailbox. + The next request will get the same object. However, op == WAIT or NO_WAIT, + the data will be removed from the mailbox.
mailbox_id - The Mailbox ID on which to operate.
data_ref - An array into which the returned object will be placed. If + this value is null, the current size of the mailbox is returned. Note + that in the case of data_ref being null, if op is WAIT or COPY_WAIT and + the mailbox is empty, the thread will block.
check - If set to 1 and the type of object in the mailbox is + incompatible with the type of object in data_ref[0], a -1 is returned and + the data is left in the mailbox. If such a type mismatch occurs and check + is 0, an exception will be thrown. +
Returns:
Returns the number of entries in the mailbox, or -1 if there is + a type mismatch and check is set to 1.
+
+
+
+ +

+trigger

+
+public static void trigger(JunoEvent... events)
+
+
Triggers one or more JunoEvents in ONE_SHOT mode. +

+

+
Parameters:
events - An array of JunoEvent objects that should be triggered.
+
+
+
+ +

+trigger

+
+public static void trigger(int op,
+                           JunoEvent... events)
+
+
Triggers one or more JunoEvents. +

+

+
Parameters:
op - One of OFF, ON, ONE_SHOT, + ONE_BLAST, and HAND_SHAKE.
events - An array of JunoEvent objects that should be triggered.
+
+
+
+ +

+sync

+
+public static int sync(int op,
+                       JunoEvent... events)
+
+
Wait on a given set of JunoEvents to occur.

+ Description of operation for various values of op: +

    +
  • CHECK - Check each JunoEvent in events. If any JunoEvent is OFF, return + 0, else return 1. +
  • ALL - Block until each JunoEvent in events has been triggered. +
  • ANY - Block until any JunoEvent in events has been triggered. +
  • ORDER - Block until each JunoEvent in events has been triggered in + the order they appear in the events array. +
+

+ TBD: under which circumstances do events which have occured before the + sync call satisfy the sync? +

+

+
Parameters:
op - One of CHECK, ALL, ANY, or ORDER.
events - An array of JunoEvents on which to sync. +
Returns:
if op == CHECK and any of the JunoEvents in events are OFF, a 0 + is returned, else a 1 is returned.
+
+
+
+ +

+enter_context

+
+public static void enter_context()
+
+
Enter a new thread context. This helps manage which threads should be + waited on during a wait_child() call. +

+

+
+
+
+
+ +

+leave_context

+
+public static void leave_context()
+
+
Leave a thread context. This helps manage which threads should be + waited on during a wait_child() call. +

+

+
+
+
+
+ +

+fork

+
+public static com.newisys.eventsim.SimulationThread fork(java.lang.Runnable r)
+
+
Fork a new thread of execution. +

+

+
Parameters:
r - the Runnable that will be executed in the new Thread. +
Returns:
a new SimulationThread which will run Runnable r.
+
+
+
+ +

+fork

+
+public static com.newisys.eventsim.SimulationThread fork(java.lang.String name,
+                                                         java.lang.Runnable r)
+
+
Fork a new thread of execution. +

+

+
Parameters:
name - a String identifier for the Thread
r - the Runnable that will be executed in the new Thread. +
Returns:
a new SimulationThread which will run Runnable r.
+
+
+
+ +

+wait_child

+
+public static void wait_child()
+
+
Block until all threads marked as children of the current thread have + exited. +

+

+
+
+
+
+ +

+dumpStack

+
+public static void dumpStack(java.io.OutputStream oStream)
+
+
+
+
+
+
+ +

+psprintf

+
+public static java.lang.String psprintf(java.lang.String format,
+                                        java.lang.Object... args)
+
+
psprintf built-in function. +

+ This method is akin to C's printf() with a few differences: +

    + non-C format specs +
      +
    • %b binary +
    • %p prints name of the main program +
    • %m prints hierarchical trace, from main() to context of psprintf +
    • %v prints instance path of the Vera shell +
    • %_ prints path separator for the current simulator +
    +

    + Conversion notes:
    + enumeration literals are printed as numeric values. enumeration variables + are printed as (ENUM_VAR:XXXXXXXX) as described below +

    +

      +
    • Conversions to binary (%b) +
        +
      • x/z values are printed in lowercase +
      • prints ASCII representation of strings in binary with + string.charAt(0) residing in the MSB of the bit vector. each char has its + bits reversed. Thus the string "AF" 0x41, 0x46 is represented as: + 1000_0010_0110_0010 (0x82, 0x62) in string +
      • prints enumerations as "(ENUM_VAR:XXXXXXXX)", with X being 0-f +
      • prints null or void as "(NULL)" +
      +
    • Conversions to character (%c) +
        +
      • prints character representation of lowest byte of int/BitVector +
      • X/Z values print empty strings +
      • prints first character of a string +
      • prints empty string for enumerations +
      • prints null or void as "(NULL)" +
      +
    • Conversions to signed decimal (%d, %i) +
        +
      • prints Integer as a signed value +
      • prints BitVector as an unsigned value +
      • prints quantities with X/Z as "?" +
      • prints enumerations as "(ENUM_VAR:XXXXXXXXXX)", with X being 0-9 +
      • for strings, each character is converted to a decimal value and + these are concatenated together. this is just silly. +
      • prints null or void as "(NULL)" +
      +
    • Conversions to hexadecimal (%h, %x) +
        +
      • X/Z values are printed in uppercase +
      • hex digits are printed in lowercase +
      • prints strings as empty string +
      • prints enumerations as "(ENUM_VAR:XXXXXXXX)", with X being 0-f +
      • prints null or void as "(NULL)" +
      +
    • Conversions to stack trace (%m) +
        +
      • format width specifies how many stack frames prior to printfcontext + to omit. for instance A()->B()->C()->printf("%1m") will print a stack + trace of A()->B() +
      +
    • Conversions to octal (%o) +
        +
      • all Z's in a 3-bit quantity prints "Z" +
      • all X's in a 3-bit quantity prints "X" +
      • any 0/1/X/Z combination in a 3-bit quantity prints "?" +
      • for strings, each character is converted to an octal value and these + are concatenated together +
      • with no width specifier, 12 octal digits are printed +
      • prints null or void as "(NULL)" +
      +
    • Conversions to program name (%p) +
        +
      • TODO: need to document printf %p specifier +
      +
    • Conversions to string (%s) +
        +
      • prints integers as 4 characters -- 1 per byte +
      • quantities with X/Z values print empty strings +
      • prints integers/bit vectors/bits as their ASCII representation, as + though they were a string in memory (for instance, 16'4B4A is printed as + "KJ"). vectors that are not a multiple of 4 bits are zero-padded +
      • prints enumerations as their "string name" (e.g. "red") +
      • prints null or void as "(NULL)" +
      +
    • Conversions to unsigned decimal (%u) +
        +
      • prints 32 bit values as an unsigned quantities +
      • otherwise behaves as (%d, %i) +
      +
    + + Note that the sequence "\\" is not unescaped by this function. +

    +

    +
    Parameters:
    format - the format specifier to use
    args - an array of Objects to be used when processing format + specifiers +
    Returns:
    the resulting String
    +
    +
+
+ +

+sprintf

+
+public static void sprintf(JunoString str,
+                           java.lang.String format,
+                           java.lang.Object... args)
+
+
sprintf built-in function. +

+ Note that the sequence "\\" is not unescaped by this function. +

+

+
Parameters:
str - the String to assign into
format - the psprintf format to use
args - the arguments to be used when processing the format string
See Also:
psprintf(String, Object[])
+
+
+
+ +

+sscanf

+
+public static void sscanf(java.lang.String str,
+                          java.lang.String format,
+                          java.lang.Object[] args,
+                          java.lang.Class[] types)
+
+
built-in sscanf function. This function takes two strings -- a + source string and a format string. It then tries to parse the source + string based on the format string, extracting various pieces based on + the format string. +

+

+
Parameters:
str - The source string which should not contain format specifiers.
format - The format string which is used to parse the source string.
args - The array in which Objects matching the format specifiers of + the format string should be put.
types - An array describing the types to which each extracted arg + should be converted. +
Throws: +
java.lang.RuntimeException - if the extracted object cannot be converted to + the desired type.
+
+
+
+ +

+printf

+
+public static void printf(java.lang.String format,
+                          java.lang.Object... args)
+
+
printf built-in function. +

+ This method prints the results of psprintf(format, args) to + System.out. +

+

+
Parameters:
format - the psprintf format to use
args - the arguments to be used when processing the format string
See Also:
psprintf(String, Object[])
+
+
+
+ +

+fopen

+
+public static int fopen(java.lang.String filename,
+                        java.lang.String mode)
+
+
fopen built-in function +

+ This method opens a file in a given mode and returns an file descriptor + suitable for passing to other file I/O methods. It calls + fopen(String,String,int) with a third parameter of + VERBOSE. +

+

+
Parameters:
filename - the name of the file to open
mode - one of "r", "w", or "a" +
Returns:
a file descriptor
+
+
+
+ +

+fopen

+
+public static int fopen(java.lang.String filename,
+                        java.lang.String mode,
+                        int verbose)
+
+
fopen built-in function +

+ This method opens a file in a given mode and returns an file descriptor + suitable for passing to other file I/O methods. +

+ Some notes: +

    +
  • Legal Modes +
      +
    • "r": open the file for reading +
    • "w": open the file for writing, truncating if the file exists, + creating it otherwise. +
    • "a": open the file for writing, appending to it if the file exists, + creating it otherwise. +
    • all other characters are illegal +
    +
  • Implementation Details +
      +
    • The legal mode characters are read in order. The first legal + character is the mode used. +
    • If an illegal character comes after a legal character it is ignored + even with VERBOSE specified. +
    • Legal characters can be repeated without errors +
    • If an illegal character is the first character in mode, fopen will + fail and return a 0. if VERBOSE is enabled, an error message with stack + trace is dumped, and program execution continues +
    +
+

+

+
Parameters:
filename - the name of the file to open
mode - one of "r", "w", or "a"
verbose - one of VERBOSEor SILENT +
Returns:
a file descriptor
+
+
+
+ +

+fclose

+
+public static void fclose(int fd)
+
+
fclose built-in function. +

+ Closes the file descriptor fd. If fd is an invalid descriptor, this + method silently succeeds. Attempts to close built in the streams, + STDIN,STDOUT, and STDERRare ignored. +

+

+
Parameters:
fd - the file descriptor to close
+
+
+
+ +

+fprintf

+
+public static void fprintf(int fd,
+                           java.lang.String format,
+                           java.lang.Object... args)
+
+
fprintf built-in function. +

+ This method prints the results of psprintf(format, args) to the file + described by fd. +

+ If fd is invalid or is STDIN, a RuntimeException occurs. + Further, if fd has been opened in read mode, the call to fprintf is + ignored and the ferror status for fd is set to true. +

+

+
Parameters:
fd - the file descriptor to which to write
format - the fprintf format to use
args - the arguments to be used when processing the format string
See Also:
psprintf(String, Object[])
+
+
+
+ +

+freadb

+
+public static com.newisys.verilog.util.BitVector freadb(int fd,
+                                                        int mode)
+
+
Reads a binary value from a file and returns the corresponding BitVector. + Comments and lines containing only whitespace are ignored. If the mode is + VERBOSE, a message will be printed when the end of file is detected. +

+ Each valid line of the file should correspond to the regular expression: + ([01_])+ +

+

+
Parameters:
fd - The file descriptor from which to read.
mode - One of VERBOSE or SILENT +
Returns:
a BitVector having the value of the binary value read from the + file or null if an error occurs.
+
+
+
+ +

+freadh

+
+public static com.newisys.verilog.util.BitVector freadh(int fd,
+                                                        int mode)
+
+
Reads a hexadecimal value from a file and returns the corresponding BitVector. + Comments and lines containing only whitespace are ignored. If the mode is + VERBOSE, a message will be printed when the end of file is detected. +

+ Each valid line of the file should correspond to the regular expression: + ([A-Za-z0-9_])+ +

+

+
Parameters:
fd - The file descriptor from which to read.
mode - One of VERBOSE or SILENT +
Returns:
a BitVector having the value of the hexadecimal value read from + the file or null if an error occurs.
+
+
+
+ +

+freadstr

+
+public static java.lang.String freadstr(int fd)
+
+
freadstr built-in function. +

+ This call is equivalent to freadstr(fd, Vera.VERBOSE); +

+

+

+
Parameters:
fd - +
Returns:
the string read from the file
See Also:
freadstr(int, int)
+
+
+
+ +

+freadstr

+
+public static java.lang.String freadstr(int fd,
+                                        int mode)
+
+
freadstr built-in function. +

+ Read a line from a file and return it as a String. +

+

    + Modes +
  • VERBOSEUpon reaching EOF, a warning is printed and a null + string is returned. +
  • SILENTUpon reaching EOF, a null string is returned, but no + warning is printed. +
  • RAWINIdentical to SILENT except blank lines and comments + are not filtered out. +
+ Both VERBOSE and SILENT modes will filter out lines containing only + whitespace and comments. All modes will set the ferror status of fd to + true upon reaching the end of file. +

+ Passing an invalid file descriptor or a file descriptor that was not + opened in read mode will result in a RuntimeException. +

+

+
Parameters:
fd - the file descriptor from which to read
mode - one of VERBOSE,SILENT, or RAWIN +
Returns:
the string read from the file
+
+
+
+ +

+fflush

+
+public static void fflush(int fd)
+
+
fflush built-in function. +

+ Flush any buffered output to the file described by fd. +

+ If fd describes a file opened in read mode or STDIN, fflush + returns immediately. If fd is invalid, a RuntimeException is thrown. +

+

+
Parameters:
fd - the file descriptor to flush
+
+
+
+ +

+rewind

+
+public static void rewind(int fd)
+
+
rewind built-in function. +

+ Returns the file pointer associated with fd to the beginning of the file. +

+ For STDIN,STDOUT, and STDERR, this method + returns immediately. If fd is an invalid file descriptor, a + RuntimeException is thrown. +

+ Calling this method clears the ferror status of fd. This is the only way + to clear this error status, short of closing the file and reopening it. +

+

+
Parameters:
fd - the file descriptor to rewind.
+
+
+
+ +

+lock_file

+
+public static boolean lock_file(java.lang.String filename,
+                                int timeout)
+
+
lock_file built-in function. +

+ Locks a file for use by this JVM only. +

+ lock_file creates a file, <filename>.lock_file any further attempts + to lock the file by the same process are successful. attempts by another + process to lock the file will block timeout seconds, or forever if + timeout == 0. further, if <filename>.lock_file exists but is empty, + the lock_file attempt times out or blocks as specified by the timeout + parameter. if filename is a directory, the lock file is written in the + parent directory of the dir. if write access is not allowed in that + directory, a RuntimeException is thrown. +

+ Note: This implementation does not use PIDs as they aren't really used by + Vera anyway +

+

+
Parameters:
filename - the name of the file to lock
timeout - the timeout value in seconds, or 0 for no timeout. +
Returns:
true if the file was locked, false if a timeout occurred
See Also:
unlock_file(String)
+
+
+
+ +

+unlock_file

+
+public static void unlock_file(java.lang.String filename)
+
+
unlock_file built-in function +

+ unlock_file removes <filename>.lock_file, even if it is not the + locking JVM. +

+ Note: Vera puts its UNIX PID in the lockfile. Then when lock_file() is + called, if the lockfile exists, and the PID doesn't match, the lock + blocks. However, any UNIX PID can call unlock_file on the file and remove + the lockfile. This would make the whole business of putting the PID in + the file moot. For this reason, PIDs are not used in this implementation. +

+

+

+
Parameters:
filename - the filename to unlock
See Also:
lock_file(String, int)
+
+
+
+ +

+feof

+
+public static boolean feof(int fd)
+
+
feof built-in function. +

+ Check if fd is at the end of the file. +

+ Notes: These are valid as of Vera 6.2.15. Vera dumps stack and dies if fd == + STDIN +

+ Vera behaves strangely if fd == STDOUT || fd == STDERR: + +

+   integer foo = feof([23]); // this SIGSEGVs
+   printf("%0d\n", feof([23])); // this prints a cryptic printf err
+ 
+ +

+ Vera dumps stack and dies if fd is not a valid file descriptor +

+ This implementation returns false if fd is STDIN, STDOUT, or STDERR. If + fd is an invalid descriptor, a RuntimeException is thrown. If fd + describes a file not opened in read mode, false is returned. +

+

+
Parameters:
fd - the file descriptor on which to check for the EOF condition +
Returns:
true if the file described by fd is at the end of file, false + otherwise.
+
+
+
+ +

+ferror

+
+public static boolean ferror(int fd)
+
+
ferror built-in function +

+ This method returns the ferror status of a file descriptor. +

+ A file descriptors ferror status becomes true when +

+ A file descriptors ferror status becomes false when +
    +
  • the file is first opened +
  • rewind(int)is called on the file descriptor +
+

+ If fd is an invalid file descriptor, a RuntimeException will be thrown. +

+

+
Parameters:
fd - the file descriptor on which to check for ferror status +
Returns:
true if an error has occurred on the file descriptor, false + otherwise
+
+
+
+ +

+warning

+
+public static void warning(java.lang.String warning)
+
+
+
+
+
+
+ +

+error

+
+public static void error(java.lang.String format,
+                         java.lang.Object... args)
+
+
error built-in function. +

+ This function prints the string generated by psprintf(format, args) to + System.err and throws a RuntimeException. +

+

+
Parameters:
format - The format specifier to pass to psprintf
args - The arguments for any format specifiers in format +
Throws: +
java.lang.RuntimeException - containing the formatted message
+
+
+
+ +

+error_mode

+
+public static void error_mode(int enable,
+                              int ec)
+
+
NOTE: error_mode is currently unsupported. +

+

+
Parameters:
enable -
ec -
+
+
+
+ +

+flag

+
+public static int flag()
+
+
Returns the status of the internal flag variable. +

+

+ +
Returns:
the flag status
+
+
+
+ +

+flag

+
+public static int flag(int enable)
+
+
Sets and gets the status of the internal flag variable. If enable == -1, + the current flag status is returned. Otherwise, the flag is turned on or + off as specified by enable and the previous flag status is returned. +

+

+
Parameters:
enable - on of either ON, OFF, or -1 +
Returns:
the flag status
+
+
+
+ +

+get_time

+
+public static int get_time(int part)
+
+
Get the current DV.simulation time in ticks. Since the current DV.simulation + time is a 64 bit quantity and this function only returns an int, it takes + a parameter, part, that determines whether the high or low 32 bits of the + current time are returned. +

+

+
Parameters:
part - One of LO or HI +
Returns:
The low or high 32 bits of the current DV.simulation time as specified + by param.
+
+
+
+ +

+get_systime

+
+public static int get_systime()
+
+
Returns the current DV.simulation wall-clock time in seconds. +

+

+ +
Returns:
the wall-clock time of the DV.simulation in seconds.
+
+
+
+ +

+delay

+
+public static void delay(int ticks)
+
+
Block the current thread until the specified number of ticks have occurred. +

+

+
Parameters:
ticks - The number of ticks to wait before resuming this thread.
+
+
+
+ +

+os_command

+
+public static int os_command(java.lang.String command)
+
+
Run a command outside of the Jove environment. +

+

+
Parameters:
command - A String containing the full command to run. +
Returns:
The exit value of the command. +
Throws: +
java.lang.RuntimeException - if an error occurs running the command
+
+
+
+ +

+exit

+
+public static void exit(int status)
+
+
Exit the DV.simulation with the given exit status. +

+

+
Parameters:
status - the exit status
+
+
+
+ +

+srandom

+
+public static void srandom(int seed)
+
+
Creates a new random number generator for the DV.simulation and seeds it with + the given value. +

+

+
Parameters:
seed - the value with which to seed the PRNG.
+
+
+
+ +

+srandom

+
+public static void srandom(int seed,
+                           JunoObject obj)
+
+
Creates a new random number generator for the DV.simulation and seeds it with + the given value. It then associates that random number generated with the + given JunoObject. +

+

+
Parameters:
seed - the value with which to seed the PRNG.
obj - the object with which the new random number generator should be + associated.
+
+
+
+ +

+random

+
+public static int random()
+
+
Return a 32 bit signed random value. +

+

+ +
Returns:
a 32 bit signed random value.
+
+
+
+ +

+random

+
+public static int random(int seed)
+
+
Seeds the random number generator and then returns a 32 bit signed rand + value. This is equivalent to: +

+ srandom(seed); random(); +

+

+
Parameters:
seed - the value with which to seed the PRNG. +
Returns:
a 32 bit signed random value.
+
+
+
+ +

+urandom

+
+public static com.newisys.verilog.util.BitVector urandom()
+
+
Returns a 32 bit unsigned random value. +

+

+ +
Returns:
a 32 bit unsigned random value
+
+
+
+ +

+urandom

+
+public static com.newisys.verilog.util.BitVector urandom(int seed)
+
+
Seeds the random number generator and then returns a 32 bit unsigned rand + value. This is equivalent to: +

+ srandom(seed); urandom(); +

+

+
Parameters:
seed - the value with which to seed the PRNG. +
Returns:
a 32 bit unsigned random value.
+
+
+
+ +

+rand48

+
+public static int rand48()
+
+
Returns a 32 bit signed random value generated using a 48 bit linear + congruential algorithm. +

+

+ +
Returns:
a 32 bit signed random value.
+
+
+
+ +

+rand48

+
+public static int rand48(int seed)
+
+
Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit signed rand value generated from it. +

+

+
Parameters:
seed - the value with which to seed the PRNG. +
Returns:
a 32 bit signed random value.
+
+
+
+ +

+urand48

+
+public static com.newisys.verilog.util.BitVector urand48()
+
+
Returns a 32 bit unsigned random value generated using a 48 bit linear + congruential algorithm. +

+

+ +
Returns:
a 32 bit unsigned random value.
+
+
+
+ +

+urand48

+
+public static com.newisys.verilog.util.BitVector urand48(int seed)
+
+
Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit unsigned rand value generated from it. +

+

+
Parameters:
seed - the value with which to seed the PRNG. +
Returns:
a 32 bit unsigned random value.
+
+
+
+ +

+urandom_range

+
+public static com.newisys.verilog.util.BitVector urandom_range(com.newisys.verilog.util.BitVector maxval)
+
+
Returns a 32 bit unsigned random value between 0 and maxval, inclusive. + If maxval is > 32 bits, only the bottom 32 bits will be used. +

+

+
Parameters:
maxval - The maximum value which the return value can assume. +
Returns:
a 32 bit unsigned random value between 0 and maxval, inclusive.
+
+
+
+ +

+urandom_range

+
+public static com.newisys.verilog.util.BitVector urandom_range(com.newisys.verilog.util.BitVector maxval,
+                                                               com.newisys.verilog.util.BitVector minval)
+
+
Returns a 32 bit unsigned random value between minval and maxval, inclusive. + If maxval or minval is > 32 bits, only the bottom 32 bits will be used. +

+

+
Parameters:
maxval - The maximum value which the return value can assume.
minval - The minimum value which the return value can assume. +
Returns:
a 32 bit unsigned random value between minval and maxval, inclusive.
+
+
+
+ +

+randcase

+
+public static int randcase(int... weights)
+
+
Choose a value based on a weighted randomization. Each index in the + weights array has a value associated with it. This function will randomly + choose an index in weights with each index having a weighting equal to + its value. +

+ As an example if weights is {25, 0, 50}, 0 will be returned 33% of the time, + 1 will be returned 0% of the time, and 2 will be returned 67% of the time. +

+

+
Parameters:
weights - an array in which each index is the weighting of that index. +
Returns:
an index of the array, chosen randomly by weight.
+
+
+
+ +

+vera_is_bound

+
+public static boolean vera_is_bound(com.newisys.dv.Signal signal)
+
+
Check if a signal is bound to the design. +

+

+
Parameters:
signal - The signal to check. +
Returns:
true if the signal is non-null, false otherwise.
+
+
+
+ +

+vera_get_name

+
+public static java.lang.String vera_get_name(com.newisys.dv.Signal signal)
+
+
Return a signal's name. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The name of the given signal.
+
+
+
+ +

+vera_get_ifc_name

+
+public static java.lang.String vera_get_ifc_name(com.newisys.dv.Signal signal)
+
+
NOTE: vera_get_ifc_name is currently unsupported. +

+

+
Parameters:
signal - The Signal to check. +
Returns:
The name of the interface containing signal.
+
+
+
+ +

+vera_get_clk_name

+
+public static java.lang.String vera_get_clk_name(com.newisys.dv.Signal signal)
+
+
Return the name of the clock associated with the given signal. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The name of the clock signal associated with signal.
+
+
+
+ +

+vera_get_dir

+
+public static int vera_get_dir(com.newisys.dv.Signal signal)
+
+
Returns the direction of the given signal. The table below describes the + return value: +

+
+
+ + + +
Return ValueDirection
0Input Signal
1Output Signal
2InOut Signal
+

+

+
Parameters:
signal - The signal to check. +
Returns:
0, 1, or 2 depending on the direction of the signal.
+
+
+
+ +

+vera_get_width

+
+public static int vera_get_width(com.newisys.dv.Signal signal)
+
+
Returns the width of the given signal. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The width of the given signal.
+
+
+
+ +

+vera_get_in_type

+
+public static int vera_get_in_type(com.newisys.dv.Signal signal)
+
+
Returns the type of input signal is represented by the given signal. + The table below describes the + return value: +

+
+
+ + + + +
Return ValueSignal Type
0NSAMPLE
1PSAMPLE
2CLOCK
3DDR
+

+

+
Parameters:
signal - The signal to check. +
Returns:
0, 1, 2, or 3, depending on the type of the signal.
+
+
+
+ +

+vera_get_in_skew

+
+public static int vera_get_in_skew(com.newisys.dv.Signal signal)
+
+
Returns the input skew of the given signal. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The input skew ofthe given signal.
+
+
+
+ +

+vera_get_in_depth

+
+public static int vera_get_in_depth(com.newisys.dv.Signal signal)
+
+
Returns the input depth of the given signal. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The input depth ofthe given signal.
+
+
+
+ +

+vera_get_out_type

+
+public static int vera_get_out_type(com.newisys.dv.Signal signal)
+
+
Returns the type of output signal is represented by the given signal. + The table below describes the + return value: +

+
+
+ + + +
Return ValueSignal Type
0NHOLD
1PHOLD
10DDR
+

+

+
Parameters:
signal - The signal to check. +
Returns:
0, 1, or 10, depending on the type of the signal.
+
+
+
+ +

+vera_get_out_skew

+
+public static int vera_get_out_skew(com.newisys.dv.Signal signal)
+
+
Returns the output skew of the given signal. +

+

+
Parameters:
signal - The signal to check. +
Returns:
The output skew ofthe given signal.
+
+
+
+ +

+vera_report_profile

+
+public static void vera_report_profile(int type,
+                                       java.lang.String filename)
+
+
NOTE: vera_report_profile is currently unsupported +

+

+
Parameters:
type -
filename -
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoEnum.html b/docs/api/com/newisys/juno/runtime/JunoEnum.html new file mode 100644 index 0000000..66102e9 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoEnum.html @@ -0,0 +1,462 @@ + + + + + + +JunoEnum (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Interface JunoEnum<E extends java.lang.Enum<E> & JunoEnum<E>>

+
+
+
public interface JunoEnum<E extends java.lang.Enum<E> & JunoEnum<E>>
+ + +

+Interface implemented by enum types translated from Vera. Provides + Vera-like facilities for conversion, increment/decrement, packing, etc. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ EgetForValue(java.lang.Integer value, + boolean checked) + +
+          Returns the enum constant associated with the specified value.
+ intgetPackedSize() + +
+          Returns the number of bits needed to encode the values of this + enumeration.
+ booleanisDefined() + +
+          Returns whether this value is a defined enumeration value, as opposed to + the special UNDEFINED enumeration value.
+ booleanisSigned() + +
+          Returns whether or not this is a signed enumeration.
+ Enext() + +
+          Returns the enum constant following this one, in declaration order.
+ Enext(int count) + +
+          Returns the n'th enum constant following this one, in declaration order, + wrapping from the last constant to the first as necessary.
+ Eprevious() + +
+          Returns the enum constant preceding this one, in declaration order.
+ Eprevious(int count) + +
+          Returns the n'th enum constant preceding this one, in declaration order, + wrapping from the first constant to the last as necessary.
+ inttoInt() + +
+          Returns the int value corresponding to this enumeration + value.
+ java.lang.IntegertoInteger() + +
+          Returns the Integer value corresponding to this enumeration.
+ java.lang.StringtoString() + +
+          Returns the String representation of this enumeration value.
+  +

+ + + + + + + + +
+Method Detail
+ +

+next

+
+E next()
+
+
Returns the enum constant following this one, in declaration order. + If this is the last enum constant declared, this method returns the + first enum constant. +

+

+ +
Returns:
the next enum constant
+
+
+
+ +

+next

+
+E next(int count)
+
+
Returns the n'th enum constant following this one, in declaration order, + wrapping from the last constant to the first as necessary. Calling + next(1) is equivalent to calling next(). +

+

+
Parameters:
count - the number of constants to advance +
Returns:
the n'th enum constant following this one
+
+
+
+ +

+previous

+
+E previous()
+
+
Returns the enum constant preceding this one, in declaration order. + If this is the first enum constant declared, this method returns the + last enum constant. +

+

+ +
Returns:
the previous enum constant
+
+
+
+ +

+previous

+
+E previous(int count)
+
+
Returns the n'th enum constant preceding this one, in declaration order, + wrapping from the first constant to the last as necessary. Calling + previous(1) is equivalent to calling previous(). +

+

+
Parameters:
count - the number of constants to advance +
Returns:
the n'th enum constant preceding this one
+
+
+
+ +

+getForValue

+
+E getForValue(java.lang.Integer value,
+              boolean checked)
+
+
Returns the enum constant associated with the specified value. If no + enumeration value corresponds the given value and + checked is false, this method throws an + IllegalArgumentException. If there is no corresponding value and + checked is true, this method returns the UNDEFINED value. +

+

+
Parameters:
value - the value corresponding to the desired enum constant
checked - true if the caller will check/handle an + undefined enumeration value, false if this method + should throw an exception +
Returns:
the enum constant corresponding to value, or the + UNDEFINED value if there is none
+
+
+
+ +

+getPackedSize

+
+int getPackedSize()
+
+
Returns the number of bits needed to encode the values of this + enumeration. +

+

+ +
Returns:
the number of bits needed to encode this enumeration
+
+
+
+ +

+isSigned

+
+boolean isSigned()
+
+
Returns whether or not this is a signed enumeration. +

+

+ +
Returns:
true if this enumeration is signed, + false otherwise
+
+
+
+ +

+isDefined

+
+boolean isDefined()
+
+
Returns whether this value is a defined enumeration value, as opposed to + the special UNDEFINED enumeration value. +

+

+ +
Returns:
true if this enumeration value is defined, + false if it is UNDEFINED
+
+
+
+ +

+toInt

+
+int toInt()
+
+
Returns the int value corresponding to this enumeration + value. +

+

+ +
Returns:
the int value corresponding to this enumeration + value
+
+
+
+ +

+toInteger

+
+java.lang.Integer toInteger()
+
+
Returns the Integer value corresponding to this enumeration. For the + UNDEFINED enumeration value, this method returns null. +

+

+ +
Returns:
the Integer value corresponding to this enumeration value
+
+
+
+ +

+toString

+
+java.lang.String toString()
+
+
Returns the String representation of this enumeration value. For the + UNDEFINED enumeration value, this method returns "** UNDEFINED **". +

+

+
Overrides:
toString in class java.lang.Object
+
+
+ +
Returns:
the String representation of this enumeration value
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoEnumUtil.html b/docs/api/com/newisys/juno/runtime/JunoEnumUtil.html new file mode 100644 index 0000000..6bbd2b7 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoEnumUtil.html @@ -0,0 +1,322 @@ + + + + + + +JunoEnumUtil (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoEnumUtil

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoEnumUtil
+
+
+
+
public final class JunoEnumUtil
extends java.lang.Object
+ + +

+Static utility methods used in the implementation of translated enum types. +

+ +

+


+ +

+ + + + + + + + + + + +
+Constructor Summary
JunoEnumUtil() + +
+           
+  + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+E
+
advance(E cur, + int count) + +
+           
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+E
+
forValue(java.lang.Class<E> cls, + java.lang.Integer value, + boolean checked) + +
+           
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+java.lang.String
+
toString(E e) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+JunoEnumUtil

+
+public JunoEnumUtil()
+
+
+ + + + + + + + +
+Method Detail
+ +

+advance

+
+public static <E extends java.lang.Enum<E> & JunoEnum<E>> E advance(E cur,
+                                                                   int count)
+
+
+
+
+
+
+ +

+forValue

+
+public static <E extends java.lang.Enum<E> & JunoEnum<E>> E forValue(java.lang.Class<E> cls,
+                                                                    java.lang.Integer value,
+                                                                    boolean checked)
+
+
+
+
+
+
+ +

+toString

+
+public static <E extends java.lang.Enum<E> & JunoEnum<E>> java.lang.String toString(E e)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoEvent.html b/docs/api/com/newisys/juno/runtime/JunoEvent.html new file mode 100644 index 0000000..3097fec --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoEvent.html @@ -0,0 +1,263 @@ + + + + + + +JunoEvent (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoEvent

+
+java.lang.Object
+  extended by com.newisys.eventsim.Event
+      extended by com.newisys.eventsim.PulseEvent
+          extended by com.newisys.juno.runtime.JunoEvent
+
+
+
+
public class JunoEvent
extends com.newisys.eventsim.PulseEvent
+ + +

+A Jove Event with the semantics of Vera's built-in events. +

+ +

+


+ +

+ + + + + + + + + + + + + + +
+Constructor Summary
JunoEvent() + +
+          Creates a new JunoEvent.
JunoEvent(java.lang.String name) + +
+          Creates a new JunoEvent with the specified name.
+  + + + + + + + +
+Method Summary
+ + + + + + + +
Methods inherited from class com.newisys.eventsim.PulseEvent
hasOccurred
+ + + + + + + +
Methods inherited from class com.newisys.eventsim.Event
toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+JunoEvent

+
+public JunoEvent()
+
+
Creates a new JunoEvent. +

+

+
+ +

+JunoEvent

+
+public JunoEvent(java.lang.String name)
+
+
Creates a new JunoEvent with the specified name. +

+

+
Parameters:
name - the name of this JunoEvent
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoEventValueFactory.html b/docs/api/com/newisys/juno/runtime/JunoEventValueFactory.html new file mode 100644 index 0000000..368788d --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoEventValueFactory.html @@ -0,0 +1,324 @@ + + + + + + +JunoEventValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoEventValueFactory

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoEventValueFactory
+
+
+
All Implemented Interfaces:
ValueFactory<JunoEvent>
+
+
+
+
public final class JunoEventValueFactory
extends java.lang.Object
implements ValueFactory<JunoEvent>
+ + +

+Implements a ValueFactory for JunoEvent objects. +

+ +

+


+ +

+ + + + + + + + + + + +
+Field Summary
+static JunoEventValueFactoryINSTANCE + +
+          A singleton instance of JunoEventValueFactory.
+  + + + + + + + + + + +
+Constructor Summary
JunoEventValueFactory() + +
+           
+  + + + + + + + + + + + + + + + +
+Method Summary
+ JunoEventcopyInstance(JunoEvent other) + +
+          Instantiates a new JunoEvent and returns it.
+ JunoEventnewInstance() + +
+          Instantiates a new JunoEvent and returns it.
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+INSTANCE

+
+public static final JunoEventValueFactory INSTANCE
+
+
A singleton instance of JunoEventValueFactory. +

+

+
+
+ + + + + + + + +
+Constructor Detail
+ +

+JunoEventValueFactory

+
+public JunoEventValueFactory()
+
+
+ + + + + + + + +
+Method Detail
+ +

+newInstance

+
+public JunoEvent newInstance()
+
+
Instantiates a new JunoEvent and returns it. +

+

+
Specified by:
newInstance in interface ValueFactory<JunoEvent>
+
+
+ +
Returns:
a new JunoEvent
+
+
+
+ +

+copyInstance

+
+public JunoEvent copyInstance(JunoEvent other)
+
+
Instantiates a new JunoEvent and returns it. +

+

+
Specified by:
copyInstance in interface ValueFactory<JunoEvent>
+
+
+
Parameters:
other - the JunoEvent to copy. This argument is ignored in this + implementation. +
Returns:
a new JunoEvent
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoObject.PackingPosition.html b/docs/api/com/newisys/juno/runtime/JunoObject.PackingPosition.html new file mode 100644 index 0000000..8a1ea20 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoObject.PackingPosition.html @@ -0,0 +1,312 @@ + + + + + + +JunoObject.PackingPosition (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoObject.PackingPosition

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoObject.PackingPosition
+
+
+
Enclosing class:
JunoObject
+
+
+
+
public static final class JunoObject.PackingPosition
extends java.lang.Object
+ + +

+


+ +

+ + + + + + + + + + + + + + + + + + + +
+Field Summary
+ longindex + +
+           
+ intleft + +
+           
+ intright + +
+           
+  + + + + + + + + + + + + + +
+Constructor Summary
JunoObject.PackingPosition() + +
+           
JunoObject.PackingPosition(long index, + int left, + int right) + +
+           
+  + + + + + + + +
+Method Summary
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+index

+
+public long index
+
+
+
+
+
+ +

+left

+
+public int left
+
+
+
+
+
+ +

+right

+
+public int right
+
+
+
+
+ + + + + + + + +
+Constructor Detail
+ +

+JunoObject.PackingPosition

+
+public JunoObject.PackingPosition()
+
+
+
+ +

+JunoObject.PackingPosition

+
+public JunoObject.PackingPosition(long index,
+                                  int left,
+                                  int right)
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoObject.html b/docs/api/com/newisys/juno/runtime/JunoObject.html new file mode 100644 index 0000000..bd9e754 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoObject.html @@ -0,0 +1,1128 @@ + + + + + + +JunoObject (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoObject

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoObject
+
+
+
All Implemented Interfaces:
com.newisys.randsolver.RandomHooks, java.lang.Cloneable
+
+
+
Direct Known Subclasses:
OVAAssert, OVAEngine, OVAEvent
+
+
+
+
public class JunoObject
extends java.lang.Object
implements java.lang.Cloneable, com.newisys.randsolver.RandomHooks
+ + +

+Base class for all translated Vera classes. Implements the built-in methods + callable on all Vera objects. +

+ +

+


+ +

+ + + + + + + + + + + +
+Nested Class Summary
+static classJunoObject.PackingPosition + +
+           
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Field Summary
+static intCONSTRAINT_MODE_FAIL + +
+           
+static intFAIL + +
+           
+static intOFF + +
+           
+static intOK + +
+           
+static intON + +
+           
+static intRAND_MODE_FAIL + +
+           
+static intREPORT + +
+           
+  + + + + + + + + + + +
+Constructor Summary
JunoObject() + +
+          Creates a new JunoObject.
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ java.lang.Objectclone() + +
+          Creates and returns a copy of this object.
+ intconstraint_mode(int action) + +
+          Toggles the randomization mode of all constraints on this object.
+ intconstraint_mode(int action, + java.lang.String cons) + +
+          Toggles the randomization mode of the specified constraint on this object.
+ voidfinalize() + +
+           
+ intobject_compare(JunoObject other) + +
+          Performs a deep compare of this object with the specified object.
+ JunoObjectobject_copy() + +
+          Performs a deep copy of this JunoObject and returns the new JunoObject.
+ voidobject_print() + +
+          Prints the object instance hierarchy of this object to + Juno.STDOUT.
+ voidobject_print(int fd) + +
+          Prints the object instance hierarchy of this object to the specified + Vera file descriptor.
+ voidobject_print(int fd, + java.lang.String attrs) + +
+          Prints the object instance hierarchy of this object to the specified + Vera file descriptor with the specified attributes.
+ intpack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+ voidpost_pack() + +
+           
+ voidpost_randomize() + +
+          Allows code to be run just after this object has been randomized.
+ voidpost_unpack() + +
+           
+ voidpostRandomize() + +
+          Allows code to be run just after this object is randomized.
+ voidpre_pack() + +
+           
+ voidpre_randomize() + +
+          Allows code to be run just prior to this object being randomized.
+ voidpre_unpack() + +
+           
+ voidpreRandomize() + +
+          Allows code to be run just prior to this object being randomized.
+ intrand_mode(int action) + +
+          Toggles the randomization mode of all random variables in this object.
+ intrand_mode(int action, + java.lang.String var) + +
+          Toggles the randomization mode of the specified random variable in this + object.
+ intrand_mode(int action, + java.lang.String var, + int index) + +
+          Toggles the randomization mode of the specified random variable in this + object.
+ intrandomize() + +
+          Randomize this JunoObject.
+ voidsetRandom(com.newisys.random.PRNG prng) + +
+          Sets the random number generator for this object.
+ intunpack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+FAIL

+
+public static final int FAIL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OK

+
+public static final int OK
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OFF

+
+public static final int OFF
+
+
+
See Also:
Constant Field Values
+
+
+ +

+ON

+
+public static final int ON
+
+
+
See Also:
Constant Field Values
+
+
+ +

+REPORT

+
+public static final int REPORT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+RAND_MODE_FAIL

+
+public static final int RAND_MODE_FAIL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+CONSTRAINT_MODE_FAIL

+
+public static final int CONSTRAINT_MODE_FAIL
+
+
+
See Also:
Constant Field Values
+
+ + + + + + + + +
+Constructor Detail
+ +

+JunoObject

+
+public JunoObject()
+
+
Creates a new JunoObject. +

+

+ + + + + + + + +
+Method Detail
+ +

+clone

+
+public java.lang.Object clone()
+
+
Creates and returns a copy of this object. +

+

+
Overrides:
clone in class java.lang.Object
+
+
+ +
Returns:
a clone of this JunoObject
See Also:
Object.clone()
+
+
+
+ +

+randomize

+
+public final int randomize()
+
+
Randomize this JunoObject. If the constraints on this object are such + that there is no legal combination of random variables to satify those + constraints, FAIL is returned. Otherwise OK is returned. +

+

+
+
+
+ +
Returns:
OK if the randomization was successful or + FAIL if there was an error during randomization.
+
+
+
+ +

+preRandomize

+
+public final void preRandomize()
+
+
Allows code to be run just prior to this object being randomized. This + method calls pre_randomize, which + should be overridden by subclasses needing this functionality. +

+

+
Specified by:
preRandomize in interface com.newisys.randsolver.RandomHooks
+
+
+
+
+
+
+ +

+postRandomize

+
+public final void postRandomize()
+
+
Allows code to be run just after this object is randomized. This + method calls post_randomize, which + should be overridden by subclasses needing this functionality. +

+

+
Specified by:
postRandomize in interface com.newisys.randsolver.RandomHooks
+
+
+
+
+
+
+ +

+pre_randomize

+
+public void pre_randomize()
+
+
Allows code to be run just prior to this object being randomized. + This method should be overridden by subclasses that wish to execute some + code just before this object is randomized. If this object contains + subobjects that are being randomized, the order in which each object's + pre_randomize method is called is undefined. +

+

+
+
+
+
+
+
+
+ +

+post_randomize

+
+public void post_randomize()
+
+
Allows code to be run just after this object has been randomized. + This method should be overridden by subclasses that wish to execute some + code just after this object is randomized. If this object contains + subobjects that are being randomized, the order in which each object's + post_randomize method is called is undefined. +

+

+
+
+
+
+
+
+
+ +

+setRandom

+
+public final void setRandom(com.newisys.random.PRNG prng)
+
+
Sets the random number generator for this object. +

+

+
+
+
+
Parameters:
prng - the random number generator to be used by this object
+
+
+
+ +

+rand_mode

+
+public final int rand_mode(int action)
+
+
Toggles the randomization mode of all random variables in this object. + + If action is ON, all random + variables associated with this object will be enabled. If + action is OFF, all random + variables associated with this object will be disabled. If + action is REPORT a warning is + printed and RAND_MODE_FAIL is returned. +

+

+
+
+
+
Parameters:
action - one of ON, OFF or REPORT +
Returns:
action is returned, unless there is a failure or + action is REPORT, in which case + RAND_MODE_FAIL is returned
+
+
+
+ +

+rand_mode

+
+public final int rand_mode(int action,
+                           java.lang.String var)
+
+
Toggles the randomization mode of the specified random variable in this + object. + + If action is ON, randomization of + var in this instance will be enabled. If action + is OFF, randomization of var in + this instance will be disabled. If action is + REPORT ON will be returned if + var is enabled, OFF otherwise. +

+

+
+
+
+
Parameters:
action - one of ON, OFF or REPORT
var - the variable to check +
Returns:
action is returned, unless there is a failure in which + case RAND_MODE_FAIL is returned
+
+
+
+ +

+rand_mode

+
+public final int rand_mode(int action,
+                           java.lang.String var,
+                           int index)
+
+
Toggles the randomization mode of the specified random variable in this + object. + + If action is ON, randomization of + var in this instance will be enabled. If action + is OFF, randomization of var in + this instance will be disabled. If action is + REPORT ON will be + returned if var is enabled, OFF otherwise. + + The index parameter is used if var is an array. + This feature is currently unsupported and index must be + -1. +

+

+
+
+
+
Parameters:
action - one of ON, OFF or REPORT
var - the variable to check
index - the array index to check. This currently must be -1. +
Returns:
action is returned, unless there is a failure in which + case RAND_MODE_FAIL is returned
+
+
+
+ +

+constraint_mode

+
+public final int constraint_mode(int action)
+
+
Toggles the randomization mode of all constraints on this object. + + If action is ON, all constraints + associated with this object will be enabled. If action is + OFF, all constraints associated with this object + will be disabled. If action is + REPORT a warning is printed and + CONSTRAINT_MODE_FAIL is returned. +

+

+
+
+
+
Parameters:
action - one of ON, OFF or REPORT +
Returns:
action is returned, unless there is a failure or + action is REPORT, in which case + CONSTRAINT_MODE_FAIL is returned
+
+
+
+ +

+constraint_mode

+
+public final int constraint_mode(int action,
+                                 java.lang.String cons)
+
+
Toggles the randomization mode of the specified constraint on this object. + + If action is ON, cons + will be enabled when randomizing this instance. If action is + OFF, all constraints associated with this + object will be disabled. If action is REPORT + a warning is printed and + CONSTRAINT_MODE_FAIL is returned. +

+

+
+
+
+
Parameters:
action - one of ON, OFF or REPORT
cons - the constraint to check +
Returns:
action is returned, unless there is a failure, in + which case CONSTRAINT_MODE_FAIL is returned
+
+
+
+ +

+object_print

+
+public final void object_print()
+
+
Prints the object instance hierarchy of this object to + Juno.STDOUT. + + This is equivalent to calling +

+ object_print(Vera.STDOUT,"") +

+ This method is currently unsupported. +

+

+
+
+
+
+
+
+
+ +

+object_print

+
+public final void object_print(int fd)
+
+
Prints the object instance hierarchy of this object to the specified + Vera file descriptor. + + This is equivalent to calling +

+ object_print(fd,"") +

+ This method is currently unsupported. +

+

+
+
+
+
Parameters:
fd - the file descriptor to which output will be written
+
+
+
+ +

+object_print

+
+public final void object_print(int fd,
+                               java.lang.String attrs)
+
+
Prints the object instance hierarchy of this object to the specified + Vera file descriptor with the specified attributes. + + attrs is a string of space-delimited key=value pairs. Valid + attributes are shown in the table below along with their default values. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keydefault valuedescription
depth0the number of levels of the hierarchy to print
indent4the number of spaces to indent members and array elements
severitylowone of low or high. low + ignores errors encountered during printing
portyesone of yes or no. yes will + print port signals, no will omit them.
formatsee descriptionone of bin, dec, or hex. + bin will have an underscore frequency of 4. the + default is to print integers in decimal, bit vectors and signals + without X/Z values in hexadecimal, and bit vectors and signals + with X/Z values in binary
array_depth20a decimal value specifying the maximum number of array elements + to print
+

+ This method is currently unsupported. +

+

+
+
+
+
Parameters:
fd - the file descriptor to which output will be written
attrs - an attribute string as defined above
+
+
+
+ +

+object_compare

+
+public int object_compare(JunoObject other)
+
+
Performs a deep compare of this object with the specified object. The + comparison includes both super objects and contained objects. Comparisons + are made based on object contents, not based on object references. +

+ This method is currently unsupported. +

+

+
+
+
+
Parameters:
other - the JunoObject to compare against +
Returns:
1 if the two objects are equal, 0 otherwise
+
+
+
+ +

+object_copy

+
+public final JunoObject object_copy()
+
+
Performs a deep copy of this JunoObject and returns the new JunoObject. + The new JunoObject contains deep copies of this JunoObject's super objects + and contained objects. +

+ This method is currently unsupported. +

+

+
+
+
+ +
Returns:
a new deep copy of this JunoObject
+
+
+
+ +

+pack

+
+public final int pack(BitBitAssocArray array,
+                      JunoObject.PackingPosition pos)
+
+
+
+
+
+
+
+
+
+ +

+pre_pack

+
+public void pre_pack()
+
+
+
+
+
+
+
+
+
+ +

+post_pack

+
+public void post_pack()
+
+
+
+
+
+
+
+
+
+ +

+unpack

+
+public final int unpack(BitBitAssocArray array,
+                        JunoObject.PackingPosition pos)
+
+
+
+
+
+
+
+
+
+ +

+pre_unpack

+
+public void pre_unpack()
+
+
+
+
+
+
+
+
+
+ +

+post_unpack

+
+public void post_unpack()
+
+
+
+
+
+
+
+
+
+ +

+finalize

+
+public void finalize()
+
+
+
Overrides:
finalize in class java.lang.Object
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoRuntimeException.html b/docs/api/com/newisys/juno/runtime/JunoRuntimeException.html new file mode 100644 index 0000000..087d183 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoRuntimeException.html @@ -0,0 +1,285 @@ + + + + + + +JunoRuntimeException (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoRuntimeException

+
+java.lang.Object
+  extended by java.lang.Throwable
+      extended by java.lang.Exception
+          extended by java.lang.RuntimeException
+              extended by com.newisys.juno.runtime.JunoRuntimeException
+
+
+
All Implemented Interfaces:
java.io.Serializable
+
+
+
+
public class JunoRuntimeException
extends java.lang.RuntimeException
+ + +

+Exception thrown by the Juno runtime when the original Vera code would have + encountered a Vera runtime error. +

+ +

+

+
See Also:
Serialized Form
+
+ +

+ + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
JunoRuntimeException() + +
+           
JunoRuntimeException(java.lang.String message) + +
+           
JunoRuntimeException(java.lang.String message, + java.lang.Throwable cause) + +
+           
JunoRuntimeException(java.lang.Throwable cause) + +
+           
+  + + + + + + + +
+Method Summary
+ + + + + + + +
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+JunoRuntimeException

+
+public JunoRuntimeException()
+
+
+
+ +

+JunoRuntimeException

+
+public JunoRuntimeException(java.lang.String message)
+
+
+
+ +

+JunoRuntimeException

+
+public JunoRuntimeException(java.lang.Throwable cause)
+
+
+
+ +

+JunoRuntimeException

+
+public JunoRuntimeException(java.lang.String message,
+                            java.lang.Throwable cause)
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoString.html b/docs/api/com/newisys/juno/runtime/JunoString.html new file mode 100644 index 0000000..05a36ee --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoString.html @@ -0,0 +1,1438 @@ + + + + + + +JunoString (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoString

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoString
+
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
+
public final class JunoString
extends java.lang.Object
implements java.lang.Cloneable
+ + +

+An implementation of Vera's built-in string type. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + +
+Field Summary
+static JunoStringNULL + +
+          A constant null string.
+static intOK + +
+          Vera's OK define.
+static intSTR_ERR_OUT_OF_RANGE + +
+          Vera's STR_ERR_OUT_OF_RANGE define.
+static intSTR_ERR_REGEXP_SYNTAX + +
+          Vera's STR_ERR_REGEXP_SYNTAX define.
+  + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
JunoString() + +
+          Creates a new, empty JunoString.
JunoString(JunoString other) + +
+          Creates a new JunoString, which is a copy of other.
JunoString(java.lang.String str) + +
+          Creates a new JunoString, which is a copy of str.
JunoString(java.lang.String str, + int status, + java.util.regex.Matcher matcher) + +
+          Creates a new JunoString, which is a copy of str and has + the specified status and matcher state.
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ JunoStringassign(JunoString other) + +
+          Assigns other to this JunoString.
+ JunoStringassign(java.lang.String str) + +
+          Assigns str to this JunoString.
+ com.newisys.verilog.util.BitVectoratobin() + +
+          Parses this JunoString as a binary value and returns the equivalent + BitVector.
+ com.newisys.verilog.util.BitVectoratohex() + +
+          Parses this JunoString as a hexadecimal value and returns the equivalent + BitVector.
+ intatoi() + +
+          Parses this JunoString as a decimal value and returns the resulting int.
+ com.newisys.verilog.util.BitVectoratooct() + +
+          Parses this JunoString as an octal value and returns the equivalent + BitVector.
+ JunoStringbackref(int index) + +
+          Returns the substring corresponding to the specified capture group of the + previous match.
+ voidbittostr(com.newisys.verilog.util.BitVector bv) + +
+          Assigns the specified BitVector to this JunoString.
+ intcompare(JunoString other) + +
+          Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String).
+ intcompare(java.lang.String other) + +
+          Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String).
+ booleanequals(java.lang.Object obj) + +
+           
+ java.lang.Stringget_status_msg() + +
+          Returns a String representation of the current status of this JunoString.
+ intget_status() + +
+          Returns the status of this JunoString.
+ intgetc(int index) + +
+          Returns the character at the specified index in this JunoString.
+ JunoEventgetChangeEvent() + +
+          Returns a JunoEvent that is notified whenever this JunoString changes.
+ inthash(int size) + +
+          Returns a hash code for this JunoString.
+ inthashCode() + +
+           
+ inticompare(JunoString other) + +
+          Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String).
+ inticompare(java.lang.String other) + +
+          Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String).
+ voiditoa(int i) + +
+          Assigns the specified int to this JunoString.
+ intlen() + +
+          Returns the length of this JunoString.
+ intmatch(JunoString pattern) + +
+          Finds the specified regular expression in this JunoString.
+ intmatch(java.lang.String pattern) + +
+          Finds the specified regular expression in this JunoString.
+ JunoStringpostmatch() + +
+          Returns the substring of this JunoString including all characters after + the end of the previous match.
+ JunoStringprematch() + +
+          Returns the substring of this JunoString including all characters up to + the beginning of the previous match.
+ voidputc(int index, + char c) + +
+          Inserts the specified character into this JunoString at the specified + index.
+ voidputc(int index, + int c) + +
+          Inserts the specified character into this JunoString at the specified + index.
+ voidputc(int index, + java.lang.String s) + +
+          Inserts the first character of the specified String into this JunoString + at the specified index.
+ intsearch(JunoString pattern) + +
+          Searches for the specified pattern in this JunoString.
+ JunoStringsubstr(int start) + +
+          Returns a substring of this JunoString.
+ JunoStringsubstr(int start, + int end) + +
+          Returns a substring of this JunoString.
+ JunoStringthismatch() + +
+          Returns the substring corresponding to the previous match.
+ JunoStringtolower() + +
+          Returns a new JunoString which is a copy of this JunoString will all + characters converted to lower case.
+ java.lang.StringtoString() + +
+          Returns a String containing the contents of this JunoString, or "(NULL)" + if this JunoString contains the null string.
+ java.lang.StringtoStringOrBlank() + +
+          Returns a String containing the contents of this JunoString, or an empty + string if this JunoString contains the null string.
+ java.lang.StringtoStringOrNull() + +
+          Returns a String containing the contents of this JunoString, or null if + this JunoString contains the null string.
+ JunoStringtoupper() + +
+          Returns a new JunoString which is a copy of this JunoString will all + characters converted to upper case.
+ + + + + + + +
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+NULL

+
+public static final JunoString NULL
+
+
A constant null string. +

+

+
+
+
+ +

+OK

+
+public static final int OK
+
+
Vera's OK define. +

+

+
See Also:
Constant Field Values
+
+
+ +

+STR_ERR_OUT_OF_RANGE

+
+public static final int STR_ERR_OUT_OF_RANGE
+
+
Vera's STR_ERR_OUT_OF_RANGE define. +

+

+
See Also:
Constant Field Values
+
+
+ +

+STR_ERR_REGEXP_SYNTAX

+
+public static final int STR_ERR_REGEXP_SYNTAX
+
+
Vera's STR_ERR_REGEXP_SYNTAX define. +

+

+
See Also:
Constant Field Values
+
+ + + + + + + + +
+Constructor Detail
+ +

+JunoString

+
+public JunoString()
+
+
Creates a new, empty JunoString. +

+

+
+ +

+JunoString

+
+public JunoString(java.lang.String str)
+
+
Creates a new JunoString, which is a copy of str. +

+

+
Parameters:
str - the String to copy
+
+
+ +

+JunoString

+
+public JunoString(java.lang.String str,
+                  int status,
+                  java.util.regex.Matcher matcher)
+
+
Creates a new JunoString, which is a copy of str and has + the specified status and matcher state. +

+

+
Parameters:
str - the String to copy
status - one of OK, STR_ERR_OUT_OF_RANGE, or + STR_ERR_REGEXP_SYNTAX
matcher - a Matcher to be used in JunoString's various match methods
+
+
+ +

+JunoString

+
+public JunoString(JunoString other)
+
+
Creates a new JunoString, which is a copy of other. +

+

+
Parameters:
other - the JunoString to copy
+
+ + + + + + + + +
+Method Detail
+ +

+getChangeEvent

+
+public JunoEvent getChangeEvent()
+
+
Returns a JunoEvent that is notified whenever this JunoString changes. +

+

+
+
+
+ +
Returns:
the change event for this JunoString
+
+
+
+ +

+assign

+
+public JunoString assign(java.lang.String str)
+
+
Assigns str to this JunoString. +

+

+
+
+
+
Parameters:
str - the String to assign +
Returns:
this JunoString after the assignment
+
+
+
+ +

+assign

+
+public JunoString assign(JunoString other)
+
+
Assigns other to this JunoString. +

+

+
+
+
+
Parameters:
other - the JunoString to assign +
Returns:
this JunoString after the assignment
+
+
+
+ +

+len

+
+public int len()
+
+
Returns the length of this JunoString. +

+

+
+
+
+ +
Returns:
the number of characters in this JunoString
+
+
+
+ +

+getc

+
+public int getc(int index)
+
+
Returns the character at the specified index in this JunoString. +

+

+
+
+
+
Parameters:
index - the index of the character to return +
Returns:
the character at index, or 0 if index + is outside the bounds of this JunoString.
+
+
+
+ +

+tolower

+
+public JunoString tolower()
+
+
Returns a new JunoString which is a copy of this JunoString will all + characters converted to lower case. +

+

+
+
+
+ +
Returns:
a new JunoString with the contents of this JunoString converted + to lower case.
+
+
+
+ +

+toupper

+
+public JunoString toupper()
+
+
Returns a new JunoString which is a copy of this JunoString will all + characters converted to upper case. +

+

+
+
+
+ +
Returns:
a new JunoString with the contents of this JunoString converted + to upper case.
+
+
+
+ +

+putc

+
+public void putc(int index,
+                 char c)
+
+
Inserts the specified character into this JunoString at the specified + index. If index is outside the bounds of this JunoString, the status of + this JunoString is changed to STR_ERR_OUT_OF_RANGE. +

+

+
+
+
+
Parameters:
index - the index at which to insert c
c - the character to insert at index
+
+
+
+ +

+putc

+
+public void putc(int index,
+                 int c)
+
+
Inserts the specified character into this JunoString at the specified + index. +

+ This is equivalent to putc(index, (char)c). +

+

+
+
+
+
Parameters:
index - the index at which to insert c
c - the character to insert at index
+
+
+
+ +

+putc

+
+public void putc(int index,
+                 java.lang.String s)
+
+
Inserts the first character of the specified String into this JunoString + at the specified index. If s is null or + s.length() is 0, 0 is inserted. +

+

+
+
+
+
Parameters:
index - the index at which to insert the character
s - a String, the first character of which will be inserted into + this JunoString at index
+
+
+
+ +

+get_status

+
+public int get_status()
+
+
Returns the status of this JunoString. +

+

+
+
+
+ +
Returns:
the current status of this JunoString.
+
+
+
+ +

+get_status_msg

+
+public java.lang.String get_status_msg()
+
+
Returns a String representation of the current status of this JunoString. +

+

+
+
+
+ +
Returns:
a String representing the status of this JunoString
+
+
+
+ +

+compare

+
+public int compare(java.lang.String other)
+
+
Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String). +

+

+
+
+
+
Parameters:
other - the string to compare +
Returns:
a negative value, 0, or a positive value as specified in + String.compareTo
See Also:
String.compareTo(java.lang.String)
+
+
+
+ +

+compare

+
+public int compare(JunoString other)
+
+
Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String). +

+

+
+
+
+
Parameters:
other - the string to compare +
Returns:
a negative value, 0, or a positive value as specified in + String.compareTo
See Also:
String.compareTo(java.lang.String)
+
+
+
+ +

+icompare

+
+public int icompare(java.lang.String other)
+
+
Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String). +

+

+
+
+
+
Parameters:
other - the JunoString to compare +
Returns:
a negative value, 0, or a positive value as specified in + String.compareToIgnoreCase
See Also:
String.compareToIgnoreCase(java.lang.String)
+
+
+
+ +

+icompare

+
+public int icompare(JunoString other)
+
+
Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String). +

+

+
+
+
+
Parameters:
other - the JunoString to compare +
Returns:
a negative value, 0, or a positive value as specified in + String.compareToIgnoreCase
See Also:
String.compareToIgnoreCase(java.lang.String)
+
+
+
+ +

+hash

+
+public int hash(int size)
+
+
Returns a hash code for this JunoString. The returns value will be + a value in the interval [0, size). +

+

+
+
+
+
Parameters:
size - the maximum value the hash code should take on, exclusive +
Returns:
the hash code, or -1 if this JunoString's buffer is null.
+
+
+
+ +

+substr

+
+public JunoString substr(int start)
+
+
Returns a substring of this JunoString. The substring will contain all + characters in this JunoString from start through the end + of the JunoString. +

+

+
+
+
+
Parameters:
start - the beginning index, inclusive +
Returns:
a new JunoString containing the specified substring, or the + empty string if start is out of the bounds of this + JunoString
+
+
+
+ +

+substr

+
+public JunoString substr(int start,
+                         int end)
+
+
Returns a substring of this JunoString. The substring will contain all + characters in this JunoString from start (inclusive) through + end (exclusive). +

+

+
+
+
+
Parameters:
start - the beginning index, inclusive
end - the ending index, exclusive +
Returns:
a new JunoString containing the specified substring, or the + empty string if start or end is out of the + bounds of this JunoString
+
+
+
+ +

+search

+
+public int search(JunoString pattern)
+
+
Searches for the specified pattern in this JunoString. It will find the + first occurrence of pattern in this JunoString and return + the starting index of that occurrence or -1 if the pattern cannot be + found. +

+

+
+
+
+
Parameters:
pattern - the JunoString containing the pattern for which to search +
Returns:
the index of the first character of pattern in this + JunoString, or -1 if the pattern cannot be found.
+
+
+
+ +

+match

+
+public int match(java.lang.String pattern)
+
+
Finds the specified regular expression in this JunoString. +

+ If the pattern is found in this JunoString, 1 is returned. + Otherwise, 0 is returned. +

+ If pattern is not a legal regular expression, 0 is returned + and the status of this JunoString is set to STR_ERR_REGEXP_SYNTAX. +

+ It should be noted that this method creates matcher state in this JunoString + that is used by prematch(), postmatch(), thismatch(), + and backref(int). This matcher state is reset each time match + is called. +

+

+
+
+
+
Parameters:
pattern - the regular expression to match +
Returns:
1 if a match was found, 0 otherwise
+
+
+
+ +

+match

+
+public int match(JunoString pattern)
+
+
Finds the specified regular expression in this JunoString. +

+ If the pattern is found in this JunoString, 1 is returned. + Otherwise, 0 is returned. +

+ If pattern is not a legal regular expression, 0 is returned + and the status of this JunoString is set to STR_ERR_REGEXP_SYNTAX. +

+ It should be noted that this method creates matcher state in this JunoString + that is used by prematch(), postmatch(), thismatch(), + and backref(int). This matcher state is reset each time match + is called. +

+

+
+
+
+
Parameters:
pattern - the regular expression to match +
Returns:
1 if a match was found, 0 otherwise
+
+
+
+ +

+prematch

+
+public JunoString prematch()
+
+
Returns the substring of this JunoString including all characters up to + the beginning of the previous match. This method expects a valid + matcher state as generated by match(String) or + JunoString(String, int, Matcher). +

+ It returns a substring equivalent to substr(0, matcher.start()). +

+

+
+
+
+ +
Returns:
a new JunoString containing the substring of all characters before + the start of the previous match, or the NULL string if there is not + a valid match state
+
+
+
+ +

+postmatch

+
+public JunoString postmatch()
+
+
Returns the substring of this JunoString including all characters after + the end of the previous match. This method expects a valid + matcher state as generated by match(String) or + JunoString(String, int, Matcher). +

+ It returns a substring equivalent to substr(matcher.end()). +

+

+
+
+
+ +
Returns:
a new JunoString containing the substring of all characters after + the end of the previous match, or the NULL string if there is not + a valid match state
+
+
+
+ +

+thismatch

+
+public JunoString thismatch()
+
+
Returns the substring corresponding to the previous match. This method + expects a valid matcher state as generated by match(String) or + JunoString(String, int, Matcher). +

+ It returns a substring equivalent to + substr(matcher.start(), matcher.end()). +

+

+
+
+
+ +
Returns:
a new JunoString containing the substring of all characters + contained in the previous match, or the NULL string if there is not + a valid match state
+
+
+
+ +

+backref

+
+public JunoString backref(int index)
+
+
Returns the substring corresponding to the specified capture group of the + previous match. This method expects a valid matcher state as generated by + match(String) or JunoString(String, int, Matcher). +

+

+
+
+
+
Parameters:
index - the index of the capture group +
Returns:
a substring containing the characters matched by the specified + capture group in the previous match, or the NULL string if the + match state is invalid
+
+
+
+ +

+atoi

+
+public int atoi()
+
+
Parses this JunoString as a decimal value and returns the resulting int. + Underscores are allowed in this JunoString. +

+

+
+
+
+ +
Returns:
an int corresponding to the decimal value of this JunoString
+
+
+
+ +

+itoa

+
+public void itoa(int i)
+
+
Assigns the specified int to this JunoString. The string assigned is + equivalent to String.valueOf(i). +

+

+
+
+
+
Parameters:
i - the int to assign to this JunoString
+
+
+
+ +

+atohex

+
+public com.newisys.verilog.util.BitVector atohex()
+
+
Parses this JunoString as a hexadecimal value and returns the equivalent + BitVector. +

+

+
+
+
+ +
Returns:
a BitVector having the value of this JunoString when treated as + a hexadecimal value
+
+
+
+ +

+atooct

+
+public com.newisys.verilog.util.BitVector atooct()
+
+
Parses this JunoString as an octal value and returns the equivalent + BitVector. +

+

+
+
+
+ +
Returns:
a BitVector having the value of this JunoString when treated as + an octal value
+
+
+
+ +

+atobin

+
+public com.newisys.verilog.util.BitVector atobin()
+
+
Parses this JunoString as a binary value and returns the equivalent + BitVector. +

+

+
+
+
+ +
Returns:
a BitVector having the value of this JunoString when treated as + a binary value
+
+
+
+ +

+bittostr

+
+public void bittostr(com.newisys.verilog.util.BitVector bv)
+
+
Assigns the specified BitVector to this JunoString. Each 8 bits of + bv are treated as a character to assign to this JunoString. + Furthermore, the most significant byte of bv is placed in + the first character of this JunoString. +

+ For example if bv is the BitVector 32'h41424344, the resulting + JunoString will be "ABCD", where A = 0x41, B = 0x42, etc. in ASCII. +

+

+
+
+
+
Parameters:
bv - the BitVector to assign to this JunoString
+
+
+
+ +

+equals

+
+public boolean equals(java.lang.Object obj)
+
+
+
Overrides:
equals in class java.lang.Object
+
+
+
+
+
+
+ +

+hashCode

+
+public int hashCode()
+
+
+
Overrides:
hashCode in class java.lang.Object
+
+
+
+
+
+
+ +

+toString

+
+public java.lang.String toString()
+
+
Returns a String containing the contents of this JunoString, or "(NULL)" + if this JunoString contains the null string. +

+

+
Overrides:
toString in class java.lang.Object
+
+
+ +
Returns:
String
See Also:
Object.toString()
+
+
+
+ +

+toStringOrBlank

+
+public java.lang.String toStringOrBlank()
+
+
Returns a String containing the contents of this JunoString, or an empty + string if this JunoString contains the null string. +

+

+
+
+
+ +
Returns:
String
See Also:
Object.toString()
+
+
+
+ +

+toStringOrNull

+
+public java.lang.String toStringOrNull()
+
+
Returns a String containing the contents of this JunoString, or null if + this JunoString contains the null string. +

+

+
+
+
+ +
Returns:
String or null
See Also:
Object.toString()
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/JunoStringValueFactory.html b/docs/api/com/newisys/juno/runtime/JunoStringValueFactory.html new file mode 100644 index 0000000..98dd621 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/JunoStringValueFactory.html @@ -0,0 +1,323 @@ + + + + + + +JunoStringValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class JunoStringValueFactory

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoStringValueFactory
+
+
+
All Implemented Interfaces:
ValueFactory<JunoString>
+
+
+
+
public final class JunoStringValueFactory
extends java.lang.Object
implements ValueFactory<JunoString>
+ + +

+Implementation of ValueFactory for JunoString objects. +

+ +

+


+ +

+ + + + + + + + + + + +
+Field Summary
+static JunoStringValueFactoryINSTANCE + +
+          A singleton instance of JunoStringValueFactory.
+  + + + + + + + + + + +
+Constructor Summary
JunoStringValueFactory() + +
+           
+  + + + + + + + + + + + + + + + +
+Method Summary
+ JunoStringcopyInstance(JunoString other) + +
+          Returns a new JunoString, which is a copy of other.
+ JunoStringnewInstance() + +
+          Instantiates a new JunoString and returns it.
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+INSTANCE

+
+public static final JunoStringValueFactory INSTANCE
+
+
A singleton instance of JunoStringValueFactory. +

+

+
+
+ + + + + + + + +
+Constructor Detail
+ +

+JunoStringValueFactory

+
+public JunoStringValueFactory()
+
+
+ + + + + + + + +
+Method Detail
+ +

+newInstance

+
+public JunoString newInstance()
+
+
Instantiates a new JunoString and returns it. +

+

+
Specified by:
newInstance in interface ValueFactory<JunoString>
+
+
+ +
Returns:
a new JunoString
+
+
+
+ +

+copyInstance

+
+public JunoString copyInstance(JunoString other)
+
+
Returns a new JunoString, which is a copy of other. +

+

+
Specified by:
copyInstance in interface ValueFactory<JunoString>
+
+
+
Parameters:
other - the JunoString to copy +
Returns:
a new JunoString, which is a copy of other
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/LongWrapperOp.html b/docs/api/com/newisys/juno/runtime/LongWrapperOp.html new file mode 100644 index 0000000..abc9721 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/LongWrapperOp.html @@ -0,0 +1,1285 @@ + + + + + + +LongWrapperOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class LongWrapperOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.LongWrapperOp
+
+
+
+
public final class LongWrapperOp
extends java.lang.Object
+ + +

+Long conversion and operation methods referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static java.lang.Longadd(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseAnd(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseAndNot(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseNot(java.lang.Long l) + +
+           
+static java.lang.LongbitwiseOr(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseOrNot(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseReverse(java.lang.Long l) + +
+           
+static java.lang.LongbitwiseXor(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongbitwiseXorNot(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.Longdec(java.lang.Long l) + +
+           
+static java.lang.Longdivide(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.Bitequal(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitexactEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitexactNotEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.Bitgreater(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitgreaterOrEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.Longinc(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.Bitless(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitlessOrEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LonglogicalAnd(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LonglogicalNegative(java.lang.Long l) + +
+           
+static java.lang.LonglogicalOr(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static booleanlowBitToBoolean(java.lang.Long l) + +
+           
+static booleanlowBitToBooleanXZTrue(java.lang.Long l) + +
+           
+static java.lang.Longmod(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.Longmultiply(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.Longnegate(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitnotEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitreductiveAnd(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitreductiveAndNot(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitreductiveOr(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitreductiveOrNot(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitreductiveXor(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitreductiveXorNot(java.lang.Long l) + +
+           
+static java.lang.LongshiftLeft(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.LongshiftRight(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static java.lang.Longsubtract(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Long l) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Long l, + int len) + +
+           
+static com.newisys.verilog.util.BitVectortoBitVector(java.lang.Long l, + int len, + boolean signExtend) + +
+           
+static booleantoBoolean(java.lang.Long l) + +
+           
+static booleantoBooleanXZTrue(java.lang.Long l) + +
+           
+static inttoInt(java.lang.Long l) + +
+           
+static longtoLong(java.lang.Long l) + +
+           
+static java.lang.LongtoLongWrapper(com.newisys.verilog.util.Bit b) + +
+           
+static java.lang.LongtoLongWrapper(com.newisys.verilog.util.BitVector bv) + +
+           
+static java.lang.LongtoLongWrapper(com.newisys.verilog.util.BitVector bv, + boolean signed) + +
+           
+static java.lang.LongtoLongWrapper(java.lang.Integer i) + +
+           
+static java.lang.LongtoLongWrapper(java.lang.Object o) + +
+           
+static java.lang.LongtoLongWrapper(java.lang.String s) + +
+           
+static inttoShiftCount(java.lang.Long l) + +
+           
+static inttoShiftCount(java.lang.Long l, + int max) + +
+           
+static com.newisys.verilog.util.BitwildEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+static com.newisys.verilog.util.BitwildNotEqual(java.lang.Long l1, + java.lang.Long l2) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+toBoolean

+
+public static boolean toBoolean(java.lang.Long l)
+
+
+
+
+
+
+ +

+lowBitToBoolean

+
+public static boolean lowBitToBoolean(java.lang.Long l)
+
+
+
+
+
+
+ +

+toBooleanXZTrue

+
+public static boolean toBooleanXZTrue(java.lang.Long l)
+
+
+
+
+
+
+ +

+lowBitToBooleanXZTrue

+
+public static boolean lowBitToBooleanXZTrue(java.lang.Long l)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Long l)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Long l,
+                                                             int len)
+
+
+
+
+
+
+ +

+toBitVector

+
+public static com.newisys.verilog.util.BitVector toBitVector(java.lang.Long l,
+                                                             int len,
+                                                             boolean signExtend)
+
+
+
+
+
+
+ +

+toInt

+
+public static int toInt(java.lang.Long l)
+
+
+
+
+
+
+ +

+toLong

+
+public static long toLong(java.lang.Long l)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(java.lang.Long l,
+                               int max)
+
+
+
+
+
+
+ +

+toShiftCount

+
+public static int toShiftCount(java.lang.Long l)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(com.newisys.verilog.util.Bit b)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(com.newisys.verilog.util.BitVector bv,
+                                           boolean signed)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(java.lang.Integer i)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(java.lang.String s)
+
+
+
+
+
+
+ +

+toLongWrapper

+
+public static java.lang.Long toLongWrapper(java.lang.Object o)
+
+
+
+
+
+
+ +

+add

+
+public static java.lang.Long add(java.lang.Long l1,
+                                 java.lang.Long l2)
+
+
+
+
+
+
+ +

+subtract

+
+public static java.lang.Long subtract(java.lang.Long l1,
+                                      java.lang.Long l2)
+
+
+
+
+
+
+ +

+multiply

+
+public static java.lang.Long multiply(java.lang.Long l1,
+                                      java.lang.Long l2)
+
+
+
+
+
+
+ +

+divide

+
+public static java.lang.Long divide(java.lang.Long l1,
+                                    java.lang.Long l2)
+
+
+
+
+
+
+ +

+mod

+
+public static java.lang.Long mod(java.lang.Long l1,
+                                 java.lang.Long l2)
+
+
+
+
+
+
+ +

+negate

+
+public static java.lang.Long negate(java.lang.Long l)
+
+
+
+
+
+
+ +

+inc

+
+public static java.lang.Long inc(java.lang.Long l)
+
+
+
+
+
+
+ +

+dec

+
+public static java.lang.Long dec(java.lang.Long l)
+
+
+
+
+
+
+ +

+bitwiseAnd

+
+public static java.lang.Long bitwiseAnd(java.lang.Long l1,
+                                        java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseAndNot

+
+public static java.lang.Long bitwiseAndNot(java.lang.Long l1,
+                                           java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseOr

+
+public static java.lang.Long bitwiseOr(java.lang.Long l1,
+                                       java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseOrNot

+
+public static java.lang.Long bitwiseOrNot(java.lang.Long l1,
+                                          java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseXor

+
+public static java.lang.Long bitwiseXor(java.lang.Long l1,
+                                        java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseXorNot

+
+public static java.lang.Long bitwiseXorNot(java.lang.Long l1,
+                                           java.lang.Long l2)
+
+
+
+
+
+
+ +

+bitwiseNot

+
+public static java.lang.Long bitwiseNot(java.lang.Long l)
+
+
+
+
+
+
+ +

+bitwiseReverse

+
+public static java.lang.Long bitwiseReverse(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveAnd

+
+public static com.newisys.verilog.util.Bit reductiveAnd(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveAndNot

+
+public static com.newisys.verilog.util.Bit reductiveAndNot(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveOr

+
+public static com.newisys.verilog.util.Bit reductiveOr(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveOrNot

+
+public static com.newisys.verilog.util.Bit reductiveOrNot(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveXor

+
+public static com.newisys.verilog.util.Bit reductiveXor(java.lang.Long l)
+
+
+
+
+
+
+ +

+reductiveXorNot

+
+public static com.newisys.verilog.util.Bit reductiveXorNot(java.lang.Long l)
+
+
+
+
+
+
+ +

+logicalAnd

+
+public static java.lang.Long logicalAnd(java.lang.Long l1,
+                                        java.lang.Long l2)
+
+
+
+
+
+
+ +

+logicalOr

+
+public static java.lang.Long logicalOr(java.lang.Long l1,
+                                       java.lang.Long l2)
+
+
+
+
+
+
+ +

+logicalNegative

+
+public static java.lang.Long logicalNegative(java.lang.Long l)
+
+
+
+
+
+
+ +

+equal

+
+public static com.newisys.verilog.util.Bit equal(java.lang.Long l1,
+                                                 java.lang.Long l2)
+
+
+
+
+
+
+ +

+notEqual

+
+public static com.newisys.verilog.util.Bit notEqual(java.lang.Long l1,
+                                                    java.lang.Long l2)
+
+
+
+
+
+
+ +

+exactEqual

+
+public static com.newisys.verilog.util.Bit exactEqual(java.lang.Long l1,
+                                                      java.lang.Long l2)
+
+
+
+
+
+
+ +

+exactNotEqual

+
+public static com.newisys.verilog.util.Bit exactNotEqual(java.lang.Long l1,
+                                                         java.lang.Long l2)
+
+
+
+
+
+
+ +

+wildEqual

+
+public static com.newisys.verilog.util.Bit wildEqual(java.lang.Long l1,
+                                                     java.lang.Long l2)
+
+
+
+
+
+
+ +

+wildNotEqual

+
+public static com.newisys.verilog.util.Bit wildNotEqual(java.lang.Long l1,
+                                                        java.lang.Long l2)
+
+
+
+
+
+
+ +

+greater

+
+public static com.newisys.verilog.util.Bit greater(java.lang.Long l1,
+                                                   java.lang.Long l2)
+
+
+
+
+
+
+ +

+greaterOrEqual

+
+public static com.newisys.verilog.util.Bit greaterOrEqual(java.lang.Long l1,
+                                                          java.lang.Long l2)
+
+
+
+
+
+
+ +

+less

+
+public static com.newisys.verilog.util.Bit less(java.lang.Long l1,
+                                                java.lang.Long l2)
+
+
+
+
+
+
+ +

+lessOrEqual

+
+public static com.newisys.verilog.util.Bit lessOrEqual(java.lang.Long l1,
+                                                       java.lang.Long l2)
+
+
+
+
+
+
+ +

+shiftLeft

+
+public static java.lang.Long shiftLeft(java.lang.Long l1,
+                                       java.lang.Long l2)
+
+
+
+
+
+
+ +

+shiftRight

+
+public static java.lang.Long shiftRight(java.lang.Long l1,
+                                        java.lang.Long l2)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/OVAAssert.html b/docs/api/com/newisys/juno/runtime/OVAAssert.html new file mode 100644 index 0000000..a204e05 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/OVAAssert.html @@ -0,0 +1,434 @@ + + + + + + +OVAAssert (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class OVAAssert

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoObject
+      extended by com.newisys.juno.runtime.OVAAssert
+
+
+
All Implemented Interfaces:
com.newisys.randsolver.RandomHooks, java.lang.Cloneable
+
+
+
+
public class OVAAssert
extends JunoObject
+ + +

+An implementation of the OpenVera OVAAssert class. +

+ +

+


+ +

+ + + + + + + +
+Nested Class Summary
+ + + + + + + +
Nested classes/interfaces inherited from class com.newisys.juno.runtime.JunoObject
JunoObject.PackingPosition
+  + + + + + + + +
+Field Summary
+ + + + + + + +
Fields inherited from class com.newisys.juno.runtime.JunoObject
CONSTRAINT_MODE_FAIL, FAIL, OFF, OK, ON, RAND_MODE_FAIL, REPORT
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ voidDisableTrigger(OVAEvent event) + +
+          Disables the specified OVAEvent from being triggered when the event type + associated with it occurs.
+ voidDoAction(int action) + +
+          Causes this OVAAssert to perform the specified action.
+ voidEnableCount(int op) + +
+          Enables counting of successful or failed match attmpts, depending on + the specified operation.
+ voidEnableTrigger(OVAEvent event) + +
+          Enables the specified OVAEvent to be triggered when the event type + associated with it occurs.
+ intGetCount(int op) + +
+          Retrieves the current success or failure count of this OVAAssert, + depending on the specified operation.
+ java.lang.StringGetName() + +
+          Returns the name of this OVAAssert.
+ java.lang.StringtoString() + +
+           
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.JunoObject
clone, constraint_mode, constraint_mode, finalize, object_compare, object_copy, object_print, object_print, object_print, pack, post_pack, post_randomize, post_unpack, postRandomize, pre_pack, pre_randomize, pre_unpack, preRandomize, rand_mode, rand_mode, rand_mode, randomize, setRandom, unpack
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+GetName

+
+public java.lang.String GetName()
+
+
Returns the name of this OVAAssert. +

+

+ +
Returns:
the name of this OVAAssert
+
+
+
+ +

+EnableTrigger

+
+public void EnableTrigger(OVAEvent event)
+
+
Enables the specified OVAEvent to be triggered when the event type + associated with it occurs. +

+ This is currently unimplemented. +

+

+
Parameters:
event - the OVAEvent to trigger +
Throws: +
java.lang.UnsupportedOperationException - unconditionally
+
+
+
+ +

+DisableTrigger

+
+public void DisableTrigger(OVAEvent event)
+
+
Disables the specified OVAEvent from being triggered when the event type + associated with it occurs. +

+ This is currently unimplemented. +

+

+
Parameters:
event - the OVAEvent to disable from triggering +
Throws: +
java.lang.UnsupportedOperationException - unconditionally
+
+
+
+ +

+DoAction

+
+public void DoAction(int action)
+
+
Causes this OVAAssert to perform the specified action. Valid values for + action are OVAEngine.OVA_RESET, + OVAEngine.OVA_ENABLE, and OVAEngine.OVA_DISABLE. +

+ OVA_RESET resets this OVAAssert. All matching attempts are + cancelled and new attempts will begin on the following cycle. +

+ OVA_ENABLE enables this OVAAssert. Matching attempts will + begin on the following cycle and will stay enabled unless a subsequent + OVA_DISABLE action is performed. +

+ OVA_DISABLE disables this OVAAssert. Matching attempts will + end immediately and will stay disabled unless a subsequent + OVA_ENABLE action is performed. +

+

+
Parameters:
action - one of OVA_RESET, OVA_ENABLE, + or OVA_DISABLE
+
+
+
+ +

+EnableCount

+
+public void EnableCount(int op)
+
+
Enables counting of successful or failed match attmpts, depending on + the specified operation. Valid values for op are + OVAEngine.OVA_SUCCESS and OVAEngine.OVA_FAILURE. +

+ Note that once counting has started, it cannot be stopped. +

+

+
Parameters:
op - one of OVA_SUCCESS or OVA_FAILURE
+
+
+
+ +

+GetCount

+
+public int GetCount(int op)
+
+
Retrieves the current success or failure count of this OVAAssert, + depending on the specified operation. Valid values for op + are OVAEngine.OVA_SUCCESS and OVAEngine.OVA_FAILURE. +

+

+
Parameters:
op - one of OVA_SUCCESS or OVA_FAILURE +
Returns:
the number of times this OVAAssert has matched successfully or + failed to match, depending on op
+
+
+
+ +

+toString

+
+public java.lang.String toString()
+
+
+
Overrides:
toString in class java.lang.Object
+
+
+
See Also:
Object.toString()
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/OVAEngine.html b/docs/api/com/newisys/juno/runtime/OVAEngine.html new file mode 100644 index 0000000..98ff0d3 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/OVAEngine.html @@ -0,0 +1,829 @@ + + + + + + +OVAEngine (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class OVAEngine

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoObject
+      extended by com.newisys.juno.runtime.OVAEngine
+
+
+
All Implemented Interfaces:
com.newisys.randsolver.RandomHooks, java.lang.Cloneable
+
+
+
+
public final class OVAEngine
extends JunoObject
+ + +

+An implementation of the OpenVera OVAEngine class. +

+ +

+


+ +

+ + + + + + + +
+Nested Class Summary
+ + + + + + + +
Nested classes/interfaces inherited from class com.newisys.juno.runtime.JunoObject
JunoObject.PackingPosition
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Field Summary
+static intOVA_ALL + +
+           
+static intOVA_ASSERTID_NULL + +
+           
+static intOVA_CLIENTID_NULL + +
+           
+static intOVA_DISABLE + +
+           
+static intOVA_ENABLE + +
+           
+static intOVA_FAILURE + +
+           
+static intOVA_FALSE + +
+           
+static intOVA_FINISH + +
+           
+static intOVA_INFO + +
+           
+static intOVA_MANAGE_ATTEMPTS + +
+           
+static intOVA_NO_OP + +
+           
+static intOVA_NULL + +
+           
+static intOVA_QUIET + +
+           
+static intOVA_REPORT + +
+           
+static intOVA_RESET + +
+           
+static intOVA_SUCCESS + +
+           
+static intOVA_TERMINATE + +
+           
+static intOVA_TRUE + +
+           
+ + + + + + + +
Fields inherited from class com.newisys.juno.runtime.JunoObject
CONSTRAINT_MODE_FAIL, FAIL, OFF, OK, ON, RAND_MODE_FAIL, REPORT
+  + + + + + + + + + + +
+Constructor Summary
OVAEngine() + +
+           
+  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+ voidConfigure(int op, + int value) + +
+          Configures this OVAEngine's options.
+ voidDisableTrigger(OVAEvent event) + +
+          Disables the specified OVAEvent from being triggered when the event type + associated with it occurs.
+ voidDoAction(int action) + +
+          Causes this OVAEngine to perform the specified action.
+ voidEnableTrigger(OVAEvent event) + +
+          Enables the specified OVAEvent to be triggered when the event type + associated with it occurs.
+ java.lang.StringgetApiVersion() + +
+          Returns the OVA API version as returned by the underlying OVA implementation
+ OVAAssertGetAssert(java.lang.String name) + +
+          Returns the OVAAssert with the specified name.
+ OVAAssertGetFirstAssert() + +
+          Returns the first assertion from the underlying OVA implementation.
+ OVAAssertGetNextAssert() + +
+          Returns the next assertion from the underlying OVA implementation.
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.JunoObject
clone, constraint_mode, constraint_mode, finalize, object_compare, object_copy, object_print, object_print, object_print, pack, post_pack, post_randomize, post_unpack, postRandomize, pre_pack, pre_randomize, pre_unpack, preRandomize, rand_mode, rand_mode, rand_mode, randomize, setRandom, unpack
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+OVA_FALSE

+
+public static final int OVA_FALSE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_TRUE

+
+public static final int OVA_TRUE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_INFO

+
+public static final int OVA_INFO
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_QUIET

+
+public static final int OVA_QUIET
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_REPORT

+
+public static final int OVA_REPORT
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_MANAGE_ATTEMPTS

+
+public static final int OVA_MANAGE_ATTEMPTS
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_RESET

+
+public static final int OVA_RESET
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_FINISH

+
+public static final int OVA_FINISH
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_TERMINATE

+
+public static final int OVA_TERMINATE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_DISABLE

+
+public static final int OVA_DISABLE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_ENABLE

+
+public static final int OVA_ENABLE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_FAILURE

+
+public static final int OVA_FAILURE
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_SUCCESS

+
+public static final int OVA_SUCCESS
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_ALL

+
+public static final int OVA_ALL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_NULL

+
+public static final int OVA_NULL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_NO_OP

+
+public static final int OVA_NO_OP
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_CLIENTID_NULL

+
+public static final int OVA_CLIENTID_NULL
+
+
+
See Also:
Constant Field Values
+
+
+ +

+OVA_ASSERTID_NULL

+
+public static final int OVA_ASSERTID_NULL
+
+
+
See Also:
Constant Field Values
+
+ + + + + + + + +
+Constructor Detail
+ +

+OVAEngine

+
+public OVAEngine()
+
+
+ + + + + + + + +
+Method Detail
+ +

+getApiVersion

+
+public java.lang.String getApiVersion()
+
+
Returns the OVA API version as returned by the underlying OVA implementation +

+

+ +
Returns:
a String representing the OVA API Version
+
+
+
+ +

+Configure

+
+public void Configure(int op,
+                      int value)
+
+
Configures this OVAEngine's options. Valid values for op + are OVA_INFO, OVA_QUIET, and OVA_REPORT. + Valid values for value are OVA_TRUE and + OVA_FALSE. +

+ Defaults for the options are:
+ + + + + +
OptionDefault ValueDescription
OVA_INFOOVA_FALSELine Information in assertion messages
OVA_PRINTOVA_FALSEAssertion messages printed at runtime
OVA_REPORTOVA_TRUEAssertion report at the end of simulation
+

+

+
Parameters:
op - one of OVA_INFO, OVA_QUIET, or + OVA_REPORT
value - one of OVA_TRUE or OVA_FALSE
+
+
+
+ +

+DoAction

+
+public void DoAction(int action)
+
+
Causes this OVAEngine to perform the specified action. Valid values for + action are OVA_RESET and OVA_TERMINATE. +

+ OVA_RESET resets all OVA assertions and expressions. All + matching attempts are cancelled and new attempts will begin on the + following cycle. +

+ OVA_TERMINATE terminates all current matching attempts. No + new attempts to match will started. Attempts to match cannot be started + again once this action is performed. +

+

+
Parameters:
action - one of OVA_RESET or OVA_TERMINATE
+
+
+
+ +

+GetFirstAssert

+
+public OVAAssert GetFirstAssert()
+
+
Returns the first assertion from the underlying OVA implementation. If + there are no OVA assertions in the design, null is returned. +

+

+ +
Returns:
the first OVAAssert in the design, or null if no + OVAAsserts are present
+
+
+
+ +

+GetNextAssert

+
+public OVAAssert GetNextAssert()
+
+
Returns the next assertion from the underlying OVA implementation. If + there are no more OVA assertions in the design, null is + returned. This method may be called repeatedly after + GetFirstAssert(). +

+

+ +
Returns:
the next OVAAssert in the design, or null if no more + OVAAsserts are present
+
+
+
+ +

+GetAssert

+
+public OVAAssert GetAssert(java.lang.String name)
+
+
Returns the OVAAssert with the specified name. +

+

+
Parameters:
name - the name of the desired OVAAssert +
Returns:
the OVAAssert with the specified name, or null if + no such OVAAssert exists
+
+
+
+ +

+EnableTrigger

+
+public void EnableTrigger(OVAEvent event)
+
+
Enables the specified OVAEvent to be triggered when the event type + associated with it occurs. +

+ This is currently unimplemented. +

+

+
Parameters:
event - the OVAEvent to trigger +
Throws: +
java.lang.UnsupportedOperationException - unconditionally
+
+
+
+ +

+DisableTrigger

+
+public void DisableTrigger(OVAEvent event)
+
+
Disables the specified OVAEvent from being triggered when the event type + associated with it occurs. +

+ This is currently unimplemented. +

+

+
Parameters:
event - the OVAEvent to disable from triggering +
Throws: +
java.lang.UnsupportedOperationException - unconditionally
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/OVAEvent.html b/docs/api/com/newisys/juno/runtime/OVAEvent.html new file mode 100644 index 0000000..17c73b9 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/OVAEvent.html @@ -0,0 +1,375 @@ + + + + + + +OVAEvent (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class OVAEvent

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.JunoObject
+      extended by com.newisys.juno.runtime.OVAEvent
+
+
+
All Implemented Interfaces:
com.newisys.randsolver.RandomHooks, java.lang.Cloneable
+
+
+
+
public class OVAEvent
extends JunoObject
+ + +

+An implementation of the OpenVera OVAEvent class. +

+ +

+


+ +

+ + + + + + + +
+Nested Class Summary
+ + + + + + + +
Nested classes/interfaces inherited from class com.newisys.juno.runtime.JunoObject
JunoObject.PackingPosition
+  + + + + + + + + + + + +
+Field Summary
+ JunoEventEvent + +
+          Publicly usable JunoEvent
+ + + + + + + +
Fields inherited from class com.newisys.juno.runtime.JunoObject
CONSTRAINT_MODE_FAIL, FAIL, OFF, OK, ON, RAND_MODE_FAIL, REPORT
+  + + + + + + + + + + +
+Constructor Summary
OVAEvent(int eventType) + +
+          Create an OVA Event associated with the type of event described by the + event parameter.
+  + + + + + + + + + + + + + + + +
+Method Summary
+ intGetNextEvent() + +
+          Returns the event type that unblocked this thread.
+ voidWait() + +
+          Wait on the event, blocking the current thread.
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.JunoObject
clone, constraint_mode, constraint_mode, finalize, object_compare, object_copy, object_print, object_print, object_print, pack, post_pack, post_randomize, post_unpack, postRandomize, pre_pack, pre_randomize, pre_unpack, preRandomize, rand_mode, rand_mode, rand_mode, randomize, setRandom, unpack
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Field Detail
+ +

+Event

+
+public JunoEvent Event
+
+
Publicly usable JunoEvent +

+

+
+
+ + + + + + + + +
+Constructor Detail
+ +

+OVAEvent

+
+public OVAEvent(int eventType)
+
+
Create an OVA Event associated with the type of event described by the + event parameter. +

+ When used in the context of an OVAEngine object, event can take on the + values of OVAEngine.OVA_RESET or OVAEngine.OVA_TERMINATE. +

+ When used in the context of an OVAAssert object, event can take on the + values of OVAEngine.OVA_RESET, OVAEngine.OVA_SUCCESS, + OVAEngine.OVA_FAILURE, OVAEngine.OVA_ENABLE, + OVAEngine.OVA_DISABLE, or OVAEngine.OVA_ALL. +

+

+
Parameters:
eventType - the event type to associate with this OVAEvent
+
+ + + + + + + + +
+Method Detail
+ +

+Wait

+
+public void Wait()
+
+
Wait on the event, blocking the current thread. +

+

+
See Also:
GetNextEvent()
+
+
+
+ +

+GetNextEvent

+
+public int GetNextEvent()
+
+
Returns the event type that unblocked this thread. If more than one event + caused the thread to unblock, this method may be called multiple times, + until OVAEngine.OVA_NULL is returned. +

+ If there are multiple calls to Wait() without intervening calls to + getNextEvent, getNextEvent will return the set of event types corresponding + to the last Wait(). +

+

+ +
Returns:
the event type that unblocked this thread or + OVAEngine.OVA_NULL if there are no more events.
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/StringAssocArray.html b/docs/api/com/newisys/juno/runtime/StringAssocArray.html new file mode 100644 index 0000000..b3e77e9 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/StringAssocArray.html @@ -0,0 +1,332 @@ + + + + + + +StringAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class StringAssocArray<V>

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<java.lang.String,V>
+      extended by com.newisys.juno.runtime.StringAssocArray<V>
+
+
+
Type Parameters:
V - value type
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
Direct Known Subclasses:
StringObjectAssocArray
+
+
+
+
public class StringAssocArray<V>
extends AssocArray<java.lang.String,V>
+ + +

+String-keyed associative array. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
StringAssocArray() + +
+          Creates a StringAssocArray.
StringAssocArray(StringAssocArray<? extends V> other) + +
+          Creates a StringAssocArray which is a copy of the specified array.
StringAssocArray(V nullValue) + +
+          Creates a StringAssocArray with the specified default value.
StringAssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates a StringAssocArray with the specified default value factory.
+  + + + + + + + + + + + +
+Method Summary
+ StringAssocArray<V>clone() + +
+           
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.AssocArray
check, check, delete, delete, first, get, getOrCreate, next, put, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+StringAssocArray

+
+public StringAssocArray()
+
+
Creates a StringAssocArray. +

+

+
+ +

+StringAssocArray

+
+public StringAssocArray(V nullValue)
+
+
Creates a StringAssocArray with the specified default value. If a key is + requested that does not exist in this array, the default value will be + returned. +

+

+
Parameters:
nullValue - the default value for this array
+
+
+ +

+StringAssocArray

+
+public StringAssocArray(ValueFactory<? extends V> nullValueFactory)
+
+
Creates a StringAssocArray with the specified default value factory. If + a key is requested that does not exist in this array, the factory will + be used to instantiate the default value. +

+

+
Parameters:
nullValueFactory - the value factory used to create default values
+
+
+ +

+StringAssocArray

+
+public StringAssocArray(StringAssocArray<? extends V> other)
+
+
Creates a StringAssocArray which is a copy of the specified array. +

+

+
Parameters:
other - the array to copy
+
+ + + + + + + + +
+Method Detail
+ +

+clone

+
+public StringAssocArray<V> clone()
+
+
+
Overrides:
clone in class AssocArray<java.lang.String,V>
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/StringObjectAssocArray.html b/docs/api/com/newisys/juno/runtime/StringObjectAssocArray.html new file mode 100644 index 0000000..7add9d8 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/StringObjectAssocArray.html @@ -0,0 +1,328 @@ + + + + + + +StringObjectAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class StringObjectAssocArray

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.AssocArray<java.lang.String,V>
+      extended by com.newisys.juno.runtime.StringAssocArray<java.lang.Object>
+          extended by com.newisys.juno.runtime.StringObjectAssocArray
+
+
+
All Implemented Interfaces:
java.lang.Cloneable
+
+
+
+
public final class StringObjectAssocArray
extends StringAssocArray<java.lang.Object>
+ + +

+String-to-Object associative array. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + +
+Constructor Summary
StringObjectAssocArray() + +
+          Creates a StringObjectAssocArray.
StringObjectAssocArray(AssocArray other) + +
+          Creates a StringObjectAssocArray which is a copy of the specified AssocArray.
StringObjectAssocArray(java.lang.Object nullValue) + +
+          Creates a StringObjectAssocArray with the specified default value.
StringObjectAssocArray(ValueFactory<?> nullValueFactory) + +
+          Creates a StringObjectAssocArray with the specified ValueFactory.
+  + + + + + + + + + + + +
+Method Summary
+ StringObjectAssocArrayclone() + +
+           
+ + + + + + + +
Methods inherited from class com.newisys.juno.runtime.AssocArray
check, check, delete, delete, first, get, getOrCreate, next, put, toString
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
+  +

+ + + + + + + + +
+Constructor Detail
+ +

+StringObjectAssocArray

+
+public StringObjectAssocArray()
+
+
Creates a StringObjectAssocArray. +

+

+
+ +

+StringObjectAssocArray

+
+public StringObjectAssocArray(java.lang.Object nullValue)
+
+
Creates a StringObjectAssocArray with the specified default value. If a key is + requested that does not exist in this StringObjectAssocArray, the default + value will be returned. +

+

+
Parameters:
nullValue - the default value for this StringObjectAssocArray
+
+
+ +

+StringObjectAssocArray

+
+public StringObjectAssocArray(ValueFactory<?> nullValueFactory)
+
+
Creates a StringObjectAssocArray with the specified ValueFactory. If a key is + requested that does not exist in this StringObjectAssocArray, nullValueFactory + will be used to instantiate the default value. +

+

+
Parameters:
nullValueFactory - the ValueFactory for this StringObjectAssocArray
+
+
+ +

+StringObjectAssocArray

+
+public StringObjectAssocArray(AssocArray other)
+
+
Creates a StringObjectAssocArray which is a copy of the specified AssocArray. +

+

+
Parameters:
other - the AssocArray to copy
+
+ + + + + + + + +
+Method Detail
+ +

+clone

+
+public StringObjectAssocArray clone()
+
+
+
Overrides:
clone in class StringAssocArray<java.lang.Object>
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/StringOp.html b/docs/api/com/newisys/juno/runtime/StringOp.html new file mode 100644 index 0000000..be29d02 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/StringOp.html @@ -0,0 +1,894 @@ + + + + + + +StringOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class StringOp

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.StringOp
+
+
+
+
public final class StringOp
extends java.lang.Object
+ + +

+String conversion and operation methods referenced by translated code. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static com.newisys.verilog.util.BitVectoratobin(java.lang.String s) + +
+           
+static com.newisys.verilog.util.BitVectoratohex(java.lang.String s) + +
+           
+static intatoi(java.lang.String s) + +
+           
+static com.newisys.verilog.util.BitVectoratooct(java.lang.String s) + +
+           
+static java.lang.Stringbackref(java.lang.String s, + java.util.regex.Matcher matcher, + int index) + +
+           
+static java.lang.Stringbittostr(com.newisys.verilog.util.BitVector bv) + +
+           
+static intcompare(java.lang.String s1, + java.lang.String s2) + +
+           
+static java.lang.Stringconcat(java.lang.String... strs) + +
+           
+static booleanequals(java.lang.String s, + java.lang.Object obj) + +
+           
+static java.lang.Stringget_status_msg(int status) + +
+           
+static intgetc(java.lang.String s, + int index) + +
+           
+static inthash(java.lang.String s, + int size) + +
+           
+static inthashCode(java.lang.String s) + +
+           
+static inticompare(java.lang.String s1, + java.lang.String s2) + +
+           
+static java.lang.Stringitoa(int i) + +
+           
+static intlen(java.lang.String s) + +
+           
+static intmatch(java.lang.String s, + java.lang.String pattern) + +
+           
+static intmatch(java.lang.String s, + java.lang.String pattern, + java.util.regex.Matcher[] matcher_ref, + int[] status_ref) + +
+           
+static java.lang.Stringpostmatch(java.lang.String s, + java.util.regex.Matcher matcher) + +
+           
+static java.lang.Stringprematch(java.lang.String s, + java.util.regex.Matcher matcher) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + char c) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + char c, + int[] status_ref) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + int c) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + int c, + int[] status_ref) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + java.lang.String c) + +
+           
+static java.lang.Stringputc(java.lang.String s, + int index, + java.lang.String c, + int[] status_ref) + +
+           
+static java.lang.Stringreplicate(int count, + java.lang.String str) + +
+           
+static intsearch(java.lang.String s, + java.lang.String pattern) + +
+           
+static java.lang.Stringsubstr(java.lang.String s, + int start) + +
+           
+static java.lang.Stringsubstr(java.lang.String s, + int start, + int end) + +
+           
+static java.lang.Stringthismatch(java.lang.String s, + java.util.regex.Matcher matcher) + +
+           
+static java.lang.StringtoDisplayString(java.lang.String s) + +
+           
+static java.lang.StringtoStringOrBlank(java.lang.String s) + +
+           
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+len

+
+public static int len(java.lang.String s)
+
+
+
+
+
+
+ +

+getc

+
+public static int getc(java.lang.String s,
+                       int index)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    char c)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    char c,
+                                    int[] status_ref)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    int c)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    int c,
+                                    int[] status_ref)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    java.lang.String c)
+
+
+
+
+
+
+ +

+putc

+
+public static java.lang.String putc(java.lang.String s,
+                                    int index,
+                                    java.lang.String c,
+                                    int[] status_ref)
+
+
+
+
+
+
+ +

+get_status_msg

+
+public static java.lang.String get_status_msg(int status)
+
+
+
+
+
+
+ +

+compare

+
+public static int compare(java.lang.String s1,
+                          java.lang.String s2)
+
+
+
+
+
+
+ +

+icompare

+
+public static int icompare(java.lang.String s1,
+                           java.lang.String s2)
+
+
+
+
+
+
+ +

+hash

+
+public static int hash(java.lang.String s,
+                       int size)
+
+
+
+
+
+
+ +

+substr

+
+public static java.lang.String substr(java.lang.String s,
+                                      int start)
+
+
+
+
+
+
+ +

+substr

+
+public static java.lang.String substr(java.lang.String s,
+                                      int start,
+                                      int end)
+
+
+
+
+
+
+ +

+search

+
+public static int search(java.lang.String s,
+                         java.lang.String pattern)
+
+
+
+
+
+
+ +

+match

+
+public static int match(java.lang.String s,
+                        java.lang.String pattern)
+
+
+
+
+
+
+ +

+match

+
+public static int match(java.lang.String s,
+                        java.lang.String pattern,
+                        java.util.regex.Matcher[] matcher_ref,
+                        int[] status_ref)
+
+
+
+
+
+
+ +

+prematch

+
+public static java.lang.String prematch(java.lang.String s,
+                                        java.util.regex.Matcher matcher)
+
+
+
+
+
+
+ +

+postmatch

+
+public static java.lang.String postmatch(java.lang.String s,
+                                         java.util.regex.Matcher matcher)
+
+
+
+
+
+
+ +

+thismatch

+
+public static java.lang.String thismatch(java.lang.String s,
+                                         java.util.regex.Matcher matcher)
+
+
+
+
+
+
+ +

+backref

+
+public static java.lang.String backref(java.lang.String s,
+                                       java.util.regex.Matcher matcher,
+                                       int index)
+
+
+
+
+
+
+ +

+atoi

+
+public static int atoi(java.lang.String s)
+
+
+
+
+
+
+ +

+itoa

+
+public static java.lang.String itoa(int i)
+
+
+
+
+
+
+ +

+atohex

+
+public static com.newisys.verilog.util.BitVector atohex(java.lang.String s)
+
+
+
+
+
+
+ +

+atooct

+
+public static com.newisys.verilog.util.BitVector atooct(java.lang.String s)
+
+
+
+
+
+
+ +

+atobin

+
+public static com.newisys.verilog.util.BitVector atobin(java.lang.String s)
+
+
+
+
+
+
+ +

+bittostr

+
+public static java.lang.String bittostr(com.newisys.verilog.util.BitVector bv)
+
+
+
+
+
+
+ +

+concat

+
+public static java.lang.String concat(java.lang.String... strs)
+
+
+
+
+
+
+ +

+replicate

+
+public static java.lang.String replicate(int count,
+                                         java.lang.String str)
+
+
+
+
+
+
+ +

+equals

+
+public static boolean equals(java.lang.String s,
+                             java.lang.Object obj)
+
+
+
+
+
+
+ +

+hashCode

+
+public static int hashCode(java.lang.String s)
+
+
+
+
+
+
+ +

+toDisplayString

+
+public static java.lang.String toDisplayString(java.lang.String s)
+
+
+
+
+
+
+ +

+toStringOrBlank

+
+public static java.lang.String toStringOrBlank(java.lang.String s)
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/TestbenchFactory.html b/docs/api/com/newisys/juno/runtime/TestbenchFactory.html new file mode 100644 index 0000000..66028d8 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/TestbenchFactory.html @@ -0,0 +1,309 @@ + + + + + + +TestbenchFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Class TestbenchFactory

+
+java.lang.Object
+  extended by com.newisys.juno.runtime.TestbenchFactory
+
+
+
+
public final class TestbenchFactory
extends java.lang.Object
+ + +

+Factory used to instantiate a testbench in a polymorphic fashion. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + + + + + + + + + +
+Method Summary
+static java.lang.Objectcreate() + +
+          Instantiates a testbench as specified by +testbenchClass on the command + line.
+static java.lang.Objectcreate(java.lang.Object[] args, + java.lang.Class[] argTypes, + java.lang.String defaultClsName) + +
+          Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line.
+static java.lang.Objectcreate(java.lang.Object[] args, + java.lang.String defaultClsName) + +
+          Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line.
+static java.lang.Objectcreate(java.lang.String defaultClsName) + +
+          Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line.
+ + + + + + + +
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
+  +

+ + + + + + + + +
+Method Detail
+ +

+create

+
+public static java.lang.Object create()
+
+
Instantiates a testbench as specified by +testbenchClass on the command + line. +

+ This is equivalent to create(null, null, null). +

+

+ +
Returns:
the new TestBench
+
+
+
+ +

+create

+
+public static java.lang.Object create(java.lang.String defaultClsName)
+
+
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +

+ This is equivalent to create(null, null, defaultClsName). +

+

+
Parameters:
defaultClsName - the classname to use if +testbenchClass is not + specified on the command line +
Returns:
the new TestBench
+
+
+
+ +

+create

+
+public static java.lang.Object create(java.lang.Object[] args,
+                                      java.lang.String defaultClsName)
+
+
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +

+

+
Parameters:
args - an array of arguments to pass to the testbench's constructor
defaultClsName - the classname to use if +testbenchClass is not + specified on the command line +
Returns:
the new TestBench
+
+
+
+ +

+create

+
+public static java.lang.Object create(java.lang.Object[] args,
+                                      java.lang.Class[] argTypes,
+                                      java.lang.String defaultClsName)
+
+
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +

+

+
Parameters:
args - an array of arguments to pass to the testbench's constructor
argTypes - an array of Class objects that describes the types in + args
defaultClsName - the classname to use if +testbenchClass is not + specified on the command line +
Returns:
the new TestBench
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/ValueFactory.html b/docs/api/com/newisys/juno/runtime/ValueFactory.html new file mode 100644 index 0000000..2103d09 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/ValueFactory.html @@ -0,0 +1,235 @@ + + + + + + +ValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ +

+ +com.newisys.juno.runtime +
+Interface ValueFactory<T>

+
+
Type Parameters:
T - object type produced by factory
+
+
All Known Implementing Classes:
ImmutableValueFactory, JunoEventValueFactory, JunoStringValueFactory
+
+
+
+
public interface ValueFactory<T>
+ + +

+A factory interface that supports creating and copying objects. +

+ +

+


+ +

+ + + + + + + + + + + + + + + + +
+Method Summary
+ TcopyInstance(T other) + +
+          Create a copy of the specified object.
+ TnewInstance() + +
+          Create a new instance of the underlying object.
+  +

+ + + + + + + + +
+Method Detail
+ +

+newInstance

+
+T newInstance()
+
+
Create a new instance of the underlying object. +

+

+ +
Returns:
a new instance of the Object
+
+
+
+ +

+copyInstance

+
+T copyInstance(T other)
+
+
Create a copy of the specified object. +

+

+
Parameters:
other - the object to copy +
Returns:
a copy of other
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/AbstractMethodCallError.html b/docs/api/com/newisys/juno/runtime/class-use/AbstractMethodCallError.html new file mode 100644 index 0000000..9c57be7 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/AbstractMethodCallError.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.AbstractMethodCallError (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.AbstractMethodCallError

+
+No usage of com.newisys.juno.runtime.AbstractMethodCallError +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/AssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/AssocArray.html new file mode 100644 index 0000000..9193687 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/AssocArray.html @@ -0,0 +1,276 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.AssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.AssocArray

+
+ + + + + +
+Uses of AssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Subclasses of AssocArray in com.newisys.juno.runtime
+ classBitAssocArray<V> + +
+          BitVector-keyed associative array.
+ classBitBitAssocArray + +
+          BitVector-to-BitVector associative array.
+ classBitObjectAssocArray + +
+          BitVector-to-Object associative array.
+ classStringAssocArray<V> + +
+          String-keyed associative array.
+ classStringObjectAssocArray + +
+          String-to-Object associative array.
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return AssocArray
+ AssocArray<K,V>AssocArray.clone() + +
+           
+  +

+ + + + + + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type AssocArray
+static intJuno.assoc_index(int op, + AssocArray<?,?> array) + +
+          assoc_index built-in function for dealing with entire arrays.
+static intJuno.assoc_index(int op, + AssocArray array, + int[] index_ref) + +
+          See Juno.assoc_index(int, AssocArray, Object[]).
+static intJuno.assoc_index(int op, + AssocArray array, + java.lang.Object index) + +
+          assoc_index built-in function for dealing with array elements.
+static intJuno.assoc_index(int op, + AssocArray array, + java.lang.Object[] index_ref) + +
+          assoc_index built-in function for dealing with array elements.
+  +

+ + + + + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type AssocArray
AssocArray(AssocArray<? extends K,? extends V> other) + +
+          Creates a new AssocArray which is a copy of the specified array.
StringObjectAssocArray(AssocArray other) + +
+          Creates a StringObjectAssocArray which is a copy of the specified AssocArray.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BitAssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/BitAssocArray.html new file mode 100644 index 0000000..b6021ea --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BitAssocArray.html @@ -0,0 +1,199 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BitAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BitAssocArray

+
+ + + + + +
+Uses of BitAssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + +
Subclasses of BitAssocArray in com.newisys.juno.runtime
+ classBitBitAssocArray + +
+          BitVector-to-BitVector associative array.
+ classBitObjectAssocArray + +
+          BitVector-to-Object associative array.
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return BitAssocArray
+ BitAssocArray<V>BitAssocArray.clone() + +
+           
+  +

+ + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type BitAssocArray
BitAssocArray(BitAssocArray<? extends V> other) + +
+          Creates a BitAssocArray which is a copy of the specified array.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BitBitAssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/BitBitAssocArray.html new file mode 100644 index 0000000..5eac035 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BitBitAssocArray.html @@ -0,0 +1,201 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BitBitAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BitBitAssocArray

+
+ + + + + +
+Uses of BitBitAssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return BitBitAssocArray
+ BitBitAssocArrayBitBitAssocArray.clone() + +
+           
+  +

+ + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type BitBitAssocArray
+ intJunoObject.pack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+ intJunoObject.unpack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+  +

+ + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type BitBitAssocArray
BitBitAssocArray(BitBitAssocArray other) + +
+          Creates a BitBitAssocArray that is a copy of the specified array.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BitObjectAssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/BitObjectAssocArray.html new file mode 100644 index 0000000..31412d6 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BitObjectAssocArray.html @@ -0,0 +1,175 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BitObjectAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BitObjectAssocArray

+
+ + + + + +
+Uses of BitObjectAssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return BitObjectAssocArray
+ BitObjectAssocArrayBitObjectAssocArray.clone() + +
+           
+  +

+ + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type BitObjectAssocArray
BitObjectAssocArray(BitObjectAssocArray other) + +
+          Creates a BitObjectAssocArray which is a copy of the specified array.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BitOp.html b/docs/api/com/newisys/juno/runtime/class-use/BitOp.html new file mode 100644 index 0000000..715b1f6 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BitOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BitOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BitOp

+
+No usage of com.newisys.juno.runtime.BitOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BitVectorOp.html b/docs/api/com/newisys/juno/runtime/class-use/BitVectorOp.html new file mode 100644 index 0000000..586768c --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BitVectorOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BitVectorOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BitVectorOp

+
+No usage of com.newisys.juno.runtime.BitVectorOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/BooleanOp.html b/docs/api/com/newisys/juno/runtime/class-use/BooleanOp.html new file mode 100644 index 0000000..d72975e --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/BooleanOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.BooleanOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.BooleanOp

+
+No usage of com.newisys.juno.runtime.BooleanOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/ImmutableValueFactory.html b/docs/api/com/newisys/juno/runtime/class-use/ImmutableValueFactory.html new file mode 100644 index 0000000..2ca9c29 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/ImmutableValueFactory.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.ImmutableValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.ImmutableValueFactory

+
+No usage of com.newisys.juno.runtime.ImmutableValueFactory +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/IntOp.html b/docs/api/com/newisys/juno/runtime/class-use/IntOp.html new file mode 100644 index 0000000..b673f17 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/IntOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.IntOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.IntOp

+
+No usage of com.newisys.juno.runtime.IntOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/IntegerOp.html b/docs/api/com/newisys/juno/runtime/class-use/IntegerOp.html new file mode 100644 index 0000000..7875471 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/IntegerOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.IntegerOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.IntegerOp

+
+No usage of com.newisys.juno.runtime.IntegerOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/Juno.html b/docs/api/com/newisys/juno/runtime/class-use/Juno.html new file mode 100644 index 0000000..0c607d3 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/Juno.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.Juno (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.Juno

+
+No usage of com.newisys.juno.runtime.Juno +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoEnum.html b/docs/api/com/newisys/juno/runtime/class-use/JunoEnum.html new file mode 100644 index 0000000..36a89ff --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoEnum.html @@ -0,0 +1,223 @@ + + + + + + +Uses of Interface com.newisys.juno.runtime.JunoEnum (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Interface
com.newisys.juno.runtime.JunoEnum

+
+ + + + + +
+Uses of JunoEnum in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Classes in com.newisys.juno.runtime with type parameters of type JunoEnum
+ interfaceJunoEnum<E extends Enum<E> & JunoEnum<E>> + +
+          Interface implemented by enum types translated from Vera.
+  +

+ + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with type parameters of type JunoEnum
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+E
+
JunoEnumUtil.advance(E cur, + int count) + +
+           
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+E
+
JunoEnumUtil.forValue(java.lang.Class<E> cls, + java.lang.Integer value, + boolean checked) + +
+           
+static + + + + +
+<E extends java.lang.Enum<E> & JunoEnum<E>> +
+java.lang.String
+
JunoEnumUtil.toString(E e) + +
+           
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoEnumUtil.html b/docs/api/com/newisys/juno/runtime/class-use/JunoEnumUtil.html new file mode 100644 index 0000000..a74a00e --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoEnumUtil.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoEnumUtil (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoEnumUtil

+
+No usage of com.newisys.juno.runtime.JunoEnumUtil +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoEvent.html b/docs/api/com/newisys/juno/runtime/class-use/JunoEvent.html new file mode 100644 index 0000000..01589c5 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoEvent.html @@ -0,0 +1,235 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoEvent (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoEvent

+
+ + + + + +
+Uses of JunoEvent in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Fields in com.newisys.juno.runtime declared as JunoEvent
+ JunoEventOVAEvent.Event + +
+          Publicly usable JunoEvent
+  +

+ + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime that return JunoEvent
+ JunoEventJunoEventValueFactory.copyInstance(JunoEvent other) + +
+          Instantiates a new JunoEvent and returns it.
+ JunoEventJunoString.getChangeEvent() + +
+          Returns a JunoEvent that is notified whenever this JunoString changes.
+ JunoEventJunoEventValueFactory.newInstance() + +
+          Instantiates a new JunoEvent and returns it.
+  +

+ + + + + + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type JunoEvent
+ JunoEventJunoEventValueFactory.copyInstance(JunoEvent other) + +
+          Instantiates a new JunoEvent and returns it.
+static intJuno.sync(int op, + JunoEvent... events) + +
+          Wait on a given set of JunoEvents to occur.
+static voidJuno.trigger(int op, + JunoEvent... events) + +
+          Triggers one or more JunoEvents.
+static voidJuno.trigger(JunoEvent... events) + +
+          Triggers one or more JunoEvents in ONE_SHOT mode.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoEventValueFactory.html b/docs/api/com/newisys/juno/runtime/class-use/JunoEventValueFactory.html new file mode 100644 index 0000000..aa8f7ae --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoEventValueFactory.html @@ -0,0 +1,161 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoEventValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoEventValueFactory

+
+ + + + + +
+Uses of JunoEventValueFactory in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Fields in com.newisys.juno.runtime declared as JunoEventValueFactory
+static JunoEventValueFactoryJunoEventValueFactory.INSTANCE + +
+          A singleton instance of JunoEventValueFactory.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoObject.PackingPosition.html b/docs/api/com/newisys/juno/runtime/class-use/JunoObject.PackingPosition.html new file mode 100644 index 0000000..35d2dbe --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoObject.PackingPosition.html @@ -0,0 +1,171 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoObject.PackingPosition (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoObject.PackingPosition

+
+ + + + + +
+Uses of JunoObject.PackingPosition in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type JunoObject.PackingPosition
+ intJunoObject.pack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+ intJunoObject.unpack(BitBitAssocArray array, + JunoObject.PackingPosition pos) + +
+           
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoObject.html b/docs/api/com/newisys/juno/runtime/class-use/JunoObject.html new file mode 100644 index 0000000..ee044ee --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoObject.html @@ -0,0 +1,219 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoObject (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoObject

+
+ + + + + +
+Uses of JunoObject in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + + + + + +
Subclasses of JunoObject in com.newisys.juno.runtime
+ classOVAAssert + +
+          An implementation of the OpenVera OVAAssert class.
+ classOVAEngine + +
+          An implementation of the OpenVera OVAEngine class.
+ classOVAEvent + +
+          An implementation of the OpenVera OVAEvent class.
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return JunoObject
+ JunoObjectJunoObject.object_copy() + +
+          Performs a deep copy of this JunoObject and returns the new JunoObject.
+  +

+ + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type JunoObject
+ intJunoObject.object_compare(JunoObject other) + +
+          Performs a deep compare of this object with the specified object.
+static voidJuno.srandom(int seed, + JunoObject obj) + +
+          Creates a new random number generator for the DV.simulation and seeds it with + the given value.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoRuntimeException.html b/docs/api/com/newisys/juno/runtime/class-use/JunoRuntimeException.html new file mode 100644 index 0000000..2e29cda --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoRuntimeException.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoRuntimeException (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoRuntimeException

+
+No usage of com.newisys.juno.runtime.JunoRuntimeException +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoString.html b/docs/api/com/newisys/juno/runtime/class-use/JunoString.html new file mode 100644 index 0000000..3ff2e97 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoString.html @@ -0,0 +1,354 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoString (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoString

+
+ + + + + +
+Uses of JunoString in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Fields in com.newisys.juno.runtime declared as JunoString
+static JunoStringJunoString.NULL + +
+          A constant null string.
+  +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime that return JunoString
+ JunoStringJunoString.assign(JunoString other) + +
+          Assigns other to this JunoString.
+ JunoStringJunoString.assign(java.lang.String str) + +
+          Assigns str to this JunoString.
+ JunoStringJunoString.backref(int index) + +
+          Returns the substring corresponding to the specified capture group of the + previous match.
+ JunoStringJunoStringValueFactory.copyInstance(JunoString other) + +
+          Returns a new JunoString, which is a copy of other.
+ JunoStringJunoStringValueFactory.newInstance() + +
+          Instantiates a new JunoString and returns it.
+ JunoStringJunoString.postmatch() + +
+          Returns the substring of this JunoString including all characters after + the end of the previous match.
+ JunoStringJunoString.prematch() + +
+          Returns the substring of this JunoString including all characters up to + the beginning of the previous match.
+ JunoStringJunoString.substr(int start) + +
+          Returns a substring of this JunoString.
+ JunoStringJunoString.substr(int start, + int end) + +
+          Returns a substring of this JunoString.
+ JunoStringJunoString.thismatch() + +
+          Returns the substring corresponding to the previous match.
+ JunoStringJunoString.tolower() + +
+          Returns a new JunoString which is a copy of this JunoString will all + characters converted to lower case.
+ JunoStringJunoString.toupper() + +
+          Returns a new JunoString which is a copy of this JunoString will all + characters converted to upper case.
+  +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type JunoString
+ JunoStringJunoString.assign(JunoString other) + +
+          Assigns other to this JunoString.
+ intJunoString.compare(JunoString other) + +
+          Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String).
+ JunoStringJunoStringValueFactory.copyInstance(JunoString other) + +
+          Returns a new JunoString, which is a copy of other.
+ intJunoString.icompare(JunoString other) + +
+          Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String).
+ intJunoString.match(JunoString pattern) + +
+          Finds the specified regular expression in this JunoString.
+ intJunoString.search(JunoString pattern) + +
+          Searches for the specified pattern in this JunoString.
+static voidJuno.sprintf(JunoString str, + java.lang.String format, + java.lang.Object... args) + +
+          sprintf built-in function.
+  +

+ + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type JunoString
JunoString(JunoString other) + +
+          Creates a new JunoString, which is a copy of other.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/JunoStringValueFactory.html b/docs/api/com/newisys/juno/runtime/class-use/JunoStringValueFactory.html new file mode 100644 index 0000000..37d4ee9 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/JunoStringValueFactory.html @@ -0,0 +1,161 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.JunoStringValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.JunoStringValueFactory

+
+ + + + + +
+Uses of JunoStringValueFactory in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Fields in com.newisys.juno.runtime declared as JunoStringValueFactory
+static JunoStringValueFactoryJunoStringValueFactory.INSTANCE + +
+          A singleton instance of JunoStringValueFactory.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/LongWrapperOp.html b/docs/api/com/newisys/juno/runtime/class-use/LongWrapperOp.html new file mode 100644 index 0000000..3d7d887 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/LongWrapperOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.LongWrapperOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.LongWrapperOp

+
+No usage of com.newisys.juno.runtime.LongWrapperOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/OVAAssert.html b/docs/api/com/newisys/juno/runtime/class-use/OVAAssert.html new file mode 100644 index 0000000..b29e134 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/OVAAssert.html @@ -0,0 +1,177 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.OVAAssert (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.OVAAssert

+
+ + + + + +
+Uses of OVAAssert in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime that return OVAAssert
+ OVAAssertOVAEngine.GetAssert(java.lang.String name) + +
+          Returns the OVAAssert with the specified name.
+ OVAAssertOVAEngine.GetFirstAssert() + +
+          Returns the first assertion from the underlying OVA implementation.
+ OVAAssertOVAEngine.GetNextAssert() + +
+          Returns the next assertion from the underlying OVA implementation.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/OVAEngine.html b/docs/api/com/newisys/juno/runtime/class-use/OVAEngine.html new file mode 100644 index 0000000..96ce6f7 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/OVAEngine.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.OVAEngine (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.OVAEngine

+
+No usage of com.newisys.juno.runtime.OVAEngine +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/OVAEvent.html b/docs/api/com/newisys/juno/runtime/class-use/OVAEvent.html new file mode 100644 index 0000000..9a8ad5a --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/OVAEvent.html @@ -0,0 +1,189 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.OVAEvent (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.OVAEvent

+
+ + + + + +
+Uses of OVAEvent in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type OVAEvent
+ voidOVAEngine.DisableTrigger(OVAEvent event) + +
+          Disables the specified OVAEvent from being triggered when the event type + associated with it occurs.
+ voidOVAAssert.DisableTrigger(OVAEvent event) + +
+          Disables the specified OVAEvent from being triggered when the event type + associated with it occurs.
+ voidOVAEngine.EnableTrigger(OVAEvent event) + +
+          Enables the specified OVAEvent to be triggered when the event type + associated with it occurs.
+ voidOVAAssert.EnableTrigger(OVAEvent event) + +
+          Enables the specified OVAEvent to be triggered when the event type + associated with it occurs.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/StringAssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/StringAssocArray.html new file mode 100644 index 0000000..007a623 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/StringAssocArray.html @@ -0,0 +1,191 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.StringAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.StringAssocArray

+
+ + + + + +
+Uses of StringAssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Subclasses of StringAssocArray in com.newisys.juno.runtime
+ classStringObjectAssocArray + +
+          String-to-Object associative array.
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return StringAssocArray
+ StringAssocArray<V>StringAssocArray.clone() + +
+           
+  +

+ + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type StringAssocArray
StringAssocArray(StringAssocArray<? extends V> other) + +
+          Creates a StringAssocArray which is a copy of the specified array.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/StringObjectAssocArray.html b/docs/api/com/newisys/juno/runtime/class-use/StringObjectAssocArray.html new file mode 100644 index 0000000..42f9d6e --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/StringObjectAssocArray.html @@ -0,0 +1,161 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.StringObjectAssocArray (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.StringObjectAssocArray

+
+ + + + + +
+Uses of StringObjectAssocArray in com.newisys.juno.runtime
+  +

+ + + + + + + + + +
Methods in com.newisys.juno.runtime that return StringObjectAssocArray
+ StringObjectAssocArrayStringObjectAssocArray.clone() + +
+           
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/StringOp.html b/docs/api/com/newisys/juno/runtime/class-use/StringOp.html new file mode 100644 index 0000000..8de4f8a --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/StringOp.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.StringOp (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.StringOp

+
+No usage of com.newisys.juno.runtime.StringOp +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/TestbenchFactory.html b/docs/api/com/newisys/juno/runtime/class-use/TestbenchFactory.html new file mode 100644 index 0000000..76c5eee --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/TestbenchFactory.html @@ -0,0 +1,138 @@ + + + + + + +Uses of Class com.newisys.juno.runtime.TestbenchFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Class
com.newisys.juno.runtime.TestbenchFactory

+
+No usage of com.newisys.juno.runtime.TestbenchFactory +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/class-use/ValueFactory.html b/docs/api/com/newisys/juno/runtime/class-use/ValueFactory.html new file mode 100644 index 0000000..7355835 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/class-use/ValueFactory.html @@ -0,0 +1,260 @@ + + + + + + +Uses of Interface com.newisys.juno.runtime.ValueFactory (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Interface
com.newisys.juno.runtime.ValueFactory

+
+ + + + + +
+Uses of ValueFactory in com.newisys.juno.runtime
+  +

+ + + + + + + + + + + + + + + + + +
Classes in com.newisys.juno.runtime that implement ValueFactory
+ classImmutableValueFactory<T> + +
+          Implementation of ValueFactory for immutable objects.
+ classJunoEventValueFactory + +
+          Implements a ValueFactory for JunoEvent objects.
+ classJunoStringValueFactory + +
+          Implementation of ValueFactory for JunoString objects.
+  +

+ + + + + + + + + + + + + +
Methods in com.newisys.juno.runtime with parameters of type ValueFactory
+static + + + + +
+<T> T[]
+
Juno.copyArray(T[] dstArray, + T[] srcArray, + ValueFactory<T> factory) + +
+          Clones the elements in the given source array into the given destination + array, and initializes any extra elements in the destination array, using + the given value factory.
+static + + + + +
+<T> T[]
+
Juno.initArray(T[] array, + ValueFactory<T> factory, + int start) + +
+          Initializes the given Object array with values from the given factory, + starting at the given index and continuing to the end of the array.
+  +

+ + + + + + + + + + + + + + + + + + + + +
Constructors in com.newisys.juno.runtime with parameters of type ValueFactory
AssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates an AssocArray with the specified default value factory.
BitAssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates a BitAssocArray with the specified default value factory.
BitObjectAssocArray(ValueFactory<?> nullValueFactory) + +
+          Creates a BitObjectAssocArray with the specified default value factory.
StringAssocArray(ValueFactory<? extends V> nullValueFactory) + +
+          Creates a StringAssocArray with the specified default value factory.
StringObjectAssocArray(ValueFactory<?> nullValueFactory) + +
+          Creates a StringObjectAssocArray with the specified ValueFactory.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/package-frame.html b/docs/api/com/newisys/juno/runtime/package-frame.html new file mode 100644 index 0000000..ecc4ed4 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/package-frame.html @@ -0,0 +1,117 @@ + + + + + + +com.newisys.juno.runtime (Jove API) + + + + + + + + + + + +com.newisys.juno.runtime + + + + +
+Interfaces  + +
+JunoEnum +
+ValueFactory
+ + + + + + +
+Classes  + +
+AssocArray +
+BitAssocArray +
+BitBitAssocArray +
+BitObjectAssocArray +
+BitOp +
+BitVectorOp +
+BooleanOp +
+ImmutableValueFactory +
+IntegerOp +
+IntOp +
+Juno +
+JunoEnumUtil +
+JunoEvent +
+JunoEventValueFactory +
+JunoObject +
+JunoObject.PackingPosition +
+JunoString +
+JunoStringValueFactory +
+LongWrapperOp +
+OVAAssert +
+OVAEngine +
+OVAEvent +
+StringAssocArray +
+StringObjectAssocArray +
+StringOp +
+TestbenchFactory
+ + + + + + +
+Exceptions  + +
+JunoRuntimeException
+ + + + + + +
+Errors  + +
+AbstractMethodCallError
+ + + + diff --git a/docs/api/com/newisys/juno/runtime/package-summary.html b/docs/api/com/newisys/juno/runtime/package-summary.html new file mode 100644 index 0000000..bcf14b0 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/package-summary.html @@ -0,0 +1,321 @@ + + + + + + +com.newisys.juno.runtime (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+

+Package com.newisys.juno.runtime +

+Provides runtime support for Vera built-in functions, data structures, and + types. +

+See: +
+          Description +

+ + + + + + + + + + + + + +
+Interface Summary
JunoEnum<E extends Enum<E> & JunoEnum<E>>Interface implemented by enum types translated from Vera.
ValueFactory<T>A factory interface that supports creating and copying objects.
+  + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Class Summary
AssocArray<K,V>Base implementation of associative arrays.
BitAssocArray<V>BitVector-keyed associative array.
BitBitAssocArrayBitVector-to-BitVector associative array.
BitObjectAssocArrayBitVector-to-Object associative array.
BitOpBit conversion and operation methods referenced by translated code.
BitVectorOpBitVector conversion and operation methods referenced by translated code.
BooleanOpboolean conversion and operation methods referenced by + translated code.
ImmutableValueFactory<T>Implementation of ValueFactory for immutable objects.
IntegerOpInteger conversion and operation methods referenced by translated code.
IntOpint/long conversion and operation methods + referenced by translated code.
JunoImplementations of Vera's built-in functions for use by translated code.
JunoEnumUtilStatic utility methods used in the implementation of translated enum types.
JunoEventA Jove Event with the semantics of Vera's built-in events.
JunoEventValueFactoryImplements a ValueFactory for JunoEvent objects.
JunoObjectBase class for all translated Vera classes.
JunoObject.PackingPosition 
JunoStringAn implementation of Vera's built-in string type.
JunoStringValueFactoryImplementation of ValueFactory for JunoString objects.
LongWrapperOpLong conversion and operation methods referenced by translated code.
OVAAssertAn implementation of the OpenVera OVAAssert class.
OVAEngineAn implementation of the OpenVera OVAEngine class.
OVAEventAn implementation of the OpenVera OVAEvent class.
StringAssocArray<V>String-keyed associative array.
StringObjectAssocArrayString-to-Object associative array.
StringOpString conversion and operation methods referenced by translated code.
TestbenchFactoryFactory used to instantiate a testbench in a polymorphic fashion.
+  + +

+ + + + + + + + + +
+Exception Summary
JunoRuntimeExceptionException thrown by the Juno runtime when the original Vera code would have + encountered a Vera runtime error.
+  + +

+ + + + + + + + + +
+Error Summary
AbstractMethodCallErrorException thrown by translator-generated stub methods in non-abstract classes + when an abstract method is unimplemented.
+  + +

+

+Package com.newisys.juno.runtime Description +

+ +

+Provides runtime support for Vera built-in functions, data structures, and + types. +

+ All Vera built-in functions can be found in Juno. +

+ +

+

+
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/package-tree.html b/docs/api/com/newisys/juno/runtime/package-tree.html new file mode 100644 index 0000000..42998f2 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/package-tree.html @@ -0,0 +1,176 @@ + + + + + + +com.newisys.juno.runtime Class Hierarchy (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Hierarchy For Package com.newisys.juno.runtime +

+
+

+Class Hierarchy +

+ +

+Interface Hierarchy +

+ +
+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/com/newisys/juno/runtime/package-use.html b/docs/api/com/newisys/juno/runtime/package-use.html new file mode 100644 index 0000000..3524c44 --- /dev/null +++ b/docs/api/com/newisys/juno/runtime/package-use.html @@ -0,0 +1,241 @@ + + + + + + +Uses of Package com.newisys.juno.runtime (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Uses of Package
com.newisys.juno.runtime

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Classes in com.newisys.juno.runtime used by com.newisys.juno.runtime
AssocArray + +
+          Base implementation of associative arrays.
BitAssocArray + +
+          BitVector-keyed associative array.
BitBitAssocArray + +
+          BitVector-to-BitVector associative array.
BitObjectAssocArray + +
+          BitVector-to-Object associative array.
JunoEnum + +
+          Interface implemented by enum types translated from Vera.
JunoEvent + +
+          A Jove Event with the semantics of Vera's built-in events.
JunoEventValueFactory + +
+          Implements a ValueFactory for JunoEvent objects.
JunoObject + +
+          Base class for all translated Vera classes.
JunoObject.PackingPosition + +
+           
JunoString + +
+          An implementation of Vera's built-in string type.
JunoStringValueFactory + +
+          Implementation of ValueFactory for JunoString objects.
OVAAssert + +
+          An implementation of the OpenVera OVAAssert class.
OVAEvent + +
+          An implementation of the OpenVera OVAEvent class.
StringAssocArray + +
+          String-keyed associative array.
StringObjectAssocArray + +
+          String-to-Object associative array.
ValueFactory + +
+          A factory interface that supports creating and copying objects.
+  +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/constant-values.html b/docs/api/constant-values.html new file mode 100644 index 0000000..c6e7836 --- /dev/null +++ b/docs/api/constant-values.html @@ -0,0 +1,528 @@ + + + + + + +Constant Field Values (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Constant Field Values

+
+
+Contents + + + + + + +
+com.newisys.*
+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
com.newisys.juno.runtime.Juno
+public static final intALL1
+public static final intANY2
+public static final intCHECK0
+public static final intCOPY_NO_WAIT2
+public static final intCOPY_WAIT3
+public static final intDELETE3
+public static final intFIRST1
+public static final intHAND_SHAKE4
+public static final intHI1
+public static final intHNUM3
+public static final intLO0
+public static final intMAILBOX2
+public static final intNEXT2
+public static final intNO_WAIT0
+public static final intNUM1
+public static final intOFF0
+public static final intON1
+public static final intONE_BLAST3
+public static final intONE_SHOT2
+public static final intORDER3
+public static final intRAWIN1
+public static final intREGION1
+public static final intSEMAPHORE0
+public static final intSILENT0
+public static final intSTR2
+public static final intVERBOSE4
+public static final intWAIT1
+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
com.newisys.juno.runtime.JunoObject
+public static final intCONSTRAINT_MODE_FAIL-1
+public static final intFAIL0
+public static final intOFF0
+public static final intOK1
+public static final intON1
+public static final intRAND_MODE_FAIL-1
+public static final intREPORT2
+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + +
com.newisys.juno.runtime.JunoString
+public static final intOK0
+public static final intSTR_ERR_OUT_OF_RANGE1
+public static final intSTR_ERR_REGEXP_SYNTAX2
+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
com.newisys.juno.runtime.OVAEngine
+public static final intOVA_ALL11
+public static final intOVA_ASSERTID_NULL0
+public static final intOVA_CLIENTID_NULL0
+public static final intOVA_DISABLE7
+public static final intOVA_ENABLE8
+public static final intOVA_FAILURE9
+public static final intOVA_FALSE0
+public static final intOVA_FINISH5
+public static final intOVA_INFO0
+public static final intOVA_MANAGE_ATTEMPTS3
+public static final intOVA_NO_OP14
+public static final intOVA_NULL12
+public static final intOVA_QUIET1
+public static final intOVA_REPORT2
+public static final intOVA_RESET4
+public static final intOVA_SUCCESS10
+public static final intOVA_TERMINATE6
+public static final intOVA_TRUE1
+ +

+ +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/deprecated-list.html b/docs/api/deprecated-list.html new file mode 100644 index 0000000..8a4e82c --- /dev/null +++ b/docs/api/deprecated-list.html @@ -0,0 +1,140 @@ + + + + + + +Deprecated List (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Deprecated API

+
+
+Contents
    +
+ +
+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/help-doc.html b/docs/api/help-doc.html new file mode 100644 index 0000000..602ecfc --- /dev/null +++ b/docs/api/help-doc.html @@ -0,0 +1,211 @@ + + + + + + +API Help (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+How This API Document Is Organized

+
+This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

+Package

+
+ +

+Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

    +
  • Interfaces (italic)
  • Classes
  • Enums
  • Exceptions
  • Errors
  • Annotation Types
+
+

+Class/Interface

+
+ +

+Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

    +
  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description +

    +

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary +

    +

  • Field Detail
  • Constructor Detail
  • Method Detail
+Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.
+ +

+Annotation Type

+
+ +

+Each annotation type has its own separate page with the following sections:

    +
  • Annotation Type declaration
  • Annotation Type description
  • Required Element Summary
  • Optional Element Summary
  • Element Detail
+
+ +

+Enum

+
+ +

+Each enum has its own separate page with the following sections:

    +
  • Enum declaration
  • Enum description
  • Enum Constant Summary
  • Enum Constant Detail
+
+

+Use

+
+Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.
+

+Tree (Class Hierarchy)

+
+There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
    +
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.
+
+

+Deprecated API

+
+The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.
+

+Index

+
+The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.
+

+Prev/Next

+These links take you to the next or previous class, interface, package, or related page.

+Frames/No Frames

+These links show and hide the HTML frames. All pages are available with or without frames. +

+

+Serialized Form

+Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description. +

+

+Constant Field Values

+The Constant Field Values page lists the static final fields and their values. +

+ + +This help file applies to API documentation generated using the standard doclet. + +
+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/index-files/index-1.html b/docs/api/index-files/index-1.html new file mode 100644 index 0000000..1e76002 --- /dev/null +++ b/docs/api/index-files/index-1.html @@ -0,0 +1,221 @@ + + + + + + +A-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+A

+
+
AbstractMethodCallError - Error in com.newisys.juno.runtime
Exception thrown by translator-generated stub methods in non-abstract classes + when an abstract method is unimplemented.
AbstractMethodCallError() - +Constructor for error com.newisys.juno.runtime.AbstractMethodCallError +
  +
AbstractMethodCallError(String) - +Constructor for error com.newisys.juno.runtime.AbstractMethodCallError +
  +
add(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
add(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
advance(E, int) - +Static method in class com.newisys.juno.runtime.JunoEnumUtil +
  +
ALL - +Static variable in class com.newisys.juno.runtime.Juno +
  +
alloc(int, int, int) - +Static method in class com.newisys.juno.runtime.Juno +
alloc built-in function for allocating a REGION or a MAILBOX. +
alloc(int, int, int, int) - +Static method in class com.newisys.juno.runtime.Juno +
alloc built-in function for allocating a REGION or a MAILBOX. +
ANY - +Static variable in class com.newisys.juno.runtime.Juno +
  +
assign(String) - +Method in class com.newisys.juno.runtime.JunoString +
Assigns str to this JunoString. +
assign(JunoString) - +Method in class com.newisys.juno.runtime.JunoString +
Assigns other to this JunoString. +
assoc_index(int, AssocArray<?, ?>) - +Static method in class com.newisys.juno.runtime.Juno +
assoc_index built-in function for dealing with entire arrays. +
assoc_index(int, AssocArray, Object) - +Static method in class com.newisys.juno.runtime.Juno +
assoc_index built-in function for dealing with array elements. +
assoc_index(int, AssocArray, int[]) - +Static method in class com.newisys.juno.runtime.Juno +
See Juno.assoc_index(int, AssocArray, Object[]). +
assoc_index(int, AssocArray, Object[]) - +Static method in class com.newisys.juno.runtime.Juno +
assoc_index built-in function for dealing with array elements. +
AssocArray<K,V> - Class in com.newisys.juno.runtime
Base implementation of associative arrays.
AssocArray() - +Constructor for class com.newisys.juno.runtime.AssocArray +
Creates an AssocArray with a default value of null. +
AssocArray(V) - +Constructor for class com.newisys.juno.runtime.AssocArray +
Creates an AssocArray with the specified default value. +
AssocArray(ValueFactory<? extends V>) - +Constructor for class com.newisys.juno.runtime.AssocArray +
Creates an AssocArray with the specified default value factory. +
AssocArray(AssocArray<? extends K, ? extends V>) - +Constructor for class com.newisys.juno.runtime.AssocArray +
Creates a new AssocArray which is a copy of the specified array. +
atobin() - +Method in class com.newisys.juno.runtime.JunoString +
Parses this JunoString as a binary value and returns the equivalent + BitVector. +
atobin(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
atohex() - +Method in class com.newisys.juno.runtime.JunoString +
Parses this JunoString as a hexadecimal value and returns the equivalent + BitVector. +
atohex(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
atoi() - +Method in class com.newisys.juno.runtime.JunoString +
Parses this JunoString as a decimal value and returns the resulting int. +
atoi(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
atooct() - +Method in class com.newisys.juno.runtime.JunoString +
Parses this JunoString as an octal value and returns the equivalent + BitVector. +
atooct(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-10.html b/docs/api/index-files/index-10.html new file mode 100644 index 0000000..0b9fb7b --- /dev/null +++ b/docs/api/index-files/index-10.html @@ -0,0 +1,189 @@ + + + + + + +J-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+J

+
+
Juno - Class in com.newisys.juno.runtime
Implementations of Vera's built-in functions for use by translated code.
Juno() - +Constructor for class com.newisys.juno.runtime.Juno +
  +
JunoEnum<E extends java.lang.Enum<E> & JunoEnum<E>> - Interface in com.newisys.juno.runtime
Interface implemented by enum types translated from Vera.
JunoEnumUtil - Class in com.newisys.juno.runtime
Static utility methods used in the implementation of translated enum types.
JunoEnumUtil() - +Constructor for class com.newisys.juno.runtime.JunoEnumUtil +
  +
JunoEvent - Class in com.newisys.juno.runtime
A Jove Event with the semantics of Vera's built-in events.
JunoEvent() - +Constructor for class com.newisys.juno.runtime.JunoEvent +
Creates a new JunoEvent. +
JunoEvent(String) - +Constructor for class com.newisys.juno.runtime.JunoEvent +
Creates a new JunoEvent with the specified name. +
JunoEventValueFactory - Class in com.newisys.juno.runtime
Implements a ValueFactory for JunoEvent objects.
JunoEventValueFactory() - +Constructor for class com.newisys.juno.runtime.JunoEventValueFactory +
  +
JunoObject - Class in com.newisys.juno.runtime
Base class for all translated Vera classes.
JunoObject() - +Constructor for class com.newisys.juno.runtime.JunoObject +
Creates a new JunoObject. +
JunoObject.PackingPosition - Class in com.newisys.juno.runtime
 
JunoObject.PackingPosition() - +Constructor for class com.newisys.juno.runtime.JunoObject.PackingPosition +
  +
JunoObject.PackingPosition(long, int, int) - +Constructor for class com.newisys.juno.runtime.JunoObject.PackingPosition +
  +
JunoRuntimeException - Exception in com.newisys.juno.runtime
Exception thrown by the Juno runtime when the original Vera code would have + encountered a Vera runtime error.
JunoRuntimeException() - +Constructor for exception com.newisys.juno.runtime.JunoRuntimeException +
  +
JunoRuntimeException(String) - +Constructor for exception com.newisys.juno.runtime.JunoRuntimeException +
  +
JunoRuntimeException(Throwable) - +Constructor for exception com.newisys.juno.runtime.JunoRuntimeException +
  +
JunoRuntimeException(String, Throwable) - +Constructor for exception com.newisys.juno.runtime.JunoRuntimeException +
  +
JunoString - Class in com.newisys.juno.runtime
An implementation of Vera's built-in string type.
JunoString() - +Constructor for class com.newisys.juno.runtime.JunoString +
Creates a new, empty JunoString. +
JunoString(String) - +Constructor for class com.newisys.juno.runtime.JunoString +
Creates a new JunoString, which is a copy of str. +
JunoString(String, int, Matcher) - +Constructor for class com.newisys.juno.runtime.JunoString +
Creates a new JunoString, which is a copy of str and has + the specified status and matcher state. +
JunoString(JunoString) - +Constructor for class com.newisys.juno.runtime.JunoString +
Creates a new JunoString, which is a copy of other. +
JunoStringValueFactory - Class in com.newisys.juno.runtime
Implementation of ValueFactory for JunoString objects.
JunoStringValueFactory() - +Constructor for class com.newisys.juno.runtime.JunoStringValueFactory +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-11.html b/docs/api/index-files/index-11.html new file mode 100644 index 0000000..868460c --- /dev/null +++ b/docs/api/index-files/index-11.html @@ -0,0 +1,202 @@ + + + + + + +L-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+L

+
+
leave_context() - +Static method in class com.newisys.juno.runtime.Juno +
Leave a thread context. +
left - +Variable in class com.newisys.juno.runtime.JunoObject.PackingPosition +
  +
len() - +Method in class com.newisys.juno.runtime.JunoString +
Returns the length of this JunoString. +
len(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
less(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
less(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
less(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
lessOrEqual(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
lessOrEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
lessOrEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
LO - +Static variable in class com.newisys.juno.runtime.Juno +
  +
lock_file(String, int) - +Static method in class com.newisys.juno.runtime.Juno +
lock_file built-in function. +
logicalAnd(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
logicalAnd(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
logicalNegative(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
logicalNegative(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
logicalOr(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
logicalOr(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
LongWrapperOp - Class in com.newisys.juno.runtime
Long conversion and operation methods referenced by translated code.
lowBitToBoolean(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
lowBitToBoolean(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
lowBitToBooleanXZTrue(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
lowBitToBooleanXZTrue(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-12.html b/docs/api/index-files/index-12.html new file mode 100644 index 0000000..f3922d6 --- /dev/null +++ b/docs/api/index-files/index-12.html @@ -0,0 +1,181 @@ + + + + + + +M-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+M

+
+
MAILBOX - +Static variable in class com.newisys.juno.runtime.Juno +
  +
mailbox_get(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the size of the given mailbox. +
mailbox_get(int, int, Object[]) - +Static method in class com.newisys.juno.runtime.Juno +
Retrieve an object from a given mailbox. +
mailbox_get(int, int, Object[], int) - +Static method in class com.newisys.juno.runtime.Juno +
Retrieve an object from a given mailbox. +
mailbox_put(int, Object) - +Static method in class com.newisys.juno.runtime.Juno +
Put an object into a given mailbox. +
match(String) - +Method in class com.newisys.juno.runtime.JunoString +
Finds the specified regular expression in this JunoString. +
match(JunoString) - +Method in class com.newisys.juno.runtime.JunoString +
Finds the specified regular expression in this JunoString. +
match(String, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
match(String, String, Matcher[], int[]) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
mod(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
mod(boolean, boolean) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
mod(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
mod(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
multiply(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
multiply(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-13.html b/docs/api/index-files/index-13.html new file mode 100644 index 0000000..c2cc6ca --- /dev/null +++ b/docs/api/index-files/index-13.html @@ -0,0 +1,194 @@ + + + + + + +N-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+N

+
+
negate(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
negate(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
newInstance() - +Method in class com.newisys.juno.runtime.ImmutableValueFactory +
Returns the immutable object for this factory. +
newInstance() - +Method in class com.newisys.juno.runtime.JunoEventValueFactory +
Instantiates a new JunoEvent and returns it. +
newInstance() - +Method in class com.newisys.juno.runtime.JunoStringValueFactory +
Instantiates a new JunoString and returns it. +
newInstance() - +Method in interface com.newisys.juno.runtime.ValueFactory +
Create a new instance of the underlying object. +
next(K) - +Method in class com.newisys.juno.runtime.AssocArray +
Returns the key following the given key in this associative array. +
next(BitVector) - +Method in class com.newisys.juno.runtime.BitAssocArray +
Returns the key following the given key in this associative array. +
NEXT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
next() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the enum constant following this one, in declaration order. +
next(int) - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the n'th enum constant following this one, in declaration order, + wrapping from the last constant to the first as necessary. +
NO_WAIT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
notEqual(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
notEqual(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
notEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
notEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
NULL - +Static variable in class com.newisys.juno.runtime.JunoString +
A constant null string. +
NULL_KEY - +Static variable in class com.newisys.juno.runtime.BitAssocArray +
  +
NUM - +Static variable in class com.newisys.juno.runtime.Juno +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-14.html b/docs/api/index-files/index-14.html new file mode 100644 index 0000000..273398b --- /dev/null +++ b/docs/api/index-files/index-14.html @@ -0,0 +1,245 @@ + + + + + + +O-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+O

+
+
object_compare(JunoObject) - +Method in class com.newisys.juno.runtime.JunoObject +
Performs a deep compare of this object with the specified object. +
object_copy() - +Method in class com.newisys.juno.runtime.JunoObject +
Performs a deep copy of this JunoObject and returns the new JunoObject. +
object_print() - +Method in class com.newisys.juno.runtime.JunoObject +
Prints the object instance hierarchy of this object to + Juno.STDOUT. +
object_print(int) - +Method in class com.newisys.juno.runtime.JunoObject +
Prints the object instance hierarchy of this object to the specified + Vera file descriptor. +
object_print(int, String) - +Method in class com.newisys.juno.runtime.JunoObject +
Prints the object instance hierarchy of this object to the specified + Vera file descriptor with the specified attributes. +
OFF - +Static variable in class com.newisys.juno.runtime.Juno +
  +
OFF - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
OK - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
OK - +Static variable in class com.newisys.juno.runtime.JunoString +
Vera's OK define. +
ON - +Static variable in class com.newisys.juno.runtime.Juno +
  +
ON - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
ONE_BLAST - +Static variable in class com.newisys.juno.runtime.Juno +
  +
ONE_SHOT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
ORDER - +Static variable in class com.newisys.juno.runtime.Juno +
  +
os_command(String) - +Static method in class com.newisys.juno.runtime.Juno +
Run a command outside of the Jove environment. +
OVA_ALL - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_ASSERTID_NULL - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_CLIENTID_NULL - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_DISABLE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_ENABLE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_FAILURE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_FALSE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_FINISH - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_INFO - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_MANAGE_ATTEMPTS - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_NO_OP - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_NULL - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_QUIET - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_REPORT - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_RESET - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_SUCCESS - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_TERMINATE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVA_TRUE - +Static variable in class com.newisys.juno.runtime.OVAEngine +
  +
OVAAssert - Class in com.newisys.juno.runtime
An implementation of the OpenVera OVAAssert class.
OVAEngine - Class in com.newisys.juno.runtime
An implementation of the OpenVera OVAEngine class.
OVAEngine() - +Constructor for class com.newisys.juno.runtime.OVAEngine +
  +
OVAEvent - Class in com.newisys.juno.runtime
An implementation of the OpenVera OVAEvent class.
OVAEvent(int) - +Constructor for class com.newisys.juno.runtime.OVAEvent +
Create an OVA Event associated with the type of event described by the + event parameter. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-15.html b/docs/api/index-files/index-15.html new file mode 100644 index 0000000..6d6b996 --- /dev/null +++ b/docs/api/index-files/index-15.html @@ -0,0 +1,231 @@ + + + + + + +P-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+P

+
+
pack(BitBitAssocArray, JunoObject.PackingPosition) - +Method in class com.newisys.juno.runtime.JunoObject +
  +
post_pack() - +Method in class com.newisys.juno.runtime.JunoObject +
  +
post_randomize() - +Method in class com.newisys.juno.runtime.JunoObject +
Allows code to be run just after this object has been randomized. +
post_unpack() - +Method in class com.newisys.juno.runtime.JunoObject +
  +
postmatch() - +Method in class com.newisys.juno.runtime.JunoString +
Returns the substring of this JunoString including all characters after + the end of the previous match. +
postmatch(String, Matcher) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
postRandomize() - +Method in class com.newisys.juno.runtime.JunoObject +
Allows code to be run just after this object is randomized. +
pre_pack() - +Method in class com.newisys.juno.runtime.JunoObject +
  +
pre_randomize() - +Method in class com.newisys.juno.runtime.JunoObject +
Allows code to be run just prior to this object being randomized. +
pre_unpack() - +Method in class com.newisys.juno.runtime.JunoObject +
  +
prematch() - +Method in class com.newisys.juno.runtime.JunoString +
Returns the substring of this JunoString including all characters up to + the beginning of the previous match. +
prematch(String, Matcher) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
preRandomize() - +Method in class com.newisys.juno.runtime.JunoObject +
Allows code to be run just prior to this object being randomized. +
previous() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the enum constant preceding this one, in declaration order. +
previous(int) - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the n'th enum constant preceding this one, in declaration order, + wrapping from the first constant to the last as necessary. +
printf(String, Object...) - +Static method in class com.newisys.juno.runtime.Juno +
printf built-in function. +
promote(BitVector, int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
psprintf(String, Object...) - +Static method in class com.newisys.juno.runtime.Juno +
psprintf built-in function. +
put(K, V) - +Method in class com.newisys.juno.runtime.AssocArray +
Associates the specified value with the specified key in this + associative array. +
put(BitVector, V) - +Method in class com.newisys.juno.runtime.BitAssocArray +
Associates the specified value with the specified key in this + associative array. +
putc(int, char) - +Method in class com.newisys.juno.runtime.JunoString +
Inserts the specified character into this JunoString at the specified + index. +
putc(int, int) - +Method in class com.newisys.juno.runtime.JunoString +
Inserts the specified character into this JunoString at the specified + index. +
putc(int, String) - +Method in class com.newisys.juno.runtime.JunoString +
Inserts the first character of the specified String into this JunoString + at the specified index. +
putc(String, int, char) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
putc(String, int, char, int[]) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
putc(String, int, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
putc(String, int, int, int[]) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
putc(String, int, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
putc(String, int, String, int[]) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-16.html b/docs/api/index-files/index-16.html new file mode 100644 index 0000000..c7b132b --- /dev/null +++ b/docs/api/index-files/index-16.html @@ -0,0 +1,270 @@ + + + + + + +R-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+R

+
+
rand48() - +Static method in class com.newisys.juno.runtime.Juno +
Returns a 32 bit signed random value generated using a 48 bit linear + congruential algorithm. +
rand48(int) - +Static method in class com.newisys.juno.runtime.Juno +
Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit signed rand value generated from it. +
rand_mode(int) - +Method in class com.newisys.juno.runtime.JunoObject +
Toggles the randomization mode of all random variables in this object. +
rand_mode(int, String) - +Method in class com.newisys.juno.runtime.JunoObject +
Toggles the randomization mode of the specified random variable in this + object. +
rand_mode(int, String, int) - +Method in class com.newisys.juno.runtime.JunoObject +
Toggles the randomization mode of the specified random variable in this + object. +
RAND_MODE_FAIL - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
randcase(int...) - +Static method in class com.newisys.juno.runtime.Juno +
Choose a value based on a weighted randomization. +
random() - +Static method in class com.newisys.juno.runtime.Juno +
Return a 32 bit signed random value. +
random(int) - +Static method in class com.newisys.juno.runtime.Juno +
Seeds the random number generator and then returns a 32 bit signed rand + value. +
randomize() - +Method in class com.newisys.juno.runtime.JunoObject +
Randomize this JunoObject. +
RAWIN - +Static variable in class com.newisys.juno.runtime.Juno +
  +
reductiveAnd(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveAnd(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveAnd(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveAnd(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
reductiveAndNot(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveAndNot(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveAndNot(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveAndNot(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
reductiveOr(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveOr(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveOr(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveOr(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
reductiveOrNot(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveOrNot(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveOrNot(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveOrNot(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
reductiveXor(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveXor(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveXor(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveXor(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
reductiveXorNot(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
reductiveXorNot(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveXorNot(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
reductiveXorNot(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
REGION - +Static variable in class com.newisys.juno.runtime.Juno +
  +
region_enter(int, int, Object[]) - +Static method in class com.newisys.juno.runtime.Juno +
NOTE: region_enter is currently unsupported. +
region_exit(int, Object[]) - +Static method in class com.newisys.juno.runtime.Juno +
NOTE: region_exit is currently unsupported. +
replicate(int, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
replicate(int, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
REPORT - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
rewind(int) - +Static method in class com.newisys.juno.runtime.Juno +
rewind built-in function. +
right - +Variable in class com.newisys.juno.runtime.JunoObject.PackingPosition +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-17.html b/docs/api/index-files/index-17.html new file mode 100644 index 0000000..4a388b9 --- /dev/null +++ b/docs/api/index-files/index-17.html @@ -0,0 +1,244 @@ + + + + + + +S-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+S

+
+
search(JunoString) - +Method in class com.newisys.juno.runtime.JunoString +
Searches for the specified pattern in this JunoString. +
search(String, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
SEMAPHORE - +Static variable in class com.newisys.juno.runtime.Juno +
  +
semaphore_get(int, int, int) - +Static method in class com.newisys.juno.runtime.Juno +
Acquire one or more keys from a given semaphore. +
semaphore_put(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
Release the specified number of keys to the specified semaphore. +
setBits(BitVector, int, int, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
Wrapper for BitVector.setBits() that allows high and low indices to be + swapped. +
setRandom(PRNG) - +Method in class com.newisys.juno.runtime.JunoObject +
Sets the random number generator for this object. +
shiftLeft(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
shiftLeft(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
shiftRight(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
shiftRight(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
SILENT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
sprintf(JunoString, String, Object...) - +Static method in class com.newisys.juno.runtime.Juno +
sprintf built-in function. +
srandom(int) - +Static method in class com.newisys.juno.runtime.Juno +
Creates a new random number generator for the DV.simulation and seeds it with + the given value. +
srandom(int, JunoObject) - +Static method in class com.newisys.juno.runtime.Juno +
Creates a new random number generator for the DV.simulation and seeds it with + the given value. +
sscanf(String, String, Object[], Class[]) - +Static method in class com.newisys.juno.runtime.Juno +
built-in sscanf function. +
STR - +Static variable in class com.newisys.juno.runtime.Juno +
  +
STR_ERR_OUT_OF_RANGE - +Static variable in class com.newisys.juno.runtime.JunoString +
Vera's STR_ERR_OUT_OF_RANGE define. +
STR_ERR_REGEXP_SYNTAX - +Static variable in class com.newisys.juno.runtime.JunoString +
Vera's STR_ERR_REGEXP_SYNTAX define. +
StringAssocArray<V> - Class in com.newisys.juno.runtime
String-keyed associative array.
StringAssocArray() - +Constructor for class com.newisys.juno.runtime.StringAssocArray +
Creates a StringAssocArray. +
StringAssocArray(V) - +Constructor for class com.newisys.juno.runtime.StringAssocArray +
Creates a StringAssocArray with the specified default value. +
StringAssocArray(ValueFactory<? extends V>) - +Constructor for class com.newisys.juno.runtime.StringAssocArray +
Creates a StringAssocArray with the specified default value factory. +
StringAssocArray(StringAssocArray<? extends V>) - +Constructor for class com.newisys.juno.runtime.StringAssocArray +
Creates a StringAssocArray which is a copy of the specified array. +
StringObjectAssocArray - Class in com.newisys.juno.runtime
String-to-Object associative array.
StringObjectAssocArray() - +Constructor for class com.newisys.juno.runtime.StringObjectAssocArray +
Creates a StringObjectAssocArray. +
StringObjectAssocArray(Object) - +Constructor for class com.newisys.juno.runtime.StringObjectAssocArray +
Creates a StringObjectAssocArray with the specified default value. +
StringObjectAssocArray(ValueFactory<?>) - +Constructor for class com.newisys.juno.runtime.StringObjectAssocArray +
Creates a StringObjectAssocArray with the specified ValueFactory. +
StringObjectAssocArray(AssocArray) - +Constructor for class com.newisys.juno.runtime.StringObjectAssocArray +
Creates a StringObjectAssocArray which is a copy of the specified AssocArray. +
StringOp - Class in com.newisys.juno.runtime
String conversion and operation methods referenced by translated code.
substr(int) - +Method in class com.newisys.juno.runtime.JunoString +
Returns a substring of this JunoString. +
substr(int, int) - +Method in class com.newisys.juno.runtime.JunoString +
Returns a substring of this JunoString. +
substr(String, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
substr(String, int, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
subtract(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
subtract(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
sync(int, JunoEvent...) - +Static method in class com.newisys.juno.runtime.Juno +
Wait on a given set of JunoEvents to occur. +
systemClock - +Static variable in class com.newisys.juno.runtime.Juno +
Represents the system clock, "CLOCK". +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-18.html b/docs/api/index-files/index-18.html new file mode 100644 index 0000000..f403ba4 --- /dev/null +++ b/docs/api/index-files/index-18.html @@ -0,0 +1,376 @@ + + + + + + +T-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+T

+
+
TestbenchFactory - Class in com.newisys.juno.runtime
Factory used to instantiate a testbench in a polymorphic fashion.
thismatch() - +Method in class com.newisys.juno.runtime.JunoString +
Returns the substring corresponding to the previous match. +
thismatch(String, Matcher) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
toBit(int) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(long) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(Integer) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(Long) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(BitVector) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(String) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBit(Object) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBitVector(int, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toBitVector(boolean[]) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toBitVector(Bit) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toBitVector(Object) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toBitVector(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toBitVector(Integer, int) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toBitVector(Integer, int, boolean) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toBitVector(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toBitVector(Long, int) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toBitVector(Long, int, boolean) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toBoolean(Bit, boolean) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(BitVector) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(BitVector, boolean, boolean) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(Object) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(Object, boolean, boolean) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(String) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBoolean(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toBoolean(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toBooleanXZTrue(BitVector) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
toBooleanXZTrue(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toBooleanXZTrue(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toDisplayString(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
toInt(Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toInt(BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toInt(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInt(Object) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
toInt(String) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
toInt() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the int value corresponding to this enumeration + value. +
toInt(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toInteger(Bit) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger(BitVector) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger(BitVector, boolean) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger(Long) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger(String) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger(Object) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toInteger() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the Integer value corresponding to this enumeration. +
toLogicalBit(int) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toLogicalBit(long) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toLogicalBit(Integer) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toLogicalBit(Long) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toLogicalBit(BitVector) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toLong(Object) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
toLong(String) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
toLong(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(Bit) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(BitVector) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(BitVector, boolean) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(Integer) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(String) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toLongWrapper(Object) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
tolower() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a new JunoString which is a copy of this JunoString will all + characters converted to lower case. +
toShiftCount(Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
toShiftCount(BitVector, int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toShiftCount(BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
toShiftCount(Integer, int) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toShiftCount(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
toShiftCount(Long, int) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toShiftCount(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
toString() - +Method in class com.newisys.juno.runtime.AssocArray +
  +
toString() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the String representation of this enumeration value. +
toString(E) - +Static method in class com.newisys.juno.runtime.JunoEnumUtil +
  +
toString() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a String containing the contents of this JunoString, or "(NULL)" + if this JunoString contains the null string. +
toString() - +Method in class com.newisys.juno.runtime.OVAAssert +
  +
toStringOrBlank() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a String containing the contents of this JunoString, or an empty + string if this JunoString contains the null string. +
toStringOrBlank(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
toStringOrNull() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a String containing the contents of this JunoString, or null if + this JunoString contains the null string. +
toupper() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a new JunoString which is a copy of this JunoString will all + characters converted to upper case. +
trigger(JunoEvent...) - +Static method in class com.newisys.juno.runtime.Juno +
Triggers one or more JunoEvents in ONE_SHOT mode. +
trigger(int, JunoEvent...) - +Static method in class com.newisys.juno.runtime.Juno +
Triggers one or more JunoEvents. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-19.html b/docs/api/index-files/index-19.html new file mode 100644 index 0000000..f6581e6 --- /dev/null +++ b/docs/api/index-files/index-19.html @@ -0,0 +1,163 @@ + + + + + + +U-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+U

+
+
unlock_file(String) - +Static method in class com.newisys.juno.runtime.Juno +
unlock_file built-in function +
unpack(BitBitAssocArray, JunoObject.PackingPosition) - +Method in class com.newisys.juno.runtime.JunoObject +
  +
urand48() - +Static method in class com.newisys.juno.runtime.Juno +
Returns a 32 bit unsigned random value generated using a 48 bit linear + congruential algorithm. +
urand48(int) - +Static method in class com.newisys.juno.runtime.Juno +
Seeds the 48 bit linear congruential random number generator and then + returns a 32 bit unsigned rand value generated from it. +
urandom() - +Static method in class com.newisys.juno.runtime.Juno +
Returns a 32 bit unsigned random value. +
urandom(int) - +Static method in class com.newisys.juno.runtime.Juno +
Seeds the random number generator and then returns a 32 bit unsigned rand + value. +
urandom_range(BitVector) - +Static method in class com.newisys.juno.runtime.Juno +
Returns a 32 bit unsigned random value between 0 and maxval, inclusive. +
urandom_range(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.Juno +
Returns a 32 bit unsigned random value between minval and maxval, inclusive. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-2.html b/docs/api/index-files/index-2.html new file mode 100644 index 0000000..5047d9d --- /dev/null +++ b/docs/api/index-files/index-2.html @@ -0,0 +1,256 @@ + + + + + + +B-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+B

+
+
backref(int) - +Method in class com.newisys.juno.runtime.JunoString +
Returns the substring corresponding to the specified capture group of the + previous match. +
backref(String, Matcher, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
badCast() - +Static method in class com.newisys.juno.runtime.Juno +
  +
BIT_0 - +Static variable in class com.newisys.juno.runtime.BitVectorOp +
  +
BIT_1 - +Static variable in class com.newisys.juno.runtime.BitVectorOp +
  +
BIT_X - +Static variable in class com.newisys.juno.runtime.BitVectorOp +
  +
BIT_Z - +Static variable in class com.newisys.juno.runtime.BitVectorOp +
  +
BitAssocArray<V> - Class in com.newisys.juno.runtime
BitVector-keyed associative array.
BitAssocArray() - +Constructor for class com.newisys.juno.runtime.BitAssocArray +
Creates a BitAssocArray with a default value of null. +
BitAssocArray(V) - +Constructor for class com.newisys.juno.runtime.BitAssocArray +
Creates a BitAssocArray with the specified default value. +
BitAssocArray(ValueFactory<? extends V>) - +Constructor for class com.newisys.juno.runtime.BitAssocArray +
Creates a BitAssocArray with the specified default value factory. +
BitAssocArray(BitAssocArray<? extends V>) - +Constructor for class com.newisys.juno.runtime.BitAssocArray +
Creates a BitAssocArray which is a copy of the specified array. +
BitBitAssocArray - Class in com.newisys.juno.runtime
BitVector-to-BitVector associative array.
BitBitAssocArray(int) - +Constructor for class com.newisys.juno.runtime.BitBitAssocArray +
Creates a BitBitAssocArray which has a default value of X with the + specified number of bits. +
BitBitAssocArray(BitBitAssocArray) - +Constructor for class com.newisys.juno.runtime.BitBitAssocArray +
Creates a BitBitAssocArray that is a copy of the specified array. +
bitCount(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
bitCount(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
BitObjectAssocArray - Class in com.newisys.juno.runtime
BitVector-to-Object associative array.
BitObjectAssocArray() - +Constructor for class com.newisys.juno.runtime.BitObjectAssocArray +
Creates a BitObjectAssocArray. +
BitObjectAssocArray(Object) - +Constructor for class com.newisys.juno.runtime.BitObjectAssocArray +
Creates a BitObjectAssocArray with the specified default value. +
BitObjectAssocArray(ValueFactory<?>) - +Constructor for class com.newisys.juno.runtime.BitObjectAssocArray +
Creates a BitObjectAssocArray with the specified default value factory. +
BitObjectAssocArray(BitObjectAssocArray) - +Constructor for class com.newisys.juno.runtime.BitObjectAssocArray +
Creates a BitObjectAssocArray which is a copy of the specified array. +
BitOp - Class in com.newisys.juno.runtime
Bit conversion and operation methods referenced by translated code.
bittostr(BitVector) - +Method in class com.newisys.juno.runtime.JunoString +
Assigns the specified BitVector to this JunoString. +
bittostr(BitVector) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
BitVectorOp - Class in com.newisys.juno.runtime
BitVector conversion and operation methods referenced by translated code.
bitwiseAnd(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseAnd(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseAndNot(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseAndNot(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseNot(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseNot(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseOr(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseOr(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseOrNot(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseOrNot(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseReverse(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseReverse(int) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
bitwiseReverse(long) - +Static method in class com.newisys.juno.runtime.IntOp +
  +
bitwiseReverse(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseXor(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseXor(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
bitwiseXorNot(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
bitwiseXorNot(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
BooleanOp - Class in com.newisys.juno.runtime
boolean conversion and operation methods referenced by + translated code.
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-20.html b/docs/api/index-files/index-20.html new file mode 100644 index 0000000..88eb978 --- /dev/null +++ b/docs/api/index-files/index-20.html @@ -0,0 +1,175 @@ + + + + + + +V-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+V

+
+
ValueFactory<T> - Interface in com.newisys.juno.runtime
A factory interface that supports creating and copying objects.
vera_get_clk_name(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Return the name of the clock associated with the given signal. +
vera_get_dir(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the direction of the given signal. +
vera_get_ifc_name(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
NOTE: vera_get_ifc_name is currently unsupported. +
vera_get_in_depth(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the input depth of the given signal. +
vera_get_in_skew(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the input skew of the given signal. +
vera_get_in_type(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the type of input signal is represented by the given signal. +
vera_get_name(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Return a signal's name. +
vera_get_out_skew(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the output skew of the given signal. +
vera_get_out_type(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the type of output signal is represented by the given signal. +
vera_get_width(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Returns the width of the given signal. +
vera_is_bound(Signal) - +Static method in class com.newisys.juno.runtime.Juno +
Check if a signal is bound to the design. +
vera_report_profile(int, String) - +Static method in class com.newisys.juno.runtime.Juno +
NOTE: vera_report_profile is currently unsupported +
VERBOSE - +Static variable in class com.newisys.juno.runtime.Juno +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-21.html b/docs/api/index-files/index-21.html new file mode 100644 index 0000000..7e7940d --- /dev/null +++ b/docs/api/index-files/index-21.html @@ -0,0 +1,167 @@ + + + + + + +W-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+W

+
+
WAIT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
Wait() - +Method in class com.newisys.juno.runtime.OVAEvent +
Wait on the event, blocking the current thread. +
wait_child() - +Static method in class com.newisys.juno.runtime.Juno +
Block until all threads marked as children of the current thread have + exited. +
warning(String) - +Static method in class com.newisys.juno.runtime.Juno +
  +
wildEqual(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
wildEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
wildEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
wildNotEqual(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
wildNotEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
wildNotEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-3.html b/docs/api/index-files/index-3.html new file mode 100644 index 0000000..806b788 --- /dev/null +++ b/docs/api/index-files/index-3.html @@ -0,0 +1,241 @@ + + + + + + +C-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+C

+
+
check() - +Method in class com.newisys.juno.runtime.AssocArray +
Checks if there are any entries in this associative array. +
check(K) - +Method in class com.newisys.juno.runtime.AssocArray +
Checks if there is a mapping in this associative array for the specified + key. +
CHECK - +Static variable in class com.newisys.juno.runtime.Juno +
  +
clone() - +Method in class com.newisys.juno.runtime.AssocArray +
  +
clone() - +Method in class com.newisys.juno.runtime.BitAssocArray +
  +
clone() - +Method in class com.newisys.juno.runtime.BitBitAssocArray +
  +
clone() - +Method in class com.newisys.juno.runtime.BitObjectAssocArray +
  +
clone() - +Method in class com.newisys.juno.runtime.JunoObject +
Creates and returns a copy of this object. +
clone() - +Method in class com.newisys.juno.runtime.StringAssocArray +
  +
clone() - +Method in class com.newisys.juno.runtime.StringObjectAssocArray +
  +
com.newisys.juno.runtime - package com.newisys.juno.runtime
Provides runtime support for Vera built-in functions, data structures, and + types.
compare(String) - +Method in class com.newisys.juno.runtime.JunoString +
Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String). +
compare(JunoString) - +Method in class com.newisys.juno.runtime.JunoString +
Compares this JunoString to the specified string and returns the results + of the comparison with semantics identical to String.compareTo(java.lang.String). +
compare(String, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
concat(BitVector...) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
concat(String...) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
Configure(int, int) - +Method in class com.newisys.juno.runtime.OVAEngine +
Configures this OVAEngine's options. +
constraint_mode(int) - +Method in class com.newisys.juno.runtime.JunoObject +
Toggles the randomization mode of all constraints on this object. +
constraint_mode(int, String) - +Method in class com.newisys.juno.runtime.JunoObject +
Toggles the randomization mode of the specified constraint on this object. +
CONSTRAINT_MODE_FAIL - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
COPY_NO_WAIT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
COPY_WAIT - +Static variable in class com.newisys.juno.runtime.Juno +
  +
copyArray(T[], T[], T) - +Static method in class com.newisys.juno.runtime.Juno +
Copies the given source array into the given destination array, and + initializes any extra elements in the destination array with the given + value. +
copyArray(T[], T[], ValueFactory<T>) - +Static method in class com.newisys.juno.runtime.Juno +
Clones the elements in the given source array into the given destination + array, and initializes any extra elements in the destination array, using + the given value factory. +
copyInstance(T) - +Method in class com.newisys.juno.runtime.ImmutableValueFactory +
Returns the immutable object passed as an argument. +
copyInstance(JunoEvent) - +Method in class com.newisys.juno.runtime.JunoEventValueFactory +
Instantiates a new JunoEvent and returns it. +
copyInstance(JunoString) - +Method in class com.newisys.juno.runtime.JunoStringValueFactory +
Returns a new JunoString, which is a copy of other. +
copyInstance(T) - +Method in interface com.newisys.juno.runtime.ValueFactory +
Create a copy of the specified object. +
create() - +Static method in class com.newisys.juno.runtime.TestbenchFactory +
Instantiates a testbench as specified by +testbenchClass on the command + line. +
create(String) - +Static method in class com.newisys.juno.runtime.TestbenchFactory +
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +
create(Object[], String) - +Static method in class com.newisys.juno.runtime.TestbenchFactory +
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +
create(Object[], Class[], String) - +Static method in class com.newisys.juno.runtime.TestbenchFactory +
Instantiates a testbench, using defaultClsName if + +testbenchClass is not specified on the command line. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-4.html b/docs/api/index-files/index-4.html new file mode 100644 index 0000000..9ceb00f --- /dev/null +++ b/docs/api/index-files/index-4.html @@ -0,0 +1,184 @@ + + + + + + +D-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+D

+
+
dec(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
dec(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
delay(int) - +Static method in class com.newisys.juno.runtime.Juno +
Block the current thread until the specified number of ticks have occurred. +
delete() - +Method in class com.newisys.juno.runtime.AssocArray +
Remove all entries from this associative array. +
delete(K) - +Method in class com.newisys.juno.runtime.AssocArray +
Deletes the entry in this associative array for the specified key (if + one exists). +
DELETE - +Static variable in class com.newisys.juno.runtime.Juno +
  +
DisableTrigger(OVAEvent) - +Method in class com.newisys.juno.runtime.OVAAssert +
Disables the specified OVAEvent from being triggered when the event type + associated with it occurs. +
DisableTrigger(OVAEvent) - +Method in class com.newisys.juno.runtime.OVAEngine +
Disables the specified OVAEvent from being triggered when the event type + associated with it occurs. +
divide(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
divide(boolean, boolean) - +Static method in class com.newisys.juno.runtime.BooleanOp +
  +
divide(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
divide(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
DoAction(int) - +Method in class com.newisys.juno.runtime.OVAAssert +
Causes this OVAAssert to perform the specified action. +
DoAction(int) - +Method in class com.newisys.juno.runtime.OVAEngine +
Causes this OVAEngine to perform the specified action. +
dumpStack(OutputStream) - +Static method in class com.newisys.juno.runtime.Juno +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-5.html b/docs/api/index-files/index-5.html new file mode 100644 index 0000000..ef4dbb9 --- /dev/null +++ b/docs/api/index-files/index-5.html @@ -0,0 +1,196 @@ + + + + + + +E-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+E

+
+
EnableCount(int) - +Method in class com.newisys.juno.runtime.OVAAssert +
Enables counting of successful or failed match attmpts, depending on + the specified operation. +
EnableTrigger(OVAEvent) - +Method in class com.newisys.juno.runtime.OVAAssert +
Enables the specified OVAEvent to be triggered when the event type + associated with it occurs. +
EnableTrigger(OVAEvent) - +Method in class com.newisys.juno.runtime.OVAEngine +
Enables the specified OVAEvent to be triggered when the event type + associated with it occurs. +
enter_context() - +Static method in class com.newisys.juno.runtime.Juno +
Enter a new thread context. +
equal(Bit, Bit) - +Static method in class com.newisys.juno.runtime.BitOp +
  +
equal(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
equal(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
equal(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
equals(Object, Object) - +Static method in class com.newisys.juno.runtime.Juno +
  +
equals(Object) - +Method in class com.newisys.juno.runtime.JunoString +
  +
equals(String, Object) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
error(String, Object...) - +Static method in class com.newisys.juno.runtime.Juno +
error built-in function. +
error_mode(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
NOTE: error_mode is currently unsupported. +
Event - +Variable in class com.newisys.juno.runtime.OVAEvent +
Publicly usable JunoEvent +
exactEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
exactEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
exactNotEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
exactNotEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
exit(int) - +Static method in class com.newisys.juno.runtime.Juno +
Exit the DV.simulation with the given exit status. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-6.html b/docs/api/index-files/index-6.html new file mode 100644 index 0000000..305de95 --- /dev/null +++ b/docs/api/index-files/index-6.html @@ -0,0 +1,199 @@ + + + + + + +F-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+F

+
+
FAIL - +Static variable in class com.newisys.juno.runtime.JunoObject +
  +
fclose(int) - +Static method in class com.newisys.juno.runtime.Juno +
fclose built-in function. +
feof(int) - +Static method in class com.newisys.juno.runtime.Juno +
feof built-in function. +
ferror(int) - +Static method in class com.newisys.juno.runtime.Juno +
ferror built-in function +
fflush(int) - +Static method in class com.newisys.juno.runtime.Juno +
fflush built-in function. +
finalize() - +Method in class com.newisys.juno.runtime.JunoObject +
  +
first() - +Method in class com.newisys.juno.runtime.AssocArray +
Returns the first key in this associative array. +
first() - +Method in class com.newisys.juno.runtime.BitAssocArray +
Returns the first key in this associative array. +
FIRST - +Static variable in class com.newisys.juno.runtime.Juno +
  +
flag() - +Static method in class com.newisys.juno.runtime.Juno +
Returns the status of the internal flag variable. +
flag(int) - +Static method in class com.newisys.juno.runtime.Juno +
Sets and gets the status of the internal flag variable. +
fopen(String, String) - +Static method in class com.newisys.juno.runtime.Juno +
fopen built-in function +
fopen(String, String, int) - +Static method in class com.newisys.juno.runtime.Juno +
fopen built-in function +
fork(Runnable) - +Static method in class com.newisys.juno.runtime.Juno +
Fork a new thread of execution. +
fork(String, Runnable) - +Static method in class com.newisys.juno.runtime.Juno +
Fork a new thread of execution. +
forValue(Class<E>, Integer, boolean) - +Static method in class com.newisys.juno.runtime.JunoEnumUtil +
  +
fprintf(int, String, Object...) - +Static method in class com.newisys.juno.runtime.Juno +
fprintf built-in function. +
freadb(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
Reads a binary value from a file and returns the corresponding BitVector. +
freadh(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
Reads a hexadecimal value from a file and returns the corresponding BitVector. +
freadstr(int) - +Static method in class com.newisys.juno.runtime.Juno +
freadstr built-in function. +
freadstr(int, int) - +Static method in class com.newisys.juno.runtime.Juno +
freadstr built-in function. +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-7.html b/docs/api/index-files/index-7.html new file mode 100644 index 0000000..027bd0e --- /dev/null +++ b/docs/api/index-files/index-7.html @@ -0,0 +1,245 @@ + + + + + + +G-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+G

+
+
get(K) - +Method in class com.newisys.juno.runtime.AssocArray +
Gets the value for the specified key from this associative array. +
get(BitVector) - +Method in class com.newisys.juno.runtime.BitAssocArray +
Gets the value for the specified key from this associative array. +
get_plus_arg(int, String) - +Static method in class com.newisys.juno.runtime.Juno +
Returns a plusarg value as defined in jove.ini or on the command line. +
get_status() - +Method in class com.newisys.juno.runtime.JunoString +
Returns the status of this JunoString. +
get_status_msg() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a String representation of the current status of this JunoString. +
get_status_msg(int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
get_systime() - +Static method in class com.newisys.juno.runtime.Juno +
Returns the current DV.simulation wall-clock time in seconds. +
get_time(int) - +Static method in class com.newisys.juno.runtime.Juno +
Get the current DV.simulation time in ticks. +
getApiVersion() - +Method in class com.newisys.juno.runtime.OVAEngine +
Returns the OVA API version as returned by the underlying OVA implementation +
GetAssert(String) - +Method in class com.newisys.juno.runtime.OVAEngine +
Returns the OVAAssert with the specified name. +
getBits(BitVector, int, int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
Wrapper for BitVector.getBits() that allows high and low indices to be + swapped. +
getBitsChecked(BitVector, int, int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
Wrapper for BitVector.getBits() that allows high and low indices to be + swapped, and allows the indices to extend beyond the length of the + BitVector. +
getc(int) - +Method in class com.newisys.juno.runtime.JunoString +
Returns the character at the specified index in this JunoString. +
getc(String, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
getChangeEvent() - +Method in class com.newisys.juno.runtime.JunoString +
Returns a JunoEvent that is notified whenever this JunoString changes. +
GetCount(int) - +Method in class com.newisys.juno.runtime.OVAAssert +
Retrieves the current success or failure count of this OVAAssert, + depending on the specified operation. +
GetFirstAssert() - +Method in class com.newisys.juno.runtime.OVAEngine +
Returns the first assertion from the underlying OVA implementation. +
getForValue(Integer, boolean) - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the enum constant associated with the specified value. +
getMask(int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
Generates a bit mask of index+1 bits with the index bit set to ONE, and + any lower-order bits set to ZERO. +
getMask(int, int) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
Generates a bit mask of high+1 bits with each bit between high and low + (inclusive) set to ONE, and any lower-order bits set to ZERO. +
GetName() - +Method in class com.newisys.juno.runtime.OVAAssert +
Returns the name of this OVAAssert. +
GetNextAssert() - +Method in class com.newisys.juno.runtime.OVAEngine +
Returns the next assertion from the underlying OVA implementation. +
GetNextEvent() - +Method in class com.newisys.juno.runtime.OVAEvent +
Returns the event type that unblocked this thread. +
getOrCreate(K) - +Method in class com.newisys.juno.runtime.AssocArray +
Gets the value for the specified key from this associative array. +
getOrCreate(BitVector) - +Method in class com.newisys.juno.runtime.BitAssocArray +
Gets the value for the specified key from this associative array. +
getPackedSize() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns the number of bits needed to encode the values of this + enumeration. +
getProperties() - +Static method in class com.newisys.juno.runtime.Juno +
Returns a clone of the Properties from jove.ini and command line. +
getValueLength() - +Method in class com.newisys.juno.runtime.BitBitAssocArray +
Returns the length in bits of the default value +
greater(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
greater(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
greater(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
greaterOrEqual(BitVector, BitVector) - +Static method in class com.newisys.juno.runtime.BitVectorOp +
  +
greaterOrEqual(Integer, Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
greaterOrEqual(Long, Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-8.html b/docs/api/index-files/index-8.html new file mode 100644 index 0000000..7840bfe --- /dev/null +++ b/docs/api/index-files/index-8.html @@ -0,0 +1,157 @@ + + + + + + +H-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+H

+
+
HAND_SHAKE - +Static variable in class com.newisys.juno.runtime.Juno +
  +
hash(int) - +Method in class com.newisys.juno.runtime.JunoString +
Returns a hash code for this JunoString. +
hash(String, int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
hashCode() - +Method in class com.newisys.juno.runtime.JunoString +
  +
hashCode(String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
HI - +Static variable in class com.newisys.juno.runtime.Juno +
  +
HNUM - +Static variable in class com.newisys.juno.runtime.Juno +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index-files/index-9.html b/docs/api/index-files/index-9.html new file mode 100644 index 0000000..a60ce80 --- /dev/null +++ b/docs/api/index-files/index-9.html @@ -0,0 +1,192 @@ + + + + + + +I-Index (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+

+I

+
+
icompare(String) - +Method in class com.newisys.juno.runtime.JunoString +
Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String). +
icompare(JunoString) - +Method in class com.newisys.juno.runtime.JunoString +
Compares this JunoString to the specified string case-insensitively and + returns the results of the comparison with semantics identical to + String.compareToIgnoreCase(java.lang.String). +
icompare(String, String) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
ImmutableValueFactory<T> - Class in com.newisys.juno.runtime
Implementation of ValueFactory for immutable objects.
ImmutableValueFactory(T) - +Constructor for class com.newisys.juno.runtime.ImmutableValueFactory +
Create an ImmutableValueFactory with the specified immutable object. +
inc(Integer) - +Static method in class com.newisys.juno.runtime.IntegerOp +
  +
inc(Long) - +Static method in class com.newisys.juno.runtime.LongWrapperOp +
  +
index - +Variable in class com.newisys.juno.runtime.JunoObject.PackingPosition +
  +
initArray(T[], T, int) - +Static method in class com.newisys.juno.runtime.Juno +
Initializes the given Object array with the given value, starting at the + given index and continuing to the end of the array. +
initArray(T[], ValueFactory<T>, int) - +Static method in class com.newisys.juno.runtime.Juno +
Initializes the given Object array with values from the given factory, + starting at the given index and continuing to the end of the array. +
initialize() - +Static method in class com.newisys.juno.runtime.Juno +
  +
INSTANCE - +Static variable in class com.newisys.juno.runtime.JunoEventValueFactory +
A singleton instance of JunoEventValueFactory. +
INSTANCE - +Static variable in class com.newisys.juno.runtime.JunoStringValueFactory +
A singleton instance of JunoStringValueFactory. +
IntegerOp - Class in com.newisys.juno.runtime
Integer conversion and operation methods referenced by translated code.
IntOp - Class in com.newisys.juno.runtime
int/long conversion and operation methods + referenced by translated code.
isDefined() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns whether this value is a defined enumeration value, as opposed to + the special UNDEFINED enumeration value. +
isSigned() - +Method in interface com.newisys.juno.runtime.JunoEnum +
Returns whether or not this is a signed enumeration. +
itoa(int) - +Method in class com.newisys.juno.runtime.JunoString +
Assigns the specified int to this JunoString. +
itoa(int) - +Static method in class com.newisys.juno.runtime.StringOp +
  +
+
+ + + + + + + + + + + + + + + +
+ +
+ + + +A B C D E F G H I J L M N O P R S T U V W
+ + + diff --git a/docs/api/index.html b/docs/api/index.html new file mode 100644 index 0000000..0d0f5a7 --- /dev/null +++ b/docs/api/index.html @@ -0,0 +1,34 @@ + + + + + + +Jove API + + + + + + + + +<H2> +Frame Alert</H2> + +<P> +This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. +<BR> +Link to<A HREF="com/newisys/juno/runtime/package-summary.html">Non-frame version.</A> + + + diff --git a/docs/api/overview-tree.html b/docs/api/overview-tree.html new file mode 100644 index 0000000..3d02435 --- /dev/null +++ b/docs/api/overview-tree.html @@ -0,0 +1,178 @@ + + + + + + +Class Hierarchy (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Hierarchy For All Packages

+
+
+
Package Hierarchies:
com.newisys.juno.runtime
+
+

+Class Hierarchy +

+ +

+Interface Hierarchy +

+ +
+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/package-list b/docs/api/package-list new file mode 100644 index 0000000..880f22b --- /dev/null +++ b/docs/api/package-list @@ -0,0 +1 @@ +com.newisys.juno.runtime diff --git a/docs/api/resources/inherit.gif b/docs/api/resources/inherit.gif new file mode 100644 index 0000000000000000000000000000000000000000..c814867a13deb0ca7ea2156c6ca1d5a03372af7e GIT binary patch literal 57 zcmZ?wbhEHbIIT!9-C*e{wE9>Kx3D)-;0v)C; KYxQGgum%9JOA&7X literal 0 HcmV?d00001 diff --git a/docs/api/serialized-form.html b/docs/api/serialized-form.html new file mode 100644 index 0000000..51b78ff --- /dev/null +++ b/docs/api/serialized-form.html @@ -0,0 +1,174 @@ + + + + + + +Serialized Form (Jove API) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+

+Serialized Form

+
+
+ + + + + +
+Package com.newisys.juno.runtime
+ +

+ + + + + +
+Class com.newisys.juno.runtime.AbstractMethodCallError extends java.lang.Error implements Serializable
+ +

+serialVersionUID: 3256446910465388599L + +

+ +

+ + + + + +
+Class com.newisys.juno.runtime.JunoRuntimeException extends java.lang.RuntimeException implements Serializable
+ +

+serialVersionUID: 3689909578574149686L + +

+ +

+


+ + + + + + + + + + + + + + + +
+ +
+ + + +
+ + + diff --git a/docs/api/stylesheet.css b/docs/api/stylesheet.css new file mode 100644 index 0000000..6d31fdb --- /dev/null +++ b/docs/api/stylesheet.css @@ -0,0 +1,29 @@ +/* Javadoc style sheet */ + +/* Define colors, fonts and other style attributes here to override the defaults */ + +/* Page background color */ +body { background-color: #FFFFFF } + +/* Headings */ +h1 { font-size: 145% } + +/* Table colors */ +.TableHeadingColor { background: #CCCCFF } /* Dark mauve */ +.TableSubHeadingColor { background: #EEEEFF } /* Light mauve */ +.TableRowColor { background: #FFFFFF } /* White */ + +/* Font used in left-hand frame lists */ +.FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif } +.FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif } +.FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif } + +/* Navigation bar fonts and colors */ +.NavBarCell1 { background-color:#EEEEFF;} /* Light mauve */ +.NavBarCell1Rev { background-color:#00008B;} /* Dark Blue */ +.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} +.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} + +.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} +.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} + diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..cdd5a0b --- /dev/null +++ b/docs/index.html @@ -0,0 +1,17 @@ + + + + +Juno Documentation Index + + +Juno Logo +

Juno Documentation Index

+ +

Java is a trademark or registered trademark of Sun Microsystems, Inc. in the U.S. or other countries.

+ + diff --git a/docs/juno-logo.png b/docs/juno-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..2dd91f7b98a2c4c76630e585dcc1c55e0e1178f6 GIT binary patch literal 10512 zcmV+rDeu;aP)& z0KL7vse4_|SqYMjigGOg@!il*MnT_N0Lphkz^a|q$iStgrEN$sV<-S?YisFW0>n-L z*J>g3*2C+XWcqj_lsf?J~H%*@QSNdVVZ0p48**4Ebk_3yxHFvFL6+PS3W=H_TQ7*bMF zm0L8`U=ppZt<6;iQXv3)F#yI>2H}B1Uq2~^HUQU;V9#+f@wSlmqinlW5ctNW)ue>Z zid{lHI_F#fn0R9Gellt*0Ku`TOdkMqZ)`d`I`Clu_-F^+)z6o9U+|GrrdT9xPC0#G zP1Rivfle&vlwAGq<=t{B`g0ljnp)(EOhPUoOF=q9LPFM60J?io;A$I;WlQ+XuJ6;p zl$4Z>LJ*uk07^C~uy#<#ytH&L07@wnTUS%2oR!|DfZnf=^S_+NPyvEG5BjWlw~KDp zS_su+82aDMqlR<)f->%nO@(@L@uqWvYg_MhBKy9T`fU$?JP_Tyrv2#J{%8cEQR1Q2uHMdPpec-`sRJ z4of;P_s_JRXF~n=_3fv5)tGRWgLY~^BfW`c*li}8RVMXi1<#CNwS;8QgHiX3L$0W# z<$gLzA_@0}JKdCH=3)u=bszekVP;T3_Kr#AjZ?8|J7!r>^?NEp8UTcQcjLjTnQKla z0zi!b000SaNLh0L01FZT01FZU(%pXi0000MbVXQnLvm$dbZKvHAXI5>WdJcSFEKPP zFf|Y#t(E`)03UQkSaefwW^{L9a%BKbVPkS{ZDnL>VIW3na%FdKa%*!SIJIcfcmMz( z07*naRCt{2oqv2&$CcY=UFROv1~{%vTLo72^L7~Dz0T4R+L|b zjn^33yq54I6uWGsh{Q=nys6D2OCh^J+jXp71j5GaCbVp_*th~ z&=d z%FZF+EK&va4_xh!4!m1iD)_}fmCN#&OJ;PD>r@fq;=w;uj> z3HP{M{NkiTLy**BRwsS$+{=Qev0VQZfikdP$A5jkI$x@^t^t+l^6oiT=kcgIz^tr~ zgEckIfV_#Drd{0)j|<$8o)LP<4IP4}A51f^&JiXB$f1u7G^t$CoZUi2-s0%rL`rcZ$T1?F zRNC4Su%=8&1Nly{#OzCp4@(i z{OL|;gMiBAddVHcr!_RaR(SaGzFpJj%hJY8a;QyGiq*R7H`OSILFUbSWBc~)2SNJ! z>gqNynFLY~!kSe_M+dUHKN=;~VO+QMKpa?QujbW}iltbzaiYROJFqm{ccAii+mFxoPI?t~$lz z9Tb)8AKWFHtOBpCS#$W6O)F1Lty3ssCK;3_$;E2jKZk&-o;Ppr(fRK^Z)cXUE(QPry=cCSlg2&(9v!v@x zz5MyKbZ|rO-THEep`=C=6-%l#It>Q7?A}^TDyK{oJ-uh^RHdTD;FIELk;@hOn6@jS zrmyDa7S8Y4c;U<$&ZNiCB%Rh2`@IJafUKXl_ujXkeDc)A%~R{nQ2kSAHy0Nip*mzj zP^G8;i6vN*9M(0W%H6)X3rZs|3XZ@{6`TWY&cC9M*V9%Xe;nM9-8;Fqz=)_!VojGY z>1j?A@nCIjfs!(!%I!Nnb&~RFOpsm$tU`b9aBFpBh${Dv%@@uf*%3{W$x#IL)a85c zTi&zr)aEWiTCU#9M2Udx<5N|H=?t{v5}u1TsAr4zflvAf_=9qT%y00jxE z5Y_8|Dx!^Q2Gt};3Yr*Yt6I@w)zc`&FtK2)gmV~zYGGg9VnsqNlj1^})Kiz=U;gII z=@+NgO_DHqHATjY)S>jMs_5SsEY2hi>zYw*SUg2pB4SrVx4uA#YC}EuIH0Q7mI5k) zCT&y;>(q*9l5`xdLiYnJ;e3;z%B=&;shA{*|9K#_WzG{TAMcsn#TukatxPyxj8!!H zrHDbN-LS3|)xr&n)y1kRYRqqFeN2c-^f>x^Tla{lw32pr3sG@(Le47den&*OHlV0B zK>HP#q=jlfHmR%2&mEn)WGV%v!c+|XnI#Kk5VQI;sF2i__xJ5T2a^%(_*9%o-%W6l1s$umX3>BMNgudZ02%I9Jn!=-MF5_w+5kl&LqyER2bS+-YgTlrFU2c{n zE*Id!w#5~!80wJg?=_mc?Pf=XLrANz1Jp(Z)t9ld=(uf*(W80~N&R-ef9B~k>hjS6 z$Q5dA%+7AgC(_i^-k9Yoibe&jNFCDbn#Uw6It|Rq5^Y6Tr&APEb%TDArxV<~~MI;nboi6bcDgjT+SxKAA@*Ewy^R-sABUQ1Jk=yYsUfLq$g>^#vnPp2H8xEyYt<7_1?A;NqtW4Tz`sV|_Mc?9;#w6ps}RgV z3XB%P3Vn>Ck}ZW5P8k&{tF^j%{cSIw+j@o{r+`#`cNu9>1?2$A9f=r-MBHx2+VZ=| zXeB5WG^_0Fe=Becw(!R)DrqUKnj4P})q~Ke-e1|%wOCB5^)Uv@ZLnB^B~*eziy>k( ze#4cKQS9Zm35%N z$jbVzJF#ssDpWJqt(*6D&*@2AF9zM;q1J9B1x>0%hlgiO>vDzs=@3nPUmXXIxODKDq5B-rou zvKNcW#4uR(zOHw0Z(7GPs`yg)rTFq{6sSzMuLD%4W^>cO;wo2TFElC-m_*La@T*y? zDc~#lj`U_xStOk0_dcgLa+AO@jY?vbSPG8X$M=8mF!X<(wGQE?0~3=^*U>=^ z1M)p!c78>zhdUND#!)G^EugN`7xpQky0T`?n(YTg{a<@USu1H&n&+Fa53G5H9tPy+ zfbIDe-Fjn0b*^fxqf%^J0IJteQ!1#e0X*cqeLKIXiiWZqT53J?9F_J7Bx}v8S#51? z^=hkd{+M4exwc$A2OMjt)F)9A+ZJwvE?_gg2L3i+Ch@5{C+uHC1e@<7rgbm?_4S<@85Qj+`$R)k zRzA!sJp2?+jp_?{-C&aN#8<_RZtjiCm_n8QCBvOj5Y;Q#Vshx#^;SvHWWD{DhY!zJ z4?xd&N<`gT?dfe|Guw3yXy&2~ceipn?hDHz#;BPvR!55^iGA9mI+gtp(~S;21(x zT$S-cxnBQ+{Om^c(FQyNR#oMl^++J_^0{-<)q6!^RHXZw#G#5Js+N&w73|P;ofax? zup2w5zy+>9)$8@$-TB#Bu4t8NY5|fqtIK!$=WOSesMktDRCJ_KP3sk?lFuqqKxG-D zsBjSZ>sq}>-~D=%_-MnFSqo=>b=owpQ6)jOpk9dT1fb%##?@BgjTLe|Lx5^-E0@D{ zLnXdm(Ajz8P(@wY&$W6yYdw$s-*$QuPwC{ej#(S#U+UR9l^^9qsC?w6s1Q|eb6F~= zKEZj32CCJ+e^kdtfr>68ZV)P>2Wopkxuc-qg{-V1?j&AXNBxGb3sdVBs~eSgvYs53 zeq>aE7%aE%=n{0)A#lj=zXKcvsvm!PRF||gjRqA?q9=F?jBbO`cz?)Mq#CZgX=xqO z?Zy;PS$$s?ZQ;>ZAkD3{Bac;qt!vhNuzfqX-9a2u)_q-23GMQzQTcw{b|X*AVyI=j}ufFok@2U(YWy~9sQ@pc6mg^EK zlN=Qb)*wXHnhaIo687pMRCKPHBC2dUi8h#ZH9E?Qn_7rPjOr2T-nH7EPkdDCkwaCiwKK(`qH&x8uf6ukC$URgb4fT85)H-eRK~3_k+%T+ekD^2<9a)R|o%%v@N_hdI| z?_yLY6LuA%ULD(S%cxQ5d`_p6vWlj}N_@6LXJ>~a)UJjeu=hEAx%$D&`%FCRXvM3tL6%Nq?fmg9joS=<`(zChqWX$`3EtOGT|4ud?O z-ynGFnXqb_R#y?P6!M+XB&gWZ)EB^GD3O04Q;QT>i4T|QZWYc$=$WH@y(jr>-MYMb z{pH{GsJ9#Gtm4-#kMTQGN>qWzuYPzI15d3<$ijtfQ__pFvZ3xO0_2#&P}k@4XA5Wp zE+eQEMb$ksB_2~l;c%>luM3Xo#I5>Gb@kr+PSt646{-*;Nl-~kQ|RV>!N^;aRTY< z>+76_A%?R5yFeL=$BHKwpMF}<*U|>eEi7to6&}%v*Fw#O$S%BYcK#xNib32}q=L$d z$Ga@4veG!RY5qT6(X5f)l4|_A(UIic;(NCpco^84}AVEBl_cN|#uxp{_r9n%mkWFRWn&$JGj~g(6h67XD|sQ7e82 z)W7%l%@lVP%`LU+t|G}~U51LX`cX=(G|sH+g6fz5%phPD3We@+yR{Ej%z5XX-7kx` z8?*9HPSEQMMmVt)sF~H)w(#Pz^GhytZ8#$Z2}*evm z;y97}30YbHXmrTd&+onS&Xy0~a2mIbN?Y}NgXS8z(3U2k@|9{Qn$R(QEl)}zp- zcJITBfg-CKz$&$-6j3o&qNQ+(sI2B+6>G7=AQVM+{)Z)~Q-$KegU}BiIB?+kCw{VP zD?fT*MSpZcEgnr9;dCv|Y5>vVcr+*}2Xa{MV*{CL;Zk`2^FV6lO77K8yjm3S>x!BZ z4Ns8Z4j}*g`*^#B7SKdw+HVM{_m1+4(y3K?^;|t=RFsu)+ag6&&fx!|0bV$R*n8!w z|4A&8S_idhPOFeCOxyBnAIrvI@3uliT=NDn=vS8AZIy@^dCOB z>Ad(Da6?PC=xhOW7{bn7dJ7BvQ2%#seFPS$PF!xk`|Qkhu=ar7@4a1DxQQn9{puFI zM;Ib46;#N|jN2APBWzn}T`)D7Ex+JT)kv_|F}8301zLnAq2ns=Tel8u+WqpT{XN`W zZ*pKArhkvoPF=Mxr9wq#HT-Ql$(P!3~P3qq128DJ_LH?*a#c2GSh}Q&UpZqAxF9 zy7Ur8h-Nmux&P=!u}w`UTkvLr;1IP6l~wmEjadzIWd}v|OX&Ul=a%qCtJ2v3B7C*R zIt;B*oJL)n6-Nbj&Aa-_<42b*;kN%|T?KcFbrh&U|~MQ>LKK!ozz%+$Z!Pc?Cd+MZx9+ zb{M1*iVTy&$ zYc7qjNm9VSSyJT##}yu)hc=zxI+e32ot`Qyn?NpR32r8+QCZCvJk=ze>Um<4zL3OOQVrM(;*YyFkm+Td!PMa-oiY+ehz3pPWE1F{$dr zXi$-xPSUo8CM!);&?-wJZ@FA##$Tm6wJWoTHL4H5ri)K*yfT}{qEnM9!WZ>e`_Lx- zW&(#Q5d30PI)SRJ`lOE3*LNQ4n?HNWY@r8XqS#LBI=8B#mN_jy)H00b4+`o#J3EgZ z>)XEh^y$+Vx_G0=aadO)bn30pRd9`Jbf|1}Dg1Xym%`epU}9p4yanssP!Wl7#YJXh zt*VpSba3#De_kCmi;(xf^Nfd|PdU8?Ki zyG7Vx5LTMC5ElxdV#9_FxKVOuF&7C@(gUQ*#9hVcP$8?D5wPO;jmtTO>n;jne(nKQ=ZtX5pz_=CgP< zbm7w>51B29mI_TO)SmxnnM5kchrbiO1vUkOksqNmSv3)87RF{J>R_JUs$DPWO2+MA zh86Mo%QcAhHPTr;u-+Y{O$oaSdNfLXlt{H*t148D;qwo%S0aJ|t2jxJIZPaM7}2E0 z#u0obTCg(DH8xf3z{*GNdIyD3=6F<~+u**7g@lxOQ*({T)Zy?^F?T|lMqQV3huN{) z@d7n0R3y)Tgnc*`TQq~1wVKojJblDh35u$tLzP?`6`HJ*SP2S~PTyf_MA>Al?rKLN zHL!?I%SJFMU2ai!{vm1-AterhEI3<%P1^C@Muj(-W`%P03lc*Y13(aU-BMlGi0X+Q zhR*GH^=H{2n7>pT5*pG)7BMv#v$Co8B<(5Uq*SPW+}4Kgn$s0R?^kFXr9@T{x76#) z&1LnFobBTd3@2EbBgVCVnoUHa6_wc}vZ$C?l#$^=Pz`fQh%-E;XwV=fLWQa=j`Dw} ziW}*GDOr#(g8qQN#^9`=4qGtuV3P0mKvrghvHa^zD6}5BSoGbviiD#QTA~=*H48u; zTHQio;t*1TPTlt+f=a|-rjmgNiN2|IKv~+hfTFM|m0Y4Yjc#78fr_%S7|UP1huB1` zU=baR)n1bs1Qr!xwA7|v0EKlN!~D1n;@(e;il{De7+?LFOf%Y$K_~HY8$cW0_-k*^ zuQ)+kFi~gG{?ZM`3aWzV-=t`+3>OKPoS{}hwmq2|tPfKC!gBX zwPZK-HYY)atbDo>i({=vvZn3bhSo8IF zf3KoK@@JFUifj_;xT4`va3G2PL<4o1g&tI~DzUiBJ)Xy2hx|c$NnLDWy?rC6rKz{K z0XVImK+P(kVWz}-bpHY~oa`nl`EjYJX#VJbOwc^`PiNiVXm4-gQexufk8YWujf$j( zPSD^6So*u4i`$gnB(R7Wgnn!O=IYfGSkS-%j76tqQW8{zl{si|6nONY`A`KFAeJaS z@@oM9?N}{2&=Xge>|02vVI+IE(S!NF{@kGk6kZ2WQc=;+(0p?4T#Nx5kA+CXObPXv zzYpvFCMjuiTt52fmL#YsE5{31D|)dYvXmt4Efd5uK$%HU{~~T<0hFsrGjxQg7zAS)x5jOks(I?_^RBCsI;au4wi&0eO1Dk*DaMiDj8qG?urv zni2z!8+uO2^i=B{5uM4ojgV51R6kNE3KEcv*c4$l)yi#>TO>CK9f#2!bu`48w#&4y z7ZA-lfMsw4El`c|j1@L`s8Ds_KuZa!>d8C5c=p(^pvwpvr2NYZs0NjvBqdA@)CY`( zn5;s;3;{+$T4J>rVcn8sA%UzS4slX4V@i4v$4Wx|flWXQtDwkfDua*{I*x%#=DK7z zL8xXk)$AtGjLXZFRsl_+{sy+oCQ#hB{7Noxn00%@s^T z1wm9HP(rjYHGvVnFPqMZFhh~(lCLCaQq8m@kxKZC*hHKr^qM6YBnFYFwj+H5IF%7^ zEmF-?HGT=as_;70=5wavK<(^l{v=*9s!%&h$FvYksniG38(@Y4AtgT!f(OnPjId!n>x+s2j8p!l#r!CtI|6Laie{4b;RdH1n+XI)Q+S;@1 z!IkGv9jvQ6a~)*bE}MVa6`Rd}$!42*Jrw-W2_88uu8Kwz`^#}uvrlc@bAIFOE_mpA z$WLw4>gz$xvo>4ox+wT#6PQ!rk?$h*)<%x%;KA9aPR+(k3X9K7d^Q~3`O}URCs@TazLM~7{|X3Md~WWP<8@6=QZfHI>p9Da6UGVQ76QaMAE3)nV;`z4l; z3I9h85oM(5f;952;6+A)7HEkhv#ze1Ed*9_F$eZ zoR($_57>6vV)5UFZCa1VAm6-^)ua4*4lS<#cxum!<@f;2Wk8Ti*oK7{l#mJkM-AaK zS~{Sa7?0UUU9Q9lgE*=>=_<}}q6kS3kyAknk9fU^ESBuKJj~4&F10Od3oN6F@zW+ zzgm$8pYx6!Ildxq1@jL2I1e8_GBFlA&N~88tr&{MhT;F?sL^`_b4?V33UTj>0fs7` z7o<3X1!sa`KMI6~_IBSB3DPv=%CucI3h5o$%lg`5#=CgB?r`7K7Hj zoy3vhO8VOsv?At^e;3idD7?apxxf>#6=9mYpv8ry8o86!<|FbyGE~HOHh&)G?sc8IiLTYo0`+|T-ZD3zUl=&zKX?AJskJ)-D&Xeox+pZuBlX%UvdE-MBV z>7krOUU^Hsp&^9zgvWMRcWDMmM1cwoThvdg;7%#mu-rHys!IE!%&;HW@04^7*bxEAyL2dK_p(+M%dzG3_Y;Nq zK#sj%rcm-*%BY4|t14x-l7DS+Nq7Lw!(ORWYTr!kcB#f@4(%j$hDRmO+uJYqRc0nd zWvA(K&_Hki%t;_mSux_$Z{LZX%%D6kC8|nqyu7R$Dl(zf0i<#$lXX+1e$kKQUzu@2 zRGFmu4OR}=63!v&rRG@K&vNb`j*-k_QjaK8826i(c7UN|9ble~j(tP%8k#^g5Jo9g zqQY9_Cv75(g9edI=4FygPU%Rf`elC19AIOlZIRt3Wg8~lh##uByck4=2e6#P(3m_g zC8`+ZvlFpqdbv!*?ClwaY9rCH2N;ALgme*_&_% zMnr`(KwC}>tEr#X?m?PY4)y^3JHtDNl^)0>$^8tP-8&er9P~1knZ(&Knbc2zMUb-^va7tMM{tL zQR{z2>g&e9z0V=jdNNyF|SFKt_6Rd*2WDc?);KQn6bX%s~4o2GT zcH+Z+JNc1(99p$%D3kq;{AOs?V5WBwds58`^23CSR^dYlu_u0(9>J%iOyb3eyLpgl zRpe!d5B-XQ!W;)4)X0S9!hSOx{|LGCgSnY<;}S`j;hF6J{y|JeOeZ?o?=fdms6`|r zJDSAul!_}UjQfp+eGsA|Uzwo3mY$BN(#Pe-NHpro5}_h{x!z*c#dJhfH7++sFj%n& z6~_H3E@t=H(RXIJT5m%1gC40 zUv?gs8zq7>>$DFXm(QT6Z-PiIYg|5SBC#32wRqFWII5dQ#!=lgGLGt|k^c_~pPmi; SpZ7%o0000 + + + +Juno Quickstart Guide + + + + +

Juno Quick Start Guide

+

Copyright © 2005 Newisys, Inc. Licensed under the Open Software License version 2.0.

+

Product and company names mentioned herein may be trademarks of their respective owners.

+

Last updated 12/18/05

+

Overview

+

The purpose of this document is to describe how to translate and run the sample programs provided with Juno as quickly as possible.

+

Requirements

+

To run the any of samples, you will need the following software installed:

+
    +
  • A supported operating system +
      +
    • Linux (any distribution supported by a Java 5.0 JDK should work)
    • +
    • Microsoft Windows (2000, XP, or later) with the Cygwin environment
    • +
    • Apple Mac OS X
    • +
    +
  • +
  • A Java (J2SE) 5.0 JDK
  • +
  • Apache ant
  • +
  • GNU Make
  • +
  • Jove (Both binary and source distributions are supported. Version 1.0.2 is required to run the floptest example.)
  • +
  • A patched version of JavaCC +
      +
    • The patch is required to implement the functionality described in this JavaCC issue.
    • +
    • The patch itself is available here.
    • +
    • For your convenience, a patched JavaCC distribution is available in the Files section of the Juno SourceForge page.
    • +
    • NOTE When building JavaCC 3.2 under JDK 1.5, it is necessary to add source="1.2" to the javac task in src/org/javacc/parser/build.xml.
    • +
    +
  • +
+

Additionally, the floptest example requires:

+ +

Downloading

+

You can download the source distribution of Juno here. The source distribution will have a filename of the form juno-src-1.0.zip. Unzipping this file will produce the following directory structure:

+

bin/
+ docs/
+ java/
+

+

Environment Variables

+

To translate and run the examples, a number of environment variables are required as described below.

+

Required Variables

+
    +
  • JAVA_HOME should point to the root of a Java (J2SE) 5.0 JDK installation (i.e. ${JAVA_HOME}/bin/javac should exist).
  • +
  • JOVE_HOME should point to the root of a Jove distribution (i.e. ${JOVE_HOME}/bin/jove.jar should exist for a Jove binary distribution or ${JOVE_HOME}/java/jove/bin should exist for a Jove source distribution).
  • +
  • JUNO_HOME should point to the root of a Juno distribution (i.e. ${JUNO_HOME}/java/juno should exist).
  • +
  • VERA_HOME should point to the root of a Vera installation (i.e. ${VERA_HOME}/include should exist).
  • +
+

Optional Variables

+
    +
  • VCS_HOME should point to the root of a VCS installation (i.e. ${VCS_HOME}/bin/vcs should exist). This variable is required only for running the floptest example with VCS.
  • +
  • CVER_HOME should point to the root of a cver installation (i.e. ${CVER_HOME}/bin/cver should exist). This variable is required only for running the floptest example with cver.
  • +
+

Compiling Juno

+

Before running the examples, it is necessary to compile Juno. This is accomplished by setting the required environment varables and the executing the following sequence of instructions1:

+
+

cd $JUNO_HOME/java
+ ant juno

+
+

The 'xmlreader' Example

+

The Vera code for the xmlreader example can be found the java/juno-samples/xmlreader directory. Included in this example is a Vera implementation of an XML parser, a logging infrastructure, and a set of collection classes (lists, maps, etc). The Vera program is located in java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.vr. This program reads a specified XML file and parses it, logging its progress to standard out.

+

Translating & Running xmlreader

+

Once you have compiled Juno, you can run the xmlreader example. The example is run by executing the following commands:

+
+

cd $JUNO_HOME/java/juno-samples
+ make xmlreader +

+
+

The 'floptest' Example

+

The Vera code for the floptest example can be found at java/juno-samples/floptest/floptest.vr. This example tries to show off a number of constructs supported by the translator. These include:

+
    +
  • Signal sampling and driving
  • +
  • Random constraints, including post_randomize support
  • +
  • Passing by reference
  • +
  • Backwards bit indices (e.g. myreg[7:4])
  • +
  • Various built-in functions (e.g. printf, error, alloc)
  • +
  • Pre-processor macros
  • +
  • Fork/Join
  • +
  • File I/O
  • +
  • Mailboxes
  • +
  • Trigger/Sync
  • +
  • Associative Arrays
  • +
+

Translating & Running floptest

+

Once you have compiled Juno, you can run the floptest example. The example is run by executing the following commands:

+
+

cd $JUNO_HOME/java/juno-samples
+ make floptest

+
+

The above commands assume you are using the VCS simulator. If you want to use the cver simulator instead, use the following:

+
+

cd $JUNO_HOME/java/juno-samples
+ make SIMULATOR=cver floptest +

+
+

Footnotes

+

1. If you are using a source distribution of Jove, you will need to compile it before compiling Juno.

+

2. To run Jove applications with cver, a patch must be applied to the cver source code. See the Jove FAQ for details.

+ + + diff --git a/docs/juno-runtime-quickref/index.html b/docs/juno-runtime-quickref/index.html new file mode 100644 index 0000000..ab83ba5 --- /dev/null +++ b/docs/juno-runtime-quickref/index.html @@ -0,0 +1,911 @@ + + + + +Vera To Jove/Juno Quick Reference Guide + + + +

Vera To Jove/Juno Quick Reference Guide

+

Copyright © 2005 Newisys, Inc. Licensed under the Open Software License version 2.0.

+

Product and company names mentioned herein may be trademarks of their respective owners.

+

Last updated 12/20/05

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Vera
Java
Data Types
integer
int (non-X), java.lang.Integer (null for X)
integer a = 1;
+ integer b;
+ b = 2;
int a = 1;
+ Integer b = null;
+ b = 2;
bit/regcom.newisys.verilog.util.Bit
bit a = 1’b1;
+ bit b = 1’b0;
+ bit x = 1’bx;
+ bit z = 1’bz;
Bit a = Bit.ONE;
+ Bit b = Bit.ZERO;
+ Bit x = Bit.X;
+ Bit z = Bit.Z;
bit/reg [n:0]com.newisys.verilog.util.BitVector
bit[4:0] bv;
+ bv = 5’h1F;
BitVector bv = new BitVector(5);
+ bv = new BitVector(5, 0x1F); // + preferred
+ bv = new BitVector("5’h1F"); // less + efficient
stringjava.lang.String, + com.newisys.juno.runtime.JunoString
string s = "text";String s = "text";
eventcom.newisys.juno.runtime.JunoEvent
event e;
+ trigger(ON, e);
+ sync(ALL, e);
JunoEvent e = new JunoEvent();
+ Juno.trigger(Juno.ON, e);
+ Juno.sync(Juno.ALL, e);
enumsubclass of + com.newisys.juno.runtime.JunoEnum
enum Color = RED, BLUE;public enum Color implements JunoEnum<Color>
+ {
+     @RandExclude UNDEFINED(null), RED(0), BLUE(1);
+     // followed by boilerplate JunoEnum implementation;
+     // see a translated enum for complete contents

+ }
arrays (fixed, dynamic, multi-dimensional)Java arrays
integer a[4] = { 1, 2, 3, 4 };
+ integer b[4][4];
+ MyClass c[4];
+ integer d[*];
+ d = new[4];
int[] a = { 1, 2, 3, 4 };
+ Integer[][] b = new Integer[4][4];
+ MyClass[] = new MyClass[4];
+ Integer[] d;
+ d = new Integer[4];
arrays (associative)com.newisys.juno.runtime.BitBitAssocArray, + com.newisys.juno.runtime.BitObjectAssocArray, + com.newisys.juno.runtime.StringObjectAssocArray
bit[4:0] a[];
+ MyClass b[];
+ MyClass c[string];
+ // NOTE: associative arrays are intended for Vera
+ // compatibility; new code should use the Java
+ // collection classes
+

+ BitBitAssocArray a = new BitBitAssocArray(5);
+ BitObjectAssocArray b = new BitObjectAssocArray();
+ StringObjectAssocArray c = new StringObjectAssocArray();
portclass
port P
+ {
+     x;
+     y;
+ }
+ // NOTE: port classes are not intended to be
+ // written by hand; use the jove-ifgen tool
+

+ public class P
+ {
+     public InOutSignal x;
+     public InOutSignal y;
+
+     public P()
+     {
+     }
+
+     public P(InOutSignal x, InOutSignal y)
+     {
+         this.x = x;
+         this.y = y;
+     }
+ }
interfaceclass
interface I
+ {
+     input clk CLOCK hdl_node "test_top.SystemClock";
+     inout x PSAMPLE PHOLD #1 hdl_node "test_top.x";
+     inout y PSAMPLE PHOLD #1 hdl_node "test_top.y";
+ }
+
+ // NOTE: interface classes are not intended to be
+ // written by hand; use the jove-ifgen tool
+

+ public final class I
+ {
+     public final static ClockSignal clk = + Juno.simulation.getClockSignal("I_clk", 1);
+     public final static InOutSignal x = + Juno.simulation.getInOutSignal("I_x", clk, EdgeSet.POSEDGE, 0, + EdgeSet.POSEDGE, 1, 1);
+     public final static InOutSignal y = + Juno.simulation.getInOutSignal("I_y", clk, EdgeSet.POSEDGE, 0, + EdgeSet.POSEDGE, 1, 1);
+ }
+
bindconstant
bind B P
+ {
+     x I.x;
+     y I.y;
+ }
+ // NOTE: bind constants are not intended to be
+ // written by hand; use the jove-ifgen tool
+

+ public final static P B = new P(I.x, I.y);
+ // OR
+ public final static P B = new P();
+ static
+ {
+     B.x = I.x;
+     B.y = I.y;
+ }
Sequential Control
if-else
if-else
if (1) { // condition is + integer
+ } else {
+ }
if (true) { // condition is + boolean
+ } else {
+ }
case
switch (char, byte, short, int expression; constant + case labels), if-else chain
integer i;
+ case (i) {
+     1: foo();
+     2: bar();
+     default: baz();
+ }
+
+
+
+
+
+
+ string s;
+ case (s) {
+     "foo": foo();
+     "bar": bar();
+     default: baz();
+ }
int i;
+ switch (i) {
+ case 1:
+     foo();
+     break;
+ case 2:
+     bar();
+     break;
+ default:
+     baz();
+ }
+
+ String s;
+ if ("foo".equals(s)) foo();
+ else if ("bar".equals(s)) bar();
+ else baz();
repeat
for
repeat (10) {}
for (int i = 0; i < 10; ++i) {}
for
for
for (int i = 0; i < 10; ++i) {}for (int i = 0; i < 10; ++i) {}
while
while
while (1) {} // condition is + integer
while (true) {} // condition + is boolean
do-while
do-while
do () while (1); // condition + is integerdo {} while (true); // + condition is boolean
foreach
for
string words[$] = { "a", "b" };
+ foreach (words, word) {}
String[] words = { "a", "b" };
+ for (String word : words) {}
break/continue
break/continue
while (1) {
+     if (foo()) continue;
+     if (bar()) break;
+ }
while (true) {
+     if (foo()) continue;
+     if (bar()) break;
+ }
randcase
switch(Juno.randcase())
randcase {
+     50: foo();
+     25: bar();
+     25: baz();
+ }
int[] weights = { 50, 25, 25 };
+ switch (Juno.randcase(weights)) {
+ case 0:
+     foo();
+     break;
+ case 1:
+     bar();
+     break;
+ default: // use default for last case for + DA/DU
+     baz();
+ }
breakpoint
dummy statement
breakpoint;
System.out.println("breakpoint"); // set breakpoint here
Concurrency Control / Synchronization
fork
Juno.fork
fork
+ { foo(); }
+ { bar(); }
+ join none
+
+
+
+
+
+
+
+ fork
+ { foo(); }
+ { bar(); }
+ join all
Juno.fork("foo", new Runnable() {
+     public void run() {
+         foo();
+     }
+ });
+ Juno.fork("bar", new Runnable() {
+     public void run() {
+         bar();
+     }
+ });
+
+ Juno.simulation.joinAll(
+     Juno.fork("foo", new Runnable() {
+         public void run() {
+             + foo();
+         }
+     }),
+     Juno.fork("bar", new Runnable() {
+         public void run() {
+             + bar();
+         }
+     })
+ );
shadow variables
new variable initialized from snapshot + variable
shadow integer i = 1;
+ fork {
+     ++i;
+ } join none
int i = 1;
+ final int forked_i = i; // make + snapshot
+ Juno.fork(new Runnable() {
+     public void run() {
+         int i2 = forked_i; // declare new variable
+         ++i2;
+     }
+ });
suspend_thread()
Juno.simulation.yield()
suspend_thread();
Juno.simulation.yield();
wait_child()
Juno.wait_child()
fork {
+     foo();
+ } join none
+ wait_child();
// blocks containing + wait_child() must create a new thread context
+ Juno.enter_context();
+ try {
+     Juno.fork(new Runnable() {
+         public void run() {
+             + foo();
+         }
+     });
+     Juno.wait_child();
+ } finally {
+     // ensure context is always + exited
+     Juno.leave_context();
+ }
wait_var()
Juno.wait_var()
int i = 0;
+ fork {
+     wait_var(i);
+ }
+ {
+     i = 1;
+ } join all
// only final variables are + accessible to local classes;
+
// a + single-element array is a useful technique for allowing
+
// local classes to assign to shared + variables
+
final int[] i_holder = { 0 };
+ // wait_var is emulated using an associated + event
+
final JunoEvent i_changed = new JunoEvent();
+ Juno.simulation.joinAll(
+     Juno.fork(new Runnable() {
+         public void run() {
+             + Juno.sync(Juno.ANY, i_changed);
+         }
+     }),
+     Juno.fork(new Runnable() {
+         public void run() {
+             final int + old_i = i_holder[0];
+             + i_holder[0] = 1;
+             // trigger associated event iff value + changed
+             if + (i_holder[0] != old_i) Juno.trigger(i_changed);
+         }
+     })
+ );
terminate
Juno.terminate
terminate;
Juno.simulation.terminate();
mailboxes
com.newisys.dv.Mailbox
integer mb = alloc(MAILBOX, 0, 1);
+ mailbox_put(mb, foo);
+ mailbox_get(WAIT, mb, foo);
Mailbox mb = Juno.simulation.createMailbox();
+ mb.put(foo);
+ foo = mb.getWait();
semaphores
com.newisys.dv.Semaphore
integer sem = alloc(SEMAPHORE, 0, 1, 1);
+ semaphore_get(WAIT, sem, 1);
+ semaphore_put(sem, 1);
Semaphore sem = + Juno.simulation.createSemaphore(1);
+ sem.acquire(1);
+ sem.release(1);
regions
unsupported
Signal Operations
Synchronize to system clock
@(posedge CLOCK);Juno.systemClock.syncEdge(EdgeSet.POSEDGE);
Synchronize to specific edge
@(negedge bind.$foo);bind.foo.syncEdge(EdgeSet.NEGEDGE);
Synchronize to change/any edge
@(bind.$foo);bind.foo.syncEdge(EdgeSet.ANYEDGE);
Synchronize to sample edge (aka void expect)
@1 bind.$foo == void;bind.foo.syncSampleDelay(1);
Synchronize to drive edge (aka void drive)
@1 bind.$foo = void;bind.foo.syncDriveDelay(1);
Synchronous sample
var = bind.$foo;var = bind.foo.sample();
Asynchronous sample
var = bind.$foo async;
+ if (bind.$foo) {} // implicit async + sample
+
var = bind.foo.sampleAsync();
+ if (bind.foo.sampleAsync().isNotZero()) {}
Synchronous drive
bind.$foo = var;bind.foo.drive(var);
Asynchronous drive
bind.$foo = var async;bind.foo.driveAsync(var);
Vera Built-in Functions
printf(), delay(), trigger(), etc.
static methods in + com.newisys.juno.runtime.Juno
delay(10);
+ printf("%0d\n", foo);
Juno.delay(10);
+ Juno.printf("%0d\n", foo);
Unsupported Vera Features
pack/unpack
unsupported
constraint-based randomization of arrays
unsupported
Smart Queues
unsupported
+ + + + diff --git a/java/build.xml b/java/build.xml new file mode 100644 index 0000000..04665ce --- /dev/null +++ b/java/build.xml @@ -0,0 +1,74 @@ + + + + + + + JUNO_HOME is ${env.JUNO_HOME} + JOVE_HOME is ${env.JOVE_HOME} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/juno-runtime/build.xml b/java/juno-runtime/build.xml new file mode 100644 index 0000000..6824679 --- /dev/null +++ b/java/juno-runtime/build.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/juno-runtime/manifest.mf b/java/juno-runtime/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/juno-runtime/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/AbstractMethodCallError.java b/java/juno-runtime/src/com/newisys/juno/runtime/AbstractMethodCallError.java new file mode 100644 index 0000000..57c0434 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/AbstractMethodCallError.java @@ -0,0 +1,40 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Exception thrown by translator-generated stub methods in non-abstract classes + * when an abstract method is unimplemented. + * + * @author Trevor Robinson + */ +public class AbstractMethodCallError + extends Error +{ + private static final long serialVersionUID = 3256446910465388599L; + + public AbstractMethodCallError() + { + super(); + } + + public AbstractMethodCallError(String message) + { + super(message); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/AssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/AssocArray.java new file mode 100644 index 0000000..a39d69b --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/AssocArray.java @@ -0,0 +1,299 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.util.Iterator; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * Base implementation of associative arrays. + * + * @param key type + * @param value type + * @author Trevor Robinson + */ +public class AssocArray + implements Cloneable +{ + private final SortedMap map; + private final ValueFactory< ? extends V> nullValueFactory; + + // cached key iterator + private transient Iterator keyIter; + private transient K cachedPrevKey; + + /** + * Creates an AssocArray with a default value of null. + */ + public AssocArray() + { + this((V) null); + } + + /** + * Creates an AssocArray with the specified default value. If a key is + * requested that does not exist in this array, the default value will be + * returned. + * + * @param nullValue the default value for this array + */ + public AssocArray(V nullValue) + { + this.map = new TreeMap(); + this.nullValueFactory = new ImmutableValueFactory(nullValue); + } + + /** + * Creates an AssocArray with the specified default value factory. If a key + * is requested that does not exist in this array, the factory will be used + * to instantiate the default value. + * + * @param nullValueFactory the value factory used to create default values + */ + public AssocArray(ValueFactory< ? extends V> nullValueFactory) + { + this.map = new TreeMap(); + this.nullValueFactory = nullValueFactory; + } + + /** + * Creates a new AssocArray which is a copy of the specified array. + * + * @param other the array to copy + */ + public AssocArray(AssocArray< ? extends K, ? extends V> other) + { + this.map = new TreeMap(other.map); + this.nullValueFactory = other.nullValueFactory; + } + + /** + * Gets the value for the specified key from this associative array. + * + * @param key the key whose associated value is to be returned + * @param keepNew indicates whether to add a mapping to the default value + * if this associative array contains no mapping for this key + * @return the value which maps to the specified key, or the default value + * if this associative array contains no mapping for this key + */ + private V getImpl(K key, boolean keepNew) + { + V value = map.get(key); + if (value == null) + { + value = nullValueFactory.newInstance(); + if (keepNew) + { + map.put(key, value); + keyIter = null; + cachedPrevKey = null; + } + } + return value; + } + + /** + * Gets the value for the specified key from this associative array. + * + * @param key the key whose associated value is to be returned + * @return the value which maps to the specified key, or the default value + * if this associative array contains no mapping for this key + */ + public V get(K key) + { + return getImpl(key, false); + } + + /** + * Gets the value for the specified key from this associative array. If the + * array contains no mapping for the key, a mapping is added to the default + * value. + * + * @param key the key whose associated value is to be returned + * @return the value which maps to the specified key, or the default value + * if this associative array contains no mapping for this key + */ + public V getOrCreate(K key) + { + return getImpl(key, true); + } + + /** + * Associates the specified value with the specified key in this + * associative array. + * + * @param key the key with which the specified value is to be associated + * @param value the value to be associated with the specified key + */ + public void put(K key, V value) + { + map.put(key, value); + keyIter = null; + cachedPrevKey = null; + } + + /** + * Checks if there are any entries in this associative array. + * + * @return the number of entries in this associative array + */ + public int check() + { + return map.size(); + } + + /** + * Checks if there is a mapping in this associative array for the specified + * key. + * + * @param key the key to check for a mapping + * @return 1 if there is an entry in this associative array for + * key, 0 otherwise + */ + public int check(K key) + { + if (key == null) + { + throw new IllegalArgumentException("AssocArray.check: null key"); + } + return map.containsKey(key) ? 1 : 0; + } + + /** + * Remove all entries from this associative array. + * + * @return 1 + */ + public int delete() + { + map.clear(); + keyIter = null; + cachedPrevKey = null; + return 1; + } + + /** + * Deletes the entry in this associative array for the specified key (if + * one exists). + * + * @param key the key to delete the mapping of + * @return 1 if the key exists in this associative array and + * was deleted, 0 otherwise + */ + public int delete(K key) + { + if (key == null) + { + throw new IllegalArgumentException("AssocArray.delete: null key"); + } + if (map.containsKey(key)) + { + map.remove(key); + keyIter = null; + cachedPrevKey = null; + return 1; + } + return 0; + } + + /** + * Returns the first key in this associative array. This method can be used + * with {@link #next} to iterate all keys in the array. + * + * @return the first key in this associative array, or null if this array + * is empty + */ + public K first() + { + if (!map.isEmpty()) + { + keyIter = map.keySet().iterator(); + cachedPrevKey = keyIter.next(); + return cachedPrevKey; + } + return null; + } + + /** + * Returns the key following the given key in this associative array. This + * method can be used with {@link #first} to iterate all keys in the array. + * + * @param prevKey a previously returned key + * @return the key following prevKey in this associative + * array, or null if there are no more keys + */ + public K next(K prevKey) + { + // can we use cached iterator? + if (keyIter != null && cachedPrevKey.equals(prevKey)) + { + // does cached iterator contain more keys? + if (keyIter.hasNext()) + { + cachedPrevKey = keyIter.next(); + return cachedPrevKey; + } + // fall through to no more keys + } + else + { + // create new key iterator using given key + keyIter = map.tailMap(prevKey).keySet().iterator(); + if (keyIter.hasNext()) + { + cachedPrevKey = keyIter.next(); + // done if first key is greater than given key + if (!cachedPrevKey.equals(prevKey)) + { + return cachedPrevKey; + } + // skip first key + if (keyIter.hasNext()) + { + cachedPrevKey = keyIter.next(); + return cachedPrevKey; + } + // fall through to no more keys + } + // fall through to no more keys + } + + // clear cached key iterator + keyIter = null; + cachedPrevKey = null; + + return null; + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public AssocArray clone() + { + return new AssocArray(this); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() + { + return map.toString(); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BitAssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/BitAssocArray.java new file mode 100644 index 0000000..6a90871 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BitAssocArray.java @@ -0,0 +1,166 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.BitVector; + +/** + * BitVector-keyed associative array. + * + * @param value type + * @author Trevor Robinson + */ +public class BitAssocArray + extends AssocArray +{ + public static final BitVector NULL_KEY = new BitVector(64); + + /** + * Creates a BitAssocArray with a default value of null. + */ + public BitAssocArray() + { + } + + /** + * Creates a BitAssocArray with the specified default value. If a key is + * requested that does not exist in this array, the default value will be + * returned. + * + * @param nullValue the default value for this array + */ + public BitAssocArray(V nullValue) + { + super(nullValue); + } + + /** + * Creates a BitAssocArray with the specified default value factory. If a + * key is requested that does not exist in this array, the factory will be + * used to instantiate the default value. + * + * @param nullValueFactory the value factory used to create default values + */ + public BitAssocArray(ValueFactory< ? extends V> nullValueFactory) + { + super(nullValueFactory); + } + + /** + * Creates a BitAssocArray which is a copy of the specified array. + * + * @param other the array to copy + */ + public BitAssocArray(BitAssocArray< ? extends V> other) + { + super(other); + } + + /** + * Validates a key. This method insures the key is a valid numeric value + * and does not contain X/Z values. + * + * @param key the BitVector to validate + */ + private void validateKey(BitVector key) + { + if (key.containsXZ()) + { + throw new RuntimeException( + "Undefined index in associative array access"); + } + } + + /** + * Gets the value for the specified key from this associative array. + * + * @param key the key whose associated value is to be returned + * @return the value which maps to the specified key, or the default value + * if this associative array contains no mapping for this key + * @throws RuntimeException if key contains X/Z + */ + public V get(BitVector key) + { + validateKey(key); + return super.get(key); + } + + /** + * Gets the value for the specified key from this associative array. If the + * array contains no mapping for the key, a mapping is added to the default + * value. + * + * @param key the key whose associated value is to be returned + * @return the value which maps to the specified key, or the default value + * if this associative array contains no mapping for this key + * @throws RuntimeException if key contains X/Z + */ + public V getOrCreate(BitVector key) + { + validateKey(key); + return super.getOrCreate(key); + } + + /** + * Associates the specified value with the specified key in this + * associative array. + * + * @param key the key with which the specified value is to be associated + * @param value the value to be associated with the specified key + */ + public void put(BitVector key, V value) + { + validateKey(key); + super.put(key, value); + } + + /** + * Returns the first key in this associative array. This method can be used + * with {@link #next} to iterate all keys in the array. + * + * @return the first key in this associative array, or X if this array is + * empty + */ + public BitVector first() + { + BitVector first = super.first(); + return first != null ? first : NULL_KEY; + } + + /** + * Returns the key following the given key in this associative array. This + * method can be used with {@link #first} to iterate all keys in the array. + * + * @param prevKey a previously returned key + * @return the key following prevKey in this associative + * array, or X if there are no more keys + */ + public BitVector next(BitVector prevKey) + { + BitVector next = super.next(prevKey); + return next != null ? next : NULL_KEY; + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public BitAssocArray clone() + { + return new BitAssocArray(this); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BitBitAssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/BitBitAssocArray.java new file mode 100644 index 0000000..4b247a3 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BitBitAssocArray.java @@ -0,0 +1,72 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.BitVector; + +/** + * BitVector-to-BitVector associative array. + * + * @author Trevor Robinson + */ +public final class BitBitAssocArray + extends BitAssocArray +{ + private final int valueLength; + + /** + * Creates a BitBitAssocArray which has a default value of X with the + * specified number of bits. + * + * @param valueLength the length of the default value + */ + public BitBitAssocArray(int valueLength) + { + super(new BitVector(valueLength)); + this.valueLength = valueLength; + } + + /** + * Creates a BitBitAssocArray that is a copy of the specified array. + * + * @param other the array to copy + */ + public BitBitAssocArray(BitBitAssocArray other) + { + super(other); + this.valueLength = other.valueLength; + } + + /** + * Returns the length in bits of the default value + * + * @return the length of the default value + */ + public int getValueLength() + { + return valueLength; + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public BitBitAssocArray clone() + { + return new BitBitAssocArray(this); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BitObjectAssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/BitObjectAssocArray.java new file mode 100644 index 0000000..3909484 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BitObjectAssocArray.java @@ -0,0 +1,76 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * BitVector-to-Object associative array. + * + * @author Trevor Robinson + */ +public final class BitObjectAssocArray + extends BitAssocArray +{ + /** + * Creates a BitObjectAssocArray. + */ + public BitObjectAssocArray() + { + } + + /** + * Creates a BitObjectAssocArray with the specified default value. If a key + * is requested that does not exist in this array, the default value will + * be returned. + * + * @param nullValue the default value for this array + */ + public BitObjectAssocArray(Object nullValue) + { + super(nullValue); + } + + /** + * Creates a BitObjectAssocArray with the specified default value factory. + * If a key is requested that does not exist in this array, the factory + * will be used to instantiate the default value. + * + * @param nullValueFactory the value factory used to create default values + */ + public BitObjectAssocArray(ValueFactory< ? > nullValueFactory) + { + super(nullValueFactory); + } + + /** + * Creates a BitObjectAssocArray which is a copy of the specified array. + * + * @param other the array to copy + */ + public BitObjectAssocArray(BitObjectAssocArray other) + { + super(other); + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public BitObjectAssocArray clone() + { + return new BitObjectAssocArray(this); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BitOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/BitOp.java new file mode 100644 index 0000000..1ed9998 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BitOp.java @@ -0,0 +1,182 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorBuffer; + +/** + * Bit conversion and operation methods referenced by translated code. + * + * @author Trevor Robinson + */ +public final class BitOp +{ + private BitOp() + { + } + + public static Bit toBit(int i) + { + return (i & 1) != 0 ? Bit.ONE : Bit.ZERO; + } + + public static Bit toBit(long l) + { + return (l & 1) != 0 ? Bit.ONE : Bit.ZERO; + } + + public static Bit toBit(Integer i) + { + return (i != null) ? toBit(i.intValue()) : Bit.X; + } + + public static Bit toBit(Long l) + { + return (l != null) ? toBit(l.intValue()) : Bit.X; + } + + public static Bit toBit(BitVector bv) + { + return bv.getBit(0); + } + + public static Bit toBit(String s) + { + return BooleanOp.toBoolean(s) ? Bit.ONE : Bit.ZERO; + } + + public static Bit toBit(Object o) + { + if (o instanceof Bit) + { + return (Bit) o; + } + else if (o instanceof Number) + { + return toBit(((Number) o).intValue()); + } + else if (o instanceof BitVector) + { + return toBit((BitVector) o); + } + else if (o instanceof Boolean) + { + return ((Boolean) o).booleanValue() ? Bit.ONE : Bit.ZERO; + } + else if (o instanceof String) + { + return toBit((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static Bit toLogicalBit(int i) + { + return i != 0 ? Bit.ONE : Bit.ZERO; + } + + public static Bit toLogicalBit(long l) + { + return l != 0 ? Bit.ONE : Bit.ZERO; + } + + public static Bit toLogicalBit(Integer i) + { + return (i != null) ? toLogicalBit(i.intValue()) : Bit.X; + } + + public static Bit toLogicalBit(Long l) + { + return (l != null) ? toLogicalBit(l.intValue()) : Bit.X; + } + + public static Bit toLogicalBit(BitVector bv) + { + return bv.containsXZ() ? Bit.X : (bv.isNotZero() ? Bit.ONE : Bit.ZERO); + } + + public static BitVector toBitVector(int len, Bit b) + { + return new BitVectorBuffer(len, Bit.ZERO).setBit(0, b).toBitVector(); + } + + public static int toInt(Bit b) + { + if (b.isXZ()) + { + throw new IllegalArgumentException("Value is X/Z"); + } + return b == Bit.ONE ? 1 : 0; + } + + public static int toShiftCount(Bit b) + { + if (b.isXZ()) + { + throw new IllegalArgumentException("Shift count cannot be X/Z"); + } + return b == Bit.ONE ? 1 : 0; + } + + public static Bit divide(Bit b1, Bit b2) + { + if (b2 == Bit.ZERO) + { + throw new ArithmeticException("Bit divide by zero"); + } + return b1.and(b2); + } + + public static Bit mod(Bit b1, Bit b2) + { + if (b2 == Bit.ZERO) + { + throw new ArithmeticException("Bit divide by zero"); + } + return b1.isXZ() || b2.isXZ() ? Bit.X : Bit.ZERO; + } + + public static Bit equal(Bit b1, Bit b2) + { + return (!b1.isXZ() && !b2.isXZ()) ? (b1 == b2 ? Bit.ONE : Bit.ZERO) + : Bit.X; + } + + public static Bit notEqual(Bit b1, Bit b2) + { + return (!b1.isXZ() && !b2.isXZ()) ? (b1 != b2 ? Bit.ONE : Bit.ZERO) + : Bit.X; + } + + public static Bit wildEqual(Bit b1, Bit b2) + { + return (!b1.isXZ() && !b2.isXZ()) ? (b1 == b2 ? Bit.ONE : Bit.ZERO) + : Bit.ONE; + } + + public static Bit wildNotEqual(Bit b1, Bit b2) + { + return (!b1.isXZ() && !b2.isXZ()) ? (b1 != b2 ? Bit.ONE : Bit.ZERO) + : Bit.ZERO; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BitVectorOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/BitVectorOp.java new file mode 100644 index 0000000..c7e4f45 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BitVectorOp.java @@ -0,0 +1,319 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorBuffer; + +/** + * BitVector conversion and operation methods referenced by translated code. + * + * @author Trevor Robinson + */ +public final class BitVectorOp +{ + public static final BitVector BIT_0 = new BitVector(1, Bit.ZERO); + public static final BitVector BIT_1 = new BitVector(1, Bit.ONE); + public static final BitVector BIT_Z = new BitVector(1, Bit.Z); + public static final BitVector BIT_X = new BitVector(1, Bit.X); + + private BitVectorOp() + { + } + + public static BitVector toBitVector(boolean[] ba) + { + final BitVectorBuffer buf = new BitVectorBuffer(ba.length, Bit.ZERO); + for (int i = 0; i < ba.length; ++i) + { + if (ba[i]) buf.setBit(i, Bit.ONE); + } + return buf.toBitVector(); + } + + public static BitVector toBitVector(Bit b) + { + switch (b.getID()) + { + case Bit.ID_ZERO: + return BIT_0; + case Bit.ID_ONE: + return BIT_1; + case Bit.ID_Z: + return BIT_Z; + default: + return BIT_X; + } + } + + public static BitVector toBitVector(Object value) + { + if (value instanceof BitVector) + { + return (BitVector) value; + } + else if (value instanceof Bit) + { + return toBitVector((Bit) value); + } + else if (value instanceof Integer) + { + return new BitVector(32, ((Integer) value).intValue()); + } + else if (value instanceof Long) + { + return new BitVector(64, ((Double) value).longValue()); + } + else if (value instanceof Boolean) + { + return ((Boolean) value).booleanValue() ? BIT_1 : BIT_0; + } + else if (value instanceof String) + { + return new BitVector(((String) value).getBytes()); + } + else + { + throw new ClassCastException("Not a Verilog value type"); + } + } + + public static int toInt(BitVector bv) + { + if (bv.containsXZ()) + { + throw new IllegalArgumentException("Value contains X/Z"); + } + return bv.intValue(); + } + + public static int toShiftCount(BitVector bv, int max) + { + if (bv.containsXZ()) + { + throw new IllegalArgumentException("Shift count cannot contain X/Z"); + } + return Math.min(bv.intValue(), max); + } + + public static int toShiftCount(BitVector bv) + { + return toShiftCount(bv, Integer.MAX_VALUE); + } + + public static Bit equal(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (bv1 + .equals(bv2) ? Bit.ONE : Bit.ZERO); + } + + public static Bit notEqual(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (!bv1 + .equals(bv2) ? Bit.ONE : Bit.ZERO); + } + + public static Bit greater(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (bv1 + .compareTo(bv2) > 0 ? Bit.ONE : Bit.ZERO); + } + + public static Bit greaterOrEqual(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (bv1 + .compareTo(bv2) >= 0 ? Bit.ONE : Bit.ZERO); + } + + public static Bit less(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (bv1 + .compareTo(bv2) < 0 ? Bit.ONE : Bit.ZERO); + } + + public static Bit lessOrEqual(BitVector bv1, BitVector bv2) + { + return (bv1.containsXZ() || bv2.containsXZ()) ? Bit.X : (bv1 + .compareTo(bv2) <= 0 ? Bit.ONE : Bit.ZERO); + } + + public static BitVector concat(BitVector... bvs) + { + // calculate total length of result + int total = 0; + for (final BitVector bv : bvs) + { + total += bv.length(); + } + + // write individual bit vectors into buffer, starting with MSB + final BitVectorBuffer result = new BitVectorBuffer(total); + int pos = total; + for (final BitVector bv : bvs) + { + int len = bv.length(); + result.setBits(pos - 1, pos - len, bv); + pos -= len; + } + return result.toBitVector(); + } + + public static BitVector replicate(int count, BitVector bv) + { + // calculate total length of result + final int len = bv.length(); + final int total = len * count; + + // replicate bit vector into buffer, starting with MSB + final BitVectorBuffer result = new BitVectorBuffer(total); + int pos = total; + for (int i = 0; i < count; ++i) + { + result.setBits(pos - 1, pos - len, bv); + pos -= len; + } + return result.toBitVector(); + } + + /** + * Wrapper for BitVector.getBits() that allows high and low indices to be + * swapped. + * + * @param bv the BitVector to get the bit slice from + * @param high the "high" index + * @param low the "low" index + * @return the bit slice + */ + public static BitVector getBits(BitVector bv, int high, int low) + { + if (high < low) + { + int temp = high; + high = low; + low = temp; + } + return bv.getBits(high, low); + } + + /** + * Wrapper for BitVector.getBits() that allows high and low indices to be + * swapped, and allows the indices to extend beyond the length of the + * BitVector. Any bits requested beyond the length of the BitVector are + * returned as 0. + * + * @param bv the BitVector to get the bit slice from + * @param high the "high" index + * @param low the "low" index + * @return the bit slice + */ + public static BitVector getBitsChecked(BitVector bv, int high, int low) + { + if (high < low) + { + int temp = high; + high = low; + low = temp; + } + int inputLen = bv.length(); + int resultLen = high - low + 1; + BitVector result; + if (low < inputLen) + { + if (high >= inputLen) + { + high = inputLen - 1; + result = bv.getBits(high, low).setLength(resultLen, Bit.ZERO); + } + else + { + result = bv.getBits(high, low); + } + } + else + { + result = new BitVector(resultLen, Bit.ZERO); + } + return result; + } + + /** + * Wrapper for BitVector.setBits() that allows high and low indices to be + * swapped. + * + * @param bv the BitVector to set the bit slice in + * @param high the "high" index + * @param low the "low" index + * @param value the bit slice to store + * @return the new BitVector with the bit slice written + */ + public static BitVector setBits( + BitVector bv, + int high, + int low, + BitVector value) + { + if (high < low) + { + int temp = high; + high = low; + low = temp; + } + return bv.setBits(high, low, value); + } + + /** + * Generates a bit mask of index+1 bits with the index bit set to ONE, and + * any lower-order bits set to ZERO. + * + * @param index the index of the bit to set to ONE + * @return a bit vector representing a mask containing the given bit + */ + public static BitVector getMask(int index) + { + BitVectorBuffer buf = new BitVectorBuffer(index + 1, Bit.ZERO); + buf.setBit(index, Bit.ONE); + return buf.toBitVector(); + } + + /** + * Generates a bit mask of high+1 bits with each bit between high and low + * (inclusive) set to ONE, and any lower-order bits set to ZERO. + * + * @param high the index of the highest bit to set to ONE + * @param low the index of the lowest bit to set to ONE + * @return a bit vector representing a mask containing the given bit range + */ + public static BitVector getMask(int high, int low) + { + if (high < low) + { + int temp = high; + high = low; + low = temp; + } + BitVectorBuffer buf = new BitVectorBuffer(high + 1, Bit.ZERO); + buf.fillBits(high, low, Bit.ONE); + return buf.toBitVector(); + } + + public static BitVector promote(BitVector bv, int minLen) + { + return bv.length() < minLen ? bv.setLength(minLen) : bv; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/BooleanOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/BooleanOp.java new file mode 100644 index 0000000..816fd84 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/BooleanOp.java @@ -0,0 +1,122 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * boolean conversion and operation methods referenced by + * translated code. + * + * @author Trevor Robinson + */ +public final class BooleanOp +{ + private BooleanOp() + { + } + + public static boolean toBoolean(Bit b, boolean xzTrue) + { + return !xzTrue ? b == Bit.ONE : b != Bit.ZERO; + } + + public static boolean toBoolean(BitVector bv) + { + return !bv.containsXZ() && bv.isNotZero(); + } + + public static boolean toBooleanXZTrue(BitVector bv) + { + return bv.containsXZ() || bv.isNotZero(); + } + + public static boolean toBoolean( + BitVector bv, + boolean lowBitOnly, + boolean xzTrue) + { + if (!lowBitOnly) + { + return !xzTrue ? toBoolean(bv) : toBooleanXZTrue(bv); + } + else + { + return toBoolean(bv.getBit(0), xzTrue); + } + } + + public static boolean toBoolean(Object o) + { + return toBoolean(o, false, false); + } + + public static boolean toBoolean(Object o, boolean lowBitOnly, boolean xzTrue) + { + if (o instanceof Boolean) + { + return ((Boolean) o).booleanValue(); + } + else if (o instanceof Number) + { + long l = ((Number) o).longValue(); + if (lowBitOnly) l &= 1; + return l != 0; + } + else if (o instanceof BitVector) + { + return toBoolean((BitVector) o, lowBitOnly, xzTrue); + } + else if (o instanceof Bit) + { + return toBoolean((Bit) o, xzTrue); + } + else if (o instanceof String) + { + return toBoolean((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static boolean toBoolean(String s) + { + return s != null && s.length() > 0; + } + + public static boolean divide(boolean b1, boolean b2) + { + if (!b2) + { + throw new ArithmeticException("boolean divide by zero"); + } + return b1 & b2; + } + + public static boolean mod(boolean b1, boolean b2) + { + if (!b2) + { + throw new ArithmeticException("boolean divide by zero"); + } + return false; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/ImmutableValueFactory.java b/java/juno-runtime/src/com/newisys/juno/runtime/ImmutableValueFactory.java new file mode 100644 index 0000000..0b7e385 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/ImmutableValueFactory.java @@ -0,0 +1,61 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Implementation of ValueFactory for immutable objects. + * + * @param object type produced by factory + * @author Trevor Robinson + */ +public final class ImmutableValueFactory + implements ValueFactory +{ + private final T value; + + /** + * Create an ImmutableValueFactory with the specified immutable object. + * + * @param value the immutable Object to use in this factory + */ + public ImmutableValueFactory(T value) + { + this.value = value; + } + + /** + * Returns the immutable object for this factory. + * + * @return this factory's immutable object + */ + public T newInstance() + { + return value; + } + + /** + * Returns the immutable object passed as an argument. + * + * @param other the Object to copy + * @return other + */ + public T copyInstance(T other) + { + return other; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/IntOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/IntOp.java new file mode 100644 index 0000000..0f66dc7 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/IntOp.java @@ -0,0 +1,218 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * int/long conversion and operation methods + * referenced by translated code. + * + * @author Trevor Robinson + */ +public final class IntOp +{ + private IntOp() + { + } + + public static int toInt(Object o) + { + if (o instanceof Number) + { + return ((Number) o).intValue(); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).intValue(); + } + else if (o instanceof Bit) + { + return BitOp.toInt((Bit) o); + } + else if (o instanceof Boolean) + { + return ((Boolean) o).booleanValue() ? 1 : 0; + } + else if (o instanceof String) + { + return toInt((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static int toInt(String s) + { + int len = s.length(); + int c0 = len > 0 ? s.charAt(--len) : 0; + int c1 = len > 0 ? s.charAt(--len) : 0; + int c2 = len > 0 ? s.charAt(--len) : 0; + int c3 = len > 0 ? s.charAt(--len) : 0; + return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0; + } + + public static long toLong(Object o) + { + if (o instanceof Number) + { + return ((Number) o).longValue(); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).longValue(); + } + else if (o instanceof Bit) + { + return BitOp.toInt((Bit) o); + } + else if (o instanceof Boolean) + { + return ((Boolean) o).booleanValue() ? 1L : 0L; + } + else if (o instanceof String) + { + return toLong((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static long toLong(String s) + { + int len = s.length(); + long result = 0; + for (int shift = 0; len > 0 && shift < 64; shift += 8) + { + long c = s.charAt(--len); + result |= (c << shift); + } + return result; + } + + public static int bitwiseReverse(int i) + { + int src = i; + int dst = 0; + for (int k = 0; k < 32; ++k) + { + dst = (dst << 1) & (src & 1); + src >>>= 1; + } + return dst; + } + + public static long bitwiseReverse(long l) + { + long src = l; + long dst = 0; + for (int k = 0; k < 64; ++k) + { + dst = (dst << 1) & (src & 1); + src >>>= 1; + } + return dst; + } + + public static boolean reductiveAnd(int i) + { + return (i == -1) ? true : false; + } + + public static boolean reductiveAnd(long l) + { + return (l == -1) ? true : false; + } + + public static boolean reductiveAndNot(int i) + { + return (i == -1) ? false : true; + } + + public static boolean reductiveAndNot(long l) + { + return (l == -1) ? false : true; + } + + public static boolean reductiveOr(int i) + { + return (i == 0) ? false : true; + } + + public static boolean reductiveOr(long l) + { + return (l == 0) ? false : true; + } + + public static boolean reductiveOrNot(int i) + { + return (i == 0) ? true : false; + } + + public static boolean reductiveOrNot(long l) + { + return (l == 0) ? true : false; + } + + public static boolean reductiveXor(int i) + { + return (bitCount(i) & 1) == 1 ? true : false; + } + + public static boolean reductiveXor(long l) + { + return (bitCount(l) & 1) == 1 ? true : false; + } + + public static boolean reductiveXorNot(int i) + { + return (bitCount(i) & 1) == 1 ? false : true; + } + + public static boolean reductiveXorNot(long l) + { + return (bitCount(l) & 1) == 1 ? false : true; + } + + public static int bitCount(int i) + { + int count = 0; + while (i != 0) + { + count += (i & 1); + i >>>= 1; + } + return count; + } + + public static int bitCount(long l) + { + int count = 0; + while (l != 0) + { + count += (l & 1); + l >>>= 1; + } + return count; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/IntegerOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/IntegerOp.java new file mode 100644 index 0000000..389c2b2 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/IntegerOp.java @@ -0,0 +1,393 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Integer conversion and operation methods referenced by translated code. + * + * @author Trevor Robinson + */ +public final class IntegerOp +{ + private final static Integer INTEGER_ZERO = new Integer(0); + private final static Integer INTEGER_ONE = new Integer(1); + + private IntegerOp() + { + } + + public static boolean toBoolean(Integer i) + { + return i != null && i.intValue() != 0; + } + + public static boolean lowBitToBoolean(Integer i) + { + return i != null && (i.intValue() & 1) != 0; + } + + public static boolean toBooleanXZTrue(Integer i) + { + return i == null || i.intValue() != 0; + } + + public static boolean lowBitToBooleanXZTrue(Integer i) + { + return i == null || (i.intValue() & 1) != 0; + } + + public static BitVector toBitVector(Integer i) + { + return toBitVector(i, 32, false); + } + + public static BitVector toBitVector(Integer i, int len) + { + return toBitVector(i, len, false); + } + + public static BitVector toBitVector(Integer i, int len, boolean signExtend) + { + return i != null ? new BitVector(len, i.intValue(), signExtend) + : new BitVector(len, Bit.X); + } + + public static int toInt(Integer i) + { + if (i == null) + { + throw new IllegalArgumentException("Value is undefined"); + } + return i.intValue(); + } + + public static int toShiftCount(Integer i, int max) + { + if (i == null) + { + throw new IllegalArgumentException( + "Shift count cannot be undefined"); + } + return Math.min(i.intValue(), max); + } + + public static int toShiftCount(Integer i) + { + return toShiftCount(i, Integer.MAX_VALUE); + } + + public static Integer toInteger(Bit b) + { + switch (b.getID()) + { + case 0: + return INTEGER_ZERO; + case 1: + return INTEGER_ONE; + default: + return null; + } + } + + public static Integer toInteger(BitVector bv) + { + return bv.containsXZ() ? null : new Integer(bv.intValue()); + } + + public static Integer toInteger(BitVector bv, boolean signed) + { + if (bv.containsXZ()) + { + return null; + } + else + { + int i = bv.intValue(); + if (signed) + { + int len = bv.length(); + if (len < 32) + { + int mask = 1 << (len - 1); + if ((i & mask) != 0) + { + i |= ~(mask - 1); + } + } + } + return new Integer(i); + } + } + + public static Integer toInteger(Long l) + { + return l != null ? new Integer(l.intValue()) : null; + } + + public static Integer toInteger(String s) + { + return new Integer(IntOp.toInt(s)); + } + + public static Integer toInteger(Object o) + { + if (o instanceof Integer || o == null) + { + return (Integer) o; + } + else if (o instanceof BitVector) + { + return toInteger((BitVector) o); + } + else if (o instanceof Bit) + { + return toInteger((Bit) o); + } + else if (o instanceof Number) + { + return new Integer(((Number) o).intValue()); + } + else if (o instanceof Boolean) + { + return new Integer(((Boolean) o).booleanValue() ? 1 : 0); + } + else if (o instanceof String) + { + return toInteger((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static Integer add(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + + i2.intValue()) : null; + } + + public static Integer subtract(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + - i2.intValue()) : null; + } + + public static Integer multiply(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + * i2.intValue()) : null; + } + + public static Integer divide(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + / i2.intValue()) : null; + } + + public static Integer mod(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + % i2.intValue()) : null; + } + + public static Integer negate(Integer i) + { + return (i != null) ? new Integer(-i.intValue()) : null; + } + + public static Integer inc(Integer i) + { + return (i != null) ? new Integer(i.intValue() + 1) : null; + } + + public static Integer dec(Integer i) + { + return (i != null) ? new Integer(i.intValue() - 1) : null; + } + + public static Integer bitwiseAnd(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + & i2.intValue()) : null; + } + + public static Integer bitwiseAndNot(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(~(i1.intValue() & i2 + .intValue())) : null; + } + + public static Integer bitwiseOr(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + | i2.intValue()) : null; + } + + public static Integer bitwiseOrNot(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(~(i1.intValue() | i2 + .intValue())) : null; + } + + public static Integer bitwiseXor(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(i1.intValue() + ^ i2.intValue()) : null; + } + + public static Integer bitwiseXorNot(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? new Integer(~(i1.intValue() ^ i2 + .intValue())) : null; + } + + public static Integer bitwiseNot(Integer i) + { + return (i != null) ? new Integer(~i.intValue()) : null; + } + + public static Integer bitwiseReverse(Integer i) + { + return (i != null) ? new Integer(IntOp.bitwiseReverse(i.intValue())) + : null; + } + + public static Bit reductiveAnd(Integer i) + { + return (i != null) ? (i.intValue() == -1 ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveAndNot(Integer i) + { + return (i != null) ? (i.intValue() == -1 ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Bit reductiveOr(Integer i) + { + return (i != null) ? (i.intValue() == 0 ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Bit reductiveOrNot(Integer i) + { + return (i != null) ? (i.intValue() == 0 ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveXor(Integer i) + { + return (i != null) ? ((IntOp.bitCount(i.intValue()) & 1) == 1 ? Bit.ONE + : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveXorNot(Integer i) + { + return (i != null) ? ((IntOp.bitCount(i.intValue()) & 1) == 1 + ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Integer logicalAnd(Integer i1, Integer i2) + { + return toBoolean(i1) && toBoolean(i2) ? INTEGER_ONE : INTEGER_ZERO; + } + + public static Integer logicalOr(Integer i1, Integer i2) + { + return toBoolean(i1) || toBoolean(i2) ? INTEGER_ONE : INTEGER_ZERO; + } + + public static Integer logicalNegative(Integer i) + { + return (i != null) ? (i.intValue() == 0 ? INTEGER_ONE : INTEGER_ZERO) + : null; + } + + public static Bit equal(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() == i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit notEqual(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() != i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit exactEqual(Integer i1, Integer i2) + { + return (i1 != null ? i2 != null && i1.intValue() == i2.intValue() + : i2 == null) ? Bit.ONE : Bit.ZERO; + } + + public static Bit exactNotEqual(Integer i1, Integer i2) + { + return (i1 != null ? i2 == null || i1.intValue() != i2.intValue() + : i2 != null) ? Bit.ONE : Bit.ZERO; + } + + public static Bit wildEqual(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() == i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.ONE; + } + + public static Bit wildNotEqual(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() != i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.ZERO; + } + + public static Bit greater(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() > i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit greaterOrEqual(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() >= i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit less(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() < i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit lessOrEqual(Integer i1, Integer i2) + { + return (i1 != null && i2 != null) ? (i1.intValue() <= i2.intValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Integer shiftLeft(Integer i1, Integer i2) + { + return (i1 != null) + ? new Integer(i1.intValue() << toShiftCount(i2, 31)) : null; + } + + public static Integer shiftRight(Integer i1, Integer i2) + { + return (i1 != null) + ? new Integer(i1.intValue() >> toShiftCount(i2, 31)) : null; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/Juno.java b/java/juno-runtime/src/com/newisys/juno/runtime/Juno.java new file mode 100644 index 0000000..31a32a5 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/Juno.java @@ -0,0 +1,3914 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.newisys.dv.ClockSignal; +import com.newisys.dv.DV; +import com.newisys.dv.InOutSignal; +import com.newisys.dv.InputSignal; +import com.newisys.dv.Mailbox; +import com.newisys.dv.OutputSignal; +import com.newisys.dv.PortSignalWrapper; +import com.newisys.dv.Semaphore; +import com.newisys.dv.Signal; +import com.newisys.eventsim.Event; +import com.newisys.eventsim.SimulationThread; +import com.newisys.printf.VeraPrintfFormatter; +import com.newisys.random.LinearCongruentialFactory; +import com.newisys.random.PRNG; +import com.newisys.random.PRNGFactoryFactory; +import com.newisys.util.system.SystemUtil; +import com.newisys.util.text.TextUtil; +import com.newisys.verilog.EdgeSet; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorFormat; +import com.newisys.verilog.util.ValueConverter; + +/** + * Implementations of Vera's built-in functions for use by translated code. + * + * @author Jon Nall + * @author Trevor Robinson + */ +public final class Juno +{ + //////////////////////////////////////////////////////////// + // Static data + //////////////////////////////////////////////////////////// + + /** + * Represents the system clock, "CLOCK". It must be initialized before + * any classes generated by the translator are loaded. + */ + public static ClockSignal systemClock; + + /** + * Map of SimulationThread objects to the current JunoThreadContext for each + * thread. + */ + private static Map threadContextMap; + + /** + * Property set representing the plus-args. + */ + private static Properties props; + + public static void initialize() + { + systemClock = DV.simulation.getDefaultClockSignal(); + + threadContextMap = new HashMap(); + props = new Properties(); + + // load default properties from file + final String defaultPropsFile = "jove.ini"; + try + { + FileInputStream input = new FileInputStream(defaultPropsFile); + props.load(input); + } + catch (IOException e) + { + System.err.println("Unable to open default properties file '" + + defaultPropsFile + "': " + e.getMessage()); + } + + // get properties from command line + final Iterator iter = DV.simulation.getArguments().iterator(); + while (iter.hasNext()) + { + final String arg = iter.next(); + if (arg.startsWith("+")) + { + int equalsPos = arg.indexOf('='); + if (equalsPos > 0) + { + props.setProperty(arg.substring(1, equalsPos), arg + .substring(equalsPos + 1)); + } + } + } + + // get initial random seed from command line + int seed = 1; + if (!get_plus_arg(CHECK, "random_seed=").isZero()) + { + seed = get_plus_arg(NUM, "random_seed=").intValue(); + } + srandom(seed); + } + + //////////////////////////////////////////////////////////// + // Java array translation helpers + //////////////////////////////////////////////////////////// + + /** + * Initializes the given Object array with the given value, starting at the + * given index and continuing to the end of the array. + * + * @param the array element type + * @param array the array to initialize + * @param value the initial value + * @param start the starting index + * @return the given array + */ + public static T[] initArray(T[] array, T value, int start) + { + if (!array.getClass().getComponentType().isArray()) + { + // single-dimensional array + for (int i = start; i < array.length; ++i) + { + array[i] = value; + } + } + else + { + // multi-dimensional array + for (int i = start; i < array.length; ++i) + { + @SuppressWarnings("unchecked") + T[] nestedArray = (T[]) array[i]; + initArray(nestedArray, value, 0); + } + } + return array; + } + + /** + * Initializes the given Object array with values from the given factory, + * starting at the given index and continuing to the end of the array. + * + * @param the array element type + * @param array the array to initialize + * @param factory the factory providing initial values + * @param start the starting index + * @return the given array + */ + public static T[] initArray( + T[] array, + ValueFactory factory, + int start) + { + if (!array.getClass().getComponentType().isArray()) + { + // single-dimensional array + for (int i = start; i < array.length; ++i) + { + array[i] = factory.newInstance(); + } + } + else + { + // multi-dimensional array + for (int i = start; i < array.length; ++i) + { + @SuppressWarnings("unchecked") + T[] nestedArray = (T[]) array[i]; + initArray(nestedArray, factory, 0); + } + } + return array; + } + + /** + * Copies the given source array into the given destination array, and + * initializes any extra elements in the destination array with the given + * value. + * + * @param the array element type + * @param dstArray the array to copy into + * @param srcArray the array to copy from + * @param initExtra value used to initialize the rest of the destination + * array, if the source array is shorter + * @return the destination array + */ + public static T[] copyArray(T[] dstArray, T[] srcArray, T initExtra) + { + boolean dstArrayMultiDim = dstArray.getClass().getComponentType() + .isArray(); + assert (srcArray.getClass().getComponentType().isArray() == dstArrayMultiDim); + int copyLen = Math.min(srcArray.length, dstArray.length); + if (!dstArrayMultiDim) + { + // single-dimensional array + for (int i = 0; i < copyLen; ++i) + { + dstArray[i] = srcArray[i]; + } + } + else + { + // multi-dimensional array + for (int i = 0; i < copyLen; ++i) + { + @SuppressWarnings("unchecked") + T[] nestedDstArray = (T[]) dstArray[i]; + + @SuppressWarnings("unchecked") + T[] nestedSrcArray = (T[]) srcArray[i]; + copyArray(nestedDstArray, nestedSrcArray, initExtra); + } + } + if (copyLen < dstArray.length) + { + initArray(dstArray, initExtra, copyLen); + } + return dstArray; + } + + /** + * Clones the elements in the given source array into the given destination + * array, and initializes any extra elements in the destination array, using + * the given value factory. + * + * @param the array element type + * @param dstArray the array to copy into + * @param srcArray the array to copy from + * @param factory the value factory used to copy and initialize values + * @return the destination array + */ + public static T[] copyArray( + T[] dstArray, + T[] srcArray, + ValueFactory factory) + { + boolean dstArrayMultiDim = dstArray.getClass().getComponentType() + .isArray(); + assert (srcArray.getClass().getComponentType().isArray() == dstArrayMultiDim); + int copyLen = Math.min(srcArray.length, dstArray.length); + if (!dstArrayMultiDim) + { + // single-dimensional array + for (int i = 0; i < copyLen; ++i) + { + dstArray[i] = factory.copyInstance(srcArray[i]); + } + } + else + { + // multi-dimensional array + for (int i = 0; i < copyLen; ++i) + { + @SuppressWarnings("unchecked") + T[] nestedDstArray = (T[]) dstArray[i]; + + @SuppressWarnings("unchecked") + T[] nestedSrcArray = (T[]) srcArray[i]; + copyArray(nestedDstArray, nestedSrcArray, factory); + } + } + if (copyLen < dstArray.length) + { + initArray(dstArray, factory, copyLen); + } + return dstArray; + } + + //////////////////////////////////////////////////////////// + // cast_assign translation helpers + //////////////////////////////////////////////////////////// + + public static void badCast() + { + throw new RuntimeException("Bad cast"); + } + + //////////////////////////////////////////////////////////// + // Operator translation helpers + //////////////////////////////////////////////////////////// + + public static boolean equals(Object o1, Object o2) + { + return o1 == o2 || (o1 != null && o1.equals(o2)); + } + + //////////////////////////////////////////////////////////// + // Associative array utilities + //////////////////////////////////////////////////////////// + + public static final int CHECK = 0; + public static final int FIRST = 1; + public static final int NEXT = 2; + public static final int DELETE = 3; + + /** + * assoc_index built-in function for dealing with entire arrays. + *

+ * If op == CHECK, this method returns the number of elements in array. + *

+ * If op == DELETE, this method deletes all elements in array. + *

+ * @see #assoc_index(int, AssocArray, Object) + * @see #assoc_index(int, AssocArray, Object[]) + * @param op Either {@link #CHECK}or {@link #DELETE} + * @param array the array on which to perform the operation + * @return the size of the array if op == CHECK or a 1 if op == DELETE + */ + public static int assoc_index(int op, AssocArray< ? , ? > array) + { + if (op == CHECK) + { + return array.check(); + } + else if (op == DELETE) + { + return array.delete(); + } + else + { + throw new IllegalArgumentException( + "assoc_index: op must be CHECK or DELETE"); + } + } + + /** + * assoc_index built-in function for dealing with array elements. + *

+ * If op == CHECK, return whether or not array[index] is valid. + *

+ * If op == DELETE, invalidate array[index] if it exists. + *

+ * @see #assoc_index(int, AssocArray) + * @see #assoc_index(int, AssocArray, Object[]) + * @param op Either {@link #CHECK}or {@link #DELETE} + * @param array the array on which to perform the operation + * @param index the index of array on which to perform op + * @return if op == CHECK, return 0 if index in array is valid, 0 if it is + * not valid. if op == DELETE, return 1 if the element at index was + * removed from the array, and 0 if the element was not found in the + * array. + * @throws IllegalArgumentException if index is null, or is a BitVector + * containing an X/Z value, or index is not either a BitVector, + * String or JunoString object + */ + public static int assoc_index(int op, AssocArray array, Object index) + { + // if this assertion fires, we probably need another overloaded version + // similar to Juno.assoc_index(int, AssocArray, int[]). + assert (!index.getClass().isArray()); + + if (op != CHECK && op != DELETE) + { + throw new IllegalArgumentException( + "assoc_index: op must be CHECK or DELETE"); + } + + if (index == null) + { + throw new IllegalArgumentException( + "assoc_index: index cannot be null"); + } + + if (array instanceof BitAssocArray) + { + BitAssocArray< ? > bitArray = (BitAssocArray) array; + BitVector bitIndex = ValueConverter.toBitVector(index); + if (bitIndex.containsXZ()) + { + throw new IllegalArgumentException("assoc_index: index (" + + bitIndex + ") cannot contain X/Z"); + } + return (op == DELETE) ? bitArray.delete(bitIndex) : bitArray + .check(bitIndex); + } + else if (array instanceof StringAssocArray) + { + StringAssocArray< ? > strArray = (StringAssocArray) array; + String strIndex; + if (index instanceof String) + { + strIndex = (String) index; + } + else if (index instanceof JunoString) + { + strIndex = ((JunoString) index).toStringOrNull(); + if (strIndex == null) + { + throw new IllegalArgumentException( + "assoc_index: string index cannot be null"); + } + } + else + { + throw new IllegalArgumentException( + "assoc_index: illegal index type for string array: " + + index.getClass().getName()); + } + return (op == DELETE) ? strArray.delete(strIndex) : strArray + .check(strIndex); + } + else + { + throw new IllegalArgumentException( + "assoc_index: unknown array type: " + + array.getClass().getName()); + } + } + + /** + * See {@link #assoc_index(int, AssocArray, Object[])}. This method is + * identical except the type of index_ref is + * int[]. + * + * @param op Either {@link #FIRST}or {@link #NEXT}or {@link #CHECK} or + * {@link #DELETE} + * @param array the array on which to perform the operation + * @param index_ref an array holding a reference to the index of + * array on which to perform op + * @return see {@link #assoc_index(int, AssocArray, Object[])} + * @throws IllegalArgumentException if index_ref is null or contains more + * than 1 element + */ + public static int assoc_index(int op, AssocArray array, int[] index_ref) + { + // perform manual boxing/unboxing operations and call the Object[] + // version of assoc_index. + if (index_ref == null || index_ref.length != 1) + { + throw new IllegalArgumentException( + "assoc_index: index reference must be single-element array"); + } + + Integer[] new_index_ref = new Integer[1]; + new_index_ref[0] = index_ref[0]; + final int status = assoc_index(op, array, new_index_ref); + index_ref[0] = new_index_ref[0]; + return status; + } + + /** + * assoc_index built-in function for dealing with array elements. + *

+ * If op == FIRST, index_ref[0] is set to the first valid index of the + * array. If a valid first element is found, a 1 is returned and + * index_ref[0] is set to that element. If not, a 0 is returned and + * index_ref[0] is left unchanged. + *

+ * If op == NEXT, index_ref[0] is set to the next valid index of the array. + * If a valid next element is found, a 1 is returned and index_ref[0] is set + * to that element. If not, a 0 is returned and index_ref[0] is left + * unchanged. + *

+ * If op == CHECK, return whether or not array[index] exists. If it does, a + * 1 is returned. If not, a 0 is returned. + *

+ * If op == DELETE, invalidate array[index] if it exists. If it is + * successful, a 1 is returned. If the element did not exist, a 0 is + * returned. + *

+ * @see #assoc_index(int, AssocArray) + * @param op Either {@link #FIRST}or {@link #NEXT}or {@link #CHECK} or + * {@link #DELETE} + * @param array the array on which to perform the operation + * @param index_ref an array holding a reference to the index of + * array on which to perform op + * @return see above + * @throws IllegalArgumentException if index_ref is null or contains more + * than 1 element, or if index_ref[0] is a BitVector containing + * an X/Z value, or index_ref[0] is not either a BitVector, + * String or JunoString object + */ + + public static int assoc_index(int op, AssocArray array, Object[] index_ref) + { + if (index_ref == null || index_ref.length != 1) + { + throw new IllegalArgumentException( + "assoc_index: index reference must be single-element array"); + } + + Object index = index_ref[0]; + if (op == CHECK || op == DELETE) + { + return assoc_index(op, array, index); + } + else if (op == FIRST) + { + if (array instanceof BitAssocArray) + { + BitAssocArray< ? > bitArray = (BitAssocArray) array; + BitVector bitIndex = bitArray.first(); + if (bitIndex.containsXZ()) + { + index = null; + } + else if (index_ref instanceof BitVector[]) + { + index = bitIndex; + } + else + { + assert (index_ref instanceof Integer[]); + index = IntegerOp.toInteger(bitIndex); + } + } + else if (array instanceof StringAssocArray) + { + StringAssocArray< ? > strArray = (StringAssocArray) array; + String strIndex = strArray.first(); + if (strIndex == null || index_ref instanceof String[]) + { + index = strIndex; + } + else + { + assert (index_ref instanceof JunoString[]); + assert (index instanceof JunoString); + ((JunoString) index).assign(strIndex); + } + } + else + { + throw new IllegalArgumentException( + "assoc_index: unknown array type: " + + array.getClass().getName()); + } + if (index == null) + { + // leave index_ref unchanged if first() fails + return 0; + } + index_ref[0] = index; + return 1; + } + else if (op == NEXT) + { + if (index == null) + { + throw new IllegalArgumentException( + "assoc_index: index cannot be null"); + } + + if (array instanceof BitAssocArray) + { + BitAssocArray bitArray = (BitAssocArray) array; + BitVector bitIndex = ValueConverter.toBitVector(index); + if (bitIndex.containsXZ()) + { + throw new IllegalArgumentException("assoc_index: index (" + + bitIndex + ") cannot contain X/Z"); + } + bitIndex = bitArray.next(bitIndex); + if (bitIndex.containsXZ()) + { + index = null; + } + else if (index_ref instanceof BitVector[]) + { + index = bitIndex; + } + else + { + assert (index_ref instanceof Integer[]); + index = IntegerOp.toInteger(bitIndex); + } + } + else if (array instanceof StringAssocArray) + { + StringAssocArray< ? > strArray = (StringAssocArray) array; + String strIndex; + if (index instanceof String) + { + strIndex = (String) index; + } + else if (index instanceof JunoString) + { + strIndex = ((JunoString) index).toStringOrNull(); + if (strIndex == null) + { + throw new IllegalArgumentException( + "assoc_index: string index cannot be null"); + } + } + else + { + throw new IllegalArgumentException( + "assoc_index: illegal index type for string array: " + + index.getClass().getName()); + } + strIndex = strArray.next(strIndex); + if (strIndex == null || index_ref instanceof String[]) + { + index = strIndex; + } + else + { + assert (index_ref instanceof JunoString[]); + assert (index instanceof JunoString); + ((JunoString) index).assign(strIndex); + } + } + else + { + throw new IllegalArgumentException( + "assoc_index: unknown array type: " + + array.getClass().getName()); + } + if (index == null) + { + // leave index_ref unchanged if next() fails + return 0; + } + index_ref[0] = index; + return 1; + } + else + { + throw new IllegalArgumentException( + "assoc_index: op must be CHECK, DELETE, FIRST, or NEXT"); + } + } + + public static final int NUM = 1; + public static final int STR = 2; + public static final int HNUM = 3; + + /** + * Returns a plusarg value as defined in jove.ini or on the command line. + * + * @param name A String containing the name of the property to be queried. A + * good practice is end this String with '=' (e.g. "txns="). + * @param defaultValue The String that should be returned if name is not + * specified. + * @return A String containing the user-specified value for the plusarg + * described by name, or defaultValue if such a plusarg was not specified. + */ + static String getProperty(String name, String defaultValue) + { + // Vera matches the leading substring, so: + // get_plus_arg(HNUM, "foo") with +foobad=20 + // returns a bit vector with value 0xBAD (from fooBAD) + // get_plus_arg(STR, "foo") with +foobar=20 + // returns a bit string of ASCII values for "bar=20" + // + // this is screwy and i'm not implementing it for now. sane + // users should enforce their plusargs by suffixing them with "=" + if (!name.endsWith("=")) + { + throw new RuntimeException( + "Currently only plusargs ending in \"=\" are supported"); + } + name = name.substring(0, name.length() - 1); + + return props.getProperty(name, defaultValue); + } + + /** + * Returns a clone of the Properties from jove.ini and command line. + * @return a clone of the Properties. + */ + static public Properties getProperties() + { + return (Properties) props.clone(); + } + + /** + * Returns a plusarg value as defined in jove.ini or on the command line. + * + * @param op one of {@link #CHECK}, {@link #NUM}, {@link #STR}, or + * {@link #HNUM} which determines how the value associated with a given + * plusarg is interpreted. + * @param name A String containing the name of the property to be queried. A + * good practice is end this String with '=' (e.g. "txns="). + * @return A BitVector containing the user-specified value for the plusarg + * described by name interpreted as described by op. If name was not + * specified by the user, a BitVector of value 32'h0 is returned. + */ + public static BitVector get_plus_arg(int op, String name) + { + assert (op == CHECK || op == NUM || op == STR || op == HNUM); + + int result = 0; + String s = getProperty(name, null); + if (s != null) + { + switch (op) + { + case CHECK: + result = 1; + break; + case NUM: + case HNUM: + // returns a 32 bit quantity + // Vera reads the string until an invalid character is read + // if a value >= 2^32 - 1 is given, 0xFFFFFFFF is returned + s = s.replaceAll("_", ""); + int radix; + if (op == NUM) + { + s = s.replaceFirst("[^-0-9].*", ""); + radix = 10; + } + else + { + s = s.replaceFirst("[^0-9A-Fa-f].*", ""); + radix = 16; + } + if (s.length() == 0) + { + result = 0; + } + else if (op == HNUM && s.length() > 8 || op == NUM + && s.length() > 11) + { + // 32 bit limits: + // 8 char limit for hex values + // 11 char for decimal (10 digits + minus sign) + result = ~0; + } + else + { + long longResult = Long.parseLong(s, radix); + result = (longResult > Integer.MAX_VALUE) ? ~0 + : (int) longResult; + } + break; + case STR: + // returns a "bit string" (Vera's term, not mine) + // the bit vector returned will be the length of the string + // time 8. with the bit strings containing the ASCII + // representation + if (s.startsWith("\"") && s.endsWith("\"")) + { + s = s.substring(1, s.length() - 1); + } + + // reverse the bytes since charAt(0) will be in the uppermost 8 + // bits + // of the bit vector + byte[] sBytes = s.getBytes(); + byte[] reversedBytes = new byte[sBytes.length]; + for (int i = 0, j = sBytes.length - 1; i < sBytes.length; ++i, --j) + { + reversedBytes[i] = sBytes[j]; + } + BitVector v = new BitVector(reversedBytes); + return v; + default: + assert (false); + } + } + + return new BitVector(32, result); + } + + //////////////////////////////////////////////////////////// + // Concurrency utilities + //////////////////////////////////////////////////////////// + + public static final int SEMAPHORE = 0; + public static final int REGION = 1; + public static final int MAILBOX = 2; + + private static final String[] ALLOC_NAMES = { "SEMAPHORE", "REGION", + "MAILBOX" }; + + public static final int NO_WAIT = 0; + public static final int WAIT = 1; + public static final int COPY_NO_WAIT = 2; + public static final int COPY_WAIT = 3; + + // internal variables + private static final Map semaphoreMap = new HashMap(); + private static final Map> mailboxMap = new HashMap>(); + + private static int alloc_internal(int type, int id, int count, int keyCount) + { + Map objectMap; + switch (type) + { + case SEMAPHORE: + objectMap = semaphoreMap; + break; + case REGION: + throw new UnsupportedOperationException("Regions not implemented"); + case MAILBOX: + objectMap = mailboxMap; + break; + default: + throw new IllegalArgumentException( + "Invalid object type for alloc(): " + type); + } + + if (type != SEMAPHORE) assert (keyCount == 0); + + if (count < 1) + { + throw new IllegalArgumentException("Illegal count (" + count + + ") for " + "alloc(" + ALLOC_NAMES[type] + ")"); + } + + // id is based on a lowest value of 1, not 0. + --id; + + // If id is specified, use that range, creating mailboxes/regions + // that don't exist or use an existing one if possible. + // If id is not specified, return the lowest id that can hold + // count object without conflicting with an existing object. + + int baseID = id; + if (id == -1) + { + // calculate the lowest index that can hold count objects. + baseID = -1; + SortedSet indices = new TreeSet(objectMap + .keySet()); + int allocIdx = 0; + + for (int curIdx : indices) + { + if (allocIdx + count <= curIdx) + { + // found an entry with enough capacity + break; + } + else + { + allocIdx = curIdx + 1; + } + } + baseID = allocIdx; + } + + for (int i = 0; i < count; ++i) + { + if (objectMap.containsKey(baseID + i)) + { + // Vera doesn't overwrite existing objects + continue; + } + + switch (type) + { + case SEMAPHORE: + final Semaphore semaphore = DV.simulation + .createSemaphore(keyCount); + semaphoreMap.put(baseID + i, semaphore); + break; + case REGION: + throw new UnsupportedOperationException( + "Regions not implemented"); + case MAILBOX: + final Mailbox mailbox = DV.simulation.createMailbox(); + mailboxMap.put(baseID + i, mailbox); + break; + } + } + + // baseID is based on a lowest value of 1, not 0. + ++baseID; + return baseID; + } + + /** + * alloc built-in function for allocating a REGION or a MAILBOX. + *

+ * This method allocates either a region or a mailbox, based on type. If id + * is 0, the next available id is used. This method attempts to allocate + * count region/mailboxes. + *

+ * If successful, the return value is the id of the first object. If id was + * 0, this will be a non-zero value. If id was non-zero, this will be + * identical to id. The objects are allocated contiguously so allocating N + * objects will result in N valid contiguous values, starting at the id + * returned. + *

+ * When the allocation cannot be performed (e.g. there are no more + * regions/mailboxes or count is greater than the maximum number of + * regions/mailboxes available) a RuntimeException will occur. + * + * @param type one of either {@link #MAILBOX}or {@link #REGION} + * @param id the base id to use. If 0, use the next available id. + * @param count the number of objects to create. + * @return the id of the first object created. + * @throws IllegalArgumentException if count <= 0 + */ + public static int alloc(int type, int id, int count) + { + assert (type == REGION || type == MAILBOX); + return alloc_internal(type, id, count, 0); + } + + /** + * alloc built-in function for allocating a REGION or a MAILBOX. + *

+ * This method allocates a semaphore. If id is 0, the next available id is + * used. This method attempts to allocate count semaphores. + *

+ * If successful, the return value is the id of the first semaphore. If id + * was 0, this will be a non-zero value. If id was non-zero, this will be + * identical to id. The semaphore are allocated contiguously so allocating N + * semaphores will result in N valid contiguous values, starting at the id + * returned. + *

+ * When the allocation cannot be performed (e.g. there are no more + * semaphores or count is greater than the maximum number of semaphores + * available) a RuntimeException will occur. + * + * @param type should be {@link #SEMAPHORE} + * @param id the base id to use. If 0, use the next available id. + * @param count the number of semaphores to create. + * @param keyCount the number of keys initially available in each semaphore + * @return the id of the first semaphore created. + * @throws IllegalArgumentException if count <= 0 + */ + public static int alloc(int type, int id, int count, int keyCount) + { + assert (type == SEMAPHORE); + return alloc_internal(type, id, count, keyCount); + } + + /** + * Release the specified number of keys to the specified semaphore. + * + * @param semaphore_id the semaphore to which the keys should be released + * @param keyCount the number of keys to release + */ + public static void semaphore_put(int semaphore_id, int keyCount) + { + assert (keyCount >= 0); + --semaphore_id; // indexed from 0 internally + + Semaphore sem = semaphoreMap.get(semaphore_id); + if (sem == null) + { + throw new RuntimeException("Uninitialized semaphore id [" + + semaphore_id + "] for semaphore_put"); + } + + sem.release(keyCount); + } + + /** + * Acquire one or more keys from a given semaphore. + * @param op One of {@link #WAIT} or {@link #NO_WAIT}. If op == WAIT, the + * thread will block until keyCount keys can be acquired from the semaphore. + * If op == NO_WAIT, the thread will not block and the return value can be + * examined to check for success. + * @param semaphore_id The Semaphore ID on which to operate. + * @param keyCount The number of keys that should be acquired from the + * semaphore. + * @return 1 if keyCount keys were successfully acquired from the semaphore, + * 0 otherwise. + */ + public static int semaphore_get(int op, int semaphore_id, int keyCount) + { + // semaphore_get: + // if op == WAIT, the return value is always 1, even if the + // process has to wait some number of cycles to acquire the semaphore + assert (op == WAIT || op == NO_WAIT); + --semaphore_id; // indexed from 0 internally + + Semaphore sem = semaphoreMap.get(semaphore_id); + if (sem == null) + { + throw new RuntimeException("Uninitialized semaphore id [" + + semaphore_id + "] for semaphore_get"); + } + + boolean attemptSuccessful = false; + if (op == NO_WAIT) + { + attemptSuccessful = sem.attempt(keyCount); + } + else + { + assert (op == WAIT); + sem.acquire(keyCount); + attemptSuccessful = true; + } + return (attemptSuccessful == true ? 1 : 0); + } + + /** + * NOTE: region_enter is currently unsupported. + * @param op One of {@link #WAIT} or {@link #NO_WAIT}. If op == WAIT, the + * thread will block until the region can be entered. If op == NO_WAIT, the + * thread will not block and the return value can be examined to check for + * success. + * @param region_id The Region ID on which to operate. + * @param values An array of values to acquire. + * @return 1 if the region was successfully entered, 0 otherwise. + */ + public static int region_enter(int op, int region_id, Object[] values) + { + // DEFERRED: region_enter + assert (op == WAIT || op == NO_WAIT); + --region_id; // indexed from 0 internally + throw new UnsupportedOperationException("region_enter()"); + } + + /** + * NOTE: region_exit is currently unsupported. + * @param region_id The Region ID on which to operate. + * @param values An array of values to release. + */ + public static void region_exit(int region_id, Object[] values) + { + // DEFERRED: region_exit + --region_id; // indexed from 0 internally + throw new UnsupportedOperationException("region_enter()"); + } + + /** + * Put an object into a given mailbox. + * @param mailbox_id The Mailbox ID in which to put the object. + * @param data The object to put into the mailbox. + */ + public static void mailbox_put(int mailbox_id, Object data) + { + --mailbox_id; // indexed from 0 internally + + Mailbox mbox = mailboxMap.get(mailbox_id); + if (mbox == null) + { + throw new RuntimeException("Uninitialized mailbox id [" + + mailbox_id + "] for mailbox_put"); + } + + mbox.put(data); + } + + /** + * Returns the size of the given mailbox. + *

+ * This is equivalent to calling mailbox_get(op, mailbox_id, null, 1); + * + * @param op One of {@link #WAIT}, {@link #NO_WAIT} {@link #COPY_WAIT}, or + * {@link #COPY_NO_WAIT}. If op is WAIT or COPY_WAIT and the mailbox is + * empty, the thread will block until the mailbox is non-empty. At that time + * the number of elements in the mailbox is returned. If NO_WAIT or COPY_NO_WAIT + * is specified, the number of elements in the mailbox is returned and the + * thread will not block. + * @param mailbox_id The Mailbox ID on which to operate. + * @return the size of the given mailbox. + */ + public static int mailbox_get(int op, int mailbox_id) + { + return mailbox_get(op, mailbox_id, null, 1); + } + + /** + * Retrieve an object from a given mailbox. + *

+ * This is equivalent to calling mailbox_get(op, mailbox_id, data_ref, 1); + * + * @param op One of {@link #WAIT}, {@link #NO_WAIT} {@link #COPY_WAIT}, or + * {@link #COPY_NO_WAIT}. If op is WAIT or COPY_WAIT, the thread will block + * until data is available in the mailbox. Otherwise, the thread will not + * block and the return value can be examined to check for success. If op + * is COPY_WAIT or COPY_NO_WAIT and there is data in the mailbox, the data + * will be copied to data_ref[0], but will not be removed from the mailbox. + * The next request will get the same object. However, op == WAIT or NO_WAIT, + * the data will be removed from the mailbox. + * @param mailbox_id The Mailbox ID on which to operate. + * @param data_ref An array into which the returned object will be placed. If + * this value is null, op is ignored and the current size of the mailbox is + * returned. + * @return Returns the number of entries in the mailbox, or -1 if there is + * a type mismatch. + */ + public static int mailbox_get(int op, int mailbox_id, Object[] data_ref) + { + return mailbox_get(op, mailbox_id, data_ref, 1); + } + + /** + * Retrieve an object from a given mailbox. + *

+ * @param op One of {@link #WAIT}, {@link #NO_WAIT} {@link #COPY_WAIT}, or + * {@link #COPY_NO_WAIT}. If op is WAIT or COPY_WAIT, the thread will block + * until data is available in the mailbox. Otherwise, the thread will not + * block and the return value can be examined to check for success. If op + * is COPY_WAIT or COPY_NO_WAIT and there is data in the mailbox, the data + * will be copied to data_ref[0], but will not be removed from the mailbox. + * The next request will get the same object. However, op == WAIT or NO_WAIT, + * the data will be removed from the mailbox. + * @param mailbox_id The Mailbox ID on which to operate. + * @param data_ref An array into which the returned object will be placed. If + * this value is null, the current size of the mailbox is returned. Note + * that in the case of data_ref being null, if op is WAIT or COPY_WAIT and + * the mailbox is empty, the thread will block. + * @param check If set to 1 and the type of object in the mailbox is + * incompatible with the type of object in data_ref[0], a -1 is returned and + * the data is left in the mailbox. If such a type mismatch occurs and check + * is 0, an exception will be thrown. + * @return Returns the number of entries in the mailbox, or -1 if there is + * a type mismatch and check is set to 1. + */ + public static int mailbox_get( + int op, + int mailbox_id, + Object[] data_ref, + int check) + { + assert (op == WAIT || op == NO_WAIT || op == COPY_WAIT || op == COPY_NO_WAIT); + + // if this assert fails, i didn't understand the purpose of the [] + assert (data_ref == null || data_ref.length == 1); + + --mailbox_id; // indexed from 0 internally + + Mailbox mbox = mailboxMap.get(mailbox_id); + if (mbox == null) + { + throw new RuntimeException("Uninitialized mailbox id [" + + mailbox_id + "] for mailbox_put"); + } + + boolean wait = (op == WAIT || op == COPY_WAIT); + + // don't dequeue in case there is a type mismatch. + Object obj = (wait) ? mbox.peekWait() : mbox.peekNoWait(); + int mboxSize = mbox.size(); + + if (data_ref == null) + { + // return number of elements + return mboxSize; + } + else if (mboxSize == 0 && (op == NO_WAIT || op == COPY_NO_WAIT)) + { + // no elements in the mailbox and *NO_WAIT + // VUM says to return zero here. + return 0; + } + + boolean typeMismatch = false; + Class srcClass = (obj == null ? null : obj.getClass()); + Class destClass = data_ref.getClass().getComponentType(); + Object objToAssign = null; + + if (destClass != Object.class) + { + // check for assignability + boolean srcIsNull = (obj == null); + boolean srcIsString = (obj instanceof String || obj instanceof JunoString); + boolean srcIsJunoObject = (obj instanceof JunoObject); + boolean srcIsJunoEnum = (obj instanceof JunoEnum); + boolean srcIsNumeric = (obj instanceof Integer + || obj instanceof BitVector || obj instanceof Bit); + boolean destIsNull = (data_ref == null || data_ref[0] == null); + boolean destIsString = (destClass == String.class || destClass == JunoString.class); + boolean destIsJunoObject = (JunoObject.class + .isAssignableFrom(destClass)); + boolean destIsJunoEnum = (JunoEnum.class + .isAssignableFrom(destClass)); + boolean destIsNumeric = (destClass == Integer.class + || destClass == BitVector.class || destClass == Bit.class); + // Conversions + // * BitVector/Integer/Bit -> BitVector/Integer/Bit + // The destination is assigned as much of the BitVector as it can + // contain, based on its width, and any extra width in the + // destination is zero-padded + // * BitVector/Integer/Bit -> String + // An exception is thrown + // * BitVector/Integer/Bit -> Enum + // If an enumeration in the destination enum class has the + // numeric value of this BitVector/Integer/Bit, an assignment + // is made. If the BitVector containsXZ() the undefined enum of + // that class is returned. Otherwise there is a type mismatch. + // * BitVector/Integer/Bit -> null, void, do not compile. + // Throw a RuntimeException + // + // * String -> BitVector/Integer/Bit + // The String's ASCII representation is effectively put in a + // BitVector of size (String.length() * 8) bits and the + // conversion to BitVector/Integer/Bit is as for BitVectors + // above. + // * String -> String + // The destination String is set to the source String + // * String -> Enum + // This is a type mismatch. + // + // * null/void -> BitVector/Integer/Bit + // An exception is thrown + // * null/void -> String + // The destination String is set to null + // * null/void -> Enum + // This is a type mismatch + // + // * Object -> BitVector/Integer/String/Bit + // An exception is thrown + // * Object -> Object + // If Destination object "is a" type of the source object, it + // succeeds + // Else an exception is thrown + // * Object -> Enum + // This is a type mismatch + // + // * Enum -> BitVector/Integer/Bit + // The integer value associated with the enumeration is assigned + // to the dest, truncated, or zero-extended as appropriate. If + // the src is the undefined enumeration, the destination is + // filled with X values. + // + // * Enum -> String + // This is a type mismatch. + // + // * Enum -> Object + // This is a type mismatch. + // + // * Enum -> Enum + // Succeeds if the enumeration contains elements that have the + // same value. If the src is an undefined enumeration, then the + // assignment succeeds and the dest is the undefined enumeration. + + assert (srcIsNumeric || srcIsString || srcIsJunoObject + || srcIsJunoEnum || obj == null); + assert (destIsNumeric || destIsString || destIsJunoObject || destIsJunoEnum); + + if (srcIsNull) + { + // only strings and objects can be assigned null + if (!(destIsString || destIsJunoObject)) + { + typeMismatch = true; + } + else + { + objToAssign = obj; + } + } + else if (srcIsString) + { + if (destIsNumeric) + { + String s = null; + if (obj instanceof String) + { + s = (String) obj; + } + else + { + s = ((JunoString) obj).toStringOrNull(); + if (s == null) + { + typeMismatch = true; + } + } + + // reverse the bytes + byte[] sBytes = s.getBytes(); + byte[] reversedBytes = new byte[sBytes.length]; + for (int i = 0, j = sBytes.length - 1; i < sBytes.length - 1; ++i, --j) + { + reversedBytes[i] = sBytes[j]; + } + BitVector vect = new BitVector(reversedBytes); + if (destClass == Integer.class) + { + objToAssign = IntegerOp.toInteger(vect); + } + else if (destClass == Bit.class) + { + objToAssign = BitOp.toBit(vect); + } + else if (destClass == BitVector.class) + { + assert (!destIsNull); + int length = ((BitVector) data_ref[0]).length(); + objToAssign = vect.setLength(length); + } + else + { + assert (false); + } + + } + else if (destIsString) + { + if (obj.getClass() == data_ref[0].getClass()) + { + objToAssign = obj; + } + else + { + // either String->JunoString or JunoString->String + if (obj instanceof String) + { + objToAssign = new JunoString((String) obj); + } + else + { + objToAssign = ((JunoString) obj).toString(); + } + } + } + else + { + // objects and enums can't be assigned from strings + typeMismatch = true; + } + } + else if (srcIsNumeric) + { + if (destIsString || destIsJunoObject) + { + typeMismatch = true; + } + else if (destIsJunoEnum) + { + // if there is an enumeration in the class with the + // given value, assign that. else if this src contains + // X/Z values, use the undefined enum for that class + JunoEnum< ? > e = (JunoEnum) data_ref[0]; + assert (e != null); + + assert (srcClass == BitVector.class + || srcClass == Bit.class || srcClass == Integer.class); + Integer value = IntegerOp.toInteger(obj); + + // get the value for this object, and use the default value + // if no enumeration element exists with the value given + final JunoEnum< ? > enumToAssign = e.getForValue(value, + true); + objToAssign = enumToAssign; + + // if value was not X/Z and we didn't find a valid enumeration, + // that's a type mismatch + if (value != null && !enumToAssign.isDefined()) + { + typeMismatch = true; + } + } + else + { + if (srcClass == destClass) + { + if (srcClass == BitVector.class) + { + // need to keep length of dest unchanged. + objToAssign = ((BitVector) data_ref[0]) + .assign((BitVector) obj); + } + else + { + objToAssign = obj; + } + } + else if (destClass == BitVector.class) + { + assert (srcClass == Bit.class || srcClass == Integer.class); + objToAssign = BitVectorOp.toBitVector(obj); + } + else if (destClass == Bit.class) + { + assert (srcClass == BitVector.class || srcClass == Integer.class); + objToAssign = BitOp.toBit(obj); + } + else if (destClass == Integer.class) + { + assert (srcClass == Bit.class || srcClass == BitVector.class); + objToAssign = IntegerOp.toInteger(obj); + } + else + { + assert (false); + } + + } + } + else if (srcIsJunoObject) + { + if (destIsJunoObject) + { + objToAssign = obj; + } + else + { + typeMismatch = true; + } + } + else if (srcIsJunoEnum) + { + JunoEnum< ? > e = (JunoEnum) obj; + Integer enumVal = e.toInteger(); + if (destIsNumeric) + { + if (destClass == BitVector.class) + { + objToAssign = IntegerOp.toBitVector(enumVal, 32); + } + else if (destClass == Bit.class) + { + objToAssign = BitOp.toBit(enumVal); + } + else + { + assert (destClass == Integer.class); + objToAssign = enumVal; + } + } + else if (destIsJunoEnum) + { + if (srcClass == destClass) + { + objToAssign = obj; + } + else + { + // check if destClass has an element corresponding to + // the integer value of obj. if so, use it. otherwise + // it's a type mismatch + try + { + JunoEnum< ? > destEnum = (JunoEnum) data_ref[0]; + assert (destEnum != null); + objToAssign = destEnum.getForValue(enumVal, false); + } + catch (IllegalArgumentException excp) + { + typeMismatch = true; + } + } + } + else + { + typeMismatch = true; + } + } + } + else + { + objToAssign = obj; + } + + if (typeMismatch) + { + if (check == 1) + { + return -1; + } + throw new IllegalArgumentException( + "mailbox_get: data type mismatch " + "(dest=" + destClass + + ", src=" + (obj == null ? null : srcClass) + ")"); + } + + if (op == NO_WAIT || op == WAIT) + { + // pop the mailbox if this wasn't just a COPY + obj = mbox.getNoWait(); + } + + if (data_ref != null) + { + // if we get here without throwing an exception, do the assignment + data_ref[0] = objToAssign; + } + return mboxSize; + } + + public static final int OFF = 0; + public static final int ON = 1; + public static final int ONE_SHOT = 2; + public static final int ONE_BLAST = 3; + public static final int HAND_SHAKE = 4; + + /** + * Triggers one or more JunoEvents in ONE_SHOT mode. + * + * @param events An array of JunoEvent objects that should be triggered. + */ + public static void trigger(JunoEvent... events) + { + trigger(ONE_SHOT, events); + } + + /** + * Triggers one or more JunoEvents. + * + * @param op One of {@link #OFF}, {@link #ON}, {@link #ONE_SHOT}, + * {@link #ONE_BLAST}, and {@link #HAND_SHAKE}. + * @param events An array of JunoEvent objects that should be triggered. + */ + public static void trigger(int op, JunoEvent... events) + { + assert (op == OFF || op == ON || op == ONE_SHOT || op == ONE_BLAST || op == HAND_SHAKE); + for (final JunoEvent e : events) + { + if (e == null) continue; + switch (op) + { + case OFF: + e.setOn(false); + break; + case ON: + e.setOn(true); + DV.simulation.notifyOf(e); + break; + case ONE_SHOT: + DV.simulation.notifyOf(e); + break; + case ONE_BLAST: + e.setOnDuringTime(DV.simulation.getSimTime()); + DV.simulation.notifyOf(e); + break; + case HAND_SHAKE: + e.giveHandshake(); + DV.simulation.notifyOf(e); + break; + default: + throw new UnsupportedOperationException("trigger(" + op + ")"); + } + } + } + + // DEFERRED: use switch's wherever possible as opposed to if/else. + + public static final int ALL = 1; + public static final int ANY = 2; + public static final int ORDER = 3; + + /** + * Wait on a given set of JunoEvents to occur.

+ * Description of operation for various values of op: + *

    + *
  • CHECK - Check each JunoEvent in events. If any JunoEvent is OFF, return + * 0, else return 1. + *
  • ALL - Block until each JunoEvent in events has been triggered. + *
  • ANY - Block until any JunoEvent in events has been triggered. + *
  • ORDER - Block until each JunoEvent in events has been triggered in + * the order they appear in the events array. + *
+ *

+ * TBD: under which circumstances do events which have occured before the + * sync call satisfy the sync? + * + * @param op One of {@link #CHECK}, {@link #ALL}, {@link #ANY}, or {@link #ORDER}. + * @param events An array of JunoEvents on which to sync. + * @return if op == CHECK and any of the JunoEvents in events are OFF, a 0 + * is returned, else a 1 is returned. + */ + public static int sync(int op, JunoEvent... events) + { + int result = 1; + assert (op == CHECK || op == ALL || op == ANY || op == ORDER); + if (op == CHECK) + { + for (final JunoEvent e : events) + { + if (e != null && !isEventOn(e, false)) + { + result = 0; + break; + } + } + } + else + { + final List waitEvents = new LinkedList(); + for (final JunoEvent e : events) + { + if (isEventOn(e, true)) + { + if (op == ANY) + { + waitEvents.clear(); + break; + } + } + else if (e != null) + { + waitEvents.add(e); + } + } + if (!waitEvents.isEmpty()) + { + if (op == ALL) + { + DV.simulation.waitForAll(waitEvents); + } + else if (op == ANY) + { + DV.simulation.waitForAny(waitEvents); + } + else + { + // DEFERRED: sync: ORDER + throw new UnsupportedOperationException("sync(" + op + ")"); + } + + // if we had to block, waiting on the trigger, we didn't decrement + // the handshakeCount in the isEventOn(e, true) call above. in this + // case, do that manually to avoid multiple sync's triggering + // from a single trigger(HAND_SHAKE) + // TODO: refactor sync to consolidate handshake bookkeeping + for (JunoEvent e : waitEvents) + { + e.checkHandshake(true); + } + } + } + return result; + } + + private static boolean isEventOn(Event e, boolean acquire) + { + if (e instanceof JunoEvent) + { + JunoEvent dvEvent = (JunoEvent) e; + // consume handshakes before checking for other cases + return dvEvent.checkHandshake(acquire) || dvEvent.isOn() + || dvEvent.getOnDuringTime() == DV.simulation.getSimTime(); + } + return false; + } + + //////////////////////////////////////////////////////////// + // Threading utilities + //////////////////////////////////////////////////////////// + + /** + * Enter a new thread context. This helps manage which threads should be + * waited on during a wait_child() call. + */ + public static void enter_context() + { + // get the current thread context, if any + SimulationThread t = DV.simulation.currentThread(); + assert (t != null); + JunoThreadContext pc = threadContextMap.get(t); + + // create a new thread context and map it as current + JunoThreadContext c = new JunoThreadContext(pc); + threadContextMap.put(t, c); + } + + /** + * Leave a thread context. This helps manage which threads should be + * waited on during a wait_child() call. + */ + public static void leave_context() + { + // get the current thread context + SimulationThread t = DV.simulation.currentThread(); + assert (t != null); + JunoThreadContext c = threadContextMap.get(t); + assert (c != null); + + // map the parent thread context as current + JunoThreadContext pc = c.getParentContext(); + threadContextMap.put(t, pc); + } + + /** + * Fork a new thread of execution. + * + * @param r the Runnable that will be executed in the new Thread. + * @return a new SimulationThread which will run Runnable r. + */ + public static SimulationThread fork(Runnable r) + { + return fork(null, r); + } + + /** + * Fork a new thread of execution. + * + * @param name a String identifier for the Thread + * @param r the Runnable that will be executed in the new Thread. + * @return a new SimulationThread which will run Runnable r. + */ + public static SimulationThread fork(String name, Runnable r) + { + SimulationThread t = DV.simulation.fork(name, r); + + // add the thread to any contexts of the parent thread + SimulationThread pt = DV.simulation.currentThread(); + assert (pt != null); + JunoThreadContext pc = threadContextMap.get(pt); + while (pc != null) + { + pc.addForkedThread(t); + pc = pc.getParentContext(); + } + + return t; + } + + /** + * Block until all threads marked as children of the current thread have + * exited. + */ + public static void wait_child() + { + // get the current thread context, if any + SimulationThread t = DV.simulation.currentThread(); + assert (t != null); + JunoThreadContext c = threadContextMap.get(t); + if (c != null) + { + // join all threads forked from the current context + // (or a descendent context) + List tl = c.getForkedThreads(); + SimulationThread[] ta = new SimulationThread[tl.size()]; + tl.toArray(ta); + DV.simulation.joinAll(ta); + } + } + + //////////////////////////////////////////////////////////// + // Formatting utilities + //////////////////////////////////////////////////////////// + + public static void dumpStack(OutputStream oStream) + { + assert (oStream == System.err); + Thread.dumpStack(); + } + + /** + * psprintf built-in function. + *

+ * This method is akin to C's printf() with a few differences: + *

    + * non-C format specs + *
      + *
    • %b binary + *
    • %p prints name of the main program + *
    • %m prints hierarchical trace, from main() to context of psprintf + *
    • %v prints instance path of the Vera shell + *
    • %_ prints path separator for the current simulator + *
    + *

    + * Conversion notes:
    + * enumeration literals are printed as numeric values. enumeration variables + * are printed as (ENUM_VAR:XXXXXXXX) as described below + *

    + *

      + *
    • Conversions to binary (%b) + *
        + *
      • x/z values are printed in lowercase + *
      • prints ASCII representation of strings in binary with + * string.charAt(0) residing in the MSB of the bit vector. each char has its + * bits reversed. Thus the string "AF" 0x41, 0x46 is represented as: + * 1000_0010_0110_0010 (0x82, 0x62) in string + *
      • prints enumerations as "(ENUM_VAR:XXXXXXXX)", with X being 0-f + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to character (%c) + *
        + *
      • prints character representation of lowest byte of int/BitVector + *
      • X/Z values print empty strings + *
      • prints first character of a string + *
      • prints empty string for enumerations + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to signed decimal (%d, %i) + *
        + *
      • prints Integer as a signed value + *
      • prints BitVector as an unsigned value + *
      • prints quantities with X/Z as "?" + *
      • prints enumerations as "(ENUM_VAR:XXXXXXXXXX)", with X being 0-9 + *
      • for strings, each character is converted to a decimal value and + * these are concatenated together. this is just silly. + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to hexadecimal (%h, %x) + *
        + *
      • X/Z values are printed in uppercase + *
      • hex digits are printed in lowercase + *
      • prints strings as empty string + *
      • prints enumerations as "(ENUM_VAR:XXXXXXXX)", with X being 0-f + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to stack trace (%m) + *
        + *
      • format width specifies how many stack frames prior to printfcontext + * to omit. for instance A()->B()->C()->printf("%1m") will print a stack + * trace of A()->B() + *
      + *
    • Conversions to octal (%o) + *
        + *
      • all Z's in a 3-bit quantity prints "Z" + *
      • all X's in a 3-bit quantity prints "X" + *
      • any 0/1/X/Z combination in a 3-bit quantity prints "?" + *
      • for strings, each character is converted to an octal value and these + * are concatenated together + *
      • with no width specifier, 12 octal digits are printed + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to program name (%p) + *
        + *
      • TODO: need to document printf %p specifier + *
      + *
    • Conversions to string (%s) + *
        + *
      • prints integers as 4 characters -- 1 per byte + *
      • quantities with X/Z values print empty strings + *
      • prints integers/bit vectors/bits as their ASCII representation, as + * though they were a string in memory (for instance, 16'4B4A is printed as + * "KJ"). vectors that are not a multiple of 4 bits are zero-padded + *
      • prints enumerations as their "string name" (e.g. "red") + *
      • prints null or void as "(NULL)" + *
      + *
    • Conversions to unsigned decimal (%u) + *
        + *
      • prints 32 bit values as an unsigned quantities + *
      • otherwise behaves as (%d, %i) + *
      + *
    + * + * Note that the sequence "\\" is not unescaped by this function. + * + * + * @param format the format specifier to use + * @param args an array of Objects to be used when processing format + * specifiers + * @return the resulting String + */ + public static String psprintf(String format, Object... args) + { + return psprintf(format, args, true); + } + + private static VeraPrintfFormatter formatterWithEscapes = new VeraPrintfFormatter( + true); + private static VeraPrintfFormatter formatterWithoutEscapes = new VeraPrintfFormatter( + false); + + private static String psprintf( + String format, + final Object[] args, + final boolean leaveEscapes) + { + if (leaveEscapes) + { + return formatterWithEscapes.sprintf(format, args); + } + else + { + return formatterWithoutEscapes.sprintf(format, args); + } + } + + /** + * sprintf built-in function. + *

    + * Note that the sequence "\\" is not unescaped by this function. + * + * @see #psprintf(String, Object[]) + * @param str the String to assign into + * @param format the psprintf format to use + * @param args the arguments to be used when processing the format string + */ + public static void sprintf(JunoString str, String format, Object... args) + { + str.assign(psprintf(format, args, true)); + } + + /** + * built-in sscanf function. This function takes two strings -- a + * source string and a format string. It then tries to parse the source + * string based on the format string, extracting various pieces based on + * the format string. + * + * @param str The source string which should not contain format specifiers. + * @param format The format string which is used to parse the source string. + * @param args The array in which Objects matching the format specifiers of + * the format string should be put. + * @param types An array describing the types to which each extracted arg + * should be converted. + * @throws RuntimeException if the extracted object cannot be converted to + * the desired type. + */ + public static void sscanf( + String str, + String format, + Object[] args, + Class[] types) + { + + // * There are no Format Specifier flags in sscanf. Vera prints + // a warning and ignores the specifier, continuing to evaluate the + // format string. + // * sscanf will parse str and assign objects to args until a parsing + // mismatch occurs. at this point it will return. + // * If sscanf detects an illegal specifier, the % and any + // trailing spaces are ignored. for instance: + // sscanf("abd def", "%a %s", s); will assign "abd" to string s. + // * Back to back identifiers are greedy, for instance: + // sscanf("1009edge", "%h%s", i, s); will assign 0x1009ed to i and + // "ge" to string s. + // * Any numeric specifier can match ' notation. + // This doesn't not affect greediness, it will only truncate values. + // sscanf("4'h1009edge", "%h%s", i, s); will assign 0xd to i and + // "ge" to string s. + // * A minus prefix is not allowed in w'rv notation, and will be matched + // as a string against str. + // * A newline in either the str or format ends the matching. + // * Contiguous spaces in either str or format compress down to one + // space + // * Contiguous tabs/newlines do not compress down to 1 tab/newline + // * A width specifier will parse only that many characters + // + // If we see X parse until Y + // %b -> any character other than [_01] + // %o -> any character other than [_0-7] + // %d, %u, %i -> any character other than [_-0-9] + // %h, %x -> any character other than [_0-9A-Fa-f] + // %s -> any tab or space (but not a newline) + // %c -> parse exactly one character + // any of the numeric specifiers can also parse w'rv notation + + final class SscanfException + extends RuntimeException + { + private static final long serialVersionUID = 3257004371584760117L; + + SscanfException(String s) + { + super(s); + } + } + + final class SscanfStrFinder + { + private final String mStr; + private final char[] mChars; + private int mIdx; + BitVectorFormat mFormat; + + SscanfStrFinder(String s) + { + mStr = s; + mIdx = 0; + + mChars = mStr.toCharArray(); + mFormat = new BitVectorFormat(); + } + + private boolean eos() + { + return (mIdx >= mStr.length()); + } + + String getString(int widthSpec) + { + if (eos()) return ""; + // Parse until we hit the end of the string or a space character + // Ignore any leading spaces + StringBuffer sb = new StringBuffer(); + boolean widthReached = false; + for (; mIdx < mChars.length && !widthReached; ++mIdx) + { + char c = mChars[mIdx]; + // there's no way to get a newline into a Vera string + assert (c != '\n'); + if (c == ' ' || c == '\t' || c == '\r') + { + if (sb.length() > 0) + break; + else + continue; + } + + sb.append(c); + widthReached = (widthSpec != 0 && sb.length() >= widthSpec); + + if (widthReached && c == '\\') + { + Juno + .warning("WARNING: You've hit the escaped char width corner case"); + } + } + return sb.toString(); + } + + BitVector getBitVector(int radix, int vectorWidth, int widthSpec) + { + if (eos()) return null; + + String radixPatternString = null; + switch (radix) + { + case 2: + radixPatternString = "_01XxZz"; + break; + case 8: + radixPatternString = "_0-7XxZz"; + break; + case 10: + radixPatternString = "_0-9XxZz"; + break; + case 16: + radixPatternString = "_0-9A-Fa-fXxZz"; + break; + default: + throw new RuntimeException("Internal error. Radix = " + + radix); + } + + assert (widthSpec >= 0); + String numMatchesStr = (widthSpec == 0 ? "+" : ("{1," + + widthSpec + "}")); + + // NOTE: the width/radix character matched is ignored. it can be + // anything (e.g. sscanf("2'=400", "%d", i1)) will match 400. + String numPatternStr = "([ \t\r]*-?(?:([0-9]+)?'(.))?([" + + radixPatternString + "]" + numMatchesStr + ")).*"; + Pattern numPattern = Pattern.compile(numPatternStr, + Pattern.DOTALL); + + String curString = mStr.substring(mIdx); + String valueStr = null; + Matcher matcher = numPattern.matcher(curString); + if (!matcher.matches()) + { + return null; + } + + // remove any width/radix specifier + valueStr = matcher.group(1); + mIdx += valueStr.length(); + valueStr = valueStr.trim().replaceFirst("^.*'.", ""); + try + { + mFormat.setRadix(radix); + BitVector v = (vectorWidth == -1) ? mFormat.parse(valueStr) + : mFormat.parse(valueStr, vectorWidth); + return v; + + } + catch (NumberFormatException e) + { + return null; + } + } + + boolean match(String s) + { + if (eos()) return (s.length() == 0 ? true : false); + + int endIdx = Math.min(mStr.length(), (mIdx + s.length())); + String subStr = mStr.substring(mIdx, endIdx); + mIdx += s.length(); + return s.equals(subStr); + } + } + + final class FormatSpec + { + int widthSpec = 0; + char specifier = '\0'; + + int parseFormatSpec(char[] formatArr, int idx) + { + assert (formatArr[idx - 1] == '%'); + StringBuffer sb = new StringBuffer(); + int j = idx; + outofswitch: for (; j < formatArr.length; ++j) + { + switch (formatArr[j]) + { + case '0': // widths + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + sb.append(formatArr[j]); + break; + case 'b': // valid specifiers + case 'c': + case 'd': + case 'h': + case 'i': + case 's': + case 'x': + case '%': + specifier = formatArr[j]; + break outofswitch; + default: + throw new SscanfException( + "WARNING: Unrecognized format in sscanf, \"..." + + new String(formatArr).substring(idx - 1) + + "\""); + } + } + if (sb.length() > 0) + { + widthSpec = Integer.parseInt(sb.toString()); + } + return j; + } + } + + final class SscanfObjConverter + { + public Object convert(Object o, Class from, Class to) + { + assert (o != null); + if (from == to) + { + return o; + } + + boolean fromIsBitVector = (from == BitVector.class); + boolean fromIsString = (from == String.class); + boolean toIsBit = (to == Bit.class); + boolean toIsBitVector = (to == BitVector.class); + boolean toIsString = (to == String.class); + boolean toIsJunoString = (to == JunoString.class); + boolean toIsInteger = (to == Integer.class); + + if (fromIsBitVector) + { + BitVector v = (BitVector) o; + + assert (!toIsBitVector); + + if (toIsBit) + { + return v.getBit(0); + } + else if (toIsInteger) + { + return new Integer(v.intValue()); + } + else if (toIsString || toIsJunoString) + { + return null; + } + } + else if (fromIsString) + { + String s = (String) o; + + assert (!toIsString); + assert (s.length() > 0); + if (toIsJunoString) + { + return new JunoString(s); + } + else if (toIsInteger) + { + return new Integer(new BitVector(s.getBytes()) + .intValue()); + } + else if (toIsBit) + { + return new BitVector(s.getBytes()).getBit(0); + } + else if (toIsBitVector) + { + return new BitVector(s.getBytes()); + } + } + throw new RuntimeException("Unsupported conversion: " + from + + " -> " + to); + } + } + + if (str == null) + { + throw new RuntimeException("null string passed to sscanf"); + } + + int curArg = 0; + SscanfObjConverter converter = new SscanfObjConverter(); + SscanfStrFinder finder = new SscanfStrFinder(str); + char[] formatChars = format.toCharArray(); + StringBuffer sb = new StringBuffer(); + + for (int i = 0; i < formatChars.length; ++i) + { + + boolean isFormatDelimeter = (formatChars[i] == '%' || formatChars[i] == ' '); + if (isFormatDelimeter) + { + // match anything we've found up to this point. + if (!finder.match(sb.toString())) + { + // mismatch. outta here. + return; + } + else + { + sb.setLength(0); + } + } + + if (formatChars[i] == '%') + { + // make sure there's a character left to parse + ++i; + if (i >= formatChars.length) break; + + boolean foundMatch = false; + Object matchedObj = null; + + // get format specifier + FormatSpec fSpec = new FormatSpec(); + try + { + // the parser will eat up some of the char buffer, so + // update i with the new value. + i = fSpec.parseFormatSpec(formatChars, i); + } + catch (SscanfException e) + { + System.err.println(e.getMessage()); + continue; + } + + int width = -1; + if (types[curArg] == Integer.class) + { + width = 32; + } + else if (types[curArg] == Bit.class) + { + width = 1; + } + else if (types[curArg] == BitVector.class + && args[curArg] != null) + { + width = ((BitVector) args[curArg]).length(); + } + + switch (fSpec.specifier) + { + case '%': + foundMatch = finder.match("%"); + break; + case 'c': + matchedObj = finder.getString(1); + break; + case 's': + matchedObj = finder.getString(fSpec.widthSpec); + break; + case 'b': + matchedObj = finder.getBitVector(2, width, fSpec.widthSpec); + break; + case 'o': + matchedObj = finder.getBitVector(8, width, fSpec.widthSpec); + break; + case 'd': + case 'i': + matchedObj = finder + .getBitVector(10, width, fSpec.widthSpec); + break; + case 'h': + case 'x': + matchedObj = finder + .getBitVector(16, width, fSpec.widthSpec); + break; + default: + throw new RuntimeException( + "Internal error -- unhandled specifier: " + + Integer.toHexString(fSpec.specifier)); + } + + foundMatch = (foundMatch | (matchedObj != null)); + + if (!foundMatch) + { + // mismatch. we're done. + return; + } + else if (matchedObj != null) + { + Object convertedObj = converter.convert(matchedObj, + matchedObj.getClass(), types[curArg]); + + assert (curArg < args.length); + + // assign this only if we're supposed to. + if (convertedObj != null) + { + args[curArg] = convertedObj; + } + ++curArg; + matchedObj = null; + + if (curArg >= args.length) + { + // nothing else to match. + return; + } + } + } + else if (formatChars[i] == ' ') + { + continue; + } + else + { + sb.append(formatChars[i]); + } + } + } + + //////////////////////////////////////////////////////////// + // I/O utilities + //////////////////////////////////////////////////////////// + public static final int VERBOSE = 4; + public static final int SILENT = 0; + public static final int RAWIN = 1; + + private static final Map randomAccessFileMap = new HashMap(); + + private static int errorFlag = OFF; + + private static final Map feofMap = new HashMap(); + + // key is RandomAccessFile or Integer (for standard I/O descriptors) + private static final Map ferrorMap = new HashMap(); + + // list of lock files held by this JVM + private static final List flockFileList = new LinkedList(); + + static final int STDIN = 1; + static final int STDOUT = 2; + static final int STDERR = 3; + private static final int MIN_FILE_DESC = 4; + private static int curFileDesc = MIN_FILE_DESC; + + /** + * printf built-in function. + *

    + * This method prints the results of psprintf(format, args) to + * {@link java.lang.System#out}. + * + * @see #psprintf(String, Object[]) + * @param format the psprintf format to use + * @param args the arguments to be used when processing the format string + */ + public static void printf(String format, Object... args) + { + System.out.print(psprintf(format, args, false)); + } + + /** + * fopen built-in function + *

    + * This method opens a file in a given mode and returns an file descriptor + * suitable for passing to other file I/O methods. It calls + * {@link #fopen(String,String,int)} with a third parameter of + * {@link #VERBOSE}. + * + * @param filename the name of the file to open + * @param mode one of "r", "w", or "a" + * @return a file descriptor + */ + public static int fopen(String filename, String mode) + { + return fopen(filename, mode, Juno.VERBOSE); + } + + /** + * fopen built-in function + *

    + * This method opens a file in a given mode and returns an file descriptor + * suitable for passing to other file I/O methods. + *

    + * Some notes: + *

      + *
    • Legal Modes + *
        + *
      • "r": open the file for reading + *
      • "w": open the file for writing, truncating if the file exists, + * creating it otherwise. + *
      • "a": open the file for writing, appending to it if the file exists, + * creating it otherwise. + *
      • all other characters are illegal + *
      + *
    • Implementation Details + *
        + *
      • The legal mode characters are read in order. The first legal + * character is the mode used. + *
      • If an illegal character comes after a legal character it is ignored + * even with VERBOSE specified. + *
      • Legal characters can be repeated without errors + *
      • If an illegal character is the first character in mode, fopen will + * fail and return a 0. if VERBOSE is enabled, an error message with stack + * trace is dumped, and program execution continues + *
      + *
    + * + * @param filename the name of the file to open + * @param mode one of "r", "w", or "a" + * @param verbose one of {@link #VERBOSE}or {@link #SILENT} + * @return a file descriptor + */ + public static int fopen(String filename, String mode, int verbose) + { + assert (verbose == VERBOSE || verbose == SILENT); + + int modeIdx = -1; + Pattern arw = Pattern.compile(".*?([arw]).*?"); + Matcher matcher = arw.matcher(mode); + if (matcher.matches()) + { + modeIdx = matcher.start(1); + } + boolean errorDetected = false; + int fid = 0; + + if (modeIdx == -1 || (modeIdx > 0 && verbose == VERBOSE)) + { + errorDetected = true; + } + else + { + RandomAccessFile file = null; + if (mode.charAt(modeIdx) == 'r') + { + try + { + // mode 'r' + file = new RandomAccessFile(filename, "r"); + } + catch (FileNotFoundException e) + { + errorDetected = true; + } + } + else + { + try + { + file = new RandomAccessFile(filename, "rw"); + if (mode.charAt(modeIdx) == 'a') + { + // mode 'a' + file.seek(file.length() - 1); + } + else + { + // mode 'w' + file.getChannel().truncate(0); + } + } + catch (FileNotFoundException e) + { + errorDetected = true; + } + catch (IOException e) + { + errorDetected = true; + } + } + + if (!errorDetected) + { + fid = curFileDesc; + //{ + // File f = new File(filename); + // System.out.println("fopen[" + fid + "]: (" + mode + ") " + // + f.getAbsolutePath()); + //} + randomAccessFileMap.put(fid, file); + ++curFileDesc; + } + } + + if (errorDetected) + { + System.err.println("fopen failed. filename=" + filename + ", mode=" + + mode); + dumpStack(System.err); + return 0; + } + else + { + return fid; + } + } + + /** + * fclose built-in function. + *

    + * Closes the file descriptor fd. If fd is an invalid descriptor, this + * method silently succeeds. Attempts to close built in the streams, + * {@link #STDIN},{@link #STDOUT}, and {@link #STDERR}are ignored. + * + * @param fd the file descriptor to close + */ + public static void fclose(int fd) + { + if (fd == 0) + { + throw new RuntimeException("fclose failed due to invalid " + + "file descriptor [0]"); + } + + if (fd < MIN_FILE_DESC) return; + + Integer mapID = new Integer(fd); + RandomAccessFile file = randomAccessFileMap.get(mapID); + if (file != null) + { + try + { + file.close(); + } + catch (IOException e) + { + // Vera seems to just drop errors on the floor + } + finally + { + // System.out.println("fclose[" + fd + "]"); + randomAccessFileMap.put(mapID, null); + } + } + } + + /** + * fprintf built-in function. + *

    + * This method prints the results of psprintf(format, args) to the file + * described by fd. + *

    + * If fd is invalid or is {@link #STDIN}, a RuntimeException occurs. + * Further, if fd has been opened in read mode, the call to fprintf is + * ignored and the ferror status for fd is set to true. + * + * @see #psprintf(String, Object[]) + * @param fd the file descriptor to which to write + * @param format the fprintf format to use + * @param args the arguments to be used when processing the format string + */ + + public static void fprintf(int fd, String format, Object... args) + { + if (fd == 0) + { + throw new RuntimeException("fprintf failed due to invalid " + + "file descriptor [0]"); + } + + String str = psprintf(format, args, false); + if (fd < MIN_FILE_DESC) + { + if (fd == STDOUT) + { + System.out.print(str); + } + else if (fd == STDERR) + { + System.err.print(str); + } + else + { + throw new RuntimeException("ERROR: fprintf on stdin"); + } + return; + } + + RandomAccessFile file = randomAccessFileMap.get(new Integer(fd)); + if (file == null) + { + throw new RuntimeException("fprintf failed due to invalid" + + " file descriptor [" + fd + "]"); + } + try + { + file.write(str.getBytes()); + } + catch (IOException e) + { + ferrorMap.put(file, Boolean.TRUE); + // Vera silently ignores writing to a file with mode 'r', but marks + // the fd as having an error + } + + } + + // exception used to communicate b/t readLine and fread* methods + private static class JunoFileIOException + extends RuntimeException + { + private static final long serialVersionUID = 3256444685806219829L; + private boolean isWarning; + + public JunoFileIOException(String s) + { + super(s); + this.isWarning = false; + } + + public JunoFileIOException(String s, boolean isWarning) + { + super(s); + this.isWarning = isWarning; + } + + public boolean isWarning() + { + return isWarning; + } + } + + // a private method which returns a line from the given file descriptor + private static String readLine(int fd, int mode) + { + assert (mode == VERBOSE || mode == SILENT || mode == RAWIN); + InputStream istream = null; + RandomAccessFile file = null; + boolean useIstream = false; + + if (fd == 0) + { + throw new JunoFileIOException("failed due to invalid " + + " file desriptor fd=0"); + } + + if (fd < MIN_FILE_DESC) + { + if (fd == STDIN) + { + istream = System.in; + useIstream = true; + } + else + { + throw new JunoFileIOException("trying to read on " + + (fd == STDOUT ? "STDOUT" : "STDERR")); + } + } + else + { + file = randomAccessFileMap.get(fd); + if (file == null) + { + throw new JunoFileIOException("failed due to invalid" + + " file descriptor fd=" + fd); + } + if (feofMap.containsKey(file) && feofMap.get(file)) + { + // VERBOSE prints a warning and sets the EOF and error flags + // SILENT/RAWIN only set the EOF flag + if (mode == VERBOSE) + { + errorFlag |= ON; + throw new JunoFileIOException("detected EOF", true); + } + else + { + // SILENT just returns a null string + return null; + } + } + } + + StringBuffer buf = new StringBuffer(80); // default to 80 char line + try + { + char c = 0; + boolean shouldIgnore = false; + String s = null; + do + { + shouldIgnore = false; + do + { + int signedChar = -1; + if (useIstream) + { + signedChar = istream.read(); + if (signedChar == -1) + { + throw new EOFException(); + } + c = (char) signedChar; + } + else + { + c = (char) file.readByte(); + } + if (c == '\n') + { + break; + } + + buf.append(c); + } + while (true); + + s = buf.toString(); + + if (mode == RAWIN) + { + // RAWIN takes any line, even a blank one. + break; + } + else + { + // in VERBOSE/SILENT mode, lines containing only + // whitespace or comments are ignored + s = s.replaceFirst("//.*", ""); // // comments + s = s.replaceAll("/\\*.*?\\*/", ""); // /*...*/ comments + if (s.trim().length() == 0) + { + shouldIgnore = true; + buf.delete(0, buf.length()); + } + } + } + while (shouldIgnore); + + return s; + } + catch (EOFException eof) + { + assert (!useIstream); // assume there can not be EOF on stdin + feofMap.put(file, Boolean.TRUE); + + return null; + } + catch (IOException ie) + { + // we should never see an IOException at this point + throw new RuntimeException(ie); + } + } + + /** + * Reads a binary value from a file and returns the corresponding BitVector. + * Comments and lines containing only whitespace are ignored. If the mode is + * VERBOSE, a message will be printed when the end of file is detected. + *

    + * Each valid line of the file should correspond to the regular expression: + * ([01_])+ + * + * @param fd The file descriptor from which to read. + * @param mode One of {@link #VERBOSE} or {@link #SILENT} + * @return a BitVector having the value of the binary value read from the + * file or null if an error occurs. + */ + public static BitVector freadb(int fd, int mode) + { + assert (mode == VERBOSE || mode == SILENT); + try + { + String s = readLine(fd, mode); + if (s == null || s.trim().length() == 0) + { + return new BitVector(64, 0); + } + + s = s.trim(); // get rid of leading whitespace + s = s.replaceFirst("\\s.*", ""); // get ride of trailing comments + s = s.replaceAll("_", ""); // get rid of underscores (for length calculation) + return new BitVector("'b" + s, s.length()); + } + catch (JunoFileIOException e) + { + if (e.isWarning()) + { + warning("WARNING: freadb " + e.getMessage()); + return null; + } + + throw new RuntimeException("freadb: " + e.getMessage()); + } + } + + /** + * Reads a hexadecimal value from a file and returns the corresponding BitVector. + * Comments and lines containing only whitespace are ignored. If the mode is + * VERBOSE, a message will be printed when the end of file is detected. + *

    + * Each valid line of the file should correspond to the regular expression: + * ([A-Za-z0-9_])+ + * + * @param fd The file descriptor from which to read. + * @param mode One of {@link #VERBOSE} or {@link #SILENT} + * @return a BitVector having the value of the hexadecimal value read from + * the file or null if an error occurs. + */ + public static BitVector freadh(int fd, int mode) + { + assert (mode == VERBOSE || mode == SILENT); + try + { + String s = readLine(fd, mode); + if (s == null || s.trim().length() == 0) + { + return new BitVector(64, 0); + } + + s = s.trim(); // get rid of leading whitespace + s = s.replaceFirst("\\s.*", ""); // get ride of trailing comments + s = s.replaceAll("_", ""); // get rid of underscores (for length calculation) + return new BitVector("'h" + s, s.length() * 4); + } + catch (JunoFileIOException e) + { + if (e.isWarning()) + { + warning("WARNING: freadh " + e.getMessage()); + return null; + } + + throw new RuntimeException("freadh: " + e.getMessage()); + } + } + + /** + * freadstr built-in function. + *

    + * This call is equivalent to freadstr(fd, Vera.VERBOSE); + *

    + * @see #freadstr(int, int) + * @param fd + * @return the string read from the file + */ + public static String freadstr(int fd) + { + return freadstr(fd, Juno.VERBOSE); + } + + /** + * freadstr built-in function. + *

    + * Read a line from a file and return it as a String. + *

    + *

      + * Modes + *
    • {@link #VERBOSE}Upon reaching EOF, a warning is printed and a null + * string is returned. + *
    • {@link #SILENT}Upon reaching EOF, a null string is returned, but no + * warning is printed. + *
    • {@link #RAWIN}Identical to SILENT except blank lines and comments + * are not filtered out. + *
    + * Both VERBOSE and SILENT modes will filter out lines containing only + * whitespace and comments. All modes will set the ferror status of fd to + * true upon reaching the end of file. + *

    + * Passing an invalid file descriptor or a file descriptor that was not + * opened in read mode will result in a RuntimeException. + * + * @param fd the file descriptor from which to read + * @param mode one of {@link #VERBOSE},{@link #SILENT}, or {@link #RAWIN} + * @return the string read from the file + */ + public static String freadstr(int fd, int mode) + { + // TODO: freadstr ensure reading from STDOUT/STDERR errors appropriately + // TODO: make sure multiline C-style comments are filtered properly + assert (mode == VERBOSE || mode == SILENT || mode == RAWIN); + try + { + return readLine(fd, mode); + } + catch (JunoFileIOException e) + { + if (e.isWarning()) + { + warning("WARNING: freadstr " + e.getMessage()); + return null; + } + + throw new RuntimeException("freadstr: " + e.getMessage()); + } + } + + /** + * fflush built-in function. + *

    + * Flush any buffered output to the file described by fd. + *

    + * If fd describes a file opened in read mode or {@link #STDIN}, fflush + * returns immediately. If fd is invalid, a RuntimeException is thrown. + * + * @param fd the file descriptor to flush + */ + public static void fflush(int fd) + { + // fflush + // * vera silently ignores fflush calls to input streams (inc. stdin) + // * vera dumps stack and dies if fd is not a valid file descriptor + + if (fd == 0) + { + throw new RuntimeException("fflush failed due to invalid" + + " file descriptor [0]"); + } + + if (fd < MIN_FILE_DESC) + { + if (fd == STDOUT) + System.out.flush(); + else if (fd == STDERR) System.err.flush(); + return; + } + + RandomAccessFile file = randomAccessFileMap.get(fd); + if (file == null) + { + throw new RuntimeException("fflush failed due to invalid" + + " file descriptor [" + fd + "]"); + } + else + { + try + { + file.getChannel().force(false); + } + catch (IOException e) + { + // Vera silently ignores flushes to input streams and does not + // mark them as having an error + } + } + } + + /** + * rewind built-in function. + *

    + * Returns the file pointer associated with fd to the beginning of the file. + *

    + * For {@link #STDIN},{@link #STDOUT}, and {@link #STDERR}, this method + * returns immediately. If fd is an invalid file descriptor, a + * RuntimeException is thrown. + *

    + * Calling this method clears the ferror status of fd. This is the only way + * to clear this error status, short of closing the file and reopening it. + * + * @param fd the file descriptor to rewind. + */ + public static void rewind(int fd) + { + // rewind + // * vera seems to do nothing for built-in streams (stdin, out, err) + // * vera dumps stack and dies if fd is not a valid file descriptor + // * vera clears ferror status for fd when rewind() is called + + if (fd == 0) + { + throw new RuntimeException("rewind failed due to invalid " + + " file desriptor [0]"); + } + + if (fd < MIN_FILE_DESC) + { + Integer i = new Integer(fd); + assert (!feofMap.containsKey(i)); + ferrorMap.put(i, Boolean.FALSE); + return; + } + + RandomAccessFile file = randomAccessFileMap.get(fd); + if (file == null) + { + throw new RuntimeException("rewind failed due to invalid" + + " file descriptor [" + fd + "]"); + } + else + { + try + { + file.seek(0); + // rewind clears ferror() status + feofMap.put(file, Boolean.FALSE); + ferrorMap.put(file, Boolean.FALSE); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } + } + + /** + * lock_file built-in function. + *

    + * Locks a file for use by this JVM only. + *

    + * lock_file creates a file, <filename>.lock_file any further attempts + * to lock the file by the same process are successful. attempts by another + * process to lock the file will block timeout seconds, or forever if + * timeout == 0. further, if <filename>.lock_file exists but is empty, + * the lock_file attempt times out or blocks as specified by the timeout + * parameter. if filename is a directory, the lock file is written in the + * parent directory of the dir. if write access is not allowed in that + * directory, a RuntimeException is thrown. + *

    + * Note: This implementation does not use PIDs as they aren't really used by + * Vera anyway + * + * @see #unlock_file(String) + * @param filename the name of the file to lock + * @param timeout the timeout value in seconds, or 0 for no timeout. + * @return true if the file was locked, false if a timeout occurred + */ + public static boolean lock_file(String filename, int timeout) + { + try + { + // Get a file channel for the file + int count = 0; + long baseTimeStamp = 0; + long curTimeStamp = 0; + + File fd = new File(filename + ".lock_file"); + RandomAccessFile file = new RandomAccessFile(fd, "rw"); + + while (fd.exists()) + { + if (flockFileList.contains(filename)) + { + return true; + } + + file.close(); + if (count < timeout) + { + return false; + } + + // Sleep for 1 second (even if interrupted) + curTimeStamp = System.currentTimeMillis(); + baseTimeStamp = curTimeStamp + 1000; + while (curTimeStamp < baseTimeStamp) + { + try + { + Thread.sleep(baseTimeStamp - curTimeStamp); + } + catch (InterruptedException e) + { + curTimeStamp = System.currentTimeMillis(); + } + } + file = new RandomAccessFile(fd, "rw"); + ++count; + } + + // create the lockfile + file.close(); + flockFileList.add(filename); + return true; + } + catch (FileNotFoundException e) + { + throw new RuntimeException("cound not create lockfile for: " + + filename); + } + catch (IOException e) + { + throw new RuntimeException("cound not create lockfile for: " + + filename); + } + } + + /** + * unlock_file built-in function + *

    + * unlock_file removes <filename>.lock_file, even if it is not the + * locking JVM. + *

    + * Note: Vera puts its UNIX PID in the lockfile. Then when lock_file() is + * called, if the lockfile exists, and the PID doesn't match, the lock + * blocks. However, any UNIX PID can call unlock_file on the file and remove + * the lockfile. This would make the whole business of putting the PID in + * the file moot. For this reason, PIDs are not used in this implementation. + *

    + * + * @see #lock_file(String, int) + * @param filename the filename to unlock + */ + public static void unlock_file(String filename) + { + File fd = new File(filename + ".lock_file"); + if (fd.exists()) + { + if (!fd.delete()) + { + throw new RuntimeException("Cannot remove lock file for: " + + filename); + } + } + flockFileList.remove(filename); + } + + /** + * feof built-in function. + *

    + * Check if fd is at the end of the file. + *

    + * Notes: These are valid as of Vera 6.2.15. Vera dumps stack and dies if fd == + * STDIN + *

    + * Vera behaves strangely if fd == STDOUT || fd == STDERR: + * + *

    +     *   integer foo = feof([23]); // this SIGSEGVs
    +     *   printf("%0d\n", feof([23])); // this prints a cryptic printf err
    +     * 
    + * + *

    + * Vera dumps stack and dies if fd is not a valid file descriptor + *

    + * This implementation returns false if fd is STDIN, STDOUT, or STDERR. If + * fd is an invalid descriptor, a RuntimeException is thrown. If fd + * describes a file not opened in read mode, false is returned. + * + * @param fd the file descriptor on which to check for the EOF condition + * @return true if the file described by fd is at the end of file, false + * otherwise. + */ + public static boolean feof(int fd) + { + // feof + if (fd == 0) + { + throw new RuntimeException("feof failed due to invalid" + + " file descriptor [" + fd + "]"); + } + + if (fd < MIN_FILE_DESC) + { + if (fd == STDIN) + { + throw new RuntimeException("ERROR: feof on stdin"); + } + + // Vera core dumps on: + // integer foo = feof(stdout|stderr) + // but dies gracefully (if cryptically) on + // printf("%0d\n", feof(stdout|stderr); + // We'll just do what Vera does for "regular" write streams + return false; + } + + RandomAccessFile file = randomAccessFileMap.get(fd); + if (file == null) + { + throw new RuntimeException("feof failed due to invalid" + + " file descriptor [" + fd + "]"); + } + + if (!feofMap.containsKey(file)) + { + feofMap.put(file, Boolean.FALSE); + } + return feofMap.get(file); + } + + /** + * ferror built-in function + *

    + * This method returns the ferror status of a file descriptor. + *

    + * A file descriptors ferror status becomes true when + *

      + *
    • EOF is reached during {@link #freadb},{@link #freadh}, or + * {@link #freadstr(int, int)}where {@link #SILENT}mode was not used and + * the file descriptor in question was opened in read mode. + *
    • {@link #freadb},{@link #freadh}, or {@link #freadstr(int, int)} + * was called with a file descriptor which was not opened in read mode + *
    • an attempt is made to write to an input stream + *
    + * A file descriptors ferror status becomes false when + *
      + *
    • the file is first opened + *
    • {@link #rewind}is called on the file descriptor + *
    + *

    + * If fd is an invalid file descriptor, a RuntimeException will be thrown. + * + * @param fd the file descriptor on which to check for ferror status + * @return true if an error has occurred on the file descriptor, false + * otherwise + */ + public static boolean ferror(int fd) + { + Object key = null; + if (fd == 0) + { + throw new RuntimeException("ferror failed due to invalid" + + " file descriptor [" + fd + "]"); + } + + if (fd < MIN_FILE_DESC) + { + key = new Integer(fd); + } + else + { + key = randomAccessFileMap.get(fd); + if (key == null) + { + throw new RuntimeException("ferror failed due to invalid" + + " file descriptor [" + fd + "]"); + } + } + + if (!ferrorMap.containsKey(key)) + { + ferrorMap.put(key, Boolean.FALSE); + } + return ferrorMap.get(key); + } + + //////////////////////////////////////////////////////////// + // Error utilities + //////////////////////////////////////////////////////////// + + public static void warning(String warning) + { + System.err.println(warning); + } + + /** + * error built-in function. + *

    + * This function prints the string generated by psprintf(format, args) to + * System.err and throws a RuntimeException. + * + * @param format The format specifier to pass to psprintf + * @param args The arguments for any format specifiers in format + * @throws RuntimeException containing the formatted message + */ + public static void error(String format, Object... args) + { + String msg = psprintf(format, args, false); + System.err.print(msg); + throw new RuntimeException(msg); + } + + /** + * NOTE: error_mode is currently unsupported. + * @param enable + * @param ec + */ + public static void error_mode(int enable, int ec) + { + // TODO: error_mode + throw new UnsupportedOperationException("error_mode is not implemented"); + } + + /** + * Returns the status of the internal flag variable. + * @return the flag status + */ + public static int flag() + { + assert (errorFlag == ON || errorFlag == OFF); + return errorFlag; + } + + /** + * Sets and gets the status of the internal flag variable. If enable == -1, + * the current flag status is returned. Otherwise, the flag is turned on or + * off as specified by enable and the previous flag status is returned. + * + * @param enable on of either {@link #ON}, {@link #OFF}, or -1 + * @return the flag status + */ + public static int flag(int enable) + { + // a -1 means that the argument is omitted. + // TODO: remove the -1 support once the translator supports the argument-less version + if (enable == -1) + { + return flag(); + } + + assert (enable == ON || enable == OFF); + int curFlag = errorFlag; + errorFlag = enable; + return curFlag; + } + + //////////////////////////////////////////////////////////// + // System interaction utilities + //////////////////////////////////////////////////////////// + + public static final int LO = 0; + public static final int HI = 1; + + /** + * Get the current DV.simulation time in ticks. Since the current DV.simulation + * time is a 64 bit quantity and this function only returns an int, it takes + * a parameter, part, that determines whether the high or low 32 bits of the + * current time are returned. + * + * @param part One of {@link #LO} or {@link #HI} + * @return The low or high 32 bits of the current DV.simulation time as specified + * by param. + */ + public static int get_time(int part) + { + assert (part == LO || part == HI); + long simTime = DV.simulation.getSimTime(); + return (part == HI) ? (int) (simTime >> 32) : (int) simTime; + } + + /** + * Returns the current DV.simulation wall-clock time in seconds. + * @return the wall-clock time of the DV.simulation in seconds. + */ + public static int get_systime() + { + return (int) (System.currentTimeMillis() / 1000); + } + + /** + * Block the current thread until the specified number of ticks have occurred. + * + * @param ticks The number of ticks to wait before resuming this thread. + */ + public static void delay(int ticks) + { + DV.simulation.delay(ticks); + } + + /** + * Run a command outside of the Jove environment. + * + * @param command A String containing the full command to run. + * @return The exit value of the command. + * @throws RuntimeException if an error occurs running the command + */ + public static int os_command(final String command) + { + final boolean debugMode = false; + final String osName = System.getProperty("os.name"); + if (debugMode) + { + System.out.println("os.name: " + osName); + } + + final String[] args = new String[3]; + if (osName.startsWith("Windows 9")) + { + args[0] = "command.com"; + args[1] = "/C"; + } + else if (osName.startsWith("Windows")) + { + args[0] = "cmd.exe"; + args[1] = "/C"; + } + else + { + args[0] = "/bin/sh"; + args[1] = "-c"; + } + args[2] = command; + if (debugMode) + { + System.out.println("Executing: " + TextUtil.toString(args)); + } + + try + { + final Runtime runtime = Runtime.getRuntime(); + final Process process = runtime.exec(args); + SystemUtil.echoProcess(process); + final int exitValue = process.waitFor(); + return exitValue; + } + catch (IOException e) + { + throw new RuntimeException(e); + } + catch (InterruptedException ie) + { + throw new RuntimeException(ie); + } + } + + /** + * Exit the DV.simulation with the given exit status. + * + * @param status the exit status + */ + public static void exit(int status) + { + System.out.println("exit_status: " + status); + // TODO: find a way to pass the exit status to the simulator + DV.simulation.finish(); + DV.simulation.terminateAll(); + } + + //////////////////////////////////////////////////////////// + // Random number generation utilities + //////////////////////////////////////////////////////////// + + // Rand48 does not adhere to random stability + private static PRNG rand48 = LinearCongruentialFactory.INSTANCE + .newInstance(); + + // TBD: figure out how to seed this. we need DV.simulation to be non-null and + // to be in a SimulationThread. + // { + // if (!get_plus_arg(CHECK, "+vera_random_seed=").isZero()) + // { + // srandom(get_plus_arg(NUM, "+vera_random_seed=").intValue()); + // } + // else + // { + // srandom(1); + // } + // simInitialized = true; + // } + + /** + * Creates a new random number generator for the DV.simulation and seeds it with + * the given value. + * + * @param seed the value with which to seed the PRNG. + */ + public static void srandom(int seed) + { + PRNG newRng = PRNGFactoryFactory.getDefaultFactory().newInstance(seed); + DV.simulation.setRandom(newRng); + } + + /** + * Creates a new random number generator for the DV.simulation and seeds it with + * the given value. It then associates that random number generated with the + * given JunoObject. + * + * @param seed the value with which to seed the PRNG. + * @param obj the object with which the new random number generator should be + * associated. + */ + public static void srandom(int seed, JunoObject obj) + { + PRNG newRng = PRNGFactoryFactory.getDefaultFactory().newInstance(seed); + obj.setRandom(newRng); + } + + /** + * Return a 32 bit signed random value. + * @return a 32 bit signed random value. + */ + public static int random() + { + PRNG rng = DV.simulation.getRandom(); + // Return a 31 bit positive value + return Math.abs(rng.nextBits(32)); + } + + /** + * Seeds the random number generator and then returns a 32 bit signed rand + * value. This is equivalent to: + *

    + * srandom(seed); random(); + * + * @param seed the value with which to seed the PRNG. + * @return a 32 bit signed random value. + */ + public static int random(int seed) + { + srandom(seed); + return random(); + } + + /** + * Returns a 32 bit unsigned random value. + * @return a 32 bit unsigned random value + */ + public static BitVector urandom() + { + return new BitVector(32, random()); + } + + /** + * Seeds the random number generator and then returns a 32 bit unsigned rand + * value. This is equivalent to: + *

    + * srandom(seed); urandom(); + * + * @param seed the value with which to seed the PRNG. + * @return a 32 bit unsigned random value. + */ + public static BitVector urandom(int seed) + { + srandom(seed); + return urandom(); + } + + /** + * Returns a 32 bit signed random value generated using a 48 bit linear + * congruential algorithm. + * @return a 32 bit signed random value. + */ + public static int rand48() + { + int randInt = rand48.nextInt(); + + // rand48() should only yield positive ints. + assert (randInt >= 0); + return randInt; + } + + /** + * Seeds the 48 bit linear congruential random number generator and then + * returns a 32 bit signed rand value generated from it. + * + * @param seed the value with which to seed the PRNG. + * @return a 32 bit signed random value. + */ + public static int rand48(int seed) + { + rand48 = LinearCongruentialFactory.INSTANCE.newInstance(seed); + return rand48(); + } + + /** + * Returns a 32 bit unsigned random value generated using a 48 bit linear + * congruential algorithm. + * @return a 32 bit unsigned random value. + */ + public static BitVector urand48() + { + return new BitVector(32, rand48.nextInt()); + } + + /** + * Seeds the 48 bit linear congruential random number generator and then + * returns a 32 bit unsigned rand value generated from it. + * + * @param seed the value with which to seed the PRNG. + * @return a 32 bit unsigned random value. + */ + public static BitVector urand48(int seed) + { + rand48 = LinearCongruentialFactory.INSTANCE.newInstance(seed); + return urand48(); + } + + /** + * Returns a 32 bit unsigned random value between 0 and maxval, inclusive. + * If maxval is > 32 bits, only the bottom 32 bits will be used. + * + * @param maxval The maximum value which the return value can assume. + * @return a 32 bit unsigned random value between 0 and maxval, inclusive. + */ + public static BitVector urandom_range(BitVector maxval) + { + return urandom_range(maxval, new BitVector(32, 0)); + } + + /** + * Returns a 32 bit unsigned random value between minval and maxval, inclusive. + * If maxval or minval is > 32 bits, only the bottom 32 bits will be used. + * + * @param maxval The maximum value which the return value can assume. + * @param minval The minimum value which the return value can assume. + * @return a 32 bit unsigned random value between minval and maxval, inclusive. + */ + public static BitVector urandom_range(BitVector maxval, BitVector minval) + { + // Vera allows maxval and minval to be reversed, however + // PRNGWrapper.nextInt() does not. Vera prints a warning so we will too. + if (maxval.compareTo(minval) < 0) + { + Juno.warning("WARNING: urandom_range: maxval(" + maxval + + ") is less than minval (" + minval + ")"); + Juno.warning("\tAutomatically reversing the range"); + BitVector tmp = minval; + minval = maxval; + maxval = tmp; + } + + // Even if minval/maxval are > 32'hFFFF_FFFF, just use the bottom 32 + // bits. this is consistent with Vera. + return new BitVector(32, DV.simulation.getRandom().nextInt( + minval.intValue(), maxval.intValue())); + } + + /** + * Choose a value based on a weighted randomization. Each index in the + * weights array has a value associated with it. This function will randomly + * choose an index in weights with each index having a weighting equal to + * its value. + *

    + * As an example if weights is {25, 0, 50}, 0 will be returned 33% of the time, + * 1 will be returned 0% of the time, and 2 will be returned 67% of the time. + * @param weights an array in which each index is the weighting of that index. + * @return an index of the array, chosen randomly by weight. + */ + public static int randcase(int... weights) + { + int cases = weights.length; + + // calculate sum of weights + int sum = 0; + for (int i = 0; i < cases; ++i) + { + assert (weights[i] >= 0) : "randcase weights must be non-negative"; + sum += weights[i]; + } + if (sum <= 0) + { + throw new RuntimeException("Non-positive total weight in randcase"); + } + + int rand = random() % sum; + int count = 0; + for (int i = 0; i < cases; ++i) + { + count += weights[i]; + if (rand < count) return i; + } + assert false; + return 0; + } + + //////////////////////////////////////////////////////////// + // Signal property accessors + //////////////////////////////////////////////////////////// + + /** + * Check if a signal is bound to the design. + * + * @param signal The signal to check. + * @return true if the signal is non-null, false otherwise. + */ + public static boolean vera_is_bound(Signal signal) + { + return signal != null; + } + + /** + * Return a signal's name. + * @param signal The signal to check. + * @return The name of the given signal. + */ + public static String vera_get_name(Signal signal) + { + return signal.getName(); + } + + /** + * NOTE: vera_get_ifc_name is currently unsupported. + * @param signal The Signal to check. + * @return The name of the interface containing signal. + */ + public static String vera_get_ifc_name(Signal signal) + { + // DEFERRED: vera_get_ifc_name + throw new UnsupportedOperationException("vera_get_ifc_name()"); + } + + /** + * Return the name of the clock associated with the given signal. + * @param signal The signal to check. + * @return The name of the clock signal associated with signal. + */ + public static String vera_get_clk_name(Signal signal) + { + return signal.getClock().getName(); + } + + /** + * Returns the direction of the given signal. The table below describes the + * return value: + *

    + *
    + *
    + * + * + * + *
    Return ValueDirection
    0Input Signal
    1Output Signal
    2InOut Signal
    + * + * @param signal The signal to check. + * @return 0, 1, or 2 depending on the direction of the signal. + */ + public static int vera_get_dir(Signal signal) + { + boolean isInOut = false; + boolean isOut = false; + + if (signal instanceof PortSignalWrapper) + { + PortSignalWrapper wrapper = (PortSignalWrapper) signal; + if (wrapper.isInput() && wrapper.isOutput()) + { + isInOut = true; + } + else if (wrapper.isOutput()) + { + isOut = true; + } + } + else + { + if (signal instanceof InOutSignal) + { + isInOut = true; + } + else if (signal instanceof OutputSignal) + { + isOut = true; + } + } + + if (isInOut) + { + // inout + return 2; + } + else if (isOut) + { + // output + return 1; + } + else + { + // input + return 0; + } + } + + /** + * Returns the width of the given signal. + * @param signal The signal to check. + * @return The width of the given signal. + */ + public static int vera_get_width(Signal signal) + { + return signal.getSize(); + } + + /** + * Returns the type of input signal is represented by the given signal. + * The table below describes the + * return value: + *

    + *
    + *
    + * + * + * + * + *
    Return ValueSignal Type
    0NSAMPLE
    1PSAMPLE
    2CLOCK
    3DDR
    + * + * @param signal The signal to check. + * @return 0, 1, 2, or 3, depending on the type of the signal. + */ + public static int vera_get_in_type(Signal signal) + { + boolean isClock = false; + if (signal instanceof PortSignalWrapper) + { + isClock = ((PortSignalWrapper) signal).isClock(); + } + else if (signal instanceof ClockSignal) + { + isClock = true; + ; + } + + if (isClock) + { + // CLOCK + return 2; + } + else + { + InputSignal inputSignal = (InputSignal) signal; + EdgeSet inputEdges = inputSignal.getInputEdges(); + if (EdgeSet.POSEDGE.contains(inputEdges)) + { + // PSAMPLE + return 1; + } + else if (EdgeSet.NEGEDGE.contains(inputEdges)) + { + // NSAMPLE + return 0; + } + else + { + // DDR + return 3; + } + } + } + + /** + * Returns the input skew of the given signal. + * @param signal The signal to check. + * @return The input skew ofthe given signal. + */ + public static int vera_get_in_skew(Signal signal) + { + InputSignal inputSignal = (InputSignal) signal; + return inputSignal.getInputSkew(); + } + + /** + * Returns the input depth of the given signal. + * @param signal The signal to check. + * @return The input depth ofthe given signal. + */ + public static int vera_get_in_depth(Signal signal) + { + InputSignal inputSignal = (InputSignal) signal; + return inputSignal.getInputDepth() - 1; + } + + /** + * Returns the type of output signal is represented by the given signal. + * The table below describes the + * return value: + *

    + *
    + *
    + * + * + * + *
    Return ValueSignal Type
    0NHOLD
    1PHOLD
    10DDR
    + * + * @param signal The signal to check. + * @return 0, 1, or 10, depending on the type of the signal. + */ + public static int vera_get_out_type(Signal signal) + { + OutputSignal outputSignal = (OutputSignal) signal; + EdgeSet inputEdges = outputSignal.getOutputEdges(); + if (EdgeSet.POSEDGE.contains(inputEdges)) + { + // PHOLD + return 1; + } + else if (EdgeSet.NEGEDGE.contains(inputEdges)) + { + // NHOLD + return 0; + } + else + { + // DDR + return 10; + } + } + + /** + * Returns the output skew of the given signal. + * @param signal The signal to check. + * @return The output skew ofthe given signal. + */ + public static int vera_get_out_skew(Signal signal) + { + OutputSignal outputSignal = (OutputSignal) signal; + return outputSignal.getOutputSkew(); + } + + //////////////////////////////////////////////////////////// + // Miscellaneous + //////////////////////////////////////////////////////////// + + /** + * NOTE: vera_report_profile is currently unsupported + * @param type + * @param filename + */ + public static void vera_report_profile(int type, String filename) + { + throw new UnsupportedOperationException("vera_report_profile()"); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnum.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnum.java new file mode 100644 index 0000000..e5e91be --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnum.java @@ -0,0 +1,131 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Interface implemented by enum types translated from Vera. Provides + * Vera-like facilities for conversion, increment/decrement, packing, etc. + * + * @author Trevor Robinson + */ +public interface JunoEnum & JunoEnum> +{ + /** + * Returns the enum constant following this one, in declaration order. + * If this is the last enum constant declared, this method returns the + * first enum constant. + * + * @return the next enum constant + */ + E next(); + + /** + * Returns the n'th enum constant following this one, in declaration order, + * wrapping from the last constant to the first as necessary. Calling + * next(1) is equivalent to calling next(). + * + * @param count the number of constants to advance + * @return the n'th enum constant following this one + */ + E next(int count); + + /** + * Returns the enum constant preceding this one, in declaration order. + * If this is the first enum constant declared, this method returns the + * last enum constant. + * + * @return the previous enum constant + */ + E previous(); + + /** + * Returns the n'th enum constant preceding this one, in declaration order, + * wrapping from the first constant to the last as necessary. Calling + * previous(1) is equivalent to calling previous(). + * + * @param count the number of constants to advance + * @return the n'th enum constant preceding this one + */ + E previous(int count); + + /** + * Returns the enum constant associated with the specified value. If no + * enumeration value corresponds the given value and + * checked is false, this method throws an + * IllegalArgumentException. If there is no corresponding value and + * checked is true, this method returns the UNDEFINED value. + * + * @param value the value corresponding to the desired enum constant + * @param checked true if the caller will check/handle an + * undefined enumeration value, false if this method + * should throw an exception + * @return the enum constant corresponding to value, or the + * UNDEFINED value if there is none + */ + E getForValue(Integer value, boolean checked); + + /** + * Returns the number of bits needed to encode the values of this + * enumeration. + * + * @return the number of bits needed to encode this enumeration + */ + int getPackedSize(); + + /** + * Returns whether or not this is a signed enumeration. + * + * @return true if this enumeration is signed, + * false otherwise + */ + boolean isSigned(); + + /** + * Returns whether this value is a defined enumeration value, as opposed to + * the special UNDEFINED enumeration value. + * + * @return true if this enumeration value is defined, + * false if it is UNDEFINED + */ + boolean isDefined(); + + /** + * Returns the int value corresponding to this enumeration + * value. + * + * @return the int value corresponding to this enumeration + * value + */ + int toInt(); + + /** + * Returns the Integer value corresponding to this enumeration. For the + * UNDEFINED enumeration value, this method returns null. + * + * @return the Integer value corresponding to this enumeration value + */ + Integer toInteger(); + + /** + * Returns the String representation of this enumeration value. For the + * UNDEFINED enumeration value, this method returns "** UNDEFINED **". + * + * @return the String representation of this enumeration value + */ + String toString(); +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnumUtil.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnumUtil.java new file mode 100644 index 0000000..dd96c2f --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEnumUtil.java @@ -0,0 +1,69 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Static utility methods used in the implementation of translated enum types. + * + * @author Trevor Robinson + */ +public final class JunoEnumUtil +{ + public static & JunoEnum> E advance(E cur, int count) + { + final E[] consts = cur.getDeclaringClass().getEnumConstants(); + final boolean haveUndefined = consts[0].toInteger() == null; + final int undefinedAdj = haveUndefined && consts.length > 1 ? 1 : 0; + return consts[(cur.ordinal() - undefinedAdj + count) + % (consts.length - undefinedAdj) + undefinedAdj]; + } + + public static & JunoEnum> E forValue( + Class cls, + Integer value, + boolean checked) + { + final E[] consts = cls.getEnumConstants(); + E undef = null; + for (final E e : consts) + { + final Integer i = e.toInteger(); + if (i == null) + { + if (value == null) return e; + undef = e; + } + else if (value != null && i.intValue() == value.intValue()) + { + return e; + } + } + if (!checked) + { + throw new IllegalArgumentException("Value " + value + + " does not correspond to any member of " + cls.getName()); + } + return undef; + } + + public static & JunoEnum> String toString(E e) + { + final Integer i = e.toInteger(); + return i != null ? e.name() : "** UNDEFINED **"; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoEvent.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEvent.java new file mode 100644 index 0000000..01aa3fa --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEvent.java @@ -0,0 +1,88 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.eventsim.PulseEvent; + +/** + * A Jove Event with the semantics of Vera's built-in events. + * + * @author Trevor Robinson + */ +public class JunoEvent + extends PulseEvent +{ + private boolean on = false; + private long onDuringTime = -1; + private int handshakeCount = 0; + + /** + * Creates a new JunoEvent. + */ + public JunoEvent() + { + } + + /** + * Creates a new JunoEvent with the specified name. + * + * @param name the name of this JunoEvent + */ + public JunoEvent(String name) + { + super(name); + } + + boolean isOn() + { + return on; + } + + void setOn(boolean on) + { + this.on = on; + } + + long getOnDuringTime() + { + return onDuringTime; + } + + void setOnDuringTime(long onDuringTime) + { + this.onDuringTime = onDuringTime; + } + + void giveHandshake() + { + ++handshakeCount; + } + + boolean checkHandshake(boolean acquire) + { + if (handshakeCount > 0) + { + if (acquire) --handshakeCount; + return true; + } + else + { + return false; + } + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoEventValueFactory.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEventValueFactory.java new file mode 100644 index 0000000..0f26513 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoEventValueFactory.java @@ -0,0 +1,54 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Implements a ValueFactory for JunoEvent objects. + * + * @author Trevor Robinson + */ +public final class JunoEventValueFactory + implements ValueFactory +{ + /** + * A singleton instance of JunoEventValueFactory. + */ + public static final JunoEventValueFactory INSTANCE = new JunoEventValueFactory(); + + /** + * Instantiates a new JunoEvent and returns it. + * + * @return a new JunoEvent + */ + public JunoEvent newInstance() + { + return new JunoEvent(); + } + + /** + * Instantiates a new JunoEvent and returns it. + * + * @param other the JunoEvent to copy. This argument is ignored in this + * implementation. + * @return a new JunoEvent + */ + public JunoEvent copyInstance(JunoEvent other) + { + return new JunoEvent(); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoObject.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoObject.java new file mode 100644 index 0000000..5ae2f3f --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoObject.java @@ -0,0 +1,828 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.io.ByteArrayOutputStream; + +import com.newisys.dv.DV; +import com.newisys.random.PRNG; +import com.newisys.randsolver.InvalidConstraintException; +import com.newisys.randsolver.InvalidRandomVarException; +import com.newisys.randsolver.RandomHooks; +import com.newisys.randsolver.Solver; +import com.newisys.randsolver.UnsolvableConstraintException; +import com.newisys.randsolver.annotation.Randomizable; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorBuffer; + +/** + * Base class for all translated Vera classes. Implements the built-in methods + * callable on all Vera objects. + * + * @author Trevor Robinson + */ +@Randomizable +public class JunoObject + implements Cloneable, RandomHooks +{ + public static final int FAIL = 0; + public static final int OK = 1; + + public static final int OFF = 0; + public static final int ON = 1; + public static final int REPORT = 2; + + public static final int RAND_MODE_FAIL = -1; + public static final int CONSTRAINT_MODE_FAIL = -1; + + // Get the random stream from our thread. This is different from Vera which + // creates a new random stream for each Object. + private PRNG prng = DV.simulation.getRandom(); + + /** + * Creates a new JunoObject. + */ + public JunoObject() + { + // do nothing + } + + /** + * Creates and returns a copy of this object. + * + * @return a clone of this JunoObject + * @see Object#clone + */ + @Override + public Object clone() + { + try + { + return super.clone(); + } + catch (CloneNotSupportedException e) + { + throw new Error(e); + } + } + + /** + * Randomize this JunoObject. If the constraints on this object are such + * that there is no legal combination of random variables to satify those + * constraints, {@link #FAIL} is returned. Otherwise {@link #OK} is returned. + * + * @return OK if the randomization was successful or + * FAIL if there was an error during randomization. + */ + public final int randomize() + { + try + { + Solver.randomize(this, prng); + } + catch (UnsolvableConstraintException e) + { + // TODO: throw an exception if the object cannot be randomized + return FAIL; + } + + return OK; + } + + /** + * Allows code to be run just prior to this object being randomized. This + * method calls {@link #pre_randomize pre_randomize}, which + * should be overridden by subclasses needing this functionality. + */ + public final void preRandomize() + { + pre_randomize(); + } + + /** + * Allows code to be run just after this object is randomized. This + * method calls {@link #post_randomize post_randomize}, which + * should be overridden by subclasses needing this functionality. + */ + public final void postRandomize() + { + post_randomize(); + } + + /** + * Allows code to be run just prior to this object being randomized. + * This method should be overridden by subclasses that wish to execute some + * code just before this object is randomized. If this object contains + * subobjects that are being randomized, the order in which each object's + * pre_randomize method is called is undefined. + * + */ + public void pre_randomize() + { + // do nothing + } + + /** + * Allows code to be run just after this object has been randomized. + * This method should be overridden by subclasses that wish to execute some + * code just after this object is randomized. If this object contains + * subobjects that are being randomized, the order in which each object's + * post_randomize method is called is undefined. + * + */ + public void post_randomize() + { + // do nothing + } + + /** + * Sets the random number generator for this object. + * + * @param prng the random number generator to be used by this object + */ + public final void setRandom(PRNG prng) + { + this.prng = prng; + } + + /** + * Toggles the randomization mode of all random variables in this object. + * + * If action is {@link #ON ON}, all random + * variables associated with this object will be enabled. If + * action is {@link #OFF OFF}, all random + * variables associated with this object will be disabled. If + * action is {@link #REPORT REPORT} a warning is + * printed and {@link #RAND_MODE_FAIL RAND_MODE_FAIL} is returned. + * + * @param action one of ON, OFF or REPORT + * @return action is returned, unless there is a failure or + * action is REPORT, in which case + * RAND_MODE_FAIL is returned + */ + public final int rand_mode(int action) + { + assert (action == ON || action == OFF || action == REPORT); + + int result = RAND_MODE_FAIL; + + try + { + switch (action) + { + case ON: + Solver.enableAllRand(this); + result = ON; + break; + case OFF: + Solver.disableAllRand(this); + result = OFF; + break; + case REPORT: + // TODO: throw an exception if rand_mode(REPORT) is called + Juno + .warning("WARNING: runtime: rand_mode requires a specific name as a 2nd argument for REPORT\n"); + result = RAND_MODE_FAIL; + break; + default: + throw new RuntimeException("Illegal action: " + action); + } + } + catch (InvalidRandomVarException e) + { + result = RAND_MODE_FAIL; + } + return result; + } + + /** + * Toggles the randomization mode of the specified random variable in this + * object. + * + * If action is {@link #ON ON}, randomization of + * var in this instance will be enabled. If action + * is {@link #OFF OFF}, randomization of var in + * this instance will be disabled. If action is + * {@link #REPORT REPORT} ON will be returned if + * var is enabled, OFF otherwise. + * + * @param action one of ON, OFF or REPORT + * @param var the variable to check + * @return action is returned, unless there is a failure in which + * case RAND_MODE_FAIL is returned + */ + public final int rand_mode(int action, String var) + { + return rand_mode(action, var, -1); + } + + /** + * Toggles the randomization mode of the specified random variable in this + * object. + * + * If action is {@link #ON ON}, randomization of + * var in this instance will be enabled. If action + * is {@link #OFF OFF}, randomization of var in + * this instance will be disabled. If action is + * {@link #REPORT REPORT} ON will be + * returned if var is enabled, OFF otherwise. + * + * The index parameter is used if var is an array. + * This feature is currently unsupported and index must be + * -1. + * + * @param action one of ON, OFF or REPORT + * @param var the variable to check + * @param index the array index to check. This currently must be -1. + * @return action is returned, unless there is a failure in which + * case RAND_MODE_FAIL is returned + */ + public final int rand_mode(int action, String var, int index) + { + assert (action == ON || action == OFF || action == REPORT); + + if (index != -1) + { + throw new UnsupportedOperationException( + "Array indices are not supported"); + } + + int result = RAND_MODE_FAIL; + + try + { + switch (action) + { + case ON: + Solver.enableRand(this, var); + result = ON; + break; + case OFF: + Solver.disableRand(this, var); + result = OFF; + break; + case REPORT: + boolean isEnabled = Solver.isRandEnabled(this, var); + result = isEnabled ? ON : OFF; + break; + default: + throw new RuntimeException("Illegal action: " + action); + } + } + catch (InvalidRandomVarException e) + { + result = RAND_MODE_FAIL; + } + + return result; + } + + /** + * Toggles the randomization mode of all constraints on this object. + * + * If action is {@link #ON ON}, all constraints + * associated with this object will be enabled. If action is + * {@link #OFF OFF}, all constraints associated with this object + * will be disabled. If action is + * {@link #REPORT REPORT} a warning is printed and + * {@link #CONSTRAINT_MODE_FAIL CONSTRAINT_MODE_FAIL} is returned. + * + * @param action one of ON, OFF or REPORT + * @return action is returned, unless there is a failure or + * action is REPORT, in which case + * CONSTRAINT_MODE_FAIL is returned + */ + public final int constraint_mode(int action) + { + assert (action == ON || action == OFF || action == REPORT); + + int result = CONSTRAINT_MODE_FAIL; + try + { + switch (action) + { + case ON: + Solver.enableAllConstraints(this); + result = ON; + break; + case OFF: + Solver.disableAllConstraints(this); + result = OFF; + break; + case REPORT: + // TODO: throw an exception if constraint_mode(REPORT) is called. + Juno + .warning("WARNING: runtime: constraint_mode requires a specific name as a 2nd argument for REPORT\n"); + result = CONSTRAINT_MODE_FAIL; + break; + default: + throw new RuntimeException("Illegal action: " + action); + } + } + catch (InvalidConstraintException e) + { + result = CONSTRAINT_MODE_FAIL; + } + return result; + } + + /** + * Toggles the randomization mode of the specified constraint on this object. + * + * If action is {@link #ON ON}, cons + * will be enabled when randomizing this instance. If action is + * {@link #OFF OFF}, all constraints associated with this + * object will be disabled. If action is {@link #REPORT REPORT} + * a warning is printed and + * {@link #CONSTRAINT_MODE_FAIL CONSTRAINT_MODE_FAIL} is returned. + * + * @param action one of ON, OFF or REPORT + * @param cons the constraint to check + * @return action is returned, unless there is a failure, in + * which case CONSTRAINT_MODE_FAIL is returned + */ + public final int constraint_mode(int action, String cons) + { + assert (action == ON || action == OFF || action == REPORT); + + int result = CONSTRAINT_MODE_FAIL; + switch (action) + { + case ON: + Solver.enableConstraint(this, cons); + result = ON; + break; + case OFF: + Solver.disableConstraint(this, cons); + result = OFF; + break; + case REPORT: + boolean isEnabled = Solver.isConstraintEnabled(this, cons); + result = isEnabled ? ON : OFF; + break; + default: + throw new RuntimeException("Illegal action: " + action); + } + return result; + } + + /** + * Prints the object instance hierarchy of this object to + * {@link Juno#STDOUT}. + * + * This is equivalent to calling + *

    + * object_print(Vera.STDOUT,"") + *

    + * This method is currently unsupported. + */ + public final void object_print() + { + // TODO: object_print + throw new UnsupportedOperationException("object_print()"); + } + + /** + * Prints the object instance hierarchy of this object to the specified + * Vera file descriptor. + * + * This is equivalent to calling + *

    + * object_print(fd,"") + *

    + * This method is currently unsupported. + * + * @param fd the file descriptor to which output will be written + */ + public final void object_print(int fd) + { + // TODO: object_print + throw new UnsupportedOperationException("object_print(int)"); + } + + /** + * Prints the object instance hierarchy of this object to the specified + * Vera file descriptor with the specified attributes. + * + * attrs is a string of space-delimited key=value pairs. Valid + * attributes are shown in the table below along with their default values. + *

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    keydefault valuedescription
    depth0the number of levels of the hierarchy to print
    indent4the number of spaces to indent members and array elements
    severitylowone of low or high. low + * ignores errors encountered during printing
    portyesone of yes or no. yes will + * print port signals, no will omit them.
    formatsee descriptionone of bin, dec, or hex. + * bin will have an underscore frequency of 4. the + * default is to print integers in decimal, bit vectors and signals + * without X/Z values in hexadecimal, and bit vectors and signals + * with X/Z values in binary
    array_depth20a decimal value specifying the maximum number of array elements + * to print
    + *

    + * This method is currently unsupported. + * + * @param fd the file descriptor to which output will be written + * @param attrs an attribute string as defined above + */ + public final void object_print(int fd, String attrs) + { + // TODO: object_print + throw new UnsupportedOperationException("object_print(int, String)"); + } + + /** + * Performs a deep compare of this object with the specified object. The + * comparison includes both super objects and contained objects. Comparisons + * are made based on object contents, not based on object references. + *

    + * This method is currently unsupported. + * + * @param other the JunoObject to compare against + * @return 1 if the two objects are equal, 0 otherwise + */ + public int object_compare(JunoObject other) + { + // TODO: object_compare + throw new UnsupportedOperationException("object_compare(JunoObject)"); + } + + /** + * Performs a deep copy of this JunoObject and returns the new JunoObject. + * The new JunoObject contains deep copies of this JunoObject's super objects + * and contained objects. + *

    + * This method is currently unsupported. + * + * @return a new deep copy of this JunoObject + */ + public final JunoObject object_copy() + { + // TODO: object_copy + throw new UnsupportedOperationException("object_copy()"); + } + + public static final class PackingPosition + { + public long index; + public int left; + public int right; + + public PackingPosition() + { + this.index = 0; + this.left = 0; + this.right = 0; + } + + public PackingPosition(long index, int left, int right) + { + this.index = index; + this.left = left; + this.right = right; + } + } + + public final int pack(BitBitAssocArray array, PackingPosition pos) + { + pre_pack(); + int result = doPack(array, pos); + post_pack(); + return result; + } + + protected int doPack(BitBitAssocArray array, PackingPosition pos) + { + // overridden by classes with packed fields + return 0; + } + + protected static int packBits( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + BitVector value) + { + final int wordSize = array.getValueLength(); + + final int valueSize = value.length(); + int valueWritten = 0; + + long index = pos.index; + BitVector indexBV = new BitVector(64, index); + int left = pos.left; + int right = pos.right; + + while (true) + { + int valueRemaining = valueSize - valueWritten; + if (valueRemaining == 0) break; + + int wordRemaining = wordSize - left - right; + + int writeSize = Math.min(wordRemaining, valueRemaining); + if (writeSize > 0) + { + BitVector word = array.get(indexBV); + + BitVector writeValue; + if (bigEndian ^ bitReverse) + { + writeValue = value.getBits(valueSize - valueWritten - 1, + valueSize - valueWritten - writeSize); + } + else + { + writeValue = value.getBits(valueWritten + writeSize - 1, + valueWritten); + } + valueWritten += writeSize; + + if (bitReverse) + { + writeValue = writeValue.reverse(); + } + + if (bigEndian) + { + word = word.setBits(wordSize - left - 1, wordSize - left + - writeSize, writeValue); + left += writeSize; + } + else + { + word = word.setBits(right + writeSize - 1, right, + writeValue); + right += writeSize; + } + wordRemaining -= writeSize; + + array.put(indexBV, word); + } + + if (wordRemaining == 0) + { + ++index; + indexBV = new BitVector(64, index); + left = 0; + right = 0; + } + } + + pos.index = index; + pos.left = left; + pos.right = right; + + return valueSize; + } + + protected static int packInteger( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + Integer value) + { + return packBits(array, pos, bigEndian, bitReverse, IntegerOp + .toBitVector(value)); + } + + protected static int packEnum( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + JunoEnum< ? > value) + { + return packBits(array, pos, bigEndian, bitReverse, IntegerOp + .toBitVector(value.toInteger(), value.getPackedSize())); + } + + protected static int packString( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + String s) + { + int size = 0; + byte[] bytes = s.getBytes(); + for (int i = 0; i < bytes.length; ++i) + { + BitVector bv = new BitVector(8, bytes[i]); + size += packBits(array, pos, bigEndian, bitReverse, bv); + } + BitVector bv = new BitVector(8, 0); + size += packBits(array, pos, bigEndian, bitReverse, bv); + return size; + } + + public void pre_pack() + { + // do nothing + } + + public void post_pack() + { + // do nothing + } + + public final int unpack(BitBitAssocArray array, PackingPosition pos) + { + pre_unpack(); + int result = doUnpack(array, pos); + post_unpack(); + return result; + } + + protected int doUnpack(BitBitAssocArray array, PackingPosition pos) + { + // overridden by classes with packed fields + return 0; + } + + protected static BitVector unpackBits( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + int valueSize) + { + final int wordSize = array.getValueLength(); + + final BitVectorBuffer value = new BitVectorBuffer(valueSize); + int valueRead = 0; + + long index = pos.index; + BitVector indexBV = new BitVector(64, index); + int left = pos.left; + int right = pos.right; + + while (true) + { + int valueRemaining = valueSize - valueRead; + if (valueRemaining == 0) break; + + int wordRemaining = wordSize - left - right; + + int readSize = Math.min(wordRemaining, valueRemaining); + if (readSize > 0) + { + BitVector word = array.get(indexBV); + + BitVector readValue; + if (bigEndian) + { + readValue = word.getBits(wordSize - left - 1, wordSize + - left - readSize); + left += readSize; + } + else + { + readValue = word.getBits(right + readSize - 1, right); + right += readSize; + } + wordRemaining -= readSize; + + if (bitReverse) + { + readValue = readValue.reverse(); + } + + if (bigEndian ^ bitReverse) + { + value.setBits(valueSize - valueRead - 1, valueSize + - valueRead - readSize, readValue); + } + else + { + value.setBits(valueRead + readSize - 1, valueRead, + readValue); + } + valueRead += readSize; + } + + if (wordRemaining == 0) + { + ++index; + indexBV = new BitVector(64, index); + left = 0; + right = 0; + } + } + + pos.index = index; + pos.left = left; + pos.right = right; + + return value.toBitVector(); + } + + protected static Integer unpackInteger( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse) + { + return IntegerOp.toInteger(unpackBits(array, pos, bigEndian, + bitReverse, 32)); + } + + protected static & JunoEnum> E unpackEnum( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse, + E enumInstance) + { + Integer i = IntegerOp.toInteger(unpackBits(array, pos, bigEndian, + bitReverse, enumInstance.getPackedSize()), enumInstance.isSigned()); + return enumInstance.getForValue(i, false); + } + + protected static String unpackString( + BitBitAssocArray array, + PackingPosition pos, + boolean bigEndian, + boolean bitReverse) + { + ByteArrayOutputStream stream = new ByteArrayOutputStream(64); + while (true) + { + BitVector bv = unpackBits(array, pos, bigEndian, bitReverse, 8); + if (bv.containsXZ()) + { + throw new IllegalArgumentException( + "Found X/Z bits while unpacking string"); + } + if (bv.isZero()) break; + stream.write(bv.intValue()); + } + return stream.toString(); + } + + public void pre_unpack() + { + // do nothing + } + + public void post_unpack() + { + // do nothing + } + + @Override + public void finalize() + { + // this method overrides java.lang.Object.finalize() in order + // to remove the checked exception + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoRuntimeException.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoRuntimeException.java new file mode 100644 index 0000000..b64bd96 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoRuntimeException.java @@ -0,0 +1,50 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Exception thrown by the Juno runtime when the original Vera code would have + * encountered a Vera runtime error. + * + * @author Trevor Robinson + */ +public class JunoRuntimeException + extends RuntimeException +{ + private static final long serialVersionUID = 3689909578574149686L; + + public JunoRuntimeException() + { + super(); + } + + public JunoRuntimeException(String message) + { + super(message); + } + + public JunoRuntimeException(Throwable cause) + { + super(cause); + } + + public JunoRuntimeException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoString.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoString.java new file mode 100644 index 0000000..0ac5f31 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoString.java @@ -0,0 +1,813 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import com.newisys.dv.DV; +import com.newisys.verilog.util.BitVector; + +/** + * An implementation of Vera's built-in string type. + * + * @author Trevor Robinson + */ +public final class JunoString + implements Cloneable +{ + /** + * A constant null string. + */ + public static final JunoString NULL = new JunoString(); + + /** + * Vera's OK define. + */ + public static final int OK = 0; + + /** + * Vera's STR_ERR_OUT_OF_RANGE define. + */ + public static final int STR_ERR_OUT_OF_RANGE = 1; + + /** + * Vera's STR_ERR_REGEXP_SYNTAX define. + */ + public static final int STR_ERR_REGEXP_SYNTAX = 2; + + private StringBuffer buffer; + private boolean bufferShared; + private int status; + private Matcher matcher; + private JunoEvent changeEvent; + + /** + * Creates a new, empty JunoString. + */ + public JunoString() + { + } + + /** + * Creates a new JunoString, which is a copy of str. + * + * @param str the String to copy + */ + public JunoString(String str) + { + assignWithoutNotify(str); + } + + /** + * Creates a new JunoString, which is a copy of str and has + * the specified status and matcher state. + * + * @param str the String to copy + * @param status one of {@link #OK}, {@link #STR_ERR_OUT_OF_RANGE}, or + * {@link #STR_ERR_REGEXP_SYNTAX} + * @param matcher a Matcher to be used in JunoString's various match methods + */ + public JunoString(String str, int status, Matcher matcher) + { + assignWithoutNotify(str); + this.status = status; + this.matcher = matcher; + } + + /** + * Creates a new JunoString, which is a copy of other. + * + * @param other the JunoString to copy + */ + public JunoString(JunoString other) + { + assign(other); + } + + /** + * Returns a JunoEvent that is notified whenever this JunoString changes. + * + * @return the change event for this JunoString + */ + public JunoEvent getChangeEvent() + { + synchronized (this) + { + if (changeEvent == null) + { + changeEvent = new JunoEvent(); + } + } + return changeEvent; + } + + private void notifyChange() + { + if (changeEvent != null) + { + DV.simulation.notifyOf(changeEvent); + } + } + + private void copyOnWrite() + { + if (bufferShared) + { + StringBuffer newBuffer = new StringBuffer(buffer.length()); + newBuffer.append(buffer); + buffer = newBuffer; + bufferShared = false; + } + } + + private static boolean isSameSequence(CharSequence s1, CharSequence s2) + { + int len; + if (s1 != null && s2 != null && s1 != s2 + && (len = s1.length()) == s2.length()) + { + for (int i = 0; i < len; ++i) + { + if (s1.charAt(i) != s2.charAt(i)) return false; + } + return true; + } + return s1 == s2; + } + + private void assignWithoutNotify(String str) + { + status = OK; + buffer = str != null ? new StringBuffer(str) : null; + bufferShared = false; + } + + /** + * Assigns str to this JunoString. + * + * @param str the String to assign + * @return this JunoString after the assignment + */ + public JunoString assign(String str) + { + boolean changed = !isSameSequence(str, buffer); + assignWithoutNotify(str); + if (changed) notifyChange(); + return this; + } + + /** + * Assigns other to this JunoString. + * + * @param other the JunoString to assign + * @return this JunoString after the assignment + */ + public JunoString assign(JunoString other) + { + status = OK; + boolean changed = !isSameSequence(buffer, other.buffer); + buffer = other.buffer; + boolean shared = (buffer != null); + bufferShared = shared; + other.bufferShared = shared; + if (changed) notifyChange(); + return this; + } + + /** + * Returns the length of this JunoString. + * + * @return the number of characters in this JunoString + */ + public int len() + { + status = OK; + return buffer != null ? buffer.length() : 0; + } + + /** + * Returns the character at the specified index in this JunoString. + * + * @param index the index of the character to return + * @return the character at index, or 0 if index + * is outside the bounds of this JunoString. + */ + public int getc(int index) + { + status = OK; + int len = len(); + return index >= 0 && index < len ? buffer.charAt(index) : 0; + } + + /** + * Returns a new JunoString which is a copy of this JunoString will all + * characters converted to lower case. + * + * @return a new JunoString with the contents of this JunoString converted + * to lower case. + */ + public JunoString tolower() + { + if (buffer == null) + { + throw new JunoRuntimeException( + "JunoString.tolower failed due to null string"); + } + status = OK; + return new JunoString(buffer.toString().toLowerCase()); + } + + /** + * Returns a new JunoString which is a copy of this JunoString will all + * characters converted to upper case. + * + * @return a new JunoString with the contents of this JunoString converted + * to upper case. + */ + public JunoString toupper() + { + if (buffer == null) + { + throw new JunoRuntimeException( + "JunoString.toupper failed due to null string"); + } + status = OK; + return new JunoString(buffer.toString().toUpperCase()); + } + + /** + * Inserts the specified character into this JunoString at the specified + * index. If index is outside the bounds of this JunoString, the status of + * this JunoString is changed to {@link #STR_ERR_OUT_OF_RANGE}. + * + * @param index the index at which to insert c + * @param c the character to insert at index + */ + public void putc(int index, char c) + { + copyOnWrite(); + int len = len(); + if (index >= 0 && index < len) + { + boolean changed; + if (c != 0) + { + changed = buffer.charAt(index) != c; + buffer.setCharAt(index, c); + } + else + { + changed = true; + buffer.setLength(index); + } + status = OK; + if (changed) notifyChange(); + } + else + { + status = STR_ERR_OUT_OF_RANGE; + } + } + + /** + * Inserts the specified character into this JunoString at the specified + * index. + *

    + * This is equivalent to putc(index, (char)c). + * + * @param index the index at which to insert c + * @param c the character to insert at index + */ + public void putc(int index, int c) + { + putc(index, (char) c); + } + + /** + * Inserts the first character of the specified String into this JunoString + * at the specified index. If s is null or + * s.length() is 0, 0 is inserted. + * + * @param index the index at which to insert the character + * @param s a String, the first character of which will be inserted into + * this JunoString at index + */ + public void putc(int index, String s) + { + putc(index, s != null && s.length() > 0 ? s.charAt(0) : 0); + } + + /** + * Returns the status of this JunoString. + * + * @return the current status of this JunoString. + */ + public int get_status() + { + return status; + } + + /** + * Returns a String representation of the current status of this JunoString. + * + * @return a String representing the status of this JunoString + */ + public String get_status_msg() + { + return StringOp.get_status_msg(status); + } + + /** + * Compares this JunoString to the specified string and returns the results + * of the comparison with semantics identical to {@link String#compareTo}. + * + * @param other the string to compare + * @return a negative value, 0, or a positive value as specified in + * String.compareTo + * @see String#compareTo(java.lang.String) + */ + public int compare(String other) + { + status = OK; + if (buffer != null && other != null) + { + return buffer.toString().compareTo(other); + } + return (buffer != null ? 1 : 0) - (other != null ? 1 : 0); + } + + /** + * Compares this JunoString to the specified string and returns the results + * of the comparison with semantics identical to {@link String#compareTo}. + * + * @param other the string to compare + * @return a negative value, 0, or a positive value as specified in + * String.compareTo + * @see String#compareTo(java.lang.String) + */ + public int compare(JunoString other) + { + return compare(other.toStringOrNull()); + } + + /** + * Compares this JunoString to the specified string case-insensitively and + * returns the results of the comparison with semantics identical to + * {@link String#compareToIgnoreCase}. + * + * @param other the JunoString to compare + * @return a negative value, 0, or a positive value as specified in + * String.compareToIgnoreCase + * @see String#compareToIgnoreCase + */ + public int icompare(String other) + { + status = OK; + if (buffer != null && other != null) + { + return buffer.toString().compareToIgnoreCase(other); + } + return (buffer != null ? 1 : 0) - (other != null ? 1 : 0); + } + + /** + * Compares this JunoString to the specified string case-insensitively and + * returns the results of the comparison with semantics identical to + * {@link String#compareToIgnoreCase}. + * + * @param other the JunoString to compare + * @return a negative value, 0, or a positive value as specified in + * String.compareToIgnoreCase + * @see String#compareToIgnoreCase + */ + public int icompare(JunoString other) + { + return icompare(other.toStringOrNull()); + } + + /** + * Returns a hash code for this JunoString. The returns value will be + * a value in the interval [0, size). + * + * @param size the maximum value the hash code should take on, exclusive + * @return the hash code, or -1 if this JunoString's buffer is null. + */ + public int hash(int size) + { + status = OK; + return buffer != null ? buffer.toString().hashCode() % size : -1; + } + + /** + * Returns a substring of this JunoString. The substring will contain all + * characters in this JunoString from start through the end + * of the JunoString. + * + * @param start the beginning index, inclusive + * @return a new JunoString containing the specified substring, or the + * empty string if start is out of the bounds of this + * JunoString + */ + public JunoString substr(int start) + { + status = OK; + int len = len(); + String s = (start >= 0 && start < len) ? buffer.substring(start) : ""; + return new JunoString(s); + } + + /** + * Returns a substring of this JunoString. The substring will contain all + * characters in this JunoString from start (inclusive) through + * end (exclusive). + * + * @param start the beginning index, inclusive + * @param end the ending index, exclusive + * @return a new JunoString containing the specified substring, or the + * empty string if start or end is out of the + * bounds of this JunoString + */ + public JunoString substr(int start, int end) + { + status = OK; + int len = len(); + if (end >= len) end = len - 1; + String s = (start >= 0 && start <= end) ? buffer.substring(start, + end + 1) : ""; + return new JunoString(s); + } + + /** + * Searches for the specified pattern in this JunoString. It will find the + * first occurrence of pattern in this JunoString and return + * the starting index of that occurrence or -1 if the pattern cannot be + * found. + * + * @param pattern the JunoString containing the pattern for which to search + * @return the index of the first character of pattern in this + * JunoString, or -1 if the pattern cannot be found. + */ + public int search(JunoString pattern) + { + status = OK; + if (!isEmpty() && !pattern.isEmpty()) + { + return buffer.indexOf(pattern.toString()); + } + return -1; + } + + private boolean isEmpty() + { + return buffer == null || buffer.length() == 0; + } + + /** + * Finds the specified regular expression in this JunoString. + *

    + * If the pattern is found in this JunoString, 1 is returned. + * Otherwise, 0 is returned. + *

    + * If pattern is not a legal regular expression, 0 is returned + * and the status of this JunoString is set to {@link #STR_ERR_REGEXP_SYNTAX}. + *

    + * It should be noted that this method creates matcher state in this JunoString + * that is used by {@link #prematch}, {@link #postmatch}, {@link #thismatch}, + * and {@link #backref}. This matcher state is reset each time match + * is called. + * + * @param pattern the regular expression to match + * @return 1 if a match was found, 0 otherwise + */ + public int match(String pattern) + { + status = OK; + matcher = null; + boolean matched = false; + if (buffer != null && pattern != null) + { + try + { + Pattern p = Pattern.compile(pattern); + matcher = p.matcher(buffer); + matched = matcher.find(); + } + catch (PatternSyntaxException e) + { + status = STR_ERR_REGEXP_SYNTAX; + } + } + return matched ? 1 : 0; + } + + /** + * Finds the specified regular expression in this JunoString. + *

    + * If the pattern is found in this JunoString, 1 is returned. + * Otherwise, 0 is returned. + *

    + * If pattern is not a legal regular expression, 0 is returned + * and the status of this JunoString is set to {@link #STR_ERR_REGEXP_SYNTAX}. + *

    + * It should be noted that this method creates matcher state in this JunoString + * that is used by {@link #prematch}, {@link #postmatch}, {@link #thismatch}, + * and {@link #backref}. This matcher state is reset each time match + * is called. + * + * @param pattern the regular expression to match + * @return 1 if a match was found, 0 otherwise + */ + public int match(JunoString pattern) + { + return match(pattern.toStringOrNull()); + } + + /** + * Returns the substring of this JunoString including all characters up to + * the beginning of the previous match. This method expects a valid + * matcher state as generated by {@link #match(String)} or + * {@link #JunoString(String, int, Matcher)}. + *

    + * It returns a substring equivalent to substr(0, matcher.start()). + * + * @return a new JunoString containing the substring of all characters before + * the start of the previous match, or the NULL string if there is not + * a valid match state + */ + public JunoString prematch() + { + status = OK; + if (buffer != null && matcher != null) + { + try + { + return new JunoString(buffer.substring(0, matcher.start())); + } + catch (IllegalStateException e) + { + // ignored + } + } + return NULL; + } + + /** + * Returns the substring of this JunoString including all characters after + * the end of the previous match. This method expects a valid + * matcher state as generated by {@link #match(String)} or + * {@link #JunoString(String, int, Matcher)}. + *

    + * It returns a substring equivalent to substr(matcher.end()). + * + * @return a new JunoString containing the substring of all characters after + * the end of the previous match, or the NULL string if there is not + * a valid match state + */ + public JunoString postmatch() + { + status = OK; + if (buffer != null && matcher != null) + { + try + { + return new JunoString(buffer.substring(matcher.end())); + } + catch (IllegalStateException e) + { + // ignored + } + } + return NULL; + } + + /** + * Returns the substring corresponding to the previous match. This method + * expects a valid matcher state as generated by {@link #match(String)} or + * {@link #JunoString(String, int, Matcher)}. + *

    + * It returns a substring equivalent to + * substr(matcher.start(), matcher.end()). + * + * @return a new JunoString containing the substring of all characters + * contained in the previous match, or the NULL string if there is not + * a valid match state + */ + public JunoString thismatch() + { + status = OK; + if (buffer != null && matcher != null) + { + try + { + // returns substring currently at matched location, which is + // NOT necessarily the original string that was matched + return new JunoString(buffer.substring(matcher.start(), matcher + .end())); + } + catch (IllegalStateException e) + { + // ignored + } + } + return NULL; + } + + /** + * Returns the substring corresponding to the specified capture group of the + * previous match. This method expects a valid matcher state as generated by + * {@link #match(String)} or {@link #JunoString(String, int, Matcher)}. + * + * @param index the index of the capture group + * @return a substring containing the characters matched by the specified + * capture group in the previous match, or the NULL string if the + * match state is invalid + */ + public JunoString backref(int index) + { + status = OK; + if (index < 0) + { + throw new IllegalArgumentException( + "JunoString.backref index must be >= 0"); + } + + ++index; + if (buffer != null && matcher != null && index <= matcher.groupCount() + && matcher.start(index) != -1 && matcher.end(index) != -1) + { + try + { + // returns substring currently at matched location, which is + // NOT necessarily the original string that was matched + return new JunoString(buffer.substring(matcher.start(index), + matcher.end(index))); + } + catch (IllegalStateException e) + { + // ignored + } + } + return NULL; + } + + /** + * Parses this JunoString as a decimal value and returns the resulting int. + * Underscores are allowed in this JunoString. + * + * @return an int corresponding to the decimal value of this JunoString + */ + public int atoi() + { + status = OK; + return StringOp.atoi(buffer.toString()); + } + + /** + * Assigns the specified int to this JunoString. The string assigned is + * equivalent to String.valueOf(i). + * + * @param i the int to assign to this JunoString + */ + public void itoa(int i) + { + // Vera always notifies on itoa, even if the result is the same + assignWithoutNotify(String.valueOf(i)); + notifyChange(); + } + + /** + * Parses this JunoString as a hexadecimal value and returns the equivalent + * BitVector. + * + * @return a BitVector having the value of this JunoString when treated as + * a hexadecimal value + */ + public BitVector atohex() + { + status = OK; + return StringOp.atohex(buffer.toString()); + } + + /** + * Parses this JunoString as an octal value and returns the equivalent + * BitVector. + * + * @return a BitVector having the value of this JunoString when treated as + * an octal value + */ + public BitVector atooct() + { + status = OK; + return StringOp.atooct(buffer.toString()); + } + + /** + * Parses this JunoString as a binary value and returns the equivalent + * BitVector. + * + * @return a BitVector having the value of this JunoString when treated as + * a binary value + */ + public BitVector atobin() + { + status = OK; + return StringOp.atobin(buffer.toString()); + } + + /** + * Assigns the specified BitVector to this JunoString. Each 8 bits of + * bv are treated as a character to assign to this JunoString. + * Furthermore, the most significant byte of bv is placed in + * the first character of this JunoString. + *

    + * For example if bv is the BitVector 32'h41424344, the resulting + * JunoString will be "ABCD", where A = 0x41, B = 0x42, etc. in ASCII. + * + * @param bv the BitVector to assign to this JunoString + */ + public void bittostr(BitVector bv) + { + status = OK; + String str = StringOp.bittostr(bv); + boolean changed = !isSameSequence(str, buffer); + buffer = (str != null) ? new StringBuffer(str) : null; + bufferShared = false; + if (changed) notifyChange(); + } + + protected Object clone() + { + return new JunoString(this); + } + + public boolean equals(Object obj) + { + if (obj instanceof JunoString) + { + return compare((JunoString) obj) == 0; + } + else if (obj instanceof String) + { + return buffer != null && buffer.toString().equals(obj); + } + return obj == null && buffer == null; + } + + public int hashCode() + { + return buffer != null ? buffer.toString().hashCode() : -1; + } + + /** + * Returns a String containing the contents of this JunoString, or "(NULL)" + * if this JunoString contains the null string. + * + * @return String + * @see java.lang.Object#toString() + */ + public String toString() + { + return buffer != null ? buffer.toString() : "(NULL)"; + } + + /** + * Returns a String containing the contents of this JunoString, or an empty + * string if this JunoString contains the null string. + * + * @return String + * @see java.lang.Object#toString() + */ + public String toStringOrBlank() + { + return buffer != null ? buffer.toString() : ""; + } + + /** + * Returns a String containing the contents of this JunoString, or null if + * this JunoString contains the null string. + * + * @return String or null + * @see java.lang.Object#toString() + */ + public String toStringOrNull() + { + return buffer != null ? buffer.toString() : null; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoStringValueFactory.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoStringValueFactory.java new file mode 100644 index 0000000..40a6c1a --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoStringValueFactory.java @@ -0,0 +1,53 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * Implementation of ValueFactory for JunoString objects. + * + * @author Trevor Robinson + */ +public final class JunoStringValueFactory + implements ValueFactory +{ + /** + * A singleton instance of JunoStringValueFactory. + */ + public static final JunoStringValueFactory INSTANCE = new JunoStringValueFactory(); + + /** + * Instantiates a new JunoString and returns it. + * + * @return a new JunoString + */ + public JunoString newInstance() + { + return new JunoString(); + } + + /** + * Returns a new JunoString, which is a copy of other. + * + * @param other the JunoString to copy + * @return a new JunoString, which is a copy of other + */ + public JunoString copyInstance(JunoString other) + { + return new JunoString(other); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/JunoThreadContext.java b/java/juno-runtime/src/com/newisys/juno/runtime/JunoThreadContext.java new file mode 100644 index 0000000..77ff4f6 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/JunoThreadContext.java @@ -0,0 +1,55 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.eventsim.SimulationThread; + +/** + * Used internally by the Juno runtime to track threads forked from different + * contexts, which is necessary to implement wait_child(). + * + * @author Trevor Robinson + */ +final class JunoThreadContext +{ + private final JunoThreadContext parentContext; + private final List forkedThreads = new LinkedList(); + + public JunoThreadContext(JunoThreadContext parentContext) + { + this.parentContext = parentContext; + } + + public JunoThreadContext getParentContext() + { + return parentContext; + } + + public List getForkedThreads() + { + return forkedThreads; + } + + public void addForkedThread(SimulationThread t) + { + forkedThreads.add(t); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/LongWrapperOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/LongWrapperOp.java new file mode 100644 index 0000000..2378aa3 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/LongWrapperOp.java @@ -0,0 +1,401 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Long conversion and operation methods referenced by translated code. + * + * @author Trevor Robinson + */ +public final class LongWrapperOp +{ + private final static Long LONG_ZERO = new Long(0); + private final static Long LONG_ONE = new Long(1); + + private LongWrapperOp() + { + } + + public static boolean toBoolean(Long l) + { + return l != null && l.longValue() != 0; + } + + public static boolean lowBitToBoolean(Long l) + { + return l != null && (l.longValue() & 1) != 0; + } + + public static boolean toBooleanXZTrue(Long l) + { + return l == null || l.longValue() != 0; + } + + public static boolean lowBitToBooleanXZTrue(Long l) + { + return l == null || (l.longValue() & 1) != 0; + } + + public static BitVector toBitVector(Long l) + { + return toBitVector(l, 32, false); + } + + public static BitVector toBitVector(Long l, int len) + { + return toBitVector(l, len, false); + } + + public static BitVector toBitVector(Long l, int len, boolean signExtend) + { + return l != null ? new BitVector(len, l.longValue(), signExtend) + : new BitVector(len, Bit.X); + } + + public static int toInt(Long l) + { + if (l == null) + { + throw new IllegalArgumentException("Value is undefined"); + } + return l.intValue(); + } + + public static long toLong(Long l) + { + if (l == null) + { + throw new IllegalArgumentException("Value is undefined"); + } + return l.longValue(); + } + + public static int toShiftCount(Long l, int max) + { + if (l == null) + { + throw new IllegalArgumentException( + "Shift count cannot be undefined"); + } + return (int) Math.min(l.longValue(), max); + } + + public static int toShiftCount(Long l) + { + return toShiftCount(l, Integer.MAX_VALUE); + } + + public static Long toLongWrapper(Bit b) + { + switch (b.getID()) + { + case 0: + return LONG_ZERO; + case 1: + return LONG_ONE; + default: + return null; + } + } + + public static Long toLongWrapper(BitVector bv) + { + return bv.containsXZ() ? null : new Long(bv.longValue()); + } + + public static Long toLongWrapper(BitVector bv, boolean signed) + { + if (bv.containsXZ()) + { + return null; + } + else + { + long l = bv.longValue(); + if (signed) + { + int len = bv.length(); + if (len < 64) + { + long mask = 1 << (len - 1); + if ((l & mask) != 0) + { + l |= ~(mask - 1); + } + } + } + return new Long(l); + } + } + + public static Long toLongWrapper(Integer i) + { + return i != null ? new Long(i.longValue()) : null; + } + + public static Long toLongWrapper(String s) + { + return new Long(IntOp.toLong(s)); + } + + public static Long toLongWrapper(Object o) + { + if (o instanceof Long || o == null) + { + return (Long) o; + } + else if (o instanceof BitVector) + { + return toLongWrapper((BitVector) o); + } + else if (o instanceof Bit) + { + return toLongWrapper((Bit) o); + } + else if (o instanceof Number) + { + return new Long(((Number) o).longValue()); + } + else if (o instanceof Boolean) + { + return new Long(((Boolean) o).booleanValue() ? 1L : 0L); + } + else if (o instanceof String) + { + return toLongWrapper((String) o); + } + else + { + throw new ClassCastException("Unknown value type"); + } + } + + public static Long add(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + + l2.longValue()) : null; + } + + public static Long subtract(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + - l2.longValue()) : null; + } + + public static Long multiply(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + * l2.longValue()) : null; + } + + public static Long divide(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + / l2.longValue()) : null; + } + + public static Long mod(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + % l2.longValue()) : null; + } + + public static Long negate(Long l) + { + return (l != null) ? new Long(-l.longValue()) : null; + } + + public static Long inc(Long l) + { + return (l != null) ? new Long(l.longValue() + 1) : null; + } + + public static Long dec(Long l) + { + return (l != null) ? new Long(l.longValue() - 1) : null; + } + + public static Long bitwiseAnd(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + & l2.longValue()) : null; + } + + public static Long bitwiseAndNot(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(~(l1.longValue() & l2 + .longValue())) : null; + } + + public static Long bitwiseOr(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + | l2.longValue()) : null; + } + + public static Long bitwiseOrNot(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(~(l1.longValue() | l2 + .longValue())) : null; + } + + public static Long bitwiseXor(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(l1.longValue() + ^ l2.longValue()) : null; + } + + public static Long bitwiseXorNot(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? new Long(~(l1.longValue() ^ l2 + .longValue())) : null; + } + + public static Long bitwiseNot(Long l) + { + return (l != null) ? new Long(~l.longValue()) : null; + } + + public static Long bitwiseReverse(Long l) + { + return (l != null) ? new Long(IntOp.bitwiseReverse(l.longValue())) + : null; + } + + public static Bit reductiveAnd(Long l) + { + return (l != null) ? (l.longValue() == -1 ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveAndNot(Long l) + { + return (l != null) ? (l.longValue() == -1 ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Bit reductiveOr(Long l) + { + return (l != null) ? (l.longValue() == 0 ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Bit reductiveOrNot(Long l) + { + return (l != null) ? (l.longValue() == 0 ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveXor(Long l) + { + return (l != null) ? ((IntOp.bitCount(l.longValue()) & 1) == 1 + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit reductiveXorNot(Long l) + { + return (l != null) ? ((IntOp.bitCount(l.longValue()) & 1) == 1 + ? Bit.ZERO : Bit.ONE) : Bit.X; + } + + public static Long logicalAnd(Long l1, Long l2) + { + return toBoolean(l1) && toBoolean(l2) ? LONG_ONE : LONG_ZERO; + } + + public static Long logicalOr(Long l1, Long l2) + { + return toBoolean(l1) || toBoolean(l2) ? LONG_ONE : LONG_ZERO; + } + + public static Long logicalNegative(Long l) + { + return (l != null) ? (l.longValue() == 0 ? LONG_ONE : LONG_ZERO) : null; + } + + public static Bit equal(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() == l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit notEqual(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() != l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit exactEqual(Long l1, Long l2) + { + return (l1 != null ? l2 != null && l1.longValue() == l2.longValue() + : l2 == null) ? Bit.ONE : Bit.ZERO; + } + + public static Bit exactNotEqual(Long l1, Long l2) + { + return (l1 != null ? l2 == null || l1.longValue() != l2.longValue() + : l2 != null) ? Bit.ONE : Bit.ZERO; + } + + public static Bit wildEqual(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() == l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.ONE; + } + + public static Bit wildNotEqual(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() != l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.ZERO; + } + + public static Bit greater(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() > l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit greaterOrEqual(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() >= l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit less(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() < l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Bit lessOrEqual(Long l1, Long l2) + { + return (l1 != null && l2 != null) ? (l1.longValue() <= l2.longValue() + ? Bit.ONE : Bit.ZERO) : Bit.X; + } + + public static Long shiftLeft(Long l1, Long l2) + { + return (l1 != null) ? new Long(l1.longValue() << toShiftCount(l2, 63)) + : null; + } + + public static Long shiftRight(Long l1, Long l2) + { + return (l1 != null) ? new Long(l1.longValue() >> toShiftCount(l2, 63)) + : null; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/OVAAssert.java b/java/juno-runtime/src/com/newisys/juno/runtime/OVAAssert.java new file mode 100644 index 0000000..dc03123 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/OVAAssert.java @@ -0,0 +1,174 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import com.newisys.ova.OVAAssertAction; +import com.newisys.ova.OVAAssertEventType; + +/** + * An implementation of the OpenVera OVAAssert class. + * + * @author Jon Nall + */ +public class OVAAssert + extends JunoObject +{ + private com.newisys.ova.OVAAssert ovaAssert; + + /** + * Only the OVAEngine class is allowed to create new OVAAssert objects. + * + * @param ovaAssert the underlying Jove OVAAssert + */ + OVAAssert(com.newisys.ova.OVAAssert ovaAssert) + { + this.ovaAssert = ovaAssert; + } + + /** + * Returns the name of this OVAAssert. + * + * @return the name of this OVAAssert + */ + public String GetName() + { + return ovaAssert.getName(); + } + + /** + * Enables the specified OVAEvent to be triggered when the event type + * associated with it occurs. + *

    + * This is currently unimplemented. + * + * @param event the OVAEvent to trigger + * @throws UnsupportedOperationException unconditionally + */ + public void EnableTrigger(OVAEvent event) + { + throw new UnsupportedOperationException( + "OVAAssert.EnableTrigger is not yet supported"); + } + + /** + * Disables the specified OVAEvent from being triggered when the event type + * associated with it occurs. + *

    + * This is currently unimplemented. + * + * @param event the OVAEvent to disable from triggering + * @throws UnsupportedOperationException unconditionally + */ + public void DisableTrigger(OVAEvent event) + { + throw new UnsupportedOperationException( + "OVAAssert.DisableTrigger is not yet supported"); + } + + /** + * Causes this OVAAssert to perform the specified action. Valid values for + * action are {@link OVAEngine#OVA_RESET}, + * {@link OVAEngine#OVA_ENABLE}, and {@link OVAEngine#OVA_DISABLE}. + *

    + * OVA_RESET resets this OVAAssert. All matching attempts are + * cancelled and new attempts will begin on the following cycle. + *

    + * OVA_ENABLE enables this OVAAssert. Matching attempts will + * begin on the following cycle and will stay enabled unless a subsequent + * OVA_DISABLE action is performed. + *

    + * OVA_DISABLE disables this OVAAssert. Matching attempts will + * end immediately and will stay disabled unless a subsequent + * OVA_ENABLE action is performed. + * + * @param action one of OVA_RESET, OVA_ENABLE, + * or OVA_DISABLE + */ + public void DoAction(int action) + { + OVAAssertAction ovaAction = null; + + switch (action) + { + case OVAEngine.OVA_RESET: + ovaAction = OVAAssertAction.Reset; + break; + case OVAEngine.OVA_ENABLE: + ovaAction = OVAAssertAction.EnableNewAttempts; + break; + case OVAEngine.OVA_DISABLE: + ovaAction = OVAAssertAction.DisableNewAttempts; + break; + default: + throw new IllegalArgumentException("Unsupported OVAAssert action: " + + action); + } + + final int attemptID = 0; // attemptID doesn't matter for these actions + ovaAssert.doAction(ovaAction, attemptID); + } + + /** + * Enables counting of successful or failed match attmpts, depending on + * the specified operation. Valid values for op are + * {@link OVAEngine#OVA_SUCCESS} and {@link OVAEngine#OVA_FAILURE}. + *

    + * Note that once counting has started, it cannot be stopped. + * + * @param op one of OVA_SUCCESS or OVA_FAILURE + */ + public void EnableCount(int op) + { + assert (op == OVAEngine.OVA_SUCCESS || op == OVAEngine.OVA_FAILURE); + + OVAAssertEventType eventType = (op == OVAEngine.OVA_SUCCESS) + ? OVAAssertEventType.AttemptSuccess + : OVAAssertEventType.AttemptFailure; + + ovaAssert.enableCount(eventType); + } + + /** + * Retrieves the current success or failure count of this OVAAssert, + * depending on the specified operation. Valid values for op + * are {@link OVAEngine#OVA_SUCCESS} and {@link OVAEngine#OVA_FAILURE}. + * + * @param op one of OVA_SUCCESS or OVA_FAILURE + * @return the number of times this OVAAssert has matched successfully or + * failed to match, depending on op + */ + public int GetCount(int op) + { + assert (op == OVAEngine.OVA_SUCCESS || op == OVAEngine.OVA_FAILURE); + OVAAssertEventType eventType = (op == OVAEngine.OVA_SUCCESS) + ? OVAAssertEventType.AttemptSuccess + : OVAAssertEventType.AttemptFailure; + + // Vera returns an int here + final long count = ovaAssert.getCount(eventType); + return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count; + } + + /** + * @see Object#toString() + */ + public String toString() + { + return ovaAssert.toString(); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/OVAEngine.java b/java/juno-runtime/src/com/newisys/juno/runtime/OVAEngine.java new file mode 100644 index 0000000..58ace48 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/OVAEngine.java @@ -0,0 +1,281 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.newisys.dv.DV; +import com.newisys.ova.OVAConfigSwitch; +import com.newisys.ova.OVAEngineAction; + +/** + * An implementation of the OpenVera OVAEngine class. + * + * @author Jon Nall + */ +public final class OVAEngine + extends JunoObject +{ + // Ova_Bool + public static final int OVA_FALSE = 0; + public static final int OVA_TRUE = 1; + + // Bastardized Ova_ConfigSwitch, Ova_EngAction and Ova_AssertEvent + public static final int OVA_INFO = 0; + public static final int OVA_QUIET = 1; + public static final int OVA_REPORT = 2; + public static final int OVA_MANAGE_ATTEMPTS = 3; + public static final int OVA_RESET = 4; + public static final int OVA_FINISH = 5; + public static final int OVA_TERMINATE = 6; + public static final int OVA_DISABLE = 7; + public static final int OVA_ENABLE = 8; + public static final int OVA_FAILURE = 9; + public static final int OVA_SUCCESS = 10; + public static final int OVA_ALL = 11; + public static final int OVA_NULL = 12; + public static final int OVA_NO_OP = 14; + + // OVA constants + public static final int OVA_CLIENTID_NULL = 0; + public static final int OVA_ASSERTID_NULL = 0; + + // Static members/methods + private static boolean instanceExists = false; + + // Instance members/methods + private final com.newisys.ova.OVAEngine ovaEngine; + private Map assertMap = new HashMap(); + private List assertList = null; + private Iterator assertIterator = null; + + public OVAEngine() + { + if (instanceExists) + { + Juno.error("ERROR: There can be only one instance of OVAEngine"); + } + + assert (DV.simulation.hasOVASupport()); + ovaEngine = DV.simulation.getOVAEngine(); + instanceExists = true; + } + + /** + * Returns the OVA API version as returned by the underlying OVA implementation + * @return a String representing the OVA API Version + */ + public String getApiVersion() + { + return ovaEngine.getApiVersion(); + } + + /** + * Configures this OVAEngine's options. Valid values for op + * are {@link #OVA_INFO}, {@link #OVA_QUIET}, and {@link #OVA_REPORT}. + * Valid values for value are {@link #OVA_TRUE} and + * {@link #OVA_FALSE}. + *

    + * Defaults for the options are:
    + * + * + * + * + * + *
    OptionDefault ValueDescription
    OVA_INFOOVA_FALSELine Information in assertion messages
    OVA_PRINTOVA_FALSEAssertion messages printed at runtime
    OVA_REPORTOVA_TRUEAssertion report at the end of simulation
    + * @param op one of OVA_INFO, OVA_QUIET, or + * OVA_REPORT + * @param value one of OVA_TRUE or OVA_FALSE + */ + public void Configure(int op, int value) + { + assert (op == OVA_INFO || op == OVA_QUIET || op == OVA_REPORT); + assert (value == OVA_TRUE || value == OVA_FALSE); + + OVAConfigSwitch configSwitch = null; + + switch (op) + { + case OVA_INFO: + configSwitch = OVAConfigSwitch.ShowLineInfo; + break; + case OVA_QUIET: + configSwitch = OVAConfigSwitch.Quiet; + break; + case OVA_REPORT: + configSwitch = OVAConfigSwitch.PrintReport; + break; + default: + throw new IllegalArgumentException( + "Unsupported configuration switch: " + op); + } + + ovaEngine.configure(configSwitch, (value == OVA_TRUE) ? true : false); + } + + /** + * Causes this OVAEngine to perform the specified action. Valid values for + * action are {@link #OVA_RESET} and {@link #OVA_TERMINATE}. + *

    + * OVA_RESET resets all OVA assertions and expressions. All + * matching attempts are cancelled and new attempts will begin on the + * following cycle. + *

    + * OVA_TERMINATE terminates all current matching attempts. No + * new attempts to match will started. Attempts to match cannot be started + * again once this action is performed. + * + * @param action one of OVA_RESET or OVA_TERMINATE + */ + public void DoAction(int action) + { + OVAEngineAction ovaAction = null; + + switch (action) + { + case OVA_RESET: + ovaAction = OVAEngineAction.Reset; + break; + case OVA_TERMINATE: + ovaAction = OVAEngineAction.Terminate; + break; + default: + throw new IllegalArgumentException("Unsupported OVAEngine action: " + + action); + } + + ovaEngine.doAction(ovaAction); + } + + /** + * Returns the first assertion from the underlying OVA implementation. If + * there are no OVA assertions in the design, null is returned. + * + * @return the first OVAAssert in the design, or null if no + * OVAAsserts are present + */ + public OVAAssert GetFirstAssert() + { + if (assertList == null) + { + List ovaAssertList = ovaEngine + .getAsserts(); + this.assertList = new ArrayList(ovaAssertList.size()); + for (final com.newisys.ova.OVAAssert a : ovaAssertList) + { + OVAAssert curAssert = findAssert(a); + assert (curAssert != null); + this.assertList.add(curAssert); + } + } + assertIterator = assertList.iterator(); + + return (assertIterator.hasNext()) ? assertIterator.next() : null; + } + + /** + * Returns the next assertion from the underlying OVA implementation. If + * there are no more OVA assertions in the design, null is + * returned. This method may be called repeatedly after + * {@link #GetFirstAssert()}. + * + * @return the next OVAAssert in the design, or null if no more + * OVAAsserts are present + */ + public OVAAssert GetNextAssert() + { + if (assertIterator == null) + { + return GetFirstAssert(); + } + + return (assertIterator.hasNext()) ? assertIterator.next() : null; + } + + /** + * Returns the OVAAssert with the specified name. + * + * @param name the name of the desired OVAAssert + * @return the OVAAssert with the specified name, or null if + * no such OVAAssert exists + */ + public OVAAssert GetAssert(String name) + { + com.newisys.ova.OVAAssert ovaAssert = ovaEngine.getAssert(name); + return findAssert(ovaAssert); + } + + /** + * Enables the specified OVAEvent to be triggered when the event type + * associated with it occurs. + *

    + * This is currently unimplemented. + * + * @param event the OVAEvent to trigger + * @throws UnsupportedOperationException unconditionally + */ + public void EnableTrigger(OVAEvent event) + { + assert (event.eventType == OVA_RESET || event.eventType == OVA_TERMINATE); + + throw new UnsupportedOperationException( + "OVAEngine.EnableTrigger is not yet supported"); + } + + /** + * Disables the specified OVAEvent from being triggered when the event type + * associated with it occurs. + *

    + * This is currently unimplemented. + * + * @param event the OVAEvent to disable from triggering + * @throws UnsupportedOperationException unconditionally + */ + public void DisableTrigger(OVAEvent event) + { + assert (event.eventType == OVA_RESET || event.eventType == OVA_TERMINATE); + + throw new UnsupportedOperationException( + "OVAEngine.DisableTrigger is not yet supported"); + } + + private OVAAssert findAssert(com.newisys.ova.OVAAssert ovaAssert) + { + if (ovaAssert == null) + { + return null; + } + + if (assertMap.containsKey(ovaAssert)) + { + OVAAssert veraAssert = assertMap.get(ovaAssert); + assert (veraAssert != null); + return veraAssert; + } + else + { + OVAAssert veraAssert = new OVAAssert(ovaAssert); + assertMap.put(ovaAssert, veraAssert); + return veraAssert; + } + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/OVAEvent.java b/java/juno-runtime/src/com/newisys/juno/runtime/OVAEvent.java new file mode 100644 index 0000000..8c91280 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/OVAEvent.java @@ -0,0 +1,90 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * An implementation of the OpenVera OVAEvent class. + * + * @author Jon Nall + */ +public class OVAEvent + extends JunoObject +{ + /** + * Publicly usable JunoEvent + */ + public JunoEvent Event = null; + + int eventType; + + /** + * Create an OVA Event associated with the type of event described by the + * event parameter. + *

    + * When used in the context of an OVAEngine object, event can take on the + * values of {@link OVAEngine#OVA_RESET} or {@link OVAEngine#OVA_TERMINATE}. + *

    + * When used in the context of an OVAAssert object, event can take on the + * values of {@link OVAEngine#OVA_RESET}, {@link OVAEngine#OVA_SUCCESS}, + * {@link OVAEngine#OVA_FAILURE}, {@link OVAEngine#OVA_ENABLE}, + * {@link OVAEngine#OVA_DISABLE}, or {@link OVAEngine#OVA_ALL}. + * + * @param eventType the event type to associate with this OVAEvent + */ + public OVAEvent(int eventType) + { + assert (eventType == OVAEngine.OVA_RESET + || eventType == OVAEngine.OVA_TERMINATE + || eventType == OVAEngine.OVA_SUCCESS + || eventType == OVAEngine.OVA_FAILURE + || eventType == OVAEngine.OVA_ENABLE + || eventType == OVAEngine.OVA_DISABLE || eventType == OVAEngine.OVA_ALL); + this.eventType = eventType; + + throw new UnsupportedOperationException("OVAEvent is not yet supported"); + } + + /** + * Wait on the event, blocking the current thread. + * + * @see #GetNextEvent + */ + public void Wait() + { + throw new UnsupportedOperationException( + "OVAEvent.Wait() is not yet supported"); + } + + /** + * Returns the event type that unblocked this thread. If more than one event + * caused the thread to unblock, this method may be called multiple times, + * until {@link OVAEngine#OVA_NULL} is returned. + *

    + * If there are multiple calls to {@link #Wait} without intervening calls to + * getNextEvent, getNextEvent will return the set of event types corresponding + * to the last Wait(). + * + * @return the event type that unblocked this thread or + * {@link OVAEngine#OVA_NULL} if there are no more events. + */ + public int GetNextEvent() + { + throw new UnsupportedOperationException( + "OVAEvent.GetNextEvent() is not yet supported"); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/StringAssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/StringAssocArray.java new file mode 100644 index 0000000..2dc6160 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/StringAssocArray.java @@ -0,0 +1,77 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * String-keyed associative array. + * + * @param value type + * @author Trevor Robinson + */ +public class StringAssocArray + extends AssocArray +{ + /** + * Creates a StringAssocArray. + */ + public StringAssocArray() + { + } + + /** + * Creates a StringAssocArray with the specified default value. If a key is + * requested that does not exist in this array, the default value will be + * returned. + * + * @param nullValue the default value for this array + */ + public StringAssocArray(V nullValue) + { + super(nullValue); + } + + /** + * Creates a StringAssocArray with the specified default value factory. If + * a key is requested that does not exist in this array, the factory will + * be used to instantiate the default value. + * + * @param nullValueFactory the value factory used to create default values + */ + public StringAssocArray(ValueFactory< ? extends V> nullValueFactory) + { + super(nullValueFactory); + } + + /** + * Creates a StringAssocArray which is a copy of the specified array. + * + * @param other the array to copy + */ + public StringAssocArray(StringAssocArray< ? extends V> other) + { + super(other); + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public StringAssocArray clone() + { + return new StringAssocArray(this); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/StringObjectAssocArray.java b/java/juno-runtime/src/com/newisys/juno/runtime/StringObjectAssocArray.java new file mode 100644 index 0000000..ba58b93 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/StringObjectAssocArray.java @@ -0,0 +1,76 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * String-to-Object associative array. + * + * @author Trevor Robinson + */ +public final class StringObjectAssocArray + extends StringAssocArray +{ + /** + * Creates a StringObjectAssocArray. + */ + public StringObjectAssocArray() + { + } + + /** + * Creates a StringObjectAssocArray with the specified default value. If a key is + * requested that does not exist in this StringObjectAssocArray, the default + * value will be returned. + * + * @param nullValue the default value for this StringObjectAssocArray + */ + public StringObjectAssocArray(Object nullValue) + { + super(nullValue); + } + + /** + * Creates a StringObjectAssocArray with the specified ValueFactory. If a key is + * requested that does not exist in this StringObjectAssocArray, nullValueFactory + * will be used to instantiate the default value. + * + * @param nullValueFactory the ValueFactory for this StringObjectAssocArray + */ + public StringObjectAssocArray(ValueFactory< ? > nullValueFactory) + { + super(nullValueFactory); + } + + /** + * Creates a StringObjectAssocArray which is a copy of the specified AssocArray. + * + * @param other the AssocArray to copy + */ + public StringObjectAssocArray(AssocArray other) + { + super(other); + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public StringObjectAssocArray clone() + { + return new StringObjectAssocArray(this); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/StringOp.java b/java/juno-runtime/src/com/newisys/juno/runtime/StringOp.java new file mode 100644 index 0000000..e7b3bf4 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/StringOp.java @@ -0,0 +1,431 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorFormat; + +/** + * String conversion and operation methods referenced by translated code. + * + * @author Trevor Robinson + */ +public final class StringOp +{ + private StringOp() + { + } + + public static int len(String s) + { + return s != null ? s.length() : 0; + } + + public static int getc(String s, int index) + { + int len = len(s); + return index >= 0 && index < len ? s.charAt(index) : 0; + } + + public static String putc(String s, int index, char c) + { + // ignore status + return putc(s, index, c, null); + } + + public static String putc(String s, int index, char c, int[] status_ref) + { + String result = s; + int status; + int len = len(s); + if (index >= 0 && index < len) + { + if (c != 0) + { + StringBuffer buffer = new StringBuffer(s); + buffer.setCharAt(index, c); + result = buffer.toString(); + } + else + { + // putting 0 truncates strings + result = s.substring(0, index); + } + status = JunoString.OK; + } + else + { + status = JunoString.STR_ERR_OUT_OF_RANGE; + } + if (status_ref != null) + { + status_ref[0] = status; + } + return result; + } + + public static String putc(String s, int index, int c) + { + // ignore status + return putc(s, index, c, null); + } + + public static String putc(String s, int index, int c, int[] status_ref) + { + return putc(s, index, (char) c, status_ref); + } + + public static String putc(String s, int index, String c) + { + // ignore status + return putc(s, index, c, null); + } + + public static String putc(String s, int index, String c, int[] status_ref) + { + return putc(s, index, c != null && c.length() > 0 ? c.charAt(0) : 0, + status_ref); + } + + public static String get_status_msg(int status) + { + String[] msgs = { "No error", "Error in regular expression", + "Error: location past end of string" }; + return msgs[status]; + } + + public static int compare(String s1, String s2) + { + if (s1 != null && s2 != null) + { + return s1.compareTo(s2); + } + return (s1 != null ? 1 : 0) - (s2 != null ? 1 : 0); + } + + public static int icompare(String s1, String s2) + { + if (s1 != null && s2 != null) + { + return s1.compareToIgnoreCase(s2); + } + return (s1 != null ? 1 : 0) - (s2 != null ? 1 : 0); + } + + public static int hash(String s, int size) + { + return s != null ? s.hashCode() % size : -1; + } + + public static String substr(String s, int start) + { + int len = len(s); + return (start >= 0 && start < len) ? s.substring(start) : ""; + } + + public static String substr(String s, int start, int end) + { + int len = len(s); + if (end >= len) end = len - 1; + return (start >= 0 && start <= end) ? s.substring(start, end + 1) : ""; + } + + public static int search(String s, String pattern) + { + if (s != null && pattern != null && pattern.length() > 0) + { + return s.indexOf(pattern.toString()); + } + return -1; + } + + public static int match(String s, String pattern) + { + // ignore returned matcher and status + return match(s, pattern, null, null); + } + + public static int match( + String s, + String pattern, + Matcher[] matcher_ref, + int[] status_ref) + { + Matcher matcher = null; + boolean matched = false; + int status = JunoString.OK; + if (s != null && pattern != null) + { + try + { + Pattern p = Pattern.compile(pattern); + matcher = p.matcher(s); + matched = matcher.find(); + } + catch (PatternSyntaxException e) + { + status = JunoString.STR_ERR_REGEXP_SYNTAX; + } + } + if (matcher_ref != null) + { + matcher_ref[0] = matcher; + } + if (status_ref != null) + { + status_ref[0] = status; + } + return matched ? 1 : 0; + } + + public static String prematch(String s, Matcher matcher) + { + if (s != null && matcher != null) + { + try + { + return s.substring(0, matcher.start()); + } + catch (IllegalStateException e) + { + // ignored + } + } + return null; + } + + public static String postmatch(String s, Matcher matcher) + { + if (s != null && matcher != null) + { + try + { + return s.substring(matcher.end()); + } + catch (IllegalStateException e) + { + // ignored + } + } + return null; + } + + public static String thismatch(String s, Matcher matcher) + { + if (s != null && matcher != null) + { + try + { + // returns substring currently at matched location, which is + // NOT necessarily the original string that was matched + return s.substring(matcher.start(), matcher.end()); + } + catch (IllegalStateException e) + { + // ignored + } + } + return null; + } + + public static String backref(String s, Matcher matcher, int index) + { + if (index < 0) + { + throw new IllegalArgumentException("backref() index must be >= 0"); + } + if (s != null && matcher != null && index < matcher.groupCount()) + { + try + { + // returns substring currently at matched location, which is + // NOT necessarily the original string that was matched + ++index; + return s.substring(matcher.start(index), matcher.end(index)); + } + catch (IllegalStateException e) + { + // ignored + } + } + return null; + } + + public static int atoi(String s) + { + if (s != null) + { + String num = scanNumber(s, decPattern); + num = num.replaceAll("_", ""); + return Integer.parseInt(num); + } + return 0; + } + + public static String itoa(int i) + { + return String.valueOf(i); + } + + public static BitVector atohex(String s) + { + if (s != null) + { + String num = scanNumber(s, hexPattern); + BitVectorFormat fmt = new BitVectorFormat(); + fmt.setRadix(16); + return fmt.parse(num); + } + return new BitVector(31, 0); + } + + public static BitVector atooct(String s) + { + if (s != null) + { + String num = scanNumber(s, octPattern); + BitVectorFormat fmt = new BitVectorFormat(); + fmt.setRadix(8); + return fmt.parse(num); + } + return new BitVector(31, 0); + } + + public static BitVector atobin(String s) + { + if (s != null) + { + String num = scanNumber(s, binPattern); + BitVectorFormat fmt = new BitVectorFormat(); + fmt.setRadix(2); + return fmt.parse(num); + } + return new BitVector(31, 0); + } + + private static final Pattern hexPattern = Pattern + .compile("([0-9_]*'h)?[0-9A-Fa-f_]+"); + private static final Pattern decPattern = Pattern + .compile("([0-9_]*'d)?[0-9_]+"); + private static final Pattern octPattern = Pattern + .compile("([0-9_]*'o)?[0-7_]+"); + private static final Pattern binPattern = Pattern + .compile("([0-9_]*'b)?[01_]+"); + + private static String scanNumber(String s, Pattern p) + { + Matcher m = p.matcher(s); + return m.lookingAt() ? m.group() : "0"; + } + + public static String bittostr(BitVector bv) + { + try + { + // Vera ignores \000 bytes so we have to cut them out or else + // they appear as the end of a string to the + // StringBuffer + int numChars = 0; + byte[] bytes = bv.getBytes(); + for (int i = 0; i < bytes.length; ++i) + { + if (bytes[i] != 0) + { + ++numChars; + } + } + + byte[] revBytes = new byte[numChars]; + for (int src = 0, dst = revBytes.length - 1; src < bytes.length; ++src) + { + if (bytes[src] == 0) continue; + revBytes[dst--] = bytes[src]; + } + return new String(revBytes); + } + catch (RuntimeException e) + { + return null; + } + } + + public static String concat(String... strs) + { + int len = 0; + for (final String str : strs) + { + if (str != null) len += str.length(); + } + if (len > 0) + { + final StringBuffer result = new StringBuffer(len); + for (final String str : strs) + { + if (str != null) result.append(str); + } + return result.toString(); + } + return null; + } + + public static String replicate(int count, String str) + { + if (str != null) + { + final StringBuffer result = new StringBuffer(str.length() * count); + for (int i = 0; i < count; ++i) + { + result.append(str); + } + return result.toString(); + } + return null; + } + + public static boolean equals(String s, Object obj) + { + if (obj instanceof JunoString) + { + return obj.equals(s); + } + else if (obj instanceof String) + { + return s != null && s.equals(obj); + } + return obj == null && s == null; + } + + public static int hashCode(String s) + { + return s != null ? s.hashCode() : -1; + } + + public static String toDisplayString(String s) + { + return s != null ? s : "(NULL)"; + } + + public static String toStringOrBlank(String s) + { + return s != null ? s : ""; + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/TestbenchFactory.java b/java/juno-runtime/src/com/newisys/juno/runtime/TestbenchFactory.java new file mode 100644 index 0000000..8dd9345 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/TestbenchFactory.java @@ -0,0 +1,175 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +/** + * Factory used to instantiate a testbench in a polymorphic fashion. + * + * @author Trevor Robinson + */ +public final class TestbenchFactory +{ + private TestbenchFactory() + { + } + + /** + * Instantiates a testbench as specified by +testbenchClass on the command + * line. + *

    + * This is equivalent to create(null, null, null). + * + * @return the new TestBench + */ + public static Object create() + { + return create(null, null, null); + } + + /** + * Instantiates a testbench, using defaultClsName if + * +testbenchClass is not specified on the command line. + *

    + * This is equivalent to create(null, null, defaultClsName). + * + * @param defaultClsName the classname to use if +testbenchClass is not + * specified on the command line + * @return the new TestBench + */ + public static Object create(String defaultClsName) + { + return create(null, null, defaultClsName); + } + + /** + * Instantiates a testbench, using defaultClsName if + * +testbenchClass is not specified on the command line. + * + * @param args an array of arguments to pass to the testbench's constructor + * @param defaultClsName the classname to use if +testbenchClass is not + * specified on the command line + * @return the new TestBench + */ + public static Object create(Object[] args, String defaultClsName) + { + Class[] argTypes = null; + if (args != null) + { + argTypes = new Class[args.length]; + for (int i = 0; i < args.length; ++i) + { + Object arg = args[i]; + if (arg == null) + { + throw new RuntimeException( + "Unable to determine type for null testbench " + + " constructor argument at position " + i); + } + argTypes[i] = arg.getClass(); + } + } + return create(args, argTypes, defaultClsName); + } + + /** + * Instantiates a testbench, using defaultClsName if + * +testbenchClass is not specified on the command line. + * + * @param args an array of arguments to pass to the testbench's constructor + * @param argTypes an array of Class objects that describes the types in + * args + * @param defaultClsName the classname to use if +testbenchClass is not + * specified on the command line + * @return the new TestBench + */ + public static Object create( + Object[] args, + Class[] argTypes, + String defaultClsName) + { + String clsName = Juno.getProperty("testbenchClass=", defaultClsName); + if (clsName == null) + { + throw new RuntimeException("+testbenchClass not specified"); + } + Class< ? > cls; + try + { + cls = Class.forName(clsName); + } + catch (ClassNotFoundException e) + { + throw new RuntimeException("Testbench class '" + clsName + + "' not found", e); + } + Constructor< ? > ctor; + try + { + ctor = cls.getConstructor(argTypes); + } + catch (NoSuchMethodException e) + { + throw new RuntimeException("Constructor '" + + describeConstructor(cls, argTypes) + + "' not found in testbench class", e); + } + Object tb; + try + { + tb = ctor.newInstance(args); + } + catch (InstantiationException e) + { + throw new RuntimeException("Error instantiating testbench class '" + + clsName + "'", e); + } + catch (IllegalAccessException e) + { + throw new RuntimeException("Error accessing constructor '" + + describeConstructor(cls, argTypes) + "' of testbench class", + e); + } + catch (InvocationTargetException e) + { + throw new RuntimeException("Error executing constructor '" + + describeConstructor(cls, argTypes) + "' of testbench class", + e); + } + return tb; + } + + private static String describeConstructor(Class cls, Class[] argTypes) + { + StringBuffer buf = new StringBuffer(80); + buf.append(cls.getName()); + buf.append('('); + if (argTypes != null) + { + for (int i = 0; i < argTypes.length; ++i) + { + if (i > 0) buf.append(", "); + buf.append(argTypes[i].getName()); + } + } + buf.append(')'); + return buf.toString(); + } +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/ValueFactory.java b/java/juno-runtime/src/com/newisys/juno/runtime/ValueFactory.java new file mode 100644 index 0000000..4da2d40 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/ValueFactory.java @@ -0,0 +1,42 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno.runtime; + +/** + * A factory interface that supports creating and copying objects. + * + * @param object type produced by factory + * @author Trevor Robinson + */ +public interface ValueFactory +{ + /** + * Create a new instance of the underlying object. + * + * @return a new instance of the Object + */ + T newInstance(); + + /** + * Create a copy of the specified object. + * + * @param other the object to copy + * @return a copy of other + */ + T copyInstance(T other); +} diff --git a/java/juno-runtime/src/com/newisys/juno/runtime/package-info.java b/java/juno-runtime/src/com/newisys/juno/runtime/package-info.java new file mode 100644 index 0000000..bd49abf --- /dev/null +++ b/java/juno-runtime/src/com/newisys/juno/runtime/package-info.java @@ -0,0 +1,8 @@ +/** + * Provides runtime support for Vera built-in functions, data structures, and + * types. + *

    + * All Vera built-in functions can be found in {@link com.newisys.juno.runtime.Juno}. + */ +package com.newisys.juno.runtime; + diff --git a/java/juno-runtime/src/com/newisys/printf/StringUnescaper.java b/java/juno-runtime/src/com/newisys/printf/StringUnescaper.java new file mode 100644 index 0000000..9f34d26 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/StringUnescaper.java @@ -0,0 +1,120 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +/** + * Provides a static method for unescaping character sequences. + * + * @author Jon Nall + */ +final class StringUnescaper +{ + final static class StringUnscapeException + extends RuntimeException + { + private static final long serialVersionUID = 3256438105882899509L; + private String partialString; + + public StringUnscapeException(String s, String partial) + { + super(s); + partialString = partial; + } + + public String getPartialString() + { + return partialString; + } + } + + public static CharSequence unescape(CharSequence s) + { + // look through regular text to find escape sequences + StringBuilder buf = null; + final int length = s.length(); + for (int i = 0; i < length; ++i) + { + if (s.charAt(i) == '\\') + { + // only create a new StringBuilder if there are actual escapes + if (buf == null) + { + buf = new StringBuilder(s.length()); + buf.append(s.subSequence(0, Math.max(0, i))); + } + + // handle escape sequence + if (i == length - 1) + { + // Vera quits processing at this point + throw new StringUnscapeException( + "Incomplete escape sequence", buf.toString()); + } + else + { + char escapeChar = s.charAt(++i); + + switch (escapeChar) + { + case '\\': + buf.append('\\'); + break; + case 'a': + buf.append((char) 0x07); + break; + case 'b': + buf.append('\b'); + break; + case 'f': + buf.append('\f'); + break; + case 'n': + buf.append('\n'); + break; + case 'r': + buf.append('\r'); + break; + case 't': + buf.append('\t'); + break; + case 'v': + buf.append((char) 0x0B); + break; + case '\n': + break; // line continuation + default: + buf.append(escapeChar); + } + } + } + else if (buf != null) + { + buf.append(s.charAt(i)); + } + } + + if (buf != null) + { + return buf; + } + else + { + return s; + } + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraBaseFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraBaseFormatter.java new file mode 100644 index 0000000..01daf92 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraBaseFormatter.java @@ -0,0 +1,35 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +/** + * Base class for Vera-compatible conversion formatters. + * + * @author Jon Nall + */ +abstract class VeraBaseFormatter + implements ConversionFormatter +{ + protected static final String NULL_STRING = "(NULL)"; + protected static final int NULL_STRING_LENGTH = NULL_STRING.length(); + + protected final void formatNullReference(PrintfSpec spec, StringBuilder buf) + { + buf.append(NULL_STRING); + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraInvalidConversionFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraInvalidConversionFormatter.java new file mode 100644 index 0000000..dfc2744 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraInvalidConversionFormatter.java @@ -0,0 +1,47 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +import com.newisys.printf.PrintfSpec; + +/** + * Formatter used for invalid/unknown conversions. + * + * @author Jon Nall + */ +final class VeraInvalidConversionFormatter + extends VeraBaseFormatter +{ + public int getMaximumLength(PrintfSpec spec) + { + // invalid arguments don't print anything + return 0; + } + + public boolean consumesArg(PrintfSpec spec) + { + // invalid arguments don't consume an argument + return false; + } + + public void format(PrintfSpec spec, StringBuilder buf) + { + // invalid arguments don't print anything + return; + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraNoArgFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraNoArgFormatter.java new file mode 100644 index 0000000..20678cf --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraNoArgFormatter.java @@ -0,0 +1,131 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +import com.newisys.printf.InvalidFormatSpecException; +import com.newisys.printf.PrintfSpec; + +/** + * Formatter used for conversions that do not consume an argument. + * + * @author Jon Nall + */ +final class VeraNoArgFormatter + extends VeraBaseFormatter +{ + public final int getMaximumLength(PrintfSpec spec) + { + switch (Character.toLowerCase(spec.conversionSpec)) + { + case '%': // %% always returns "%" + return 1; + case '_': // %_ always returns "." + return 1; + case 'p': // %p returns "Juno" + return 4; + case 'v': // %v always return "" + return 6; + case 'm': + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + String[] stackLevels = new String[trace.length]; + int levelsToIgnore = (spec.widthIsValid) ? 0 : spec.width; + final String stackTraceHeader = "Stack Trace:\n"; + + // get the appropriate number of stack levels + int stackLevel = 0; + int bufLength = stackTraceHeader.length(); + + for (int i = 0; i < trace.length; ++i) + { + final String className = trace[i].getClassName(); + if (className.startsWith("com.newisys.juno.runtime") + || className.startsWith("com.newisys.printf")) + { + continue; + } + + // remove "width" levels from the printout, but always print + // at least 1 level + if (levelsToIgnore > 0 && i != (trace.length - 1)) + { + --levelsToIgnore; + continue; + } + + String curLevel = trace[i].toString(); + bufLength += curLevel.length(); + bufLength += 6; // "\t at " ... "\n" + stackLevels[stackLevel++] = curLevel; + } + + StringBuilder buf = new StringBuilder(bufLength); + buf.append(stackTraceHeader); + for (final String s : stackLevels) + { + if (s == null) continue; + buf.append("\t at "); + buf.append(s); + buf.append("\n"); + } + + spec.cachedString = buf.toString(); + return bufLength; + default: + // this Formatter should not be registered with any conversions + // except those above + throw new InvalidFormatSpecException( + "Unsupported no-argument format specifier: " + + spec.conversionSpec); + } + } + + public final boolean consumesArg(PrintfSpec spec) + { + // none of these conversions consume an argument + return false; + } + + public void format(PrintfSpec spec, StringBuilder buf) + { + switch (Character.toLowerCase(spec.conversionSpec)) + { + case '%': + buf.append('%'); + break; + case '_': // TODO: Do simulators ever use a path separator other than "."? + buf.append('.'); + break; + case 'p': // TODO: What should Juno return for %p (currently "Juno")? + buf.append("Juno"); + break; + case 'v': // TODO: What should Juno return for %v (currently "")? + buf.append(""); + break; + case 'm': + assert (spec.cachedString != null); + buf.append(spec.cachedString); + break; + default: + // this Formatter should not be registered with any conversions + // except those above + throw new InvalidFormatSpecException( + "Unsupported no-argument format specifier: " + + spec.conversionSpec); + } + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraNumericFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraNumericFormatter.java new file mode 100644 index 0000000..f201b61 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraNumericFormatter.java @@ -0,0 +1,481 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +import com.newisys.juno.runtime.JunoEnum; +import com.newisys.juno.runtime.JunoString; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorFormat; + +/** + * Formatter used for numeric conversions. + * + * @author Jon Nall + */ +final class VeraNumericFormatter + extends VeraBaseFormatter +{ + private static BitVectorFormat bvFormatter = new BitVectorFormat(); + static + { + // don't print length/radix information on BitVectors + bvFormatter.setPrintRadix(false); + bvFormatter.setPrintLength(false); + bvFormatter.setXzCompression(false); + } + + public int getMaximumLength(PrintfSpec spec) + { + int baseLength = 0; + + if (spec.obj instanceof Number || spec.obj instanceof Boolean) + { + spec.cachedLength = getNaturalWidth(spec); + baseLength += spec.cachedLength; + } + else if (spec.obj instanceof Enum< ? >) + { + spec.cachedLength = getNaturalWidth(spec); + baseLength += spec.cachedLength; + baseLength += 11; // "(ENUM_VAR:" ... ")" + } + else if (spec.obj instanceof String || spec.obj instanceof JunoString) + { + final String s; + if (spec.obj instanceof JunoString) + { + s = ((JunoString) spec.obj).toStringOrBlank(); + } + else + { + s = (String) spec.obj; + } + final int length = s.length(); + + baseLength += length + * getNaturalWidth(getRadix(spec.conversionSpec), 8); + } + else if (spec.obj == null) + { + baseLength += NULL_STRING_LENGTH; + } + + return Math.max(baseLength, spec.widthIsValid ? spec.width : 0); + } + + public boolean consumesArg(PrintfSpec spec) + { + // all numeric conversions consume an argument + return true; + } + + public void format(PrintfSpec spec, StringBuilder buf) + { + if (spec.obj == null) + { + formatNullReference(spec, buf); + return; + } + + Number[] values = { null }; + boolean isEnum = spec.obj instanceof Enum< ? >; + if (spec.obj instanceof String || spec.obj instanceof JunoString) + { + final String s; + if (spec.obj instanceof JunoString) + { + s = ((JunoString) spec.obj).toStringOrBlank(); + } + else + { + s = (String) spec.obj; + } + + final int length = s.length(); + if (length == 0) + { + return; + } + + final int radix = getRadix(spec.conversionSpec); + if (radix == 16) + { + // the empty string is returned for hexadecimal conversions + return; + } + + values = new Integer[length]; + final int naturalLength = getNaturalWidth(radix, 8); + + for (int i = 0; i < length; ++i) + { + char c = s.charAt(i); + if (getRadix(spec.conversionSpec) == 2) + { + // for binary: + // the first character in the string occupies the MSB bits in + // the vector, but each byte of the string is reversed + char revC = 0; + for (int j = 0; j < 8; ++j) + { + revC |= ((c >> j) & 1) << (8 - j - 1); + } + values[i] = (int) revC; + } + else + { + values[i] = (int) c; + } + } + + spec = new PrintfSpec(spec.startIdx, spec.endIdx, + spec.conversionSpec, spec.flags, 0, false, 0, false, values[0]); + spec.cachedLength = (radix == 2) ? naturalLength : 0; + } + else if (spec.obj instanceof Enum< ? >) + { + final int ordinal; + if (spec.obj instanceof JunoEnum< ? >) + { + if (!((JunoEnum< ? >) spec.obj).isDefined()) + { + buf.append("(ENUM_VAR:X)"); + return; + } + else + { + ordinal = ((JunoEnum< ? >) spec.obj).toInt(); + } + } + else + { + ordinal = ((Enum< ? >) spec.obj).ordinal(); + } + values[0] = ordinal; + + // force a width of 0 for these values + final PrintfSpec tmpSpec = new PrintfSpec(spec.startIdx, + spec.endIdx, spec.conversionSpec, spec.flags, + spec.cachedLength, true, 0, false, spec.obj); + tmpSpec.cachedLength = spec.cachedLength; + tmpSpec.cachedString = spec.cachedString; + spec = tmpSpec; + } + else if (spec.obj instanceof Boolean) + { + values[0] = ((Boolean) spec.obj).booleanValue() ? Bit.ONE + : Bit.ZERO; + } + else if (spec.obj instanceof Number) + { + values[0] = (Number) spec.obj; + } + else + { + throw new InvalidFormatSpecException( + "Unsupported numeric conversion from type: " + + spec.obj.getClass()); + } + + if (isEnum) + { + assert (values.length == 1); + buf.append("(ENUM_VAR:"); + } + + for (int i = 0; i < values.length; ++i) + { + formatNumber(values[i], spec, buf, i > 0); + } + + if (isEnum) + { + buf.append(")"); + } + } + + private void formatNumber( + Number number, + PrintfSpec spec, + StringBuilder buf, + boolean forceNaturalWidth) + { + final int naturalWidth; + if (spec.cachedLength == -1) + { + naturalWidth = getNaturalWidth(spec); + } + else + { + naturalWidth = spec.cachedLength; + } + + String valueString = null; + final int numBits = PrintfUtils.getWidth(number); + final int radix = getRadix(spec.conversionSpec); + if (number instanceof BitVector) + { + valueString = bvFormatter.format((BitVector) number, radix); + } + else if (number instanceof Bit) + { + Bit b = (Bit) number; + if (radix == 2) + { + valueString = b.toString().toLowerCase(); + } + else if (radix == 8 || radix == 10) + { + if (b.isXZ()) + { + valueString = "?"; + } + else + { + valueString = b.toString(); + } + } + else + { + assert (radix == 16); + valueString = b.toString(); + } + } + else + { + long value = number.longValue(); + // conversions to binary, octal, or hex get printed as unsigned + // values + boolean printUnsigned = (!isSignedConversion(spec) || !isSignedType(spec.obj)); + if (printUnsigned && numBits < 64) + { + value &= ((1L << numBits) - 1); + } + + if (radix == 2) + { + valueString = Long.toBinaryString(value); + } + else if (radix == 8) + { + valueString = Long.toOctalString(value); + } + else if (radix == 10) + { + valueString = Long.toString(value); + } + else if (radix == 16) + { + valueString = Long.toHexString(value); + } + } + + final char leadingChar = valueString.charAt(0); + final boolean unknownDecimal = leadingChar == '?' + && isDecimal(spec.conversionSpec); + assert (!unknownDecimal || valueString.length() == 1); + + // use the maximum of the natural width and the specified width unless + // the specified width is zero, in which case use the minimum width + final int width; + final int length = valueString.length(); + if (unknownDecimal) + { + width = 0; + } + else if (forceNaturalWidth || !spec.widthIsValid) + { + width = naturalWidth; + } + else if (spec.width > length) + { + width = spec.width; + } + else + { + width = length; + } + + final int numPaddingChars = Math.max(width - length, 0); + final boolean leftJustify = spec.flags + .contains(PrintfFlag.LEFT_JUSTIFY); + final char paddingChar = getPaddingChar(spec, leadingChar); + if (!leftJustify) + { + for (int i = 0; i < numPaddingChars; ++i) + { + buf.append(paddingChar); + } + } + buf.append(valueString); + if (leftJustify) + { + for (int i = 0; i < numPaddingChars; ++i) + { + buf.append(' '); + } + } + } + + private int getRadix(char conversionSpec) + { + switch (Character.toLowerCase(conversionSpec)) + { + case 'b': + return 2; + case 'o': + return 8; + case 'd': + case 'i': + case 'u': + return 10; + case 'h': + case 'x': + return 16; + default: + throw new InvalidFormatSpecException( + "Unsupported numeric conversion: " + conversionSpec); + } + } + + private boolean isSignedConversion(PrintfSpec spec) + { + switch (Character.toLowerCase(spec.conversionSpec)) + { + case 'd': + case 'i': + return true; + default: + return false; + } + } + + private boolean isSignedType(Object obj) + { + // BitVector and Bit are unsigned types. All other types are signed + if (obj instanceof BitVector) + { + return false; + } + else if (obj instanceof Bit) + { + return false; + } + + return true; + } + + private boolean isDecimal(char conversionSpec) + { + switch (Character.toLowerCase(conversionSpec)) + { + case 'd': + case 'i': + case 'u': + return true; + default: + return false; + } + } + + private int getNaturalWidth(PrintfSpec spec) + { + int radix = getRadix(spec.conversionSpec); + int numBits = 0; + + final Object obj = spec.obj; + int extraWidth = 0; + if (obj instanceof Enum< ? >) + { + numBits = 32; + } + else if (obj instanceof String) + { + numBits = ((String) obj).length() * 8; + } + else if (obj instanceof JunoString) + { + numBits = ((JunoString) obj).toStringOrBlank().length() * 8; + } + else + { + numBits = PrintfUtils.getWidth(obj); + if (isDecimal(spec.conversionSpec) && isSignedType(spec.obj)) + { + // decimal conversions from numeric types have a natural width + // of 11 although it calculates as 10. possibly for the sign + // character? although that doesn't make sense for %u as it also + // has a natural width of 11. + extraWidth = 1; + } + } + + return getNaturalWidth(radix, numBits) + extraWidth; + } + + private int getNaturalWidth(final int radix, final int numBits) + { + double ln2radix = Math.log(radix) / Math.log(2); + return (int) (Math.ceil(numBits / ln2radix)); + } + + protected final char getPaddingChar(PrintfSpec spec, char leadingChar) + { + char paddingChar = ' '; + + if (spec.obj instanceof Enum< ? >) + { + // enums converted to numeric values are padded with zero + // unless they're converted to decimal, in which case spaces are + // used. + paddingChar = (isDecimal(spec.conversionSpec)) ? ' ' : '0'; + } + else if (spec.obj instanceof Number) + { + if (!Character.isDigit(leadingChar)) + { + final char lowerLeadingChar = Character + .toLowerCase(leadingChar); + + if (lowerLeadingChar == 'x' || lowerLeadingChar == 'z') + { + paddingChar = leadingChar; + } + else if (Character.isLetter(leadingChar)) + { + paddingChar = '0'; + } + else + { + paddingChar = ' '; + } + } + else if (isDecimal(spec.conversionSpec)) + { + paddingChar = ' '; + } + else + { + paddingChar = '0'; + } + } + + return paddingChar; + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraPrintfFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraPrintfFormatter.java new file mode 100644 index 0000000..fc53d60 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraPrintfFormatter.java @@ -0,0 +1,255 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +import com.newisys.printf.ConversionFormatter; +import com.newisys.printf.PrintfFlag; +import com.newisys.printf.PrintfFormatter; + +//Vera's printf function is a bit inconsistent, with quite a few corner cases. +//What follows is a list of cases I've found where Vera's printf is either +//not consistent or differs from what I expected. I've tried to be thorough, +//but some cases may be missing. +// +//Conversion specifiers. Vera adds the following: +// %m prints a stack track. it takes a width specifier which specifies how +// many levels of stack to print. if the stack has N levels where the 0th +// level is the entry to the thread and the Nth level is the printf call +// an unspecified width or width of 0 will print stack levels [0,N). a +// width of 1 will print stack levels [0,N-1) and so on. if the width is +// greater than N, stack level 0 will be printed by itself. +// +// %p prints the program name. vera seems to always print a blank string +// for this. a width specification has no effect +// +// %v prints the instance path of the shell. for vera_cs runs this prints +// "vera_cs". for vcs runs, this prints something like "test_top.vshell" +// a width specification has no effect +// +// %_ prints the simulation path separator. i don't know that this is ever +// anything besides ".". a width specification has no effect +// +// %u this is identical to %d except all values are printed as unsigned and +// the '+' flag is not respected +// +// Any conversion specifier that is not defined silently returns the empty +// string and does not consume an argument. +// +//Enumeration printing +// enum values can be printed as either strings (%s) or numeric values. when +// printed as strings, the enum value name is printed. this is equivalent +// to java's Enum.toString(). when converted to a numeric value, the value +// printed is "(ENUM_VAR: XXXX)" where XXXX is the enum's value (which is +// always 32 bits). if the enum has not been initialized, "(ENUM_VAR:X)" is +// printed. the formatting of the enum's numeric value is handled +// identically to printing any other type of number. The '-' and '+' flags +// are respected when printing enums as numbers, however ' ' is not. Also, +// any width specifier is disregarded and the numeric value is fully padded. +// The '-' flag as well as width specifiers are respected when printing an +// enum as a string. Enumerations printed as characters (%c) print the empty +// string +// +//String conversions +//Character width disrespect +//The %c specifier does not respect width. When %c is specified, exactly one +//character is printed, regardless of any width specifier. +// +//Numeric conversions +// Octal Padding +// When octal numbers are printed, they are zero-padded to be a multiple of +// 3 bits. This means that 4'bx_x10 gets promoted to 6'b00x_x10 which prints +// as "??" rather than the expected "X?" +// +// Decimal conversion with X/Z values +// Values containing X/Z, when printed as decimal print "?", no matter their +// length. +// +// Uninitialized integers are printed as "X", no matter the numeric conversion +// specifier. Width is ignored except in the case of binary conversions, in +// which case a non-zero width results in "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +// (32 "x" values). +// +// String Reversal +// When strings are printed as numeric values, each character in the string +// is converted to its ASCII value. For binary conversions, each byte of the +// value is then bit-reversed before printing. For instance, the string "AF" is +// 16'h4146 or 16'b0100_0001_0100_0110. However if "AF" was printed as a binary +// value (%b), "1000_0010_0110_0010" would be printed (underscores included +// only for readability). Note that this is equivalent to +// (><(16'h41)) << 8 | (><(16'h46)). +// +//Width specifiers +// If the width specifier is 0 or less than the natural width, the minimal +// number of characters required to print the value are used. Leading +// X/Z characters are collapsed to exactly one X/Z. Leading zero characters +// are removed entirely unless this would leave an empty string. In this +// case, exactly one 0 is left. +// Else if the type being printed is an enum and the conversion specifier is +// numeric, the width specifier is not respected and the value is padded. +// Else if the type being printed is not an integer, and the conversion +// specifier is decimal (%d, %i, %u), no padding is performed. +// Else padding is performed. For decimal conversions, the padding +// consists of spaces. For non-decimal conversions, values are zero-padded +// if the MSB character is 0-9, X, or Z. For non-decimal conversions where +// the MSB character is '?', spaces are used to pad. +// +//Flag specifiers +// ' ' flag +// According to the VUM, the ' ' flag should prepend a space character +// to a positive value printed via %d or %i. However, there seem to be a few +// bugs in the vera implementation as of vera 6.3.30. Notably: +// - A space is inserted only if the type being printed is an integer or +// string +// - When a string is printed and the space flag is present, a space is +// inserted before each byte's value. For instance: +// printf("% d", "AF") will print " 65 70" +// +// '+' flag +// For strings, the '+' flag has the same oddity as the ' ' flag: +// printf("%+d", "AF") will print "+65+70". Note that the +/' ' flags are only +// respected for signed, decimal conversions. +// +//Null arguments +// If an argument passed to printf is null or void, the string "(NULL)" is +// printed and the argument is consumed. + +/** + * Vera-compatible printf formatter. + * + * @author Jon Nall + */ +public final class VeraPrintfFormatter + extends PrintfFormatter +{ + // Static vera formatters + private static ConversionFormatter vnFormatter = new VeraNumericFormatter(); + private static ConversionFormatter vsFormatter = new VeraStringFormatter(); + private static ConversionFormatter vNoArgFormatter = new VeraNoArgFormatter(); + private static ConversionFormatter vInvalidFormatter = new VeraInvalidConversionFormatter(); + + private static ConversionFormatter[] formatters = new ConversionFormatter[128]; + + private boolean leaveEscapes; + + public VeraPrintfFormatter(boolean leaveEscapes) + { + this.leaveEscapes = leaveEscapes; + + for (char c = 0; c < 128; ++c) + { + formatters[c] = getFormatter(c); + } + } + + private final boolean isNumericConversion(char conversionSpec) + { + switch (Character.toLowerCase(conversionSpec)) + { + case 'b': + case 'd': + case 'h': + case 'i': + case 'o': + case 'u': + case 'x': + return true; + default: + return false; + } + } + + private boolean isStringConversion(char conversionSpec) + { + switch (Character.toLowerCase(conversionSpec)) + { + case 'c': + case 's': + return true; + default: + return false; + } + } + + private final boolean isValidConversion(char conversionSpec) + { + // vera adds some conversion specs + switch (Character.toLowerCase(conversionSpec)) + { + case '%': // escaped '%' + case 'm': // stack trace + case 'p': // program name + case 'v': // shell instance name + case '_': // simulator path separator character + return true; + default: + return isNumericConversion(conversionSpec) + || isStringConversion(conversionSpec); + } + } + + @Override + protected final PrintfFlag getFlag(char conversionSpec) + { + // Vera supports only a subset of the normal printf flags + switch (conversionSpec) + { + case '#': + return PrintfFlag.ALTERNATE_FORM; + case '-': + return PrintfFlag.LEFT_JUSTIFY; + case ' ': + return PrintfFlag.SPACE_BEFORE_POSITIVE_VALUE; + case '+': + return PrintfFlag.PRINT_SIGN; + default: + return null; + } + } + + @Override + protected final ConversionFormatter getFormatter(char conversionSpec) + { + if (isNumericConversion(conversionSpec)) + { + return vnFormatter; + } + else if (isStringConversion(conversionSpec)) + { + return vsFormatter; + } + else if (isValidConversion(conversionSpec)) + { + return vNoArgFormatter; + } + else + { + return vInvalidFormatter; + } + } + + @Override + protected final CharSequence postProcess(CharSequence buf) + { + if (leaveEscapes) + { + return buf; + } + + return StringUnescaper.unescape(buf); + } +} diff --git a/java/juno-runtime/src/com/newisys/printf/VeraStringFormatter.java b/java/juno-runtime/src/com/newisys/printf/VeraStringFormatter.java new file mode 100644 index 0000000..35a20a3 --- /dev/null +++ b/java/juno-runtime/src/com/newisys/printf/VeraStringFormatter.java @@ -0,0 +1,148 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.printf; + +import com.newisys.juno.runtime.JunoString; +import com.newisys.printf.PrintfSpec; + +/** + * Formatter used for string conversions. + * + * @author Jon Nall + */ +final class VeraStringFormatter + extends VeraBaseFormatter +{ + // for some cases we fall back to the base formatter + private static final StringFormatter sFormatter = new StringFormatter(); + + public final int getMaximumLength(PrintfSpec spec) + { + final Object o = spec.obj; + if (o == null) + { + spec.cachedString = NULL_STRING; + spec.cachedLength = NULL_STRING_LENGTH; + return spec.cachedLength; + } + else if (Character.toLowerCase(spec.conversionSpec) == 'c') + { + // Vera doesn't respect width for characters + spec.cachedLength = 1; + return 1; + } + else if (o instanceof String) + { + spec.cachedLength = ((String) o).length(); + spec.cachedString = (String) o; + } + else if (o instanceof JunoString) + { + String s = ((JunoString) o).toStringOrNull(); + if (s == null) + { + spec.cachedString = NULL_STRING; + spec.cachedLength = NULL_STRING_LENGTH; + return spec.cachedLength; + } + else + { + spec.cachedLength = s.length(); + spec.cachedString = s; + } + } + else if (o instanceof Number) + { + final int length = PrintfUtils.getWidth(o); + spec.cachedLength = (length / 8) + ((length % 8 == 0) ? 0 : 1); + } + else + { + String s = spec.obj.toString(); + spec.cachedLength = s.length(); + spec.cachedString = s; + } + + assert (spec.cachedLength != -1); + return Math + .max(spec.cachedLength, (spec.widthIsValid ? spec.width : 0)); + } + + public final boolean consumesArg(PrintfSpec spec) + { + // all string conversions consume an argument + return true; + } + + public final void format(PrintfSpec spec, StringBuilder buf) + { + final boolean doChar = Character.toLowerCase(spec.conversionSpec) == 'c'; + final boolean doString = Character.toLowerCase(spec.conversionSpec) == 's'; + assert (doChar || doString); + + // length should always be cached in this formatter + assert (spec.cachedLength != -1); + + if (spec.obj == null) + { + formatNullReference(spec, buf); + } + else if (doChar) + { + // special/optimized cases -- %c with cachedString + if (spec.obj instanceof Enum< ? >) + { + // %c on enumerations prints nothing + } + else if (spec.cachedString != null) + { + if (spec.cachedString.length() == 0) + { + // %c on the empty string appends nothing + } + else + { + buf.append(spec.cachedString.charAt(0)); + } + } + else + { + // override the PrintfSpec for this value to have a width of + // zero + final PrintfSpec charSpec = new PrintfSpec(spec.startIdx, + spec.endIdx, Character.toLowerCase(spec.conversionSpec), + spec.flags, 0, true, 0, false, spec.obj); + charSpec.cachedLength = spec.cachedLength; + charSpec.cachedString = spec.cachedString; + sFormatter.format(charSpec, buf); + } + } + else + { + // otherwise, Vera strings format the same as other strings, but + // make sure to use a lowercase conversion specifier + final PrintfSpec veraSpec = new PrintfSpec(spec.startIdx, + spec.endIdx, Character.toLowerCase(spec.conversionSpec), + spec.flags, spec.width, spec.widthIsValid, spec.precision, + spec.precisionIsValid, spec.obj); + veraSpec.cachedLength = spec.cachedLength; + veraSpec.cachedString = spec.cachedString; + sFormatter.format(veraSpec, buf); + } + } +} diff --git a/java/juno-samples/build.xml b/java/juno-samples/build.xml new file mode 100644 index 0000000..6abfc17 --- /dev/null +++ b/java/juno-samples/build.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/juno-samples/changesimulator.sh b/java/juno-samples/changesimulator.sh new file mode 100644 index 0000000..0be5128 --- /dev/null +++ b/java/juno-samples/changesimulator.sh @@ -0,0 +1,35 @@ +#!/bin/sh + +SIM=$1 +PLI4J_HOME=$2 + +if [ "$SIM" == "" -o "$PLI4J_HOME" == "" ] +then + echo "usage: $0 " + exit 1 +fi + +PLI4J_CONF=${PLI4J_HOME}/comp/pli4j/src/Configuration.h +IS_NOT_VCS=`grep "//#define SIMULATOR_VCS" ${PLI4J_CONF}` + +if [ "$SIM" == "vcs" ] +then + if [ "$IS_NOT_VCS" != "" ] + then + echo "Not configured for VCS. Configuring for VCS." + sed -i -e "s/\/\/#define SIMULATOR_VCS/#define SIMULATOR_VCS/" ${PLI4J_CONF} + else + echo "Configured for VCS. No changes are required" + fi +else + # check if vcs is current simulator. if so, comment that out + if [ "$IS_NOT_VCS" == "" ] + then + echo "Configured for VCS. Deonfiguring for VCS." + sed -i -e "s/#define SIMULATOR_VCS/\/\/#define SIMULATOR_VCS/" ${PLI4J_CONF} + else + echo "Not configured for VCS. No changes are required" + fi +fi + + diff --git a/java/juno-samples/floptest/dut.if.vrh b/java/juno-samples/floptest/dut.if.vrh new file mode 100644 index 0000000..2251ec1 --- /dev/null +++ b/java/juno-samples/floptest/dut.if.vrh @@ -0,0 +1,16 @@ +#ifndef _INTERFACE_DUT_ +#define _INTERFACE_DUT_ + +#define OUTPUT_EDGE PHOLD +#define OUTPUT_SKEW #1 +#define INPUT_SKEW #-1 +#define INPUT_EDGE PSAMPLE + + interface dut { + input clk CLOCK hdl_node "dut_test_top.clk"; + input [31:0] num_clks INPUT_EDGE INPUT_SKEW hdl_node "dut_test_top.num_clks"; + output [31:0] flop_in OUTPUT_EDGE OUTPUT_SKEW hdl_node "dut_test_top.flop_in"; + input [31:0] flop_out INPUT_EDGE INPUT_SKEW hdl_node "dut_test_top.flop_out"; + } // end of interface dut + +#endif diff --git a/java/juno-samples/floptest/dut.test_top.v b/java/juno-samples/floptest/dut.test_top.v new file mode 100644 index 0000000..a56cca2 --- /dev/null +++ b/java/juno-samples/floptest/dut.test_top.v @@ -0,0 +1,32 @@ +module dut_test_top; + parameter simulation_cycle = 100 ; + + reg SystemClock ; + wire clk ; + wire [31:0] num_clks ; + wire [31:0] flop_in ; + wire [31:0] flop_out ; + assign clk = SystemClock ; + + vera_shell vshell(Systemclock); + +`ifdef emu +/* DUT is in emulator, so not instantiated here */ +`else + dut dut( + .clk ( clk ), + .num_clks ( num_clks ), + .flop_in ( flop_in ), + .flop_out ( flop_out ) + ); +`endif + + initial begin + SystemClock = 0 ; + forever begin + #(simulation_cycle/2) + SystemClock = ~SystemClock ; + end + end + +endmodule diff --git a/java/juno-samples/floptest/dut.v b/java/juno-samples/floptest/dut.v new file mode 100644 index 0000000..1e023c3 --- /dev/null +++ b/java/juno-samples/floptest/dut.v @@ -0,0 +1,20 @@ +module dut(clk, num_clks, flop_in, flop_out); + input clk; + input[31:0] flop_in; + output[31:0] num_clks; + output[31:0] flop_out; + reg[31:0] num_clks; + reg[31:0] flop_out; + + initial + begin + num_clks = 0; + end + + always @(posedge clk) + num_clks = num_clks + 1; + + always @(posedge clk) + flop_out = flop_in; + +endmodule diff --git a/java/juno-samples/floptest/floptest.dat b/java/juno-samples/floptest/floptest.dat new file mode 100644 index 0000000..b4baf50 --- /dev/null +++ b/java/juno-samples/floptest/floptest.dat @@ -0,0 +1,11 @@ +2fd9a2ac +7377581d +ba1adbf +131ab2c9 +3aae165d +05e1726a +17bf9d46 +03069443 +56d61f5f +4b378015 + diff --git a/java/juno-samples/floptest/floptest.vr b/java/juno-samples/floptest/floptest.vr new file mode 100644 index 0000000..9882acf --- /dev/null +++ b/java/juno-samples/floptest/floptest.vr @@ -0,0 +1,299 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + * + * + * Vera program that shows off various features including: + * + * Signal sampling and driving + * Random constraints + * Pass by reference + * Backwards bit indices (e.g. myreg[4:7]) + * Various built-in functions (printf, error, get_time) + * Pre-processor macros + * File I/O + * Mailboxes + * Trigger/Sync + * Associative Arrays + */ + +#include + +// include interfaces +#include "dut.if.vrh" + +/* Define an assert macro to be used by vera code. + * + * Note that Juno treats 'assert' as a built-in function and will translate + * any usage to use the assert mechanism in Java. For this reason, we wrap + * the macro definition in an #ifdef __JUNO__. The __JUNO__ symbol is defined + * when Juno is analyzing a Vera source file + */ +#ifndef __JUNO__ +#define assert(expr) if ((!(expr)) !== 0) \ + error("Assertion failed(%s, line %0d): %s\n", __FILE__, __LINE__, "expr") +#endif + +// define ports, binds here if necessary +port dutPort +{ + clk; + numClks; + flopIn; + flopOut; +} + +bind dutPort dutBind +{ + clk dut.clk; + numClks dut.num_clks; + flopIn dut.flop_in; + flopOut dut.flop_out; +} + +class FlopTest +{ + rand bit[31:0] value; + rand bit[3:0] bit_7_4; + rand reg[1:0] bit_1_0; // note use of alternate 'reg' keyword + + constraint cc1 + { + (value & 'hc) != 0; + bit_7_4 < 'h6; + bit_1_0 >= 'b1; + } + + task post_randomize() + { + value[7:4] = bit_7_4; + value[1:0] = bit_1_0; + + if(bit_7_4 >= 6) + { + error("Constraint solving failed: bit_7_4 must be < 6. Actual: 0x%x\n", + bit_7_4); + } + else if(bit_1_0 < 1) + { + error("Constraint solving failed: bit_1_0 must be >= 1. Actual: 0x%x\n", + bit_1_0); + } + else if(value[2:3] == 0) + { + // note backwards indices in this else if condition + error("Constraint solving failed: value[2:3] must be != 0. Actual: 0x%x\n", + value[3:2]); + } + } + + task run(var integer count, string filename) + { + this.runRandom(count); + this.runFromFile(filename); + } + + task runRandom(var integer count) + { + integer actVal; + integer value_1; + integer origCount = count; + for(; count >= 0; --count) + { + integer status = 0; + value_1 = value; + status = randomize(); + dutBind.$flopIn = value; + @(posedge dutBind.$clk); + actVal = dutBind.$flopOut; + + if(value_1 !== actVal) + { + printf("%0d: ERROR(FlopTest): Expected 0x%08x, Observed: 0x%08x\n", + get_time(LO), value_1, actVal); + return; + } + } + + // put X's on the flop + dutBind.$flopIn = 'hx; + @(posedge dutBind.$clk); + + printf("Random FlopTest completed %0d iterations succesfully\n", origCount); + } + + task runFromFile(string filename) + { + integer count = 0; + integer actVal; + bit success = 1; + bit[31:0] driveVal, driveVal_1; + integer fd = fopen(filename, "r", SILENT); + assert(fd != 0); + + while(1) + { + driveVal_1 = driveVal; + driveVal = freadh(fd); + dutBind.$flopIn = driveVal; + @(posedge dutBind.$clk); + actVal = dutBind.$flopOut; + + if(driveVal_1 !== actVal) + { + success = 0; + break; + } + + if(feof(fd) == 1) break; + ++count; + } + if(success) + printf("File-based FlopTest completed %0d iterations succesfully\n", count); + else + printf("%0d: ERROR(FlopTest): Expected 0x%08x, Observed: 0x%08x\n", + get_time(LO), driveVal_1, actVal); + fclose(fd); + } +} + +program main +{ + runAllTests(); +} + +task runAllTests() +{ + shadow integer count = 10; + + fork + { + // test basic sampling of a signal + test_sample(count); + } + { + // test driving a flop and then sampling that value + // also shows off getting a plusarg + // also shows built-in bittostr functionality + // also shows off random constraints + // also shows off file I/O + FlopTest ft = new; + bit[2047:0] fname = get_plus_arg(STR, "filename="); + string fnamestr = ""; + fnamestr.bittostr(fname); + ft.run(count, fnamestr); + } + { + // test passing by reference (test_passbyvar declares its parameter + // as var) + integer value = 4; + test_passbyvar(value); + if(value != 3) + { + assert(value == 3); + } + else + { + printf("pass by var was successful\n"); + } + } + { + // test 2 threads passing data via a mailbox + test_mailboxes(count); + } + { + integer status = test_triggersync(); + assert(status == 1); + } + { + test_assocarrays(); + } + join all +} + +task test_sample(integer count) +{ + integer i = 0; + for(i = 0; i < count; ++i) + { + @(posedge dutBind.$clk); + printf("NumClks: %0d\n", dutBind.$numClks); + } +} + +task test_passbyvar(var integer value) +{ + --value; +} + +task test_mailboxes(integer count) +{ + integer mb = alloc(MAILBOX, 0, 1); + shadow integer i; + fork + { + for(i = 0; i < count; ++i) + { + integer expVal = i; + integer actVal; + mailbox_get(WAIT, mb, actVal); + assert(actVal === expVal); + } + } + { + for(i = 0; i < count; ++i) + { + @(posedge dutBind.$clk); + mailbox_put(mb, i); + } + } + join all + printf("Mailbox test passed\n"); +} + +function integer test_triggersync() +{ + event e; + test_triggersync = 1; + + fork + { + sync(ALL, e); + } + { + @(posedge dutBind.$clk); + trigger(e); + } + join all + + printf("Trigger/Sync test passed\n"); +} + +task test_assocarrays() +{ + string strArr[]; + integer numElts = 0; + + strArr[4] = "foo"; + strArr[100] = "bar"; + + numElts = assoc_index(CHECK, strArr); + if(numElts != 2) + { + error("strArr must contain 2 elements. Actual: %0d\n", numElts); + } + assert(strArr[4] == "foo"); + assert(strArr[100] == "bar"); + + printf("AssocArray test passed\n"); +} diff --git a/java/juno-samples/floptest/makefile b/java/juno-samples/floptest/makefile new file mode 100644 index 0000000..f3169b6 --- /dev/null +++ b/java/juno-samples/floptest/makefile @@ -0,0 +1,18 @@ +.PHONY: clean run + +default: run + +run: simv + ./simv +vera_load=floptest.vro +filename=floptest.dat + +simv: dut.v dut.test_top.v floptest.vro + $(VCS_HOME)/bin/vcs -vera dut.v dut.test_top.v floptest_shell.v + +dut.test_top.v: dut.v + $(VERA_HOME)/bin/vera -tem -t dut -c clk dut.v + +floptest.vro: floptest.vr + $(VERA_HOME)/bin/vera -cmp -vlog floptest.vr + +clean: + rm -rf csrc simv* vcs.key *.vro *tmp *_shell.v diff --git a/java/juno-samples/makefile b/java/juno-samples/makefile new file mode 100644 index 0000000..f49a5dc --- /dev/null +++ b/java/juno-samples/makefile @@ -0,0 +1,149 @@ +# Determine JOVE_HOME and PLI4J_HOME +ifndef JOVE_HOME + $(error Please set JOVE_HOME to point to the root of a Jove installation) +endif +ifndef PLI4J_HOME + ifneq ($(wildcard $(JOVE_HOME)/native),) + PLI4J_HOME := $(JOVE_HOME)/native + else + $(error Cannot find $(JOVE_HOME)/native) + endif +endif + +# Ensure VERA_HOME is set correctly +ifeq ($(wildcard $(VERA_HOME)/include),) + $(error Please set VERA_HOME to point to the root of a Vera installation) +endif + +# Ensure JUNO_HOME is set correctly +ifeq ($(wildcard $(JUNO_HOME)/bin),) + $(error Please set JUNO_HOME to point to the root of a Juno installation) +endif + +# include host.mak to get SEP variable and escape it if it's a semicolon +include $(PLI4J_HOME)/tools/util.mak +include $(PLI4J_HOME)/tools/host.mak + +# include cdefs.mak to get DLL_(PREFIX|SUFFIX) +include $(PLI4J_HOME)/tools/cdefs.mak + +# Windows uses semicolon delimited classpaths, but in cygwin, the semicolons +# need to be escaped +ifeq ($(SEP),;) + SEP := \; +endif + +ifeq ($(HOST_OS),win32) + JUNO := $(JUNO_HOME)/bin/juno.bat +else + JUNO := $(JUNO_HOME)/bin/juno +endif + +# makefile for building the jove-samples +.PHONY: java clean clean-verilog change_simulator require_simulator + +JOVE_PROJECTS := jove langschema langschema-java langschema-jove newisys-utils randsolver +ifneq ($(wildcard $(JOVE_HOME)/bin/jove.jar),) + # binary distribution + CLASSPATH_PREFIX := $(JOVE_HOME)/bin/ + CLASSPATH_SUFFIX := .jar +else + # source distribution + CLASSPATH_PREFIX := $(JOVE_HOME)/java/ + CLASSPATH_SUFFIX := /bin +endif +JOVE_CLASSPATH := $(subst $(SPACE),$(SEP),$(foreach proj,$(JOVE_PROJECTS),$(CLASSPATH_PREFIX)$(proj)$(CLASSPATH_SUFFIX)) bin) + +JUNO_PROJECTS := juno-runtime +JUNO_CLASSPATH := $(subst $(SPACE),$(SEP),$(foreach proj,$(JUNO_PROJECTS),$(JUNO_HOME)/java/$(proj)/bin)) + +CLASSPATH := $(JOVE_CLASSPATH):$(JUNO_CLASSPATH) + +SIMULATOR ?= vcs +SIMULATOR_FLAGS := +javaclasspath=$(CLASSPATH) + +RTL_SAMPLES := floptest +BEH_SAMPLES := xmlreader +SAMPLES := $(BEH_SAMPLES) $(RTL_SAMPLES) + + +default: + @echo Please choose from the following sample targets: $(SAMPLES) + +xmlreader: compile-xmlreader + java -cp $(CLASSPATH) com.newisys.behsim.BehavioralLauncher \ + juno.samples.xmlreader.xmlreader.xmlreadertest.XmlreadertestProgram \ + +filename=xmlreader/src/xmlreader/xmlreadertest/test.xml + +floptest: compile-floptest change_simulator + make -C $(PLI4J_HOME) SIMULATOR=$(SIMULATOR) pli4j + $(SIMULATOR_PATH)/$(SIMULATOR) $(SIMULATOR_FLAGS) \ + +javaclass=juno.samples.floptest.FloptestProgram \ + +filename=floptest/floptest.dat \ + floptest/dut.v floptest/dut.test_top.v src/juno/samples/floptest/floptest_shell.v + +require_simulator: +# require a simulator if the target includes an RTL example + ifneq ($(filter $(RTL_SAMPLES),$(MAKECMDGOALS)),) + ifeq ($(SIMULATOR),vcs) + ifneq ($(VCS_HOME),) + ifeq ($(wildcard $(VCS_HOME)/*),) + $(error Please set VCS_HOME to point to the root of the VCS directory) + endif + else + $(error Please set VCS_HOME to point to the root of the VCS directory) + endif + + PLI4J_TAB := $(PLI4J_HOME)/comp/pli4j/src/pli4j.tab + PLI4J_STATIC_LIBS := pli4j jnicpp vpicpp + PLI4J_STATIC_LIB_PATHS := $(foreach lib,$(PLI4J_STATIC_LIBS),$(PLI4J_HOME)/obj/$(lib)/lib$(lib).a) + SIMULATOR_PATH := $(VCS_HOME)/bin + SIMULATOR_FLAGS += +v2k +vpi -R -P $(PLI4J_TAB) $(PLI4J_STATIC_LIB_PATHS) -cc g++ -LDFLAGS -g -lpthread + else + ifeq ($(SIMULATOR),cver) + ifneq ($(CVER_HOME),) + ifeq ($(wildcard $(CVER_HOME)/*),) + $(error Please set CVER_HOME to point to the root of the cver directory) + endif + else + $(error Please set CVER_HOME to point to the root of the cver directory) + endif + + PLI4J_LIB := $(PLI4J_HOME)/obj/pli4j/$(DLL_PREFIX)pli4j$(DLL_SUFFIX) + SIMULATOR_PATH := $(CVER_HOME)/bin + SIMULATOR_FLAGS += +change_port_type +loadvpi=$(PLI4J_LIB):pli4j_register_vpi_tasks + else + $(error Unsupported simulator: $(SIMULATOR)) + endif + endif + endif + +change_simulator: require_simulator + /bin/sh changesimulator.sh $(SIMULATOR) $(PLI4J_HOME) + +xlat-floptest: + @echo "Translating floptest (output in xlat-floptest.log)" + @$(JUNO) -veraroot floptest -verafile floptest.vr -syspath $(VERA_HOME)/include \ + -javaroot src -javapkg juno.samples.floptest > xlat.floptest.log + +xlat-xmlreader: + @echo "Translating xmlreader (output in xlat-xmlreader.log)" + @$(JUNO) -veraroot xmlreader -veracomp all -syspath $(VERA_HOME)/include \ + -veraschemadump xmlreader.schema -javaroot src \ + -javapkg juno.samples.xmlreader > xlat-xmlreader.log + +compile-floptest: xlat-floptest + @echo "Compiling floptest" + @ant -q floptest + +compile-xmlreader: xlat-xmlreader + @echo "Compiling xmlreader" + @ant -q xmlreader + +clean-verilog: + rm -rf simv* csrc + +clean: clean-verilog + ant clean + rm -rf src *.log *.out xmlreader.schema + make -C $(PLI4J_HOME) clean diff --git a/java/juno-samples/xmlreader/makefile b/java/juno-samples/xmlreader/makefile new file mode 100644 index 0000000..bae5917 --- /dev/null +++ b/java/juno-samples/xmlreader/makefile @@ -0,0 +1,38 @@ + +############################################################ +# Component groups +############################################################ + +.PHONY: all + +all: \ + collections/collectionstest \ + common/logtest \ + common/randutiltest \ + xmlreader/xmlreadertest + +############################################################ +# Component dependencies +############################################################ + +collections : collections/objcollections collections/intcollections \ + collections/strcollections collections/strintcollections +collections/collectionstest : collections +collections/intcollections : collections/objcollections +collections/objcollections : common +collections/strcollections : collections/objcollections +collections/strintcollections : collections/strcollections \ + collections/intcollections +common/logtest : common +common/randutiltest : common +sax : streams +streams : common +xmlreader : sax collections +xmlreader/xmlreadertest : xmlreader + +############################################################ +# Generic component rule +############################################################ + +%: + @echo --- Component: $@ diff --git a/java/juno-samples/xmlreader/src/collections/arraylist_tmpl.vr b/java/juno-samples/xmlreader/src/collections/arraylist_tmpl.vr new file mode 100644 index 0000000..974a3bd --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/arraylist_tmpl.vr @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// ArrayList +//////////////////////////////////////////////////////////// + +typedef class ARRAY_LIST_ITERATOR_CLASS; + +class ARRAY_LIST_CLASS +extends LIST_CLASS +{ + local ELEMENT_TYPE array[]; + local integer count; + + // Collection + virtual task add(ELEMENT_TYPE o); + virtual task clear(); + virtual function integer size(); + + // List + virtual task addAt(integer index, ELEMENT_TYPE o); + virtual function ELEMENT_TYPE get(integer index); + virtual function LIST_ITERATOR_CLASS listIteratorAt(integer index); + virtual task removeAt(integer index); + virtual task set(integer index, ELEMENT_TYPE o); + + // ArrayList + task new(); +} + +task ARRAY_LIST_CLASS::add(ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.add(%s)", + getObjectName(), DUMP_STRING(o))) + + array[count++] = o; +} + +task ARRAY_LIST_CLASS::clear() +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + if (destroyOnRemove) { + integer i; + + for (i = 0; i < count; ++i) { + ELEMENT_TYPE victim = array[i]; + DESTROY(victim); + } + } + + assoc_index(DELETE, array); + count = 0; +} + +function integer ARRAY_LIST_CLASS::size() +{ + size = count; +} + +task ARRAY_LIST_CLASS::addAt(integer index, ELEMENT_TYPE o) +{ + integer i; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.addAt(%0d, %s)", + getObjectName(), index, DUMP_STRING(o))) + + assert(index >= 0 && index <= count); + + for (i = count; i > index; --i) { + array[i] = array[i - 1]; + } + ++count; + + array[index] = o; +} + +function ELEMENT_TYPE ARRAY_LIST_CLASS::get(integer index) +{ + assert(index >= 0 && index < count); + + get = array[index]; +} + +function LIST_ITERATOR_CLASS ARRAY_LIST_CLASS::listIteratorAt(integer index) +{ + ARRAY_LIST_ITERATOR_CLASS ali = new(this, index); + + listIteratorAt = ali; +} + +task ARRAY_LIST_CLASS::removeAt(integer index) +{ + integer i; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.removeAt(%0d)", + getObjectName(), index)) + + assert(index >= 0 && index < count); + + if (destroyOnRemove) { + ELEMENT_TYPE victim = array[index]; + DESTROY(victim); + } + + for (i = index + 1; i < count; ++i) { + array[i - 1] = array[i]; + } + --count; + + assoc_index(DELETE, array, count); +} + +task ARRAY_LIST_CLASS::set(integer index, ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.set(%0d, %s)", + getObjectName(), index, DUMP_STRING(o))) + + assert(index >= 0 && index < count); + + if (destroyOnRemove) { + ELEMENT_TYPE victim = array[index]; + DESTROY(victim); + } + + array[index] = o; +} + +task ARRAY_LIST_CLASS::new() +{ + setClassName("ArrayList"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new()", + getObjectName())) + + count = 0; +} + +//////////////////////////////////////////////////////////// +// ArrayListIterator +//////////////////////////////////////////////////////////// + +local class ARRAY_LIST_ITERATOR_CLASS +extends LIST_ITERATOR_CLASS +{ + local LIST_CLASS list; + local integer curIndex; + local integer lastIndex; + + task new(LIST_CLASS _list, integer index = 0); + + virtual task add(ELEMENT_TYPE o); + virtual function bit hasNext(); + virtual function bit hasPrevious(); + virtual function ELEMENT_TYPE next(); + virtual function integer nextIndex(); + virtual function ELEMENT_TYPE previous(); + virtual function integer previousIndex(); + virtual task remove(); + virtual task set(ELEMENT_TYPE o); + + local task checkLast(); +} + +task ARRAY_LIST_ITERATOR_CLASS::new(LIST_CLASS _list, integer index = 0) +{ + setClassName("ArrayListIterator"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%s, %0d)", + getObjectName(), OBJECT_NAME(_list), index)) + + list = _list; + curIndex = index; + lastIndex = -1; +} + +task ARRAY_LIST_ITERATOR_CLASS::add(ELEMENT_TYPE o) +{ + list.addAt(curIndex++, o); + lastIndex = -1; +} + +function bit ARRAY_LIST_ITERATOR_CLASS::hasNext() +{ + hasNext = (curIndex < list.size()); +} + +function bit ARRAY_LIST_ITERATOR_CLASS::hasPrevious() +{ + hasPrevious = (curIndex > 0); +} + +function ELEMENT_TYPE ARRAY_LIST_ITERATOR_CLASS::next() +{ + next = list.get(curIndex); + lastIndex = curIndex++; +} + +function integer ARRAY_LIST_ITERATOR_CLASS::nextIndex() +{ + nextIndex = curIndex; +} + +function ELEMENT_TYPE ARRAY_LIST_ITERATOR_CLASS::previous() +{ + previous = list.get(--curIndex); + lastIndex = curIndex; +} + +function integer ARRAY_LIST_ITERATOR_CLASS::previousIndex() +{ + previousIndex = curIndex - 1; +} + +task ARRAY_LIST_ITERATOR_CLASS::remove() +{ + checkLast(); + list.removeAt(lastIndex); + if (lastIndex < curIndex) --curIndex; + lastIndex = -1; +} + +task ARRAY_LIST_ITERATOR_CLASS::set(ELEMENT_TYPE o) +{ + checkLast(); + list.set(lastIndex, o); +} + +task ARRAY_LIST_ITERATOR_CLASS::checkLast() +{ + if (lastIndex == -1) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/assocarraymap_tmpl.vr b/java/juno-samples/xmlreader/src/collections/assocarraymap_tmpl.vr new file mode 100644 index 0000000..7cde8d6 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/assocarraymap_tmpl.vr @@ -0,0 +1,817 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// AssocArrayMap +//////////////////////////////////////////////////////////// + +typedef class ASSOC_ARRAY_MAP_ENTRY_SET_CLASS; +typedef class ASSOC_ARRAY_MAP_KEY_SET_CLASS; +typedef class ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS; +typedef class ASSOC_ARRAY_MAP_SUB_MAP_CLASS; + +class ASSOC_ARRAY_MAP_CLASS +extends SORTED_MAP_CLASS +{ + // For local use only! + VALUE_TYPE array[]; + + // Map + virtual task clear(); + virtual function bit containsKey(KEY_TYPE key); + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual function VALUE_TYPE get(KEY_TYPE key); + virtual function KEY_SET_CLASS keySet(); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + virtual function integer size(); + virtual function VALUE_COLLECTION_CLASS values(); + + // SortedMap + virtual function KEY_COMPARATOR_CLASS comparator(); + virtual function KEY_TYPE firstKey(); + virtual function KEY_TYPE lastKey(); + virtual function SORTED_MAP_CLASS subMap(KEY_TYPE fromKey, KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS headMap(KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS tailMap(KEY_TYPE fromKey); + + // AssocArrayMap + task new(); + + // For local use only! + function KEY_TYPE findKeyLT(KEY_TYPE key); + function KEY_TYPE findKeyGE(KEY_TYPE key); +} + +task ASSOC_ARRAY_MAP_CLASS::clear() +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + if (destroyValueOnRemove) { + integer i; + + if (assoc_index(FIRST, array, i)) { + while (1) { + VALUE_TYPE victim = array[i]; + VALUE_DESTROY(victim); + if (!assoc_index(NEXT, array, i)) break; + } + } + } + + assoc_index(DELETE, array); +} + +function bit ASSOC_ARRAY_MAP_CLASS::containsKey(KEY_TYPE key) +{ + containsKey = assoc_index(CHECK, array, key); +} + +function Set ASSOC_ARRAY_MAP_CLASS::entrySet() +{ + ASSOC_ARRAY_MAP_ENTRY_SET_CLASS assocArrayMapEntrySet = new(this); + entrySet = assocArrayMapEntrySet; +} + +function MAP_ENTRY_CLASS ASSOC_ARRAY_MAP_CLASS::findKey(KEY_TYPE key) +{ + MAP_ENTRY_CLASS entry; + + if (assoc_index(CHECK, array, key)) { + entry = new(key, array[key]); + } + + findKey = entry; +} + +function VALUE_TYPE ASSOC_ARRAY_MAP_CLASS::get(KEY_TYPE key) +{ + get = array[key]; +} + +function KEY_SET_CLASS ASSOC_ARRAY_MAP_CLASS::keySet() +{ + ASSOC_ARRAY_MAP_KEY_SET_CLASS assocArrayMapKeySet = new(this); + keySet = assocArrayMapKeySet; +} + +task ASSOC_ARRAY_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.put(%s, %s)", + getObjectName(), KEY_DUMP_STRING(key), VALUE_DUMP_STRING(value))) + + if (destroyValueOnRemove) { + VALUE_TYPE victim = array[key]; + VALUE_DESTROY(victim); + } + + array[key] = value; +} + +task ASSOC_ARRAY_MAP_CLASS::remove(KEY_TYPE key) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), KEY_DUMP_STRING(key))) + + if (destroyValueOnRemove) { + VALUE_TYPE victim = array[key]; + VALUE_DESTROY(victim); + } + + assoc_index(DELETE, array, key); +} + +function integer ASSOC_ARRAY_MAP_CLASS::size() +{ + size = assoc_index(CHECK, array); +} + +function VALUE_COLLECTION_CLASS ASSOC_ARRAY_MAP_CLASS::values() +{ + ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS assocArrayMapValues = new(this); + values = assocArrayMapValues; +} + +function KEY_COMPARATOR_CLASS ASSOC_ARRAY_MAP_CLASS::comparator() +{ + DEFAULT_KEY_COMPARATOR_CLASS defKeyComp = new; + comparator = defKeyComp; +} + +function KEY_TYPE ASSOC_ARRAY_MAP_CLASS::firstKey() +{ + bit gotFirst = assoc_index(FIRST, array, firstKey); + assert(gotFirst); +} + +function KEY_TYPE ASSOC_ARRAY_MAP_CLASS::lastKey() +{ + bit gotFirst = assoc_index(FIRST, array, lastKey); + assert(gotFirst); + + while (assoc_index(NEXT, array, lastKey)) { } +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_CLASS::subMap(KEY_TYPE fromKey, KEY_TYPE toKey) +{ + ASSOC_ARRAY_MAP_SUB_MAP_CLASS theSubMap = new(this, fromKey, 1, toKey, 1); + + subMap = theSubMap; +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_CLASS::headMap(KEY_TYPE toKey) +{ + ASSOC_ARRAY_MAP_SUB_MAP_CLASS theSubMap = new(this, KEY_NULL, 0, toKey, 1); + + headMap = theSubMap; +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_CLASS::tailMap(KEY_TYPE fromKey) +{ + ASSOC_ARRAY_MAP_SUB_MAP_CLASS theSubMap = new(this, fromKey, 1, KEY_NULL, 0); + + tailMap = theSubMap; +} + +task ASSOC_ARRAY_MAP_CLASS::new() +{ + setClassName("AssocArrayMap"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new()", + getObjectName())) +} + +function KEY_TYPE ASSOC_ARRAY_MAP_CLASS::findKeyLT(KEY_TYPE key) +{ + KEY_TYPE prevKey; + + bit gotFirst = assoc_index(FIRST, array, findKeyLT); + assert(gotFirst && findKeyLT < key); + + while (findKeyLT < key) { + prevKey = findKeyLT; + if (!assoc_index(NEXT, array, findKeyLT)) break; + } + findKeyLT = prevKey; +} + +function KEY_TYPE ASSOC_ARRAY_MAP_CLASS::findKeyGE(KEY_TYPE key) +{ + bit gotFirst = assoc_index(FIRST, array, findKeyGE); + assert(gotFirst); + + while (findKeyGE < key) { + bit gotNext = assoc_index(NEXT, array, findKeyGE); + assert(gotNext); + } +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapEntrySet +//////////////////////////////////////////////////////////// + +typedef class ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS; + +local class ASSOC_ARRAY_MAP_ENTRY_SET_CLASS +extends Set +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + + // Collection + virtual task add(Object o); + virtual task clear(); + virtual function bit contains(Object o); + virtual function Iterator iterator(); + virtual task remove(Object o); + virtual function integer size(); + + // AssocArrayMapEntrySet + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap); +} + +task ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map entry sets") +} + +task ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::clear() +{ + assocArrayMap.clear(); +} + +function bit ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = assocArrayMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function Iterator ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::iterator() +{ + KEY_TYPE firstKey; + ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS entryIter; + + if (!assoc_index(FIRST, assocArrayMap.array, firstKey)) { + firstKey = KEY_NULL; + } + + entryIter = new(assocArrayMap, firstKey); + iterator = entryIter; +} + +task ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + cast_assign(mapEntry, assocArrayMap.findKey(entry.key)); + if (mapEntry != null && mapEntry.equals(entry)) { + assocArrayMap.remove(entry.key); + } +} + +function integer ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::size() +{ + size = assocArrayMap.size(); +} + +task ASSOC_ARRAY_MAP_ENTRY_SET_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap) +{ + assocArrayMap = _assocArrayMap; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapKeySet +//////////////////////////////////////////////////////////// + +typedef class ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS; + +local class ASSOC_ARRAY_MAP_KEY_SET_CLASS +extends KEY_SET_CLASS +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + + // Collection + virtual task add(KEY_TYPE o); + virtual task clear(); + virtual function bit contains(KEY_TYPE o); + virtual function KEY_ITERATOR_CLASS iterator(); + virtual task remove(KEY_TYPE o); + virtual function integer size(); + + // AssocArrayMapKeySet + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap); +} + +task ASSOC_ARRAY_MAP_KEY_SET_CLASS::add(KEY_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map key sets") +} + +task ASSOC_ARRAY_MAP_KEY_SET_CLASS::clear() +{ + assocArrayMap.clear(); +} + +function bit ASSOC_ARRAY_MAP_KEY_SET_CLASS::contains(KEY_TYPE o) +{ + contains = assocArrayMap.containsKey(o); +} + +function KEY_ITERATOR_CLASS ASSOC_ARRAY_MAP_KEY_SET_CLASS::iterator() +{ + ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS keyIter = new(assocArrayMap); + + iterator = keyIter; +} + +task ASSOC_ARRAY_MAP_KEY_SET_CLASS::remove(KEY_TYPE o) +{ + assocArrayMap.remove(o); +} + +function integer ASSOC_ARRAY_MAP_KEY_SET_CLASS::size() +{ + size = assocArrayMap.size(); +} + +task ASSOC_ARRAY_MAP_KEY_SET_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap) +{ + assocArrayMap = _assocArrayMap; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapValueCollection +//////////////////////////////////////////////////////////// + +typedef class ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS; + +local class ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS +extends VALUE_COLLECTION_CLASS +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + + // Collection + virtual task add(VALUE_TYPE o); + virtual task clear(); + virtual function bit contains(VALUE_TYPE o); + virtual function VALUE_ITERATOR_CLASS iterator(); + virtual function integer size(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // AssocArrayMapValueCollection + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap); +} + +task ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::add(VALUE_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map value collections") +} + +function integer ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::hashCode() +{ + LOG_MSG(logIntf, LS_FATAL, "hashCode() not supported on map value collections") +} + + +function bit ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on map value collections") +} + + +task ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::clear() +{ + assocArrayMap.clear(); +} + +function bit ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::contains(VALUE_TYPE o) +{ + contains = assocArrayMap.containsValue(o); +} + +function VALUE_ITERATOR_CLASS ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::iterator() +{ + ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS valueIter = new(assocArrayMap); + + iterator = valueIter; +} + +function integer ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::size() +{ + size = assocArrayMap.size(); +} + +task ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap) +{ + assocArrayMap = _assocArrayMap; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapEntryIterator +//////////////////////////////////////////////////////////// + +local class ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS +extends Iterator +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + local KEY_TYPE curKey; + local KEY_TYPE nextKey; + local KEY_TYPE stopKey; + + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap, + KEY_TYPE _firstKey, KEY_TYPE _stopKey = KEY_NULL); + + virtual function bit hasNext(); + virtual function Object next(); + virtual task remove(); +} + +task ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap, + KEY_TYPE _firstKey, KEY_TYPE _stopKey = KEY_NULL) +{ + assocArrayMap = _assocArrayMap; + curKey = KEY_NULL; + nextKey = _firstKey; + stopKey = _stopKey; +} + +function bit ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextKey != stopKey); +} + +function Object ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS::next() +{ + MAP_ENTRY_CLASS entry; + + assert(nextKey != stopKey); + + curKey = nextKey; + entry = new(curKey, assocArrayMap.array[curKey]); + if (!assoc_index(NEXT, assocArrayMap.array, nextKey)) { + nextKey = stopKey; + } + next = entry; +} + +task ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS::remove() +{ + if (curKey == KEY_NULL) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + assocArrayMap.remove(curKey); + curKey = KEY_NULL; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapKeyIterator +//////////////////////////////////////////////////////////// + +local class ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS +extends KEY_ITERATOR_CLASS +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + local KEY_TYPE curKey; + local KEY_TYPE nextKey; + + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap); + + virtual function bit hasNext(); + virtual function KEY_TYPE next(); + virtual task remove(); +} + +task ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap) +{ + assocArrayMap = _assocArrayMap; + + curKey = KEY_NULL; + if (!assoc_index(FIRST, assocArrayMap.array, nextKey)) { + nextKey = KEY_NULL; + } +} + +function bit ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextKey != KEY_NULL); +} + +function KEY_TYPE ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS::next() +{ + MAP_ENTRY_CLASS entry; + + assert(nextKey != KEY_NULL); + + curKey = nextKey; + if (!assoc_index(NEXT, assocArrayMap.array, nextKey)) { + nextKey = KEY_NULL; + } + next = curKey; +} + +task ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS::remove() +{ + if (curKey == KEY_NULL) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + assocArrayMap.remove(curKey); + curKey = KEY_NULL; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapValueIterator +//////////////////////////////////////////////////////////// + +local class ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS +extends VALUE_ITERATOR_CLASS +{ + local ASSOC_ARRAY_MAP_CLASS assocArrayMap; + local KEY_TYPE curKey; + local KEY_TYPE nextKey; + + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap); + + virtual function bit hasNext(); + virtual function VALUE_TYPE next(); + virtual task remove(); +} + +task ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap) +{ + assocArrayMap = _assocArrayMap; + + curKey = KEY_NULL; + if (!assoc_index(FIRST, assocArrayMap.array, nextKey)) { + nextKey = KEY_NULL; + } +} + +function bit ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextKey != KEY_NULL); +} + +function VALUE_TYPE ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS::next() +{ + MAP_ENTRY_CLASS entry; + + assert(nextKey != KEY_NULL); + + curKey = nextKey; + if (!assoc_index(NEXT, assocArrayMap.array, nextKey)) { + nextKey = KEY_NULL; + } + next = assocArrayMap.array[curKey]; +} + +task ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS::remove() +{ + if (curKey == KEY_NULL) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + assocArrayMap.remove(curKey); + curKey = KEY_NULL; +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapSubMap +//////////////////////////////////////////////////////////// + +typedef class ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS; + +class ASSOC_ARRAY_MAP_SUB_MAP_CLASS +extends SORTED_MAP_CLASS +{ + // For local use only! + ASSOC_ARRAY_MAP_CLASS assocArrayMap; + KEY_TYPE fromKey; + bit fromValid; + KEY_TYPE toKey; + bit toValid; + + // Map + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + + // SortedMap + virtual function KEY_COMPARATOR_CLASS comparator(); + virtual function KEY_TYPE firstKey(); + virtual function KEY_TYPE lastKey(); + virtual function SORTED_MAP_CLASS subMap(KEY_TYPE fromKey, KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS headMap(KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS tailMap(KEY_TYPE fromKey); + + // AssocArrayMapSubMap + task new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap, + KEY_TYPE _fromKey, bit _fromValid, + KEY_TYPE _toKey, bit _toValid); + + local function bit inRange(KEY_TYPE key, bit includeToKey = 0); +} + +task ASSOC_ARRAY_MAP_SUB_MAP_CLASS::new(ASSOC_ARRAY_MAP_CLASS _assocArrayMap, + KEY_TYPE _fromKey, bit _fromValid, + KEY_TYPE _toKey, bit _toValid) +{ + assocArrayMap = _assocArrayMap; + fromKey = _fromKey; + fromValid = _fromValid; + toKey = _toKey; + toValid = _toValid; + + assert(!fromValid || !toValid || fromKey <= toKey); +} + +function Set ASSOC_ARRAY_MAP_SUB_MAP_CLASS::entrySet() +{ + ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS subMapEntrySet = new(this); + entrySet = subMapEntrySet; +} + +function MAP_ENTRY_CLASS ASSOC_ARRAY_MAP_SUB_MAP_CLASS::findKey(KEY_TYPE key) +{ + if (inRange(key)) { + findKey = assocArrayMap.findKey(key); + } +} + +task ASSOC_ARRAY_MAP_SUB_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + assert(inRange(key)); + assocArrayMap.put(key, value); +} + +task ASSOC_ARRAY_MAP_SUB_MAP_CLASS::remove(KEY_TYPE key) +{ + if (inRange(key)) { + assocArrayMap.remove(key); + } +} + +function KEY_COMPARATOR_CLASS ASSOC_ARRAY_MAP_SUB_MAP_CLASS::comparator() +{ + comparator = assocArrayMap.comparator(); +} + +function KEY_TYPE ASSOC_ARRAY_MAP_SUB_MAP_CLASS::firstKey() +{ + if (fromValid) { + firstKey = assocArrayMap.findKeyGE(fromKey); + } else { + firstKey = assocArrayMap.firstKey(); + } + + if (toValid) { + assert(firstKey < toKey); + } +} + +function KEY_TYPE ASSOC_ARRAY_MAP_SUB_MAP_CLASS::lastKey() +{ + if (toValid) { + lastKey = assocArrayMap.findKeyLT(toKey); + } else { + lastKey = assocArrayMap.lastKey(); + } + + if (fromValid) { + assert(lastKey >= fromKey); + } +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_SUB_MAP_CLASS::subMap(KEY_TYPE fromKey, KEY_TYPE toKey) +{ + assert(inRange(fromKey, 1)); + assert(inRange(toKey, 1)); + subMap = assocArrayMap.subMap(fromKey, toKey); +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_SUB_MAP_CLASS::headMap(KEY_TYPE toKey) +{ + assert(inRange(toKey, 1)); + headMap = assocArrayMap.headMap(toKey); +} + +function SORTED_MAP_CLASS ASSOC_ARRAY_MAP_SUB_MAP_CLASS::tailMap(KEY_TYPE fromKey) +{ + assert(inRange(fromKey, 1)); + tailMap = assocArrayMap.tailMap(fromKey); +} + +function bit ASSOC_ARRAY_MAP_SUB_MAP_CLASS::inRange(KEY_TYPE key, bit includeToKey = 0) +{ + inRange = (!fromValid || key >= fromKey) && + (!toValid || (includeToKey ? key <= toKey : key < toKey)); +} + +//////////////////////////////////////////////////////////// +// AssocArrayMapSubMapEntrySet +//////////////////////////////////////////////////////////// + +local class ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS +extends Set +{ + local ASSOC_ARRAY_MAP_SUB_MAP_CLASS subMap; + + // Collection + virtual task add(Object o); + virtual function bit contains(Object o); + virtual function bit isEmpty(); + virtual function Iterator iterator(); + virtual task remove(Object o); + virtual function bit equals(Object o); + + // AssocArrayMapSubMapEntrySet + task new(ASSOC_ARRAY_MAP_SUB_MAP_CLASS _subMap); +} + +task ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on sub-map entry sets") +} + +function bit ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on sub-map entry sets") +} + +function bit ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = subMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function bit ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::isEmpty() +{ + Iterator i = iterator(); + isEmpty = !i.hasNext(); +} + +function Iterator ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::iterator() +{ + ASSOC_ARRAY_MAP_CLASS assocArrayMap = subMap.assocArrayMap; + ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS entryIter = new(assocArrayMap, + subMap.fromValid ? assocArrayMap.findKeyGE(subMap.fromKey) : assocArrayMap.firstKey(), + subMap.toValid ? assocArrayMap.findKeyGE(subMap.toKey) : KEY_NULL); + + iterator = entryIter; +} + +task ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + cast_assign(mapEntry, subMap.findKey(entry.key)); + if (mapEntry != null && mapEntry.equals(entry)) { + subMap.assocArrayMap.remove(entry.key); + } +} + +task ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS::new(ASSOC_ARRAY_MAP_SUB_MAP_CLASS _subMap) +{ + subMap = _subMap; +} + diff --git a/java/juno-samples/xmlreader/src/collections/assocarrayset_tmpl.vr b/java/juno-samples/xmlreader/src/collections/assocarrayset_tmpl.vr new file mode 100644 index 0000000..05653ce --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/assocarrayset_tmpl.vr @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// AssocArraySet +//////////////////////////////////////////////////////////// + +class ASSOC_ARRAY_SET_CLASS +extends SORTED_SET_CLASS +{ + local ASSOC_ARRAY_SET_MAP_CLASS assocArrayMap; + + // Collection + virtual task add(ELEMENT_TYPE o); + virtual task clear(); + virtual function bit contains(ELEMENT_TYPE o); + virtual function ITERATOR_CLASS iterator(); + virtual task remove(ELEMENT_TYPE o); + virtual task setDestroyOnRemove(bit value); + virtual function integer size(); + + // SortedSet + virtual function COMPARATOR_CLASS comparator(); + + // AssocArraySet + task new(); +} + +task ASSOC_ARRAY_SET_CLASS::add(ELEMENT_TYPE o) +{ + assocArrayMap.put(o, null); +} + +task ASSOC_ARRAY_SET_CLASS::clear() +{ + assocArrayMap.clear(); +} + +function bit ASSOC_ARRAY_SET_CLASS::contains(ELEMENT_TYPE o) +{ + contains = assocArrayMap.containsKey(o); +} + +function ITERATOR_CLASS ASSOC_ARRAY_SET_CLASS::iterator() +{ + SET_CLASS keySet; + + keySet = assocArrayMap.keySet(); + iterator = keySet.iterator(); +} + +task ASSOC_ARRAY_SET_CLASS::remove(ELEMENT_TYPE o) +{ + assocArrayMap.remove(o); +} + +task ASSOC_ARRAY_SET_CLASS::setDestroyOnRemove(bit value) +{ + super.setDestroyOnRemove(value); + assocArrayMap.setDestroyKeyOnRemove(value); +} + +function integer ASSOC_ARRAY_SET_CLASS::size() +{ + size = assocArrayMap.size(); +} + +function COMPARATOR_CLASS ASSOC_ARRAY_SET_CLASS::comparator() +{ + comparator = assocArrayMap.comparator(); +} + +task ASSOC_ARRAY_SET_CLASS::new() +{ + setClassName("AssocArraySet"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new()", + getObjectName())) + + assocArrayMap = new(); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new: assocArrayMap=%s", + getObjectName(), OBJECT_NAME(assocArrayMap))) +} + diff --git a/java/juno-samples/xmlreader/src/collections/collection_tmpl.vr b/java/juno-samples/xmlreader/src/collections/collection_tmpl.vr new file mode 100644 index 0000000..5055d6f --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/collection_tmpl.vr @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// Iterator +//////////////////////////////////////////////////////////// + +virtual class ITERATOR_CLASS +extends CollectionsBase +{ + // all abstract + virtual function bit hasNext(); + virtual function ELEMENT_TYPE next(); + virtual task remove(); +} + +//////////////////////////////////////////////////////////// +// EmptyIterator +//////////////////////////////////////////////////////////// + +class EMPTY_ITERATOR_CLASS +extends ITERATOR_CLASS +{ + virtual function bit hasNext(); + virtual function ELEMENT_TYPE next(); + virtual task remove(); +} + +function bit EMPTY_ITERATOR_CLASS::hasNext() +{ + hasNext = 0; +} + +function ELEMENT_TYPE EMPTY_ITERATOR_CLASS::next() +{ + assert(0); +} + +task EMPTY_ITERATOR_CLASS::remove() +{ + assert(0); +} + +//////////////////////////////////////////////////////////// +// Collection +//////////////////////////////////////////////////////////// + +virtual class COLLECTION_CLASS +extends CollectionsBase +{ + protected bit destroyOnRemove; + + // Object + virtual function string dumpString(); + virtual function bit equals(Object o); // abstract + virtual function integer hashCode(); // abstract + virtual task destroy(); + + // Collection + virtual task add(ELEMENT_TYPE o); // abstract + virtual task addAll(COLLECTION_CLASS c); + virtual task clear(); + virtual function bit contains(ELEMENT_TYPE o); + virtual function bit containsAll(COLLECTION_CLASS c); + function bit isDestroyOnRemove(); + virtual function bit isEmpty(); + virtual function ITERATOR_CLASS iterator(); // abstract + virtual task remove(ELEMENT_TYPE o); + virtual task removeAll(COLLECTION_CLASS c); + virtual task retainAll(COLLECTION_CLASS c); + virtual task setDestroyOnRemove(bit value); + virtual function integer size(); + + task new(); +} + +function string COLLECTION_CLASS::dumpString() +{ + ITERATOR_CLASS i; + bit first; + string s; + + i = iterator(); + first = 1; + while (i.hasNext()) { + ELEMENT_TYPE io; + + if (!first) s = { s, ", " }; + io = i.next(); + s = { s, DUMP_STRING(io) }; + first = 0; + } + + dumpString = { "[", s, "]" }; +} + +task COLLECTION_CLASS::destroy() +{ + clear(); +} + +task COLLECTION_CLASS::addAll(COLLECTION_CLASS c) +{ + ITERATOR_CLASS ci; + + ci = c.iterator(); + while (ci.hasNext()) { + ELEMENT_TYPE cio; + + cio = ci.next(); + add(cio); + } +} + +task COLLECTION_CLASS::clear() +{ + ITERATOR_CLASS i; + + i = iterator(); + while (i.hasNext()) { + void = i.next(); + i.remove(); + } +} + +function bit COLLECTION_CLASS::contains(ELEMENT_TYPE o) +{ + ITERATOR_CLASS i; + + i = iterator(); + while (i.hasNext()) { + ELEMENT_TYPE io; + + io = i.next(); + if (EQUALS(o, io)) { + contains = 1; + return; + } + } + + contains = 0; +} + +function bit COLLECTION_CLASS::containsAll(COLLECTION_CLASS c) +{ + ITERATOR_CLASS ci; + + ci = c.iterator(); + while (ci.hasNext()) { + ELEMENT_TYPE cio; + + cio = ci.next(); + if (!contains(cio)) { + containsAll = 0; + return; + } + } + + containsAll = 1; +} + +function bit COLLECTION_CLASS::isDestroyOnRemove() +{ + isDestroyOnRemove = destroyOnRemove; +} + +function bit COLLECTION_CLASS::isEmpty() +{ + isEmpty = (size() == 0); +} + +task COLLECTION_CLASS::remove(ELEMENT_TYPE o) +{ + ITERATOR_CLASS i; + + i = iterator(); + while (i.hasNext()) { + ELEMENT_TYPE io; + + io = i.next(); + if (EQUALS(o, io)) { + i.remove(); + break; + } + } +} + +task COLLECTION_CLASS::removeAll(COLLECTION_CLASS c) +{ + ITERATOR_CLASS ci; + + ci = c.iterator(); + while (ci.hasNext()) { + ELEMENT_TYPE cio; + + cio = ci.next(); + remove(cio); + } +} + +task COLLECTION_CLASS::retainAll(COLLECTION_CLASS c) +{ + ITERATOR_CLASS i; + + i = iterator(); + while (i.hasNext()) { + ELEMENT_TYPE io; + + io = i.next(); + if (!c.contains(io)) { + i.remove(); + } + } +} + +task COLLECTION_CLASS::setDestroyOnRemove(bit value) +{ + destroyOnRemove = value; +} + +function integer COLLECTION_CLASS::size() +{ + ITERATOR_CLASS i; + + size = 0; + i = iterator(); + while (i.hasNext()) { + ++size; + void = i.next(); + } +} + +task COLLECTION_CLASS::new() +{ + destroyOnRemove = 0; +} + diff --git a/java/juno-samples/xmlreader/src/collections/collections.mak b/java/juno-samples/xmlreader/src/collections/collections.mak new file mode 100644 index 0000000..df2c93b --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/collections.mak @@ -0,0 +1,2 @@ +SRC_FILES := $(SPACE) +LOAD_COMPS := collections/objcollections collections/intcollections collections/strcollections collections/strintcollections diff --git a/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.mak b/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.mak new file mode 100644 index 0000000..17597f1 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.mak @@ -0,0 +1,2 @@ +LOAD_COMPS := collections +RUNNABLE := 1 diff --git a/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.vr b/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.vr new file mode 100644 index 0000000..a9b9abe --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/collectionstest/collectionstest.vr @@ -0,0 +1,664 @@ +#include +#include "arraylist.vrh" +#include "linkedlist.vrh" +#include "strarraylist.vrh" +#include "strlinkedlist.vrh" +#include "intarraylist.vrh" +#include "intlinkedlist.vrh" +#include "hashmap.vrh" +#include "linkedhashmap.vrh" +#include "treemap.vrh" +#include "strhashmap.vrh" +#include "strlinkedhashmap.vrh" +#include "strtreemap.vrh" +#include "hashset.vrh" +#include "treeset.vrh" +#include "strhashset.vrh" +#include "strtreeset.vrh" +#include "intassocarraymap.vrh" + +class MyClass +extends Object +{ + local string name; + + task new(string _name) + { + name = _name; + } + + virtual function string dumpString() + { + dumpString = name; + } +} + +task testLists(List list1, List list2) +{ + MyClass o1, o2, o3; + + o1 = new("o1"); + o2 = new("o2"); + o3 = new("o3"); + + printf("list1 = %s (hashCode = %0d)\n", list1.dumpString(), list1.hashCode()); + printf("list2 = %s (hashCode = %0d)\n", list2.dumpString(), list2.hashCode()); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o2);\n"); + list1.add(o2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.contains(o1) = %b\n", list1.contains(o1)); + printf("list1.contains(o2) = %b\n", list1.contains(o2)); + printf("list1.contains(o3) = %b\n", list1.contains(o3)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.addAll(list1);\n"); + list2.addAll(list1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list1.equals(list2) = %b\n", list1.equals(list2)); + printf("list2.containsAll(list1) = %b\n\n", list2.containsAll(list1)); + + printf("> list2.remove(o2);\n"); + list2.remove(o2); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list2.containsAll(list1) = %b\n", list2.containsAll(list1)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.retainAll(list2);\n"); + list1.retainAll(list2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + list1.clear(); + list2.clear(); +} + +task testStrLists(StrList list1, StrList list2) +{ + string o1, o2, o3; + + o1 = "s1"; + o2 = "s2"; + o3 = "s3"; + + printf("list1 = %s (hashCode = %0d)\n", list1.dumpString(), list1.hashCode()); + printf("list2 = %s (hashCode = %0d)\n", list2.dumpString(), list2.hashCode()); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o2);\n"); + list1.add(o2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.contains(o1) = %b\n", list1.contains(o1)); + printf("list1.contains(o2) = %b\n", list1.contains(o2)); + printf("list1.contains(o3) = %b\n", list1.contains(o3)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.addAll(list1);\n"); + list2.addAll(list1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list1.equals(list2) = %b\n", list1.equals(list2)); + printf("list2.containsAll(list1) = %b\n\n", list2.containsAll(list1)); + + printf("> list2.remove(o2);\n"); + list2.remove(o2); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list2.containsAll(list1) = %b\n", list2.containsAll(list1)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.retainAll(list2);\n"); + list1.retainAll(list2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + list1.clear(); + list2.clear(); +} + +task testIntLists(IntList list1, IntList list2) +{ + integer o1, o2, o3; + + o1 = 1; + o2 = 2; + o3 = 3; + + printf("list1 = %s (hashCode = %0d)\n", list1.dumpString(), list1.hashCode()); + printf("list2 = %s (hashCode = %0d)\n", list2.dumpString(), list2.hashCode()); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o2);\n"); + list1.add(o2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("> list1.add(o1);\n"); + list1.add(o1); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.contains(o1) = %b\n", list1.contains(o1)); + printf("list1.contains(o2) = %b\n", list1.contains(o2)); + printf("list1.contains(o3) = %b\n", list1.contains(o3)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.addAll(list1);\n"); + list2.addAll(list1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list1.equals(list2) = %b\n", list1.equals(list2)); + printf("list2.containsAll(list1) = %b\n\n", list2.containsAll(list1)); + + printf("> list2.remove(o2);\n"); + list2.remove(o2); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("list2.containsAll(list1) = %b\n", list2.containsAll(list1)); + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list1.retainAll(list2);\n"); + list1.retainAll(list2); + printf("list1 = %s (hashCode = %0d)\n\n", list1.dumpString(), list1.hashCode()); + + printf("list1.equals(list2) = %b\n\n", list1.equals(list2)); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + printf("> list2.remove(o1);\n"); + list2.remove(o1); + printf("list2 = %s (hashCode = %0d)\n\n", list2.dumpString(), list2.hashCode()); + + list1.clear(); + list2.clear(); +} + +task testMap(Map map) +{ + MyClass k1, k2, k3, va, vb, vc; + Set keySet; + Collection values; + SortedMap sortedMap; + SortedMap subMap; + Set subMapKeySet; + Collection subMapValues; + + k1 = new("Key 1"); + k2 = new("Key 2"); + k3 = new("Key 3"); + va = new("Value A"); + vb = new("Value B"); + vc = new("Value C"); + + keySet = map.keySet(); + values = map.values(); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, vb);\n"); + map.put(k2, vb); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k3, vc);\n"); + map.put(k3, vc); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k1, va);\n"); + map.put(k1, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, va);\n"); + map.put(k2, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (cast_assign(sortedMap, map, CHECK)) { + Object fk, lk; + + fk = sortedMap.firstKey(); + lk = sortedMap.lastKey(); + printf("map.firstKey() = %s, map.lastKey() = %s\n\n", + fk.dumpString(), lk.dumpString()); + + printf("> subMap = map.subMap(k1, k3);\n"); + subMap = sortedMap.subMap(k1, k3); + subMapKeySet = subMap.keySet(); + subMapValues = subMap.values(); + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + printf("> map.remove(k2);\n"); + map.remove(k2); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.remove(k1);\n"); + map.remove(k1); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (subMap != null) { + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + map.clear(); +} + +task testStrMap(StrMap map) +{ + string k1, k2, k3; + MyClass va, vb, vc; + StrSet keySet; + Collection values; + StrSortedMap sortedMap; + StrSortedMap subMap; + StrSet subMapKeySet; + Collection subMapValues; + + k1 = "Key 1"; + k2 = "Key 2"; + k3 = "Key 3"; + va = new("Value A"); + vb = new("Value B"); + vc = new("Value C"); + + keySet = map.keySet(); + values = map.values(); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, vb);\n"); + map.put(k2, vb); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k3, vc);\n"); + map.put(k3, vc); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k1, va);\n"); + map.put(k1, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, va);\n"); + map.put(k2, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (cast_assign(sortedMap, map, CHECK)) { + printf("map.firstKey() = %s, map.lastKey() = %s\n\n", + sortedMap.firstKey(), sortedMap.lastKey()); + + printf("> subMap = map.subMap(k1, k3);\n"); + subMap = sortedMap.subMap(k1, k3); + subMapKeySet = subMap.keySet(); + subMapValues = subMap.values(); + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + printf("> map.remove(k2);\n"); + map.remove(k2); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.remove(k1);\n"); + map.remove(k1); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (subMap != null) { + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + map.clear(); +} + +task testIntMap(IntMap map) +{ + integer k1, k2, k3; + MyClass va, vb, vc; + IntSet keySet; + Collection values; + IntSortedMap sortedMap; + IntSortedMap subMap; + IntSet subMapKeySet; + Collection subMapValues; + + k1 = 1; + k2 = 2; + k3 = 3; + va = new("Value A"); + vb = new("Value B"); + vc = new("Value C"); + + keySet = map.keySet(); + values = map.values(); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, vb);\n"); + map.put(k2, vb); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k3, vc);\n"); + map.put(k3, vc); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k1, va);\n"); + map.put(k1, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.put(k2, va);\n"); + map.put(k2, va); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (cast_assign(sortedMap, map, CHECK)) { + printf("map.firstKey() = %0d, map.lastKey() = %0d\n\n", + sortedMap.firstKey(), sortedMap.lastKey()); + + printf("> subMap = map.subMap(k1, k3);\n"); + subMap = sortedMap.subMap(k1, k3); + subMapKeySet = subMap.keySet(); + subMapValues = subMap.values(); + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + printf("> map.remove(k2);\n"); + map.remove(k2); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + printf("> map.remove(k1);\n"); + map.remove(k1); + printf("map = %s, keys = %s, values = %s\n\n", + map.dumpString(), keySet.dumpString(), values.dumpString()); + + if (subMap != null) { + printf("subMap = %s, keys = %s, values = %s\n\n", + subMap.dumpString(), subMapKeySet.dumpString(), subMapValues.dumpString()); + } + + map.clear(); +} + +task testSet(Set set) +{ + MyClass o1, o2, o3; + + o1 = new("o1"); + o2 = new("o2"); + o3 = new("o3"); + + printf("> set.add(o2);\n"); + set.add(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o1);\n"); + set.add(o1); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o3);\n"); + set.add(o3); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.remove(o2);\n"); + set.remove(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o2);\n"); + set.add(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + set.clear(); +} + +task testStrSet(StrSet set) +{ + string o1, o2, o3; + + o1 = "s1"; + o2 = "s2"; + o3 = "s3"; + + printf("> set.add(o2);\n"); + set.add(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o1);\n"); + set.add(o1); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o3);\n"); + set.add(o3); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.remove(o2);\n"); + set.remove(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + printf("> set.add(o2);\n"); + set.add(o2); + printf("set = %s (hashCode = %0d)\n\n", set.dumpString(), set.hashCode()); + + set.clear(); +} + +program main +{ + { + ArrayList list1, list2; + + list1 = new; + list2 = new; + + printf("========== ArrayList:\n\n"); + testLists(list1, list2); + } + + { + LinkedList list1, list2; + + list1 = new; + list2 = new; + + printf("========== LinkedList:\n\n"); + testLists(list1, list2); + } + + { + StrArrayList list1, list2; + + list1 = new; + list2 = new; + + printf("========== StrArrayList:\n\n"); + testStrLists(list1, list2); + } + + { + StrLinkedList list1, list2; + + list1 = new; + list2 = new; + + printf("========== StrLinkedList:\n\n"); + testStrLists(list1, list2); + } + + { + IntArrayList list1, list2; + + list1 = new; + list2 = new; + + printf("========== IntArrayList:\n\n"); + testIntLists(list1, list2); + } + + { + IntLinkedList list1, list2; + + list1 = new; + list2 = new; + + printf("========== IntLinkedList:\n\n"); + testIntLists(list1, list2); + } + + { + HashMap map; + + map = new; + + printf("========== HashMap:\n\n"); + testMap(map); + } + + { + LinkedHashMap map; + + map = new; + + printf("========== LinkedHashMap:\n\n"); + testMap(map); + } + + { + TreeMap map; + + map = new; + + printf("========== TreeMap:\n\n"); + testMap(map); + } + + { + StrHashMap map; + + map = new; + + printf("========== StrHashMap:\n\n"); + testStrMap(map); + } + + { + StrLinkedHashMap map; + + map = new; + + printf("========== StrLinkedHashMap:\n\n"); + testStrMap(map); + } + + { + StrTreeMap map; + + map = new; + + printf("========== StrTreeMap:\n\n"); + testStrMap(map); + } + + { + HashSet set; + + set = new; + + printf("========== HashSet:\n\n"); + testSet(set); + } + + { + TreeSet set; + + set = new; + + printf("========== TreeSet:\n\n"); + testSet(set); + } + + { + StrHashSet set; + + set = new; + + printf("========== StrHashSet:\n\n"); + testStrSet(set); + } + + { + StrTreeSet set; + + set = new; + + printf("========== StrTreeSet:\n\n"); + testStrSet(set); + } + + { + IntAssocArrayMap map; + + map = new; + + printf("========== IntAssocArrayMap:\n\n"); + testIntMap(map); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/comparator_tmpl.vr b/java/juno-samples/xmlreader/src/collections/comparator_tmpl.vr new file mode 100644 index 0000000..af1e20c --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/comparator_tmpl.vr @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// Comparator +//////////////////////////////////////////////////////////// + +virtual class COMPARATOR_CLASS +extends Object +{ + virtual function integer compare(ELEMENT_TYPE o1, ELEMENT_TYPE o2); +} + diff --git a/java/juno-samples/xmlreader/src/collections/hashmap_tmpl.vr b/java/juno-samples/xmlreader/src/collections/hashmap_tmpl.vr new file mode 100644 index 0000000..80e3051 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/hashmap_tmpl.vr @@ -0,0 +1,568 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// HashMap +//////////////////////////////////////////////////////////// + +typedef class HASH_MAP_ENTRY_CLASS; +typedef class HASH_MAP_ENTRY_SET_CLASS; +typedef class HASH_MAP_KEY_SET_CLASS; +typedef class HASH_MAP_VALUE_COLLECTION_CLASS; + +class HASH_MAP_CLASS +extends MAP_CLASS +{ + // For local use only! + HASH_MAP_ENTRY_CLASS hashTable[]; + integer tableSize; + integer count; + local integer threshold; + + // Map + virtual task clear(); + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual function KEY_SET_CLASS keySet(); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + virtual function integer size(); + virtual function VALUE_COLLECTION_CLASS values(); + + // HashMap + task new(integer initialCapacity = 16); + + local task resize(integer newTableSize); +} + +task HASH_MAP_CLASS::clear() +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + if (destroyKeyOnRemove || destroyValueOnRemove) { + integer i; + + if (assoc_index(FIRST, hashTable, i)) { + while (1) { + HASH_MAP_ENTRY_CLASS victim = hashTable[i]; + while (victim != null) { + if (destroyKeyOnRemove) { + victim.destroyKey(); + } + if (destroyValueOnRemove) { + victim.destroyValue(); + } + victim = victim.nextEntry; + } + if (!assoc_index(NEXT, hashTable, i)) break; + } + } + } + + assoc_index(DELETE, hashTable); + count = 0; +} + +function Set HASH_MAP_CLASS::entrySet() +{ + HASH_MAP_ENTRY_SET_CLASS hashMapEntrySet = new(this); + entrySet = hashMapEntrySet; +} + +function MAP_ENTRY_CLASS HASH_MAP_CLASS::findKey(KEY_TYPE key) +{ + integer hash, index; + HASH_MAP_ENTRY_CLASS entry; + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + entry = hashTable[index]; + while (entry != null) { + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + findKey = entry; + return; + } + entry = entry.nextEntry; + } + + findKey = null; +} + +function KEY_SET_CLASS HASH_MAP_CLASS::keySet() +{ + HASH_MAP_KEY_SET_CLASS hashMapKeySet = new(this); + keySet = hashMapKeySet; +} + +task HASH_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + integer hash, index; + HASH_MAP_ENTRY_CLASS entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.put(%s, %s)", + getObjectName(), KEY_DUMP_STRING(key), VALUE_DUMP_STRING(value))) + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + entry = hashTable[index]; + while (entry != null) { + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + if (destroyValueOnRemove) { + VALUE_TYPE victim = entry.value; + VALUE_DESTROY(victim); + } + entry.value = value; + return; + } + entry = entry.nextEntry; + } + + hashTable[index] = new(key, value, hash, hashTable[index]); + if (++count >= threshold) { + resize(tableSize * 2); + } +} + +task HASH_MAP_CLASS::remove(KEY_TYPE key) +{ + integer hash, index; + HASH_MAP_ENTRY_CLASS prevEntry, entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), KEY_DUMP_STRING(key))) + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + prevEntry = null; + entry = hashTable[index]; + while (entry != null) { + HASH_MAP_ENTRY_CLASS nextEntry; + + nextEntry = entry.nextEntry; + + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + --count; + if (destroyKeyOnRemove) { + entry.destroyKey(); + } + if (destroyValueOnRemove) { + entry.destroyValue(); + } + + if (prevEntry == null) { + hashTable[index] = nextEntry; + } + else { + prevEntry.nextEntry = nextEntry; + } + return; + } + + prevEntry = entry; + entry = nextEntry; + } +} + +function integer HASH_MAP_CLASS::size() +{ + size = count; +} + +function VALUE_COLLECTION_CLASS HASH_MAP_CLASS::values() +{ + HASH_MAP_VALUE_COLLECTION_CLASS hashMapValues = new(this); + values = hashMapValues; +} + +task HASH_MAP_CLASS::new(integer initialCapacity = 16) +{ + integer size; + + setClassName("HashMap"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%0d)", + getObjectName(), initialCapacity)) + + // table is initially empty + tableSize = 0; + count = 0; + + // find power of 2 table size >= initial capacity + size = 1; + while (size < initialCapacity) { + size <<= 1; + } + + // update table size and threshold + resize(size); +} + +task HASH_MAP_CLASS::resize(integer newTableSize) +{ + integer index; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.resize(%0d)", + getObjectName(), newTableSize)) + + // rebuild hash buckets + for (index = 0; index < tableSize; ++index) { + HASH_MAP_ENTRY_CLASS prevEntry, entry; + + prevEntry = null; + entry = hashTable[index]; + while (entry != null) { + HASH_MAP_ENTRY_CLASS nextEntry; + integer newIndex; + + nextEntry = entry.nextEntry; + + // move entry if index changed + newIndex = entry.hashCode & (newTableSize - 1); + if (newIndex != index) { + + // remove entry from old list + if (prevEntry == null) { + hashTable[index] = nextEntry; + } + else { + prevEntry.nextEntry = nextEntry; + } + + // add entry to new list + entry.nextEntry = hashTable[newIndex]; + hashTable[newIndex] = entry; + } + else { + // previous entry only advances if index is unchanged + prevEntry = entry; + } + + entry = nextEntry; + } + } + + // set new table size + tableSize = newTableSize; + + // resize at 75% load factor + threshold = tableSize * 3 / 4; +} + +// supplemental hash function to improve hash distribution; +// critical for power of 2 hash table size +// see http://www.concentric.net/~Ttwang/tech/inthash.htm +local function integer suppHash(integer hashCode) +{ + bit[31:0] uh = hashCode; + + uh += ~(uh << 15); + uh ^= (uh >> 10); + uh += (uh << 3); + uh ^= (uh >> 6); + uh += ~(uh << 11); + uh ^= (uh >> 16); + + suppHash = uh; +} + +//////////////////////////////////////////////////////////// +// HashMapEntry +//////////////////////////////////////////////////////////// + +class HASH_MAP_ENTRY_CLASS +extends MAP_ENTRY_CLASS +{ + integer hashCode; + HASH_MAP_ENTRY_CLASS nextEntry; + + task new(KEY_TYPE _key, VALUE_TYPE _value, integer _hashCode, + HASH_MAP_ENTRY_CLASS _nextEntry) + { + super.new(_key, _value); + + hashCode = _hashCode; + nextEntry = _nextEntry; + } +} + +//////////////////////////////////////////////////////////// +// HashMapEntrySet +//////////////////////////////////////////////////////////// + +typedef class HASH_MAP_ENTRY_ITERATOR_CLASS; + +local class HASH_MAP_ENTRY_SET_CLASS +extends Set +{ + local HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(Object o); + virtual task clear(); + virtual function bit contains(Object o); + virtual function Iterator iterator(); + virtual task remove(Object o); + virtual function integer size(); + + // HashMapEntrySet + task new(HASH_MAP_CLASS _hashMap); +} + +task HASH_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map entry sets") +} + +task HASH_MAP_ENTRY_SET_CLASS::clear() +{ + hashMap.clear(); +} + +function bit HASH_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = hashMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function Iterator HASH_MAP_ENTRY_SET_CLASS::iterator() +{ + HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + + iterator = entryIter; +} + +task HASH_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + mapEntry = hashMap.findKey(entry.key); + if (mapEntry != null && mapEntry.equals(entry)) { + hashMap.remove(entry.key); + } +} + +function integer HASH_MAP_ENTRY_SET_CLASS::size() +{ + size = hashMap.size(); +} + +task HASH_MAP_ENTRY_SET_CLASS::new(HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// HashMapKeySet +//////////////////////////////////////////////////////////// + +local class HASH_MAP_KEY_SET_CLASS +extends KEY_SET_CLASS +{ + local HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(KEY_TYPE o); + virtual task clear(); + virtual function bit contains(KEY_TYPE o); + virtual function KEY_ITERATOR_CLASS iterator(); + virtual task remove(KEY_TYPE o); + virtual function integer size(); + + // HashMapKeySet + task new(HASH_MAP_CLASS _hashMap); +} + +task HASH_MAP_KEY_SET_CLASS::add(KEY_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map key sets") +} + +task HASH_MAP_KEY_SET_CLASS::clear() +{ + hashMap.clear(); +} + +function bit HASH_MAP_KEY_SET_CLASS::contains(KEY_TYPE o) +{ + contains = hashMap.containsKey(o); +} + +function KEY_ITERATOR_CLASS HASH_MAP_KEY_SET_CLASS::iterator() +{ + HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + ENTRY_SET_KEY_ITERATOR_CLASS keyIter = new(entryIter); + + iterator = keyIter; +} + +task HASH_MAP_KEY_SET_CLASS::remove(KEY_TYPE o) +{ + hashMap.remove(o); +} + +function integer HASH_MAP_KEY_SET_CLASS::size() +{ + size = hashMap.size(); +} + +task HASH_MAP_KEY_SET_CLASS::new(HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// HashMapValueCollection +//////////////////////////////////////////////////////////// + +local class HASH_MAP_VALUE_COLLECTION_CLASS +extends VALUE_COLLECTION_CLASS +{ + local HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(VALUE_TYPE o); + virtual task clear(); + virtual function bit contains(VALUE_TYPE o); + virtual function VALUE_ITERATOR_CLASS iterator(); + virtual function integer size(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // HashMapValueCollection + task new(HASH_MAP_CLASS _hashMap); +} + +function bit HASH_MAP_VALUE_COLLECTION_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on map value collections") +} + +function integer HASH_MAP_VALUE_COLLECTION_CLASS::hashCode() +{ + hashCode = 0; + LOG_MSG(logIntf, LS_FATAL, "hashCode() not supported on map value collections") +} + +task HASH_MAP_VALUE_COLLECTION_CLASS::add(VALUE_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map value collections") +} + +task HASH_MAP_VALUE_COLLECTION_CLASS::clear() +{ + hashMap.clear(); +} + +function bit HASH_MAP_VALUE_COLLECTION_CLASS::contains(VALUE_TYPE o) +{ + contains = hashMap.containsValue(o); +} + +function VALUE_ITERATOR_CLASS HASH_MAP_VALUE_COLLECTION_CLASS::iterator() +{ + HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + ENTRY_SET_VALUE_ITERATOR_CLASS valueIter = new(entryIter); + + iterator = valueIter; +} + +function integer HASH_MAP_VALUE_COLLECTION_CLASS::size() +{ + size = hashMap.size(); +} + +task HASH_MAP_VALUE_COLLECTION_CLASS::new(HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// HashMapEntryIterator +//////////////////////////////////////////////////////////// + +local class HASH_MAP_ENTRY_ITERATOR_CLASS +extends Iterator +{ + local HASH_MAP_CLASS hashMap; + local integer curIndex; + local HASH_MAP_ENTRY_CLASS curEntry; + local HASH_MAP_ENTRY_CLASS nextEntry; + + task new(HASH_MAP_CLASS _hashMap); + + virtual function bit hasNext(); + virtual function Object next(); + virtual task remove(); + + local task advance(); +} + +task HASH_MAP_ENTRY_ITERATOR_CLASS::new(HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; + + curIndex = 0; + if (hashMap.count > 0) { + advance(); + } +} + +function bit HASH_MAP_ENTRY_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextEntry != null); +} + +function Object HASH_MAP_ENTRY_ITERATOR_CLASS::next() +{ + assert(nextEntry != null); + + curEntry = nextEntry; + advance(); + next = curEntry; +} + +task HASH_MAP_ENTRY_ITERATOR_CLASS::remove() +{ + if (curEntry == null) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + hashMap.remove(curEntry.key); + curEntry = null; +} + +task HASH_MAP_ENTRY_ITERATOR_CLASS::advance() +{ + if (nextEntry != null) { + nextEntry = nextEntry.nextEntry; + } + for (; nextEntry == null && curIndex < hashMap.tableSize; ++curIndex) { + nextEntry = hashMap.hashTable[curIndex]; + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/hashset_tmpl.vr b/java/juno-samples/xmlreader/src/collections/hashset_tmpl.vr new file mode 100644 index 0000000..272c1eb --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/hashset_tmpl.vr @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// HashSet +//////////////////////////////////////////////////////////// + +class HASH_SET_CLASS +extends SET_CLASS +{ + local HASH_SET_HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(ELEMENT_TYPE o); + virtual task clear(); + virtual function bit contains(ELEMENT_TYPE o); + virtual function ITERATOR_CLASS iterator(); + virtual task remove(ELEMENT_TYPE o); + virtual task setDestroyOnRemove(bit value); + virtual function integer size(); + + // HashSet + task new(integer initialCapacity = 16); +} + +task HASH_SET_CLASS::add(ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.add(%s)", + getObjectName(), DUMP_STRING(o))) + + hashMap.put(o, null); +} + +task HASH_SET_CLASS::clear() +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + hashMap.clear(); +} + +function bit HASH_SET_CLASS::contains(ELEMENT_TYPE o) +{ + contains = (hashMap.findKey(o) != null); +} + +function ITERATOR_CLASS HASH_SET_CLASS::iterator() +{ + SET_CLASS keySet; + + keySet = hashMap.keySet(); + iterator = keySet.iterator(); +} + +task HASH_SET_CLASS::remove(ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), DUMP_STRING(o))) + + hashMap.remove(o); +} + +task HASH_SET_CLASS::setDestroyOnRemove(bit value) +{ + super.setDestroyOnRemove(value); + hashMap.setDestroyKeyOnRemove(value); +} + +function integer HASH_SET_CLASS::size() +{ + size = hashMap.size(); +} + +task HASH_SET_CLASS::new(integer initialCapacity = 16) +{ + setClassName("HashSet"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%0d)", + getObjectName(), initialCapacity)) + + hashMap = new(initialCapacity); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new: hashMap=%s", + getObjectName(), OBJECT_NAME(hashMap))) +} + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/elem_int_defines.vr b/java/juno-samples/xmlreader/src/collections/intcollections/elem_int_defines.vr new file mode 100644 index 0000000..43efb7f --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/elem_int_defines.vr @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#define ELEMENT_TYPE integer +#define ELEMENT_NULL -1 + +#define DUMP_STRING(o) psprintf("%0d", o) +#define EQUALS(a,b) (a == b) +#define HASH_CODE(o) o +#define DESTROY(o) o = -1 + +#define ITERATOR_CLASS IntIterator +#define EMPTY_ITERATOR_CLASS IntEmptyIterator +#define COLLECTION_CLASS IntCollection + +#define LIST_ITERATOR_CLASS IntListIterator +#define LIST_CLASS IntList + +#define ARRAY_LIST_ITERATOR_CLASS IntArrayListIterator +#define ARRAY_LIST_CLASS IntArrayList + +#define LINKED_LIST_NODE_CLASS IntLinkedListNode +#define LINKED_LIST_ITERATOR_CLASS IntLinkedListIterator +#define LINKED_LIST_CLASS IntLinkedList + +#define SET_CLASS IntSet + +#define COMPARATOR_CLASS IntComparator + +#define SORTED_SET_CLASS IntSortedSet + +#define ASSOC_ARRAY_SET_CLASS IntAssocArraySet +#define ASSOC_ARRAY_SET_MAP_CLASS IntAssocArrayMap + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intarraylist.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intarraylist.vr new file mode 100644 index 0000000..7cecc14 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intarraylist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intlist.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../arraylist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intassocarraymap.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intassocarraymap.vr new file mode 100644 index 0000000..8d76f8b --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intassocarraymap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intsortedmap.vrh" + +//LOCAL +#include "kv_int_obj_defines.vr" +#include "../assocarraymap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intassocarrayset.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intassocarrayset.vr new file mode 100644 index 0000000..843ba48 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intassocarrayset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intsortedset.vrh" +#include "intassocarraymap.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../assocarrayset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intcollection.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intcollection.vr new file mode 100644 index 0000000..d474e83 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intcollection.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../collection_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.dot b/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.dot new file mode 100644 index 0000000..58fa07f --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.dot @@ -0,0 +1,54 @@ +digraph intcollections { +rankdir=LR; +node [shape=record,fontname="Helvetica",fontsize=10,height=0.2,width=0.4,color=black]; +edge [dir=back,color="midnightblue",fontname="Helvetica",fontsize=10,style=solid]; +title [label="Vera Integer Collection Classes"]; + +Object [label="Object|dumpString()\nequals()\nhashCode()"]; + +IntComparator [label="[IntComparator]|compare()"]; +Object -> IntComparator ; + +NaturalIntComparator [label="NaturalIntComparator|"]; +IntComparator -> NaturalIntComparator ; + +IntCollection [label="[IntCollection]|add()\naddAll()\nclear()\ncontains()\ncontainsAll()\nisEmpty()\niterator()\nremove()\nremoveAll()\nretainAll()\nsize()"]; +Object -> IntCollection ; + +IntIterator [label="[IntIterator]|hasNext()\nnext()\nremove()"]; + +IntList [label="[IntList]|addAt()\naddAllAt()\naddFirst()\naddLast()\nget()\ngetFirst()\ngetLast()\nindexOf()\nlastIndexOf()\nlistIterator()\nlistIteratorAt()\nremoveAt()\nset()"]; +IntCollection -> IntList ; + +IntListIterator [label="[IntListIterator]|add()\nhasPrevious()\nnextIndex()\nprevious()\npreviousIndex()\nset()"]; +IntIterator -> IntListIterator ; + +IntArrayList [label="IntArrayList|"]; +IntList -> IntArrayList ; + +IntLinkedList [label="IntLinkedList|"]; +IntList -> IntLinkedList ; + +IntSet [label="[IntSet]|"]; +IntCollection -> IntSet ; + +IntSortedSet [label="[IntSortedSet]|comparator()"]; +IntSet -> IntSortedSet ; + +AssocArraySet [label="AssocArraySet|"]; +IntSortedSet -> AssocArraySet ; + +IntMap [label="[IntMap]|clear()\ncontainsKey()\ncontainsValue()\nentrySet()\nfindKey()\nfindValue()\nget()\nisEmpty()\nkeySet()\nput()\nputAll()\nremove()\nsize()\nvalues()"]; +Object -> IntMap ; + +IntMapEntry [label="IntMapEntry|key\nvalue"]; +Object -> IntMapEntry ; + +IntSortedMap [label="[IntSortedMap]|comparator()"]; +IntMap -> IntSortedMap ; + +AssocArrayMap [label="AssocArrayMap|"]; +IntSortedMap -> AssocArrayMap ; + +} + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.mak b/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.mak new file mode 100644 index 0000000..4cc73e0 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intcollections.mak @@ -0,0 +1,14 @@ +SRC_FILES := \ + intcomparator.vr \ + intcollection.vr \ + intlist.vr \ + intarraylist.vr \ + intlinkedlist.vr \ + intset.vr \ + intsortedset.vr \ + intassocarrayset.vr \ + intmap.vr \ + intsortedmap.vr \ + intassocarraymap.vr + +LOAD_COMPS := collections/objcollections diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intcomparator.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intcomparator.vr new file mode 100644 index 0000000..f485e61 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intcomparator.vr @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "object.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../comparator_tmpl.vr" +//END_LOCAL + +//////////////////////////////////////////////////////////// +// NaturalIntComparator +//////////////////////////////////////////////////////////// + +class NaturalIntComparator +extends IntComparator +{ + task new() + { + setClassName("NaturalIntComparator"); + } + + virtual function integer compare(integer o1, integer o2) + { + compare = o1 - o2; + } + + virtual function bit equals(Object o) + { + NaturalIntComparator otherNIComp; + + equals = (o != null && cast_assign(otherNIComp, o, CHECK)); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intlinkedlist.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intlinkedlist.vr new file mode 100644 index 0000000..5ed4dba --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intlinkedlist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intlist.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../linkedlist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intlist.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intlist.vr new file mode 100644 index 0000000..2103b18 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intlist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intcollection.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../list_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intmap.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intmap.vr new file mode 100644 index 0000000..f691ed6 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intmap.vr @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" +#include "collection.vrh" +#include "set.vrh" +#include "intset.vrh" + +//LOCAL +#include "kv_int_obj_defines.vr" +#include "../map_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intset.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intset.vr new file mode 100644 index 0000000..82c7e35 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intset.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intcollection.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../set_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intsortedmap.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intsortedmap.vr new file mode 100644 index 0000000..71d567d --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intsortedmap.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intmap.vrh" +#include "intcomparator.vrh" + +//LOCAL +#include "kv_int_obj_defines.vr" +#include "../sortedmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/intsortedset.vr b/java/juno-samples/xmlreader/src/collections/intcollections/intsortedset.vr new file mode 100644 index 0000000..d9ae6c3 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/intsortedset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "intset.vrh" +#include "intcomparator.vrh" + +//LOCAL +#include "elem_int_defines.vr" +#include "../sortedset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/intcollections/kv_int_obj_defines.vr b/java/juno-samples/xmlreader/src/collections/intcollections/kv_int_obj_defines.vr new file mode 100644 index 0000000..de9a0c0 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/intcollections/kv_int_obj_defines.vr @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +// key type defines + +#define KEY_TYPE integer +#define KEY_NULL -1 + +#define KEY_DUMP_STRING(o) psprintf("%0d", o) +#define KEY_EQUALS(a,b) (a == b) +#define KEY_HASH_CODE(o) o +#define KEY_DESTROY(o) o = -1 + +#define KEY_SET_CLASS IntSet +#define KEY_ITERATOR_CLASS IntIterator +#define KEY_COMPARATOR_CLASS IntComparator +#define DEFAULT_KEY_COMPARATOR_CLASS NaturalIntComparator + +// value type defines + +#define VALUE_TYPE Object +#define VALUE_NULL null + +#define VALUE_DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define VALUE_EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define VALUE_HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define VALUE_DESTROY(o) if (o != null) o.destroy() + +#define VALUE_COLLECTION_CLASS Collection +#define VALUE_ITERATOR_CLASS Iterator + +// Map defines + +#define MAP_CLASS IntMap +#define MAP_ENTRY_CLASS IntMapEntry +#define MAP_KEY_SET_CLASS IntMapKeySet +#define MAP_VALUE_COLLECTION_CLASS IntMapValueCollection +#define ENTRY_SET_KEY_ITERATOR_CLASS IntEntrySetKeyIterator +#define ENTRY_SET_VALUE_ITERATOR_CLASS IntEntrySetValueIterator + +// SortedMap defines + +#define SORTED_MAP_CLASS IntSortedMap + +// AssocArrayMap defines + +#define ASSOC_ARRAY_MAP_CLASS IntAssocArrayMap +#define ASSOC_ARRAY_MAP_ENTRY_SET_CLASS IntAssocArrayMapEntrySet +#define ASSOC_ARRAY_MAP_KEY_SET_CLASS IntAssocArrayMapKeySet +#define ASSOC_ARRAY_MAP_VALUE_COLLECTION_CLASS IntAssocArrayMapValueCollection +#define ASSOC_ARRAY_MAP_ENTRY_ITERATOR_CLASS IntAssocArrayMapEntryIterator +#define ASSOC_ARRAY_MAP_KEY_ITERATOR_CLASS IntAssocArrayMapKeyIterator +#define ASSOC_ARRAY_MAP_VALUE_ITERATOR_CLASS IntAssocArrayMapValueIterator +#define ASSOC_ARRAY_MAP_SUB_MAP_CLASS IntAssocArrayMapSubMap +#define ASSOC_ARRAY_MAP_SUB_MAP_ENTRY_SET_CLASS IntAssocArrayMapSubMapEntrySet + diff --git a/java/juno-samples/xmlreader/src/collections/linkedhashmap_tmpl.vr b/java/juno-samples/xmlreader/src/collections/linkedhashmap_tmpl.vr new file mode 100644 index 0000000..242feda --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/linkedhashmap_tmpl.vr @@ -0,0 +1,584 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// LinkedHashMap +//////////////////////////////////////////////////////////// + +typedef class LINKED_HASH_MAP_ENTRY_CLASS; +typedef class LINKED_HASH_MAP_ENTRY_SET_CLASS; +typedef class LINKED_HASH_MAP_KEY_SET_CLASS; +typedef class LINKED_HASH_MAP_VALUE_COLLECTION_CLASS; + +class LINKED_HASH_MAP_CLASS +extends MAP_CLASS +{ + // For local use only! + LINKED_HASH_MAP_ENTRY_CLASS hashTable[]; + LINKED_HASH_MAP_ENTRY_CLASS iterHead; + LINKED_HASH_MAP_ENTRY_CLASS iterTail; + integer tableSize; + integer count; + local integer threshold; + + // Map + virtual task clear(); + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual function KEY_SET_CLASS keySet(); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + virtual function integer size(); + virtual function VALUE_COLLECTION_CLASS values(); + + // LinkedHashMap + task new(integer initialCapacity = 16); + + local task resize(integer newTableSize); +} + +task LINKED_HASH_MAP_CLASS::clear() +{ + LINKED_HASH_MAP_ENTRY_CLASS cur; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + // break back-references for garbage collection + cur = iterHead; + while (cur != null) { + if (destroyKeyOnRemove) { + cur.destroyKey(); + } + if (destroyValueOnRemove) { + cur.destroyValue(); + } + cur.iterPrev = null; + cur = cur.iterNext; + } + iterHead = null; + iterTail = null; + + assoc_index(DELETE, hashTable); + count = 0; +} + +function Set LINKED_HASH_MAP_CLASS::entrySet() +{ + LINKED_HASH_MAP_ENTRY_SET_CLASS hashMapEntrySet = new(this); + entrySet = hashMapEntrySet; +} + +function MAP_ENTRY_CLASS LINKED_HASH_MAP_CLASS::findKey(KEY_TYPE key) +{ + integer hash, index; + LINKED_HASH_MAP_ENTRY_CLASS entry; + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + entry = hashTable[index]; + while (entry != null) { + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + findKey = entry; + return; + } + entry = entry.bucketNext; + } + + findKey = null; +} + +function KEY_SET_CLASS LINKED_HASH_MAP_CLASS::keySet() +{ + LINKED_HASH_MAP_KEY_SET_CLASS hashMapKeySet = new(this); + keySet = hashMapKeySet; +} + +task LINKED_HASH_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + integer hash, index; + LINKED_HASH_MAP_ENTRY_CLASS entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.put(%s, %s)", + getObjectName(), KEY_DUMP_STRING(key), VALUE_DUMP_STRING(value))) + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + entry = hashTable[index]; + while (entry != null) { + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + if (destroyValueOnRemove) { + VALUE_TYPE victim = entry.value; + VALUE_DESTROY(victim); + } + entry.value = value; + return; + } + entry = entry.bucketNext; + } + + entry = new(key, value, hash, hashTable[index], iterTail, null); + hashTable[index] = entry; + if (iterTail != null) { + iterTail.iterNext = entry; + } + iterTail = entry; + if (iterHead == null) { + iterHead = entry; + } + + if (++count >= threshold) { + resize(tableSize * 2); + } +} + +task LINKED_HASH_MAP_CLASS::remove(KEY_TYPE key) +{ + integer hash, index; + LINKED_HASH_MAP_ENTRY_CLASS prevEntry, entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), KEY_DUMP_STRING(key))) + + hash = suppHash(KEY_HASH_CODE(key)); + index = hash & (tableSize - 1); + prevEntry = null; + entry = hashTable[index]; + while (entry != null) { + LINKED_HASH_MAP_ENTRY_CLASS bucketNext; + + bucketNext = entry.bucketNext; + + if (hash == entry.hashCode && KEY_EQUALS(key, entry.key)) { + // destroy object if requested + if (destroyKeyOnRemove) { + entry.destroyKey(); + } + if (destroyValueOnRemove) { + entry.destroyValue(); + } + + // remove from bucket chain + if (prevEntry == null) { + hashTable[index] = bucketNext; + } + else { + prevEntry.bucketNext = bucketNext; + } + + // remove from iteration chain + if (entry.iterPrev != null) { + entry.iterPrev.iterNext = entry.iterNext; + } + else { + iterHead = entry.iterNext; + } + if (entry.iterNext != null) { + entry.iterNext.iterPrev = entry.iterPrev; + } + else { + iterTail = entry.iterPrev; + } + + // break references + entry.bucketNext = null; + entry.iterPrev = null; + entry.iterNext = null; + + return; + } + + prevEntry = entry; + entry = bucketNext; + } +} + +function integer LINKED_HASH_MAP_CLASS::size() +{ + size = count; +} + +function VALUE_COLLECTION_CLASS LINKED_HASH_MAP_CLASS::values() +{ + LINKED_HASH_MAP_VALUE_COLLECTION_CLASS hashMapValues = new(this); + values = hashMapValues; +} + +task LINKED_HASH_MAP_CLASS::new(integer initialCapacity = 16) +{ + integer size; + + setClassName("LinkedHashMap"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%0d)", + getObjectName(), initialCapacity)) + + // table is initially empty + tableSize = 0; + count = 0; + + // find power of 2 table size >= initial capacity + size = 1; + while (size < initialCapacity) { + size <<= 1; + } + + // update table size and threshold + resize(size); +} + +task LINKED_HASH_MAP_CLASS::resize(integer newTableSize) +{ + integer index; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.resize(%0d)", + getObjectName(), newTableSize)) + + // rebuild hash buckets + for (index = 0; index < tableSize; ++index) { + LINKED_HASH_MAP_ENTRY_CLASS prevEntry, entry; + + prevEntry = null; + entry = hashTable[index]; + while (entry != null) { + LINKED_HASH_MAP_ENTRY_CLASS bucketNext; + integer newIndex; + + bucketNext = entry.bucketNext; + + // move entry if index changed + newIndex = entry.hashCode & (newTableSize - 1); + if (newIndex != index) { + + // remove entry from old list + if (prevEntry == null) { + hashTable[index] = bucketNext; + } + else { + prevEntry.bucketNext = bucketNext; + } + + // add entry to new list + entry.bucketNext = hashTable[newIndex]; + hashTable[newIndex] = entry; + } + else { + // previous entry only advances if index is unchanged + prevEntry = entry; + } + + entry = bucketNext; + } + } + + // set new table size + tableSize = newTableSize; + + // resize at 75% load factor + threshold = tableSize * 3 / 4; +} + +// supplemental hash function to improve hash distribution +local function integer suppHash(integer hashCode) +{ + bit[31:0] uh = hashCode; + + uh += ~(uh << 9); + uh ^= (uh >> 14); + uh += (uh << 4); + uh ^= (uh >> 10); + + suppHash = uh; +} + +//////////////////////////////////////////////////////////// +// LinkedHashMapEntry +//////////////////////////////////////////////////////////// + +class LINKED_HASH_MAP_ENTRY_CLASS +extends MAP_ENTRY_CLASS +{ + integer hashCode; + LINKED_HASH_MAP_ENTRY_CLASS bucketNext; + LINKED_HASH_MAP_ENTRY_CLASS iterPrev; + LINKED_HASH_MAP_ENTRY_CLASS iterNext; + + task new(KEY_TYPE _key, VALUE_TYPE _value, integer _hashCode, + LINKED_HASH_MAP_ENTRY_CLASS _bucketNext, + LINKED_HASH_MAP_ENTRY_CLASS _iterPrev, + LINKED_HASH_MAP_ENTRY_CLASS _iterNext) + { + super.new(_key, _value); + + hashCode = _hashCode; + bucketNext = _bucketNext; + iterPrev = _iterPrev; + iterNext = _iterNext; + } +} + +//////////////////////////////////////////////////////////// +// LinkedHashMapEntrySet +//////////////////////////////////////////////////////////// + +typedef class LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS; + +local class LINKED_HASH_MAP_ENTRY_SET_CLASS +extends Set +{ + local LINKED_HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(Object o); + virtual task clear(); + virtual function bit contains(Object o); + virtual function Iterator iterator(); + virtual task remove(Object o); + virtual function integer size(); + + // LinkedHashMapEntrySet + task new(LINKED_HASH_MAP_CLASS _hashMap); +} + +task LINKED_HASH_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map entry sets") +} + +task LINKED_HASH_MAP_ENTRY_SET_CLASS::clear() +{ + hashMap.clear(); +} + +function bit LINKED_HASH_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = hashMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function Iterator LINKED_HASH_MAP_ENTRY_SET_CLASS::iterator() +{ + LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + + iterator = entryIter; +} + +task LINKED_HASH_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + mapEntry = hashMap.findKey(entry.key); + if (mapEntry != null && mapEntry.equals(entry)) { + hashMap.remove(entry.key); + } +} + +function integer LINKED_HASH_MAP_ENTRY_SET_CLASS::size() +{ + size = hashMap.size(); +} + +task LINKED_HASH_MAP_ENTRY_SET_CLASS::new(LINKED_HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// LinkedHashMapKeySet +//////////////////////////////////////////////////////////// + +local class LINKED_HASH_MAP_KEY_SET_CLASS +extends KEY_SET_CLASS +{ + local LINKED_HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(KEY_TYPE o); + virtual task clear(); + virtual function bit contains(KEY_TYPE o); + virtual function KEY_ITERATOR_CLASS iterator(); + virtual task remove(KEY_TYPE o); + virtual function integer size(); + + // LinkedHashMapKeySet + task new(LINKED_HASH_MAP_CLASS _hashMap); +} + +task LINKED_HASH_MAP_KEY_SET_CLASS::add(KEY_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map key sets") +} + +task LINKED_HASH_MAP_KEY_SET_CLASS::clear() +{ + hashMap.clear(); +} + +function bit LINKED_HASH_MAP_KEY_SET_CLASS::contains(KEY_TYPE o) +{ + contains = hashMap.containsKey(o); +} + +function KEY_ITERATOR_CLASS LINKED_HASH_MAP_KEY_SET_CLASS::iterator() +{ + LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + ENTRY_SET_KEY_ITERATOR_CLASS keyIter = new(entryIter); + + iterator = keyIter; +} + +task LINKED_HASH_MAP_KEY_SET_CLASS::remove(KEY_TYPE o) +{ + hashMap.remove(o); +} + +function integer LINKED_HASH_MAP_KEY_SET_CLASS::size() +{ + size = hashMap.size(); +} + +task LINKED_HASH_MAP_KEY_SET_CLASS::new(LINKED_HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// LinkedHashMapValueCollection +//////////////////////////////////////////////////////////// + +local class LINKED_HASH_MAP_VALUE_COLLECTION_CLASS +extends VALUE_COLLECTION_CLASS +{ + local LINKED_HASH_MAP_CLASS hashMap; + + // Collection + virtual task add(VALUE_TYPE o); + virtual task clear(); + virtual function bit contains(VALUE_TYPE o); + virtual function VALUE_ITERATOR_CLASS iterator(); + virtual function integer size(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // LinkedHashMapValueCollection + task new(LINKED_HASH_MAP_CLASS _hashMap); +} + +function bit LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on map value collections") +} + +function integer LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::hashCode() +{ + hashCode = 0; + LOG_MSG(logIntf, LS_FATAL, "hashCode() not supported on map value collections") +} + + +task LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::add(VALUE_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map value collections") +} + +task LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::clear() +{ + hashMap.clear(); +} + +function bit LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::contains(VALUE_TYPE o) +{ + contains = hashMap.containsValue(o); +} + +function VALUE_ITERATOR_CLASS LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::iterator() +{ + LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS entryIter = new(hashMap); + ENTRY_SET_VALUE_ITERATOR_CLASS valueIter = new(entryIter); + + iterator = valueIter; +} + +function integer LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::size() +{ + size = hashMap.size(); +} + +task LINKED_HASH_MAP_VALUE_COLLECTION_CLASS::new(LINKED_HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; +} + +//////////////////////////////////////////////////////////// +// LinkedHashMapEntryIterator +//////////////////////////////////////////////////////////// + +local class LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS +extends Iterator +{ + local LINKED_HASH_MAP_CLASS hashMap; + local LINKED_HASH_MAP_ENTRY_CLASS curEntry; + local LINKED_HASH_MAP_ENTRY_CLASS nextEntry; + + task new(LINKED_HASH_MAP_CLASS _hashMap); + + virtual function bit hasNext(); + virtual function Object next(); + virtual task remove(); +} + +task LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS::new(LINKED_HASH_MAP_CLASS _hashMap) +{ + hashMap = _hashMap; + curEntry = null; + nextEntry = _hashMap.iterHead; +} + +function bit LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextEntry != null); +} + +function Object LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS::next() +{ + assert(nextEntry != null); + + curEntry = nextEntry; + nextEntry = curEntry.iterNext; + next = curEntry; +} + +task LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS::remove() +{ + if (curEntry == null) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + hashMap.remove(curEntry.key); + curEntry = null; +} + diff --git a/java/juno-samples/xmlreader/src/collections/linkedlist_tmpl.vr b/java/juno-samples/xmlreader/src/collections/linkedlist_tmpl.vr new file mode 100644 index 0000000..54d3c44 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/linkedlist_tmpl.vr @@ -0,0 +1,401 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// LinkedList +//////////////////////////////////////////////////////////// + +typedef class LINKED_LIST_NODE_CLASS; +typedef class LINKED_LIST_ITERATOR_CLASS; + +class LINKED_LIST_CLASS +extends LIST_CLASS +{ + // For local use only! + LINKED_LIST_NODE_CLASS head; + LINKED_LIST_NODE_CLASS tail; + integer count; + + // Collection + virtual task add(ELEMENT_TYPE o); + virtual task clear(); + virtual function integer size(); + + // List + virtual task addAt(integer index, ELEMENT_TYPE o); + virtual task addFirst(ELEMENT_TYPE o); + virtual task addLast(ELEMENT_TYPE o); + virtual function ELEMENT_TYPE get(integer index); + virtual function ELEMENT_TYPE getFirst(); + virtual function ELEMENT_TYPE getLast(); + virtual function LIST_ITERATOR_CLASS listIteratorAt(integer index); + virtual task removeAt(integer index); + virtual task set(integer index, ELEMENT_TYPE o); + + // LinkedList + task new(); + + // For local use only! + task addBeforeNode(LINKED_LIST_NODE_CLASS node, ELEMENT_TYPE o); + task removeNode(LINKED_LIST_NODE_CLASS node); +} + +task LINKED_LIST_CLASS::add(ELEMENT_TYPE o) +{ + addLast(o); +} + +task LINKED_LIST_CLASS::clear() +{ + LINKED_LIST_NODE_CLASS cur; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + // break prev-references for garbage collection + cur = head; + while (cur != null) { + if (destroyOnRemove) { + ELEMENT_TYPE victim = cur.item; + DESTROY(victim); + } + cur.prev = null; + cur = cur.next; + } + + head = null; + tail = null; + count = 0; +} + +function integer LINKED_LIST_CLASS::size() +{ + size = count; +} + +task LINKED_LIST_CLASS::addAt(integer index, ELEMENT_TYPE o) +{ + LIST_ITERATOR_CLASS li = listIteratorAt(index); + + li.add(o); +} + +task LINKED_LIST_CLASS::addFirst(ELEMENT_TYPE o) +{ + LINKED_LIST_NODE_CLASS newNode; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.addFirst(%s)", + getObjectName(), DUMP_STRING(o))) + + newNode = new; + newNode.item = o; + if (head != null) { + newNode.next = head; + head.prev = newNode; + } else { + tail = newNode; + } + head = newNode; + ++count; +} + +task LINKED_LIST_CLASS::addLast(ELEMENT_TYPE o) +{ + LINKED_LIST_NODE_CLASS newNode; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.addLast(%s)", + getObjectName(), DUMP_STRING(o))) + + newNode = new; + newNode.item = o; + if (tail != null) { + newNode.prev = tail; + tail.next = newNode; + } else { + head = newNode; + } + tail = newNode; + ++count; +} + +function ELEMENT_TYPE LINKED_LIST_CLASS::get(integer index) +{ + LIST_ITERATOR_CLASS li = listIteratorAt(index); + + get = li.next(); +} + +function ELEMENT_TYPE LINKED_LIST_CLASS::getFirst() +{ + assert(count > 0); + + getFirst = head.item; +} + +function ELEMENT_TYPE LINKED_LIST_CLASS::getLast() +{ + assert(count > 0); + + getLast = tail.item; +} + +function LIST_ITERATOR_CLASS LINKED_LIST_CLASS::listIteratorAt(integer index) +{ + LINKED_LIST_ITERATOR_CLASS lli = new(this, index); + + listIteratorAt = lli; +} + +task LINKED_LIST_CLASS::removeAt(integer index) +{ + LIST_ITERATOR_CLASS li = listIteratorAt(index); + + void = li.next(); + li.remove(); +} + +task LINKED_LIST_CLASS::set(integer index, ELEMENT_TYPE o) +{ + LIST_ITERATOR_CLASS li = listIteratorAt(index); + + void = li.next(); + li.set(o); +} + +task LINKED_LIST_CLASS::new() +{ + setClassName("LinkedList"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new()", + getObjectName())) + + count = 0; +} + +task LINKED_LIST_CLASS::addBeforeNode(LINKED_LIST_NODE_CLASS node, ELEMENT_TYPE o) +{ + LINKED_LIST_NODE_CLASS newNode; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.addBeforeNode(%s, %s)", + getObjectName(), OBJECT_DUMP_STRING(node), DUMP_STRING(o))) + + newNode = new; + newNode.item = o; + if (node != null) { + newNode.next = node; + newNode.prev = node.prev; + node.prev = newNode; + if (newNode.prev != null) { + newNode.prev.next = newNode; + } else { + head = newNode; + } + } else { + if (tail != null) { + newNode.prev = tail; + tail.next = newNode; + } else { + head = newNode; + } + tail = newNode; + } + ++count; +} + +task LINKED_LIST_CLASS::removeNode(LINKED_LIST_NODE_CLASS node) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.removeNode(%s)", + getObjectName(), OBJECT_DUMP_STRING(node))) + + assert(node != null); + + if (node.prev != null) { + node.prev.next = node.next; + } else { + head = node.next; + } + if (node.next != null) { + node.next.prev = node.prev; + } else { + tail = node.prev; + } + --count; + + if (destroyOnRemove) { + ELEMENT_TYPE victim = node.item; + DESTROY(victim); + } + + // break references for garbage collection + node.next = null; + node.prev = null; +} + +//////////////////////////////////////////////////////////// +// LinkedListIterator +//////////////////////////////////////////////////////////// + +local class LINKED_LIST_ITERATOR_CLASS +extends LIST_ITERATOR_CLASS +{ + local LINKED_LIST_CLASS list; + local LINKED_LIST_NODE_CLASS curNode; + local integer curIndex; + local LINKED_LIST_NODE_CLASS lastNode; + + task new(LINKED_LIST_CLASS _list, integer index = 0); + + virtual task add(ELEMENT_TYPE o); + virtual function bit hasNext(); + virtual function bit hasPrevious(); + virtual function ELEMENT_TYPE next(); + virtual function integer nextIndex(); + virtual function ELEMENT_TYPE previous(); + virtual function integer previousIndex(); + virtual task remove(); + virtual task set(ELEMENT_TYPE o); + + local task checkLast(); +} + +task LINKED_LIST_ITERATOR_CLASS::new(LINKED_LIST_CLASS _list, integer index = 0) +{ + integer size; + + setClassName("LinkedListIterator"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%s, %0d)", + getObjectName(), OBJECT_NAME(_list), index)) + + list = _list; + + size = list.count; + + assert(index >= 0 && index <= size); + + if (index < (size >> 1)) { + curNode = list.head; + for (curIndex = 0; curIndex < index; ++curIndex) { + curNode = curNode.next; + } + } + else if (index < size) { + curNode = list.tail; + for (curIndex = size - 1; curIndex > index; --curIndex) { + curNode = curNode.prev; + } + } + else { + curNode = null; + curIndex = size; + } +} + +task LINKED_LIST_ITERATOR_CLASS::add(ELEMENT_TYPE o) +{ + list.addBeforeNode(curNode, o); + ++curIndex; + lastNode = null; +} + +function bit LINKED_LIST_ITERATOR_CLASS::hasNext() +{ + hasNext = (curIndex < list.count); +} + +function bit LINKED_LIST_ITERATOR_CLASS::hasPrevious() +{ + hasPrevious = (curIndex > 0); +} + +function ELEMENT_TYPE LINKED_LIST_ITERATOR_CLASS::next() +{ + assert(curIndex < list.count); + + lastNode = curNode; + curNode = curNode.next; + ++curIndex; + next = lastNode.item; +} + +function integer LINKED_LIST_ITERATOR_CLASS::nextIndex() +{ + nextIndex = curIndex; +} + +function ELEMENT_TYPE LINKED_LIST_ITERATOR_CLASS::previous() +{ + assert(curIndex > 0); + + if (curNode != null) { + curNode = curNode.prev; + } else { + curNode = list.tail; + } + lastNode = curNode; + --curIndex; + previous = lastNode.item; +} + +function integer LINKED_LIST_ITERATOR_CLASS::previousIndex() +{ + previousIndex = curIndex - 1; +} + +task LINKED_LIST_ITERATOR_CLASS::remove() +{ + checkLast(); + if (curNode == lastNode) { + curNode = curNode.next; + } else { + --curIndex; + } + list.removeNode(lastNode); + lastNode = null; +} + +task LINKED_LIST_ITERATOR_CLASS::set(ELEMENT_TYPE o) +{ + checkLast(); + if (list.isDestroyOnRemove()) { + ELEMENT_TYPE victim = lastNode.item; + DESTROY(victim); + } + lastNode.item = o; +} + +task LINKED_LIST_ITERATOR_CLASS::checkLast() +{ + if (lastNode == null) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } +} + +//////////////////////////////////////////////////////////// +// LinkedListNode +//////////////////////////////////////////////////////////// + +class LINKED_LIST_NODE_CLASS +{ + ELEMENT_TYPE item; + LINKED_LIST_NODE_CLASS prev; + LINKED_LIST_NODE_CLASS next; + + function string dumpString() + { + dumpString = psprintf("LinkedListNode[item=%s]", DUMP_STRING(item)); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/list_tmpl.vr b/java/juno-samples/xmlreader/src/collections/list_tmpl.vr new file mode 100644 index 0000000..56f8509 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/list_tmpl.vr @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// ListIterator +//////////////////////////////////////////////////////////// + +virtual class LIST_ITERATOR_CLASS +extends ITERATOR_CLASS +{ + // all abstract + virtual task add(ELEMENT_TYPE o); + virtual function bit hasPrevious(); + virtual function integer nextIndex(); + virtual function ELEMENT_TYPE previous(); + virtual function integer previousIndex(); + virtual task set(ELEMENT_TYPE o); +} + +//////////////////////////////////////////////////////////// +// List +//////////////////////////////////////////////////////////// + +virtual class LIST_CLASS +extends COLLECTION_CLASS +{ + // Object + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // Collection + virtual function ITERATOR_CLASS iterator(); + + // List + virtual task addAt(integer index, ELEMENT_TYPE o); // abstract + virtual task addAllAt(integer index, COLLECTION_CLASS c); + virtual task addFirst(ELEMENT_TYPE o); + virtual task addLast(ELEMENT_TYPE o); + virtual function ELEMENT_TYPE get(integer index); // abstract + virtual function ELEMENT_TYPE getFirst(); + virtual function ELEMENT_TYPE getLast(); + virtual function integer indexOf(ELEMENT_TYPE o); + virtual function integer lastIndexOf(ELEMENT_TYPE o); + virtual function LIST_ITERATOR_CLASS listIterator(); + virtual function LIST_ITERATOR_CLASS listIteratorAt(integer index); // abstract + virtual task removeAt(integer index); // abstract + virtual task set(integer index, ELEMENT_TYPE o); // abstract +} + +function bit LIST_CLASS::equals(Object o) +{ + Object thisObject; + LIST_CLASS otherList; + ITERATOR_CLASS i1, i2; + + thisObject = this; + if (o == thisObject) { + equals = 1; + return; + } + if (!cast_assign(otherList, o, CHECK)) { + equals = 0; + return; + } + + i1 = iterator(); + i2 = otherList.iterator(); + while (i1.hasNext() && i2.hasNext()) { + ELEMENT_TYPE i1o, i2o; + + i1o = i1.next(); + i2o = i2.next(); + if (!EQUALS(i1o, i2o)) { + equals = 0; + return; + } + } + + equals = !i1.hasNext() && !i2.hasNext(); +} + +function integer LIST_CLASS::hashCode() +{ + ITERATOR_CLASS i; + integer h; + + i = iterator(); + h = 1; + while (i.hasNext()) { + ELEMENT_TYPE io; + + io = i.next(); + h = (h * 31) + HASH_CODE(io); + } + + hashCode = h; +} + +task LIST_CLASS::addAllAt(integer index, COLLECTION_CLASS c) +{ + LIST_ITERATOR_CLASS li; + ITERATOR_CLASS ci; + + li = listIteratorAt(index); + ci = c.iterator(); + while (ci.hasNext()) { + ELEMENT_TYPE cio; + + cio = ci.next(); + li.add(cio); + } +} + +task LIST_CLASS::addFirst(ELEMENT_TYPE o) +{ + addAt(0, o); +} + +task LIST_CLASS::addLast(ELEMENT_TYPE o) +{ + add(o); +} + +function ELEMENT_TYPE LIST_CLASS::getFirst() +{ + getFirst = get(0); +} + +function ELEMENT_TYPE LIST_CLASS::getLast() +{ + getLast = get(size() - 1); +} + +function integer LIST_CLASS::indexOf(ELEMENT_TYPE o) +{ + LIST_ITERATOR_CLASS li; + + li = listIteratorAt(0); + while (li.hasNext()) { + ELEMENT_TYPE lio; + + lio = li.next(); + if (EQUALS(o, lio)) { + indexOf = li.previousIndex(); + return; + } + } + + indexOf = -1; +} + +function ITERATOR_CLASS LIST_CLASS::iterator() +{ + iterator = listIteratorAt(0); +} + +function integer LIST_CLASS::lastIndexOf(ELEMENT_TYPE o) +{ + LIST_ITERATOR_CLASS li; + + li = listIteratorAt(size()); + while (li.hasPrevious()) { + ELEMENT_TYPE lio; + + lio = li.previous(); + if (EQUALS(o, lio)) { + lastIndexOf = li.nextIndex(); + return; + } + } + + lastIndexOf = -1; +} + +function LIST_ITERATOR_CLASS LIST_CLASS::listIterator() +{ + listIterator = listIteratorAt(0); +} + diff --git a/java/juno-samples/xmlreader/src/collections/map_tmpl.vr b/java/juno-samples/xmlreader/src/collections/map_tmpl.vr new file mode 100644 index 0000000..2ed835f --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/map_tmpl.vr @@ -0,0 +1,533 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// Map +//////////////////////////////////////////////////////////// + +typedef class MAP_ENTRY_CLASS; +typedef class MAP_KEY_SET_CLASS; +typedef class MAP_VALUE_COLLECTION_CLASS; + +virtual class MAP_CLASS +extends CollectionsBase +{ + protected bit destroyKeyOnRemove; + protected bit destroyValueOnRemove; + + // Object + virtual function string dumpString(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + virtual task destroy(); + + // Map + virtual task clear(); + virtual function bit containsKey(KEY_TYPE key); + virtual function bit containsValue(VALUE_TYPE value); + virtual function Set entrySet(); // abstract + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual function MAP_ENTRY_CLASS findValue(VALUE_TYPE value); + virtual function VALUE_TYPE get(KEY_TYPE key); + function bit isDestroyKeyOnRemove(); + function bit isDestroyValueOnRemove(); + virtual function bit isEmpty(); + virtual function KEY_SET_CLASS keySet(); + virtual task put(KEY_TYPE key, VALUE_TYPE value); // abstract + virtual task putAll(MAP_CLASS map); + virtual task remove(KEY_TYPE key); + virtual task setDestroyKeyOnRemove(bit value); + virtual task setDestroyValueOnRemove(bit value); + virtual function integer size(); + virtual function VALUE_COLLECTION_CLASS values(); + + task new(); +} + +function string MAP_CLASS::dumpString() +{ + Set es; + + es = entrySet(); + dumpString = es.dumpString(); +} + +function bit MAP_CLASS::equals(Object o) +{ + Object thisObject; + MAP_CLASS otherMap; + Set es; + Iterator i; + + thisObject = this; + if (o == thisObject) { + equals = 1; + return; + } + if (!cast_assign(otherMap, o, CHECK)) { + equals = 0; + return; + } + if (size() != otherMap.size()) { + equals = 0; + return; + } + + es = entrySet(); + i = es.iterator(); + while (i.hasNext()) { + MAP_ENTRY_CLASS thisEntry; + MAP_ENTRY_CLASS otherEntry; + + cast_assign(thisEntry, i.next()); + otherEntry = otherMap.findKey(thisEntry.key); + if (otherEntry == null || + !VALUE_EQUALS(thisEntry.value, otherEntry.value)) { + equals = 0; + return; + } + } + + equals = 1; +} + +function integer MAP_CLASS::hashCode() +{ + Set es; + + es = entrySet(); + hashCode = es.hashCode(); +} + +task MAP_CLASS::destroy() +{ + clear(); +} + +task MAP_CLASS::clear() +{ + Set es; + + es = entrySet(); + es.clear(); +} + +function bit MAP_CLASS::containsKey(KEY_TYPE key) +{ + MAP_ENTRY_CLASS entry; + + entry = findKey(key); + containsKey = (entry != null); +} + +function bit MAP_CLASS::containsValue(VALUE_TYPE value) +{ + MAP_ENTRY_CLASS entry; + + entry = findValue(value); + containsValue = (entry != null); +} + +function MAP_ENTRY_CLASS MAP_CLASS::findKey(KEY_TYPE key) +{ + Set es; + Iterator i; + + es = entrySet(); + i = es.iterator(); + while (i.hasNext()) { + MAP_ENTRY_CLASS entry; + + cast_assign(entry, i.next()); + if (KEY_EQUALS(key, entry.key)) { + findKey = entry; + return; + } + } + + findKey = null; +} + +function MAP_ENTRY_CLASS MAP_CLASS::findValue(VALUE_TYPE value) +{ + Set es; + Iterator i; + + es = entrySet(); + i = es.iterator(); + while (i.hasNext()) { + MAP_ENTRY_CLASS entry; + + cast_assign(entry, i.next()); + if (VALUE_EQUALS(value, entry.value)) { + findValue = entry; + return; + } + } + + findValue = null; +} + +function VALUE_TYPE MAP_CLASS::get(KEY_TYPE key) +{ + MAP_ENTRY_CLASS entry; + + entry = findKey(key); + get = (entry != null) ? entry.value : VALUE_NULL; +} + +function bit MAP_CLASS::isDestroyKeyOnRemove() +{ + isDestroyKeyOnRemove = destroyKeyOnRemove; +} + +function bit MAP_CLASS::isDestroyValueOnRemove() +{ + isDestroyValueOnRemove = destroyValueOnRemove; +} + +function bit MAP_CLASS::isEmpty() +{ + isEmpty = (size() == 0); +} + +function KEY_SET_CLASS MAP_CLASS::keySet() +{ + MAP_KEY_SET_CLASS mapKeySet = new(this); + keySet = mapKeySet; +} + +task MAP_CLASS::putAll(MAP_CLASS map) +{ + Set es; + Iterator i; + + es = map.entrySet(); + i = es.iterator(); + while (i.hasNext()) { + MAP_ENTRY_CLASS entry; + + cast_assign(entry, i.next()); + put(entry.key, entry.value); + } +} + +task MAP_CLASS::remove(KEY_TYPE key) +{ + Set es; + Iterator i; + + es = entrySet(); + i = es.iterator(); + while (i.hasNext()) { + MAP_ENTRY_CLASS entry; + + cast_assign(entry, i.next()); + if (KEY_EQUALS(key, entry.key)) { + i.remove(); + return; + } + } +} + +task MAP_CLASS::setDestroyKeyOnRemove(bit value) +{ + destroyKeyOnRemove = value; +} + +task MAP_CLASS::setDestroyValueOnRemove(bit value) +{ + destroyValueOnRemove = value; +} + +function integer MAP_CLASS::size() +{ + Set es; + + es = entrySet(); + size = es.size(); +} + +function VALUE_COLLECTION_CLASS MAP_CLASS::values() +{ + MAP_VALUE_COLLECTION_CLASS mapValues = new(this); + values = mapValues; +} + +task MAP_CLASS::new() +{ + destroyKeyOnRemove = 0; + destroyValueOnRemove = 0; +} + +//////////////////////////////////////////////////////////// +// MapEntry +//////////////////////////////////////////////////////////// + +class MAP_ENTRY_CLASS +extends Object +{ + KEY_TYPE key; + VALUE_TYPE value; + + // Object + virtual function string dumpString(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + task destroyKey(); + task destroyValue(); + + task new(KEY_TYPE _key, VALUE_TYPE _value); +} + +function string MAP_ENTRY_CLASS::dumpString() +{ + dumpString = { KEY_DUMP_STRING(key), "=", VALUE_DUMP_STRING(value) }; +} + +function bit MAP_ENTRY_CLASS::equals(Object o) +{ + MAP_ENTRY_CLASS otherEntry; + + if (!cast_assign(otherEntry, o, CHECK)) { + equals = 0; + return; + } + + equals = KEY_EQUALS(key, otherEntry.key) && + VALUE_EQUALS(value, otherEntry.value); +} + +function integer MAP_ENTRY_CLASS::hashCode() +{ + hashCode = KEY_HASH_CODE(key) ^ VALUE_HASH_CODE(value); +} + +task MAP_ENTRY_CLASS::destroyKey() +{ + KEY_DESTROY(key); +} + +task MAP_ENTRY_CLASS::destroyValue() +{ + VALUE_DESTROY(value); +} + +task MAP_ENTRY_CLASS::new(KEY_TYPE _key, VALUE_TYPE _value) +{ + key = _key; + value = _value; +} + +//////////////////////////////////////////////////////////// +// MapKeySet +//////////////////////////////////////////////////////////// + +typedef class ENTRY_SET_KEY_ITERATOR_CLASS; + +local class MAP_KEY_SET_CLASS +extends KEY_SET_CLASS +{ + local MAP_CLASS map; + + // Collection + virtual task add(KEY_TYPE o); + virtual function bit contains(KEY_TYPE o); + virtual function KEY_ITERATOR_CLASS iterator(); + virtual function integer size(); + + // MapKeySet + task new(MAP_CLASS _map); +} + +task MAP_KEY_SET_CLASS::add(KEY_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map key sets") +} + +function bit MAP_KEY_SET_CLASS::contains(KEY_TYPE o) +{ + contains = map.containsKey(o); +} + +function KEY_ITERATOR_CLASS MAP_KEY_SET_CLASS::iterator() +{ + Set es; + Iterator i; + ENTRY_SET_KEY_ITERATOR_CLASS keyIter; + + es = map.entrySet(); + i = es.iterator(); + keyIter = new(i); + iterator = keyIter; +} + +function integer MAP_KEY_SET_CLASS::size() +{ + size = map.size(); +} + +task MAP_KEY_SET_CLASS::new(MAP_CLASS _map) +{ + map = _map; +} + +//////////////////////////////////////////////////////////// +// MapValueCollection +//////////////////////////////////////////////////////////// + +typedef class ENTRY_SET_VALUE_ITERATOR_CLASS; + +local class MAP_VALUE_COLLECTION_CLASS +extends VALUE_COLLECTION_CLASS +{ + local MAP_CLASS map; + + // Collection + virtual task add(VALUE_TYPE o); + virtual function bit contains(VALUE_TYPE o); + virtual function VALUE_ITERATOR_CLASS iterator(); + virtual function integer size(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // MapValueCollection + task new(MAP_CLASS _map); +} + +function bit MAP_VALUE_COLLECTION_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on map value collections") +} + +function integer MAP_VALUE_COLLECTION_CLASS::hashCode() +{ + hashCode = 0; + LOG_MSG(logIntf, LS_FATAL, "hashCode() not supported on map value collections") +} + + +task MAP_VALUE_COLLECTION_CLASS::add(VALUE_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map value collections") +} + +function bit MAP_VALUE_COLLECTION_CLASS::contains(VALUE_TYPE o) +{ + contains = map.containsValue(o); +} + +function VALUE_ITERATOR_CLASS MAP_VALUE_COLLECTION_CLASS::iterator() +{ + Set es; + Iterator i; + ENTRY_SET_VALUE_ITERATOR_CLASS valueIter; + + es = map.entrySet(); + i = es.iterator(); + valueIter = new(i); + iterator = valueIter; +} + +function integer MAP_VALUE_COLLECTION_CLASS::size() +{ + size = map.size(); +} + +task MAP_VALUE_COLLECTION_CLASS::new(MAP_CLASS _map) +{ + map = _map; +} + +//////////////////////////////////////////////////////////// +// EntrySetKeyIterator +//////////////////////////////////////////////////////////// + +class ENTRY_SET_KEY_ITERATOR_CLASS +extends KEY_ITERATOR_CLASS +{ + local Iterator entrySetIter; + + task new(Iterator _entrySetIter); + + virtual function bit hasNext(); + virtual function KEY_TYPE next(); + virtual task remove(); +} + +task ENTRY_SET_KEY_ITERATOR_CLASS::new(Iterator _entrySetIter) +{ + entrySetIter = _entrySetIter; +} + +function bit ENTRY_SET_KEY_ITERATOR_CLASS::hasNext() +{ + hasNext = entrySetIter.hasNext(); +} + +function KEY_TYPE ENTRY_SET_KEY_ITERATOR_CLASS::next() +{ + MAP_ENTRY_CLASS entry; + + cast_assign(entry, entrySetIter.next()); + next = entry.key; +} + +task ENTRY_SET_KEY_ITERATOR_CLASS::remove() +{ + entrySetIter.remove(); +} + +//////////////////////////////////////////////////////////// +// EntrySetValueIterator +//////////////////////////////////////////////////////////// + +class ENTRY_SET_VALUE_ITERATOR_CLASS +extends VALUE_ITERATOR_CLASS +{ + local Iterator entrySetIter; + + task new(Iterator _entrySetIter); + + virtual function bit hasNext(); + virtual function VALUE_TYPE next(); + virtual task remove(); +} + +task ENTRY_SET_VALUE_ITERATOR_CLASS::new(Iterator _entrySetIter) +{ + entrySetIter = _entrySetIter; +} + +function bit ENTRY_SET_VALUE_ITERATOR_CLASS::hasNext() +{ + hasNext = entrySetIter.hasNext(); +} + +function VALUE_TYPE ENTRY_SET_VALUE_ITERATOR_CLASS::next() +{ + MAP_ENTRY_CLASS entry; + + cast_assign(entry, entrySetIter.next()); + next = entry.value; +} + +task ENTRY_SET_VALUE_ITERATOR_CLASS::remove() +{ + entrySetIter.remove(); +} + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/arraylist.vr b/java/juno-samples/xmlreader/src/collections/objcollections/arraylist.vr new file mode 100644 index 0000000..c34ad69 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/arraylist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "list.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../arraylist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/collection.vr b/java/juno-samples/xmlreader/src/collections/objcollections/collection.vr new file mode 100644 index 0000000..1e19851 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/collection.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../collection_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/collectionsbase.vr b/java/juno-samples/xmlreader/src/collections/objcollections/collectionsbase.vr new file mode 100644 index 0000000..f0fdc74 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/collectionsbase.vr @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "object.vrh" +#include "log.vrh" + +//////////////////////////////////////////////////////////// +// CollectionsBase +//////////////////////////////////////////////////////////// + +virtual class CollectionsBase +extends Object +{ + protected static LogInterface logIntf; + + task new(); +} + +task CollectionsBase::new() +{ + if (logIntf == null) { + logIntf = new("collections"); + // by default, only log warnings and above (regardless of +log_level) + logIntf.setMinSeverity(LS_WARNING); + logIntf.loadSettings("collections"); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/comparator.vr b/java/juno-samples/xmlreader/src/collections/objcollections/comparator.vr new file mode 100644 index 0000000..37bd612 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/comparator.vr @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "object.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../comparator_tmpl.vr" +//END_LOCAL + +//////////////////////////////////////////////////////////// +// ObjectIDComparator +//////////////////////////////////////////////////////////// + +class ObjectIDComparator +extends Comparator +{ + task new() + { + setClassName("ObjectIDComparator"); + } + + virtual function integer compare(Object o1, Object o2) + { + compare = OBJECT_ID(o1) - OBJECT_ID(o2); + } + + virtual function bit equals(Object o) + { + ObjectIDComparator otherOIDComp; + + equals = (o != null && cast_assign(otherOIDComp, o, CHECK)); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/elem_obj_defines.vr b/java/juno-samples/xmlreader/src/collections/objcollections/elem_obj_defines.vr new file mode 100644 index 0000000..b589efa --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/elem_obj_defines.vr @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#define ELEMENT_TYPE Object +#define ELEMENT_NULL null + +#define DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define DESTROY(o) if (o != null) o.destroy() + +#define ITERATOR_CLASS Iterator +#define EMPTY_ITERATOR_CLASS EmptyIterator +#define COLLECTION_CLASS Collection + +#define LIST_ITERATOR_CLASS ListIterator +#define LIST_CLASS List + +#define ARRAY_LIST_ITERATOR_CLASS ArrayListIterator +#define ARRAY_LIST_CLASS ArrayList + +#define LINKED_LIST_NODE_CLASS LinkedListNode +#define LINKED_LIST_ITERATOR_CLASS LinkedListIterator +#define LINKED_LIST_CLASS LinkedList + +#define SET_CLASS Set + +#define HASH_SET_CLASS HashSet +#define HASH_SET_HASH_MAP_CLASS HashMap + +#define COMPARATOR_CLASS Comparator + +#define SORTED_SET_CLASS SortedSet + +#define TREE_SET_CLASS TreeSet +#define TREE_SET_TREE_MAP_CLASS TreeMap + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/hashmap.vr b/java/juno-samples/xmlreader/src/collections/objcollections/hashmap.vr new file mode 100644 index 0000000..5ef6e62 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/hashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "map.vrh" + +//LOCAL +#include "kv_obj_obj_defines.vr" +#include "../hashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/hashset.vr b/java/juno-samples/xmlreader/src/collections/objcollections/hashset.vr new file mode 100644 index 0000000..2090905 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/hashset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "set.vrh" +#include "hashmap.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../hashset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/kv_obj_obj_defines.vr b/java/juno-samples/xmlreader/src/collections/objcollections/kv_obj_obj_defines.vr new file mode 100644 index 0000000..91fb3c6 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/kv_obj_obj_defines.vr @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +// key type defines + +#define KEY_TYPE Object +#define KEY_NULL null + +#define KEY_DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define KEY_EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define KEY_HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define KEY_DESTROY(o) if (o != null) o.destroy() + +#define KEY_SET_CLASS Set +#define KEY_ITERATOR_CLASS Iterator +#define KEY_COMPARATOR_CLASS Comparator +#define DEFAULT_KEY_COMPARATOR_CLASS ObjectIDComparator + +// value type defines + +#define VALUE_TYPE Object +#define VALUE_NULL null + +#define VALUE_DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define VALUE_EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define VALUE_HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define VALUE_DESTROY(o) if (o != null) o.destroy() + +#define VALUE_COLLECTION_CLASS Collection +#define VALUE_ITERATOR_CLASS Iterator + +// Map defines + +#define MAP_CLASS Map +#define MAP_ENTRY_CLASS MapEntry +#define MAP_KEY_SET_CLASS MapKeySet +#define MAP_VALUE_COLLECTION_CLASS MapValueCollection +#define ENTRY_SET_KEY_ITERATOR_CLASS EntrySetKeyIterator +#define ENTRY_SET_VALUE_ITERATOR_CLASS EntrySetValueIterator + +// HashMap defines + +#define HASH_MAP_CLASS HashMap +#define HASH_MAP_ENTRY_CLASS HashMapEntry +#define HASH_MAP_ENTRY_SET_CLASS HashMapEntrySet +#define HASH_MAP_KEY_SET_CLASS HashMapKeySet +#define HASH_MAP_VALUE_COLLECTION_CLASS HashMapValueCollection +#define HASH_MAP_ENTRY_ITERATOR_CLASS HashMapEntryIterator + +// LinkedHashMap defines + +#define LINKED_HASH_MAP_CLASS LinkedHashMap +#define LINKED_HASH_MAP_ENTRY_CLASS LinkedHashMapEntry +#define LINKED_HASH_MAP_ENTRY_SET_CLASS LinkedHashMapEntrySet +#define LINKED_HASH_MAP_KEY_SET_CLASS LinkedHashMapKeySet +#define LINKED_HASH_MAP_VALUE_COLLECTION_CLASS LinkedHashMapValueCollection +#define LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS LinkedHashMapEntryIterator + +// SortedMap defines + +#define SORTED_MAP_CLASS SortedMap + +// TreeMap defines + +#define TREE_MAP_CLASS TreeMap +#define TREE_MAP_ENTRY_CLASS TreeMapEntry +#define TREE_MAP_ENTRY_SET_CLASS TreeMapEntrySet +#define TREE_MAP_KEY_SET_CLASS TreeMapKeySet +#define TREE_MAP_VALUE_COLLECTION_CLASS TreeMapValueCollection +#define TREE_MAP_ENTRY_ITERATOR_CLASS TreeMapEntryIterator +#define TREE_MAP_SUB_MAP_CLASS TreeMapSubMap +#define TREE_MAP_SUB_MAP_ENTRY_SET_CLASS TreeMapSubMapEntrySet + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/linkedhashmap.vr b/java/juno-samples/xmlreader/src/collections/objcollections/linkedhashmap.vr new file mode 100644 index 0000000..fc922cf --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/linkedhashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "map.vrh" + +//LOCAL +#include "kv_obj_obj_defines.vr" +#include "../linkedhashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/linkedlist.vr b/java/juno-samples/xmlreader/src/collections/objcollections/linkedlist.vr new file mode 100644 index 0000000..faefb79 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/linkedlist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "list.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../linkedlist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/list.vr b/java/juno-samples/xmlreader/src/collections/objcollections/list.vr new file mode 100644 index 0000000..26c6415 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/list.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collection.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../list_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/map.vr b/java/juno-samples/xmlreader/src/collections/objcollections/map.vr new file mode 100644 index 0000000..c2d59d1 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/map.vr @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" +#include "collection.vrh" +#include "set.vrh" + +//LOCAL +#include "kv_obj_obj_defines.vr" +#include "../map_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.dot b/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.dot new file mode 100644 index 0000000..e7159a7 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.dot @@ -0,0 +1,63 @@ +digraph objcollections { +rankdir=LR; +node [shape=record,fontname="Helvetica",fontsize=10,height=0.2,width=0.4,color=black]; +edge [dir=back,color="midnightblue",fontname="Helvetica",fontsize=10,style=solid]; +title [label="Vera Object Collection Classes"]; + +Object [label="Object|dumpString()\nequals()\nhashCode()"]; + +Comparator [label="[Comparator]|compare()"]; +Object -> Comparator ; + +ObjectIDComparator [label="ObjectIDComparator|"]; +Comparator -> ObjectIDComparator ; + +Collection [label="[Collection]|add()\naddAll()\nclear()\ncontains()\ncontainsAll()\nisEmpty()\niterator()\nremove()\nremoveAll()\nretainAll()\nsize()"]; +Object -> Collection ; + +Iterator [label="[Iterator]|hasNext()\nnext()\nremove()"]; + +List [label="[List]|addAt()\naddAllAt()\naddFirst()\naddLast()\nget()\ngetFirst()\ngetLast()\nindexOf()\nlastIndexOf()\nlistIterator()\nlistIteratorAt()\nremoveAt()\nset()"]; +Collection -> List ; + +ListIterator [label="[ListIterator]|add()\nhasPrevious()\nnextIndex()\nprevious()\npreviousIndex()\nset()"]; +Iterator -> ListIterator ; + +ArrayList [label="ArrayList|"]; +List -> ArrayList ; + +LinkedList [label="LinkedList|"]; +List -> LinkedList ; + +Set [label="[Set]|"]; +Collection -> Set ; + +HashSet [label="HashSet|"]; +Set -> HashSet ; + +SortedSet [label="[SortedSet]|comparator()"]; +Set -> SortedSet ; + +TreeSet [label="TreeSet|"]; +SortedSet -> TreeSet ; + +Map [label="[Map]|clear()\ncontainsKey()\ncontainsValue()\nentrySet()\nfindKey()\nfindValue()\nget()\nisEmpty()\nkeySet()\nput()\nputAll()\nremove()\nsize()\nvalues()"]; +Object -> Map ; + +MapEntry [label="MapEntry|key\nvalue"]; +Object -> MapEntry ; + +HashMap [label="HashMap|"]; +Map -> HashMap ; + +LinkedHashMap [label="LinkedHashMap|"]; +Map -> LinkedHashMap ; + +SortedMap [label="[SortedMap]|comparator()"]; +Map -> SortedMap ; + +TreeMap [label="TreeMap|"]; +SortedMap -> TreeMap ; + +} + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.mak b/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.mak new file mode 100644 index 0000000..508206b --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/objcollections.mak @@ -0,0 +1,18 @@ +SRC_FILES := \ + collectionsbase.vr \ + comparator.vr \ + collection.vr \ + list.vr \ + arraylist.vr \ + linkedlist.vr \ + set.vr \ + hashset.vr \ + sortedset.vr \ + treeset.vr \ + map.vr \ + hashmap.vr \ + linkedhashmap.vr \ + sortedmap.vr \ + treemap.vr + +LOAD_COMPS := common diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/set.vr b/java/juno-samples/xmlreader/src/collections/objcollections/set.vr new file mode 100644 index 0000000..06973c6 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/set.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collection.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../set_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/sortedmap.vr b/java/juno-samples/xmlreader/src/collections/objcollections/sortedmap.vr new file mode 100644 index 0000000..e7d6df4 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/sortedmap.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "map.vrh" +#include "comparator.vrh" + +//LOCAL +#include "kv_obj_obj_defines.vr" +#include "../sortedmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/sortedset.vr b/java/juno-samples/xmlreader/src/collections/objcollections/sortedset.vr new file mode 100644 index 0000000..c44694d --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/sortedset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "set.vrh" +#include "comparator.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../sortedset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/treemap.vr b/java/juno-samples/xmlreader/src/collections/objcollections/treemap.vr new file mode 100644 index 0000000..e10e553 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/treemap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "sortedmap.vrh" + +//LOCAL +#include "kv_obj_obj_defines.vr" +#include "../treemap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/objcollections/treeset.vr b/java/juno-samples/xmlreader/src/collections/objcollections/treeset.vr new file mode 100644 index 0000000..bef7ede --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/objcollections/treeset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "sortedset.vrh" +#include "treemap.vrh" + +//LOCAL +#include "elem_obj_defines.vr" +#include "../treeset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/set_tmpl.vr b/java/juno-samples/xmlreader/src/collections/set_tmpl.vr new file mode 100644 index 0000000..af3193a --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/set_tmpl.vr @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// Set +//////////////////////////////////////////////////////////// + +virtual class SET_CLASS +extends COLLECTION_CLASS +{ + // Object + virtual function bit equals(Object o); + virtual function integer hashCode(); +} + +function bit SET_CLASS::equals(Object o) +{ + Object thisObject; + COLLECTION_CLASS otherCollection; + + thisObject = this; + if (o == thisObject) { + equals = 1; + return; + } + if (!cast_assign(otherCollection, o, CHECK)) { + equals = 0; + return; + } + if (size() != otherCollection.size()) { + equals = 0; + return; + } + + equals = containsAll(otherCollection); +} + +function integer SET_CLASS::hashCode() +{ + ITERATOR_CLASS i; + integer h; + + i = iterator(); + h = 0; + while (i.hasNext()) { + ELEMENT_TYPE io; + + io = i.next(); + h += HASH_CODE(io); + } + + hashCode = h; +} + diff --git a/java/juno-samples/xmlreader/src/collections/sortedmap_tmpl.vr b/java/juno-samples/xmlreader/src/collections/sortedmap_tmpl.vr new file mode 100644 index 0000000..7c1aaab --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/sortedmap_tmpl.vr @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// SortedMap +//////////////////////////////////////////////////////////// + +virtual class SORTED_MAP_CLASS +extends MAP_CLASS +{ + // SortedMap + virtual function KEY_COMPARATOR_CLASS comparator(); + virtual function KEY_TYPE firstKey(); + virtual function KEY_TYPE lastKey(); + virtual function SORTED_MAP_CLASS subMap(KEY_TYPE fromKey, KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS headMap(KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS tailMap(KEY_TYPE fromKey); +} + diff --git a/java/juno-samples/xmlreader/src/collections/sortedset_tmpl.vr b/java/juno-samples/xmlreader/src/collections/sortedset_tmpl.vr new file mode 100644 index 0000000..f7f0cc0 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/sortedset_tmpl.vr @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// SortedSet +//////////////////////////////////////////////////////////// + +virtual class SORTED_SET_CLASS +extends SET_CLASS +{ + // SortedSet + virtual function COMPARATOR_CLASS comparator(); +} + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/elem_str_defines.vr b/java/juno-samples/xmlreader/src/collections/strcollections/elem_str_defines.vr new file mode 100644 index 0000000..77e788f --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/elem_str_defines.vr @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#define ELEMENT_TYPE string +#define ELEMENT_NULL null + +#define DUMP_STRING(o) ((o != null) ? o : "(null)") +#define EQUALS(a,b) ((a != null) ? a.compare(b) == 0 : (b == null)) +#define HASH_CODE(o) ((o != null) ? o.hash(32'h7fff_ffff) : 0) +#define DESTROY(o) o = null + +#define ITERATOR_CLASS StrIterator +#define EMPTY_ITERATOR_CLASS StrEmptyIterator +#define COLLECTION_CLASS StrCollection + +#define LIST_ITERATOR_CLASS StrListIterator +#define LIST_CLASS StrList + +#define ARRAY_LIST_ITERATOR_CLASS StrArrayListIterator +#define ARRAY_LIST_CLASS StrArrayList + +#define LINKED_LIST_NODE_CLASS StrLinkedListNode +#define LINKED_LIST_ITERATOR_CLASS StrLinkedListIterator +#define LINKED_LIST_CLASS StrLinkedList + +#define SET_CLASS StrSet + +#define HASH_SET_CLASS StrHashSet +#define HASH_SET_HASH_MAP_CLASS StrHashMap + +#define COMPARATOR_CLASS StrComparator + +#define SORTED_SET_CLASS StrSortedSet + +#define TREE_SET_CLASS StrTreeSet +#define TREE_SET_TREE_MAP_CLASS StrTreeMap + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_obj_defines.vr b/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_obj_defines.vr new file mode 100644 index 0000000..eec0b7c --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_obj_defines.vr @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +// key type defines + +#define KEY_TYPE string +#define KEY_NULL null + +#define KEY_DUMP_STRING(o) ((o != null) ? o : "(null)") +#define KEY_EQUALS(a,b) ((a != null) ? a.compare(b) == 0 : (b == null)) +#define KEY_HASH_CODE(o) ((o != null) ? o.hash(32'h7fff_ffff) : 0) +#define KEY_DESTROY(o) o = null + +#define KEY_SET_CLASS StrSet +#define KEY_ITERATOR_CLASS StrIterator +#define KEY_COMPARATOR_CLASS StrComparator +#define DEFAULT_KEY_COMPARATOR_CLASS DefaultStrComparator + +// value type defines + +#define VALUE_TYPE Object +#define VALUE_NULL null + +#define VALUE_DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define VALUE_EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define VALUE_HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define VALUE_DESTROY(o) if (o != null) o.destroy() + +#define VALUE_COLLECTION_CLASS Collection +#define VALUE_ITERATOR_CLASS Iterator + +// Map defines + +#define MAP_CLASS StrMap +#define MAP_ENTRY_CLASS StrMapEntry +#define MAP_KEY_SET_CLASS StrMapKeySet +#define MAP_VALUE_COLLECTION_CLASS StrMapValueCollection +#define ENTRY_SET_KEY_ITERATOR_CLASS StrEntrySetKeyIterator +#define ENTRY_SET_VALUE_ITERATOR_CLASS StrEntrySetValueIterator + +// HashMap defines + +#define HASH_MAP_CLASS StrHashMap +#define HASH_MAP_ENTRY_CLASS StrHashMapEntry +#define HASH_MAP_ENTRY_SET_CLASS StrHashMapEntrySet +#define HASH_MAP_KEY_SET_CLASS StrHashMapKeySet +#define HASH_MAP_VALUE_COLLECTION_CLASS StrHashMapValueCollection +#define HASH_MAP_ENTRY_ITERATOR_CLASS StrHashMapEntryIterator + +// LinkedHashMap defines + +#define LINKED_HASH_MAP_CLASS StrLinkedHashMap +#define LINKED_HASH_MAP_ENTRY_CLASS StrLinkedHashMapEntry +#define LINKED_HASH_MAP_ENTRY_SET_CLASS StrLinkedHashMapEntrySet +#define LINKED_HASH_MAP_KEY_SET_CLASS StrLinkedHashMapKeySet +#define LINKED_HASH_MAP_VALUE_COLLECTION_CLASS StrLinkedHashMapValueCollection +#define LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS StrLinkedHashMapEntryIterator + +// SortedMap defines + +#define SORTED_MAP_CLASS StrSortedMap + +// TreeMap defines + +#define TREE_MAP_CLASS StrTreeMap +#define TREE_MAP_ENTRY_CLASS StrTreeMapEntry +#define TREE_MAP_ENTRY_SET_CLASS StrTreeMapEntrySet +#define TREE_MAP_KEY_SET_CLASS StrTreeMapKeySet +#define TREE_MAP_VALUE_COLLECTION_CLASS StrTreeMapValueCollection +#define TREE_MAP_ENTRY_ITERATOR_CLASS StrTreeMapEntryIterator +#define TREE_MAP_SUB_MAP_CLASS StrTreeMapSubMap +#define TREE_MAP_SUB_MAP_ENTRY_SET_CLASS StrTreeMapSubMapEntrySet + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_str_defines.vr b/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_str_defines.vr new file mode 100644 index 0000000..e322d51 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/kv_str_str_defines.vr @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +// key type defines + +#define KEY_TYPE string +#define KEY_NULL null + +#define KEY_DUMP_STRING(o) ((o != null) ? o : "(null)") +#define KEY_EQUALS(a,b) ((a != null) ? a.compare(b) == 0 : (b == null)) +#define KEY_HASH_CODE(o) ((o != null) ? o.hash(32'h7fff_ffff) : 0) +#define KEY_DESTROY(o) o = null + +#define KEY_SET_CLASS StrSet +#define KEY_ITERATOR_CLASS StrIterator +#define KEY_COMPARATOR_CLASS StrComparator +#define DEFAULT_KEY_COMPARATOR_CLASS DefaultStrComparator + +// value type defines + +#define VALUE_TYPE string +#define VALUE_NULL null + +#define VALUE_DUMP_STRING(o) ((o != null) ? o : "(null)") +#define VALUE_EQUALS(a,b) ((a != null) ? a.compare(b) == 0 : (b == null)) +#define VALUE_HASH_CODE(o) ((o != null) ? o.hash(32'h7fff_ffff) : 0) +#define VALUE_DESTROY(o) o = null + +#define VALUE_COLLECTION_CLASS StrCollection +#define VALUE_ITERATOR_CLASS StrIterator + +// Map defines + +#define MAP_CLASS StrStrMap +#define MAP_ENTRY_CLASS StrStrMapEntry +#define MAP_KEY_SET_CLASS StrStrMapKeySet +#define MAP_VALUE_COLLECTION_CLASS StrStrMapValueCollection +#define ENTRY_SET_KEY_ITERATOR_CLASS StrStrEntrySetKeyIterator +#define ENTRY_SET_VALUE_ITERATOR_CLASS StrStrEntrySetValueIterator + +// HashMap defines + +#define HASH_MAP_CLASS StrStrHashMap +#define HASH_MAP_ENTRY_CLASS StrStrHashMapEntry +#define HASH_MAP_ENTRY_SET_CLASS StrStrHashMapEntrySet +#define HASH_MAP_KEY_SET_CLASS StrStrHashMapKeySet +#define HASH_MAP_VALUE_COLLECTION_CLASS StrStrHashMapValueCollection +#define HASH_MAP_ENTRY_ITERATOR_CLASS StrStrHashMapEntryIterator + +// LinkedHashMap defines + +#define LINKED_HASH_MAP_CLASS StrStrLinkedHashMap +#define LINKED_HASH_MAP_ENTRY_CLASS StrStrLinkedHashMapEntry +#define LINKED_HASH_MAP_ENTRY_SET_CLASS StrStrLinkedHashMapEntrySet +#define LINKED_HASH_MAP_KEY_SET_CLASS StrStrLinkedHashMapKeySet +#define LINKED_HASH_MAP_VALUE_COLLECTION_CLASS StrStrLinkedHashMapValueCollection +#define LINKED_HASH_MAP_ENTRY_ITERATOR_CLASS StrStrLinkedHashMapEntryIterator + +// SortedMap defines + +#define SORTED_MAP_CLASS StrStrSortedMap + +// TreeMap defines + +#define TREE_MAP_CLASS StrStrTreeMap +#define TREE_MAP_ENTRY_CLASS StrStrTreeMapEntry +#define TREE_MAP_ENTRY_SET_CLASS StrStrTreeMapEntrySet +#define TREE_MAP_KEY_SET_CLASS StrStrTreeMapKeySet +#define TREE_MAP_VALUE_COLLECTION_CLASS StrStrTreeMapValueCollection +#define TREE_MAP_ENTRY_ITERATOR_CLASS StrStrTreeMapEntryIterator +#define TREE_MAP_SUB_MAP_CLASS StrStrTreeMapSubMap +#define TREE_MAP_SUB_MAP_ENTRY_SET_CLASS StrStrTreeMapSubMapEntrySet + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strarraylist.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strarraylist.vr new file mode 100644 index 0000000..a992736 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strarraylist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strlist.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../arraylist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strcollection.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strcollection.vr new file mode 100644 index 0000000..42e2143 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strcollection.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../collection_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strcollections.mak b/java/juno-samples/xmlreader/src/collections/strcollections/strcollections.mak new file mode 100644 index 0000000..a3dc479 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strcollections.mak @@ -0,0 +1,23 @@ +SRC_FILES := \ + strcomparator.vr \ + strcollection.vr \ + strlist.vr \ + strarraylist.vr \ + strlinkedlist.vr \ + strset.vr \ + strhashset.vr \ + strsortedset.vr \ + strtreeset.vr \ + strmap.vr \ + strhashmap.vr \ + strlinkedhashmap.vr \ + strsortedmap.vr \ + strtreemap.vr \ + \ + strstrmap.vr \ + strstrhashmap.vr \ + strstrlinkedhashmap.vr \ + strstrsortedmap.vr \ + strstrtreemap.vr \ + +LOAD_COMPS := collections/objcollections diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strcomparator.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strcomparator.vr new file mode 100644 index 0000000..3374871 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strcomparator.vr @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "object.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../comparator_tmpl.vr" +//END_LOCAL + +//////////////////////////////////////////////////////////// +// DefaultStrComparator +//////////////////////////////////////////////////////////// + +class DefaultStrComparator +extends StrComparator +{ + task new() + { + setClassName("DefaultStrComparator"); + } + + virtual function integer compare(string s1, string s2) + { + integer len1, len2; + integer pos1, pos2; + + len1 = (s1 != null) ? s1.len() : -1; + len2 = (s2 != null) ? s2.len() : -1; + pos1 = 0; + pos2 = 0; + while (pos1 < len1 && pos2 < len2) { + compare = s1.getc(pos1) - s2.getc(pos2); + if (compare != 0) return; + ++pos1; + ++pos2; + } + compare = len1 - len2; + } + + virtual function bit equals(Object o) + { + StrComparator otherStrComp; + + equals = (o != null && cast_assign(otherStrComp, o, CHECK)); + } +} + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strhashmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strhashmap.vr new file mode 100644 index 0000000..8a9c267 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strhashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strmap.vrh" + +//LOCAL +#include "kv_str_obj_defines.vr" +#include "../hashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strhashset.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strhashset.vr new file mode 100644 index 0000000..c286bbd --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strhashset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strset.vrh" +#include "strhashmap.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../hashset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedhashmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedhashmap.vr new file mode 100644 index 0000000..354130e --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedhashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strmap.vrh" + +//LOCAL +#include "kv_str_obj_defines.vr" +#include "../linkedhashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedlist.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedlist.vr new file mode 100644 index 0000000..dff1a9e --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strlinkedlist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strlist.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../linkedlist_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strlist.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strlist.vr new file mode 100644 index 0000000..ed7f676 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strlist.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strcollection.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../list_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strmap.vr new file mode 100644 index 0000000..2af39a2 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strmap.vr @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" +#include "strcollection.vrh" +#include "set.vrh" +#include "strset.vrh" + +//LOCAL +#include "kv_str_obj_defines.vr" +#include "../map_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strset.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strset.vr new file mode 100644 index 0000000..7153f26 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strset.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strcollection.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../set_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strsortedmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strsortedmap.vr new file mode 100644 index 0000000..46c6058 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strsortedmap.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strmap.vrh" +#include "strcomparator.vrh" + +//LOCAL +#include "kv_str_obj_defines.vr" +#include "../sortedmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strsortedset.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strsortedset.vr new file mode 100644 index 0000000..f1ddb52 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strsortedset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strset.vrh" +#include "strcomparator.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../sortedset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strstrhashmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strstrhashmap.vr new file mode 100644 index 0000000..cc634f6 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strstrhashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strstrmap.vrh" + +//LOCAL +#include "kv_str_str_defines.vr" +#include "../hashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strstrlinkedhashmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strstrlinkedhashmap.vr new file mode 100644 index 0000000..3d0e297 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strstrlinkedhashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strstrmap.vrh" + +//LOCAL +#include "kv_str_str_defines.vr" +#include "../linkedhashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strstrmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strstrmap.vr new file mode 100644 index 0000000..4efe3d4 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strstrmap.vr @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" +#include "strcollection.vrh" +#include "set.vrh" +#include "strset.vrh" + +//LOCAL +#include "kv_str_str_defines.vr" +#include "../map_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strstrsortedmap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strstrsortedmap.vr new file mode 100644 index 0000000..c354cb1 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strstrsortedmap.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strstrmap.vrh" +#include "strcomparator.vrh" + +//LOCAL +#include "kv_str_str_defines.vr" +#include "../sortedmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strstrtreemap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strstrtreemap.vr new file mode 100644 index 0000000..6d06552 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strstrtreemap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strstrsortedmap.vrh" + +//LOCAL +#include "kv_str_str_defines.vr" +#include "../treemap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strtreemap.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strtreemap.vr new file mode 100644 index 0000000..78f950c --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strtreemap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strsortedmap.vrh" + +//LOCAL +#include "kv_str_obj_defines.vr" +#include "../treemap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strcollections/strtreeset.vr b/java/juno-samples/xmlreader/src/collections/strcollections/strtreeset.vr new file mode 100644 index 0000000..0388e08 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strcollections/strtreeset.vr @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strsortedset.vrh" +#include "strtreemap.vrh" + +//LOCAL +#include "elem_str_defines.vr" +#include "../treeset_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strintcollections/kv_str_int_defines.vr b/java/juno-samples/xmlreader/src/collections/strintcollections/kv_str_int_defines.vr new file mode 100644 index 0000000..0d752eb --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strintcollections/kv_str_int_defines.vr @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +// key type defines + +#define KEY_TYPE string +#define KEY_NULL null + +#define KEY_DUMP_STRING(o) ((o != null) ? o : "(null)") +#define KEY_EQUALS(a,b) ((a != null) ? a.compare(b) == 0 : (b == null)) +#define KEY_HASH_CODE(o) ((o != null) ? o.hash(32'h7fff_ffff) : 0) +#define KEY_DESTROY(o) o = null + +#define KEY_SET_CLASS StrSet +#define KEY_ITERATOR_CLASS StrIterator +#define KEY_COMPARATOR_CLASS StrComparator +#define DEFAULT_KEY_COMPARATOR_CLASS DefaultStrComparator + +// value type defines + +#define VALUE_TYPE integer +#define VALUE_NULL -1 + +#define VALUE_DUMP_STRING(o) psprintf("%0d", o) +#define VALUE_EQUALS(a,b) (a == b) +#define VALUE_HASH_CODE(o) o +#define VALUE_DESTROY(o) o = -1 + +#define VALUE_COLLECTION_CLASS IntCollection +#define VALUE_ITERATOR_CLASS IntIterator + +// Map defines + +#define MAP_CLASS StrIntMap +#define MAP_ENTRY_CLASS StrIntMapEntry +#define MAP_KEY_SET_CLASS StrIntMapKeySet +#define MAP_VALUE_COLLECTION_CLASS StrIntMapValueCollection +#define ENTRY_SET_KEY_ITERATOR_CLASS StrIntEntrySetKeyIterator +#define ENTRY_SET_VALUE_ITERATOR_CLASS StrIntEntrySetValueIterator + +// HashMap defines + +#define HASH_MAP_CLASS StrIntHashMap +#define HASH_MAP_ENTRY_CLASS StrIntHashMapEntry +#define HASH_MAP_ENTRY_SET_CLASS StrIntHashMapEntrySet +#define HASH_MAP_KEY_SET_CLASS StrIntHashMapKeySet +#define HASH_MAP_VALUE_COLLECTION_CLASS StrIntHashMapValueCollection +#define HASH_MAP_ENTRY_ITERATOR_CLASS StrIntHashMapEntryIterator + diff --git a/java/juno-samples/xmlreader/src/collections/strintcollections/strintcollections.mak b/java/juno-samples/xmlreader/src/collections/strintcollections/strintcollections.mak new file mode 100644 index 0000000..8b15fc8 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strintcollections/strintcollections.mak @@ -0,0 +1,5 @@ +SRC_FILES := \ + strintmap.vr \ + strinthashmap.vr + +LOAD_COMPS := collections/strcollections collections/intcollections diff --git a/java/juno-samples/xmlreader/src/collections/strintcollections/strinthashmap.vr b/java/juno-samples/xmlreader/src/collections/strintcollections/strinthashmap.vr new file mode 100644 index 0000000..3ba0a3b --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strintcollections/strinthashmap.vr @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strintmap.vrh" + +//LOCAL +#include "kv_str_int_defines.vr" +#include "../hashmap_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/strintcollections/strintmap.vr b/java/juno-samples/xmlreader/src/collections/strintcollections/strintmap.vr new file mode 100644 index 0000000..6ae4be9 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/strintcollections/strintmap.vr @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "collectionsbase.vrh" +#include "intcollection.vrh" +#include "set.vrh" +#include "strset.vrh" + +//LOCAL +#include "kv_str_int_defines.vr" +#include "../map_tmpl.vr" +//END_LOCAL + diff --git a/java/juno-samples/xmlreader/src/collections/treemap_tmpl.vr b/java/juno-samples/xmlreader/src/collections/treemap_tmpl.vr new file mode 100644 index 0000000..aae2267 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/treemap_tmpl.vr @@ -0,0 +1,1206 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// TreeMap +//////////////////////////////////////////////////////////// + +#define BLACK 0 +#define RED 1 + +typedef class TREE_MAP_ENTRY_CLASS; +typedef class TREE_MAP_ENTRY_SET_CLASS; +typedef class TREE_MAP_KEY_SET_CLASS; +typedef class TREE_MAP_VALUE_COLLECTION_CLASS; +typedef class TREE_MAP_SUB_MAP_CLASS; + +class TREE_MAP_CLASS +extends SORTED_MAP_CLASS +{ + // For local use only! + KEY_COMPARATOR_CLASS keyComp; + TREE_MAP_ENTRY_CLASS root; + integer count; + + // Map + virtual task clear(); + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual function KEY_SET_CLASS keySet(); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + virtual function integer size(); + virtual function VALUE_COLLECTION_CLASS values(); + + // SortedMap + virtual function KEY_COMPARATOR_CLASS comparator(); + virtual function KEY_TYPE firstKey(); + virtual function KEY_TYPE lastKey(); + virtual function SORTED_MAP_CLASS subMap(KEY_TYPE fromKey, KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS headMap(KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS tailMap(KEY_TYPE fromKey); + + // TreeMap + task new(KEY_COMPARATOR_CLASS _keyComp = null); + + // For local use only! + function TREE_MAP_ENTRY_CLASS firstEntry(); + function TREE_MAP_ENTRY_CLASS lastEntry(); + function TREE_MAP_ENTRY_CLASS predecessor(TREE_MAP_ENTRY_CLASS entry); + function TREE_MAP_ENTRY_CLASS successor(TREE_MAP_ENTRY_CLASS entry); + function TREE_MAP_ENTRY_CLASS findEntryLT(KEY_TYPE key); + function TREE_MAP_ENTRY_CLASS findEntryGE(KEY_TYPE key); + task removeEntry(TREE_MAP_ENTRY_CLASS entry); + + local task rotateLeft(TREE_MAP_ENTRY_CLASS entry); + local task rotateRight(TREE_MAP_ENTRY_CLASS entry); + local task fixAfterInsert(TREE_MAP_ENTRY_CLASS entry); + local task fixAfterDelete(TREE_MAP_ENTRY_CLASS entry); +} + +task TREE_MAP_CLASS::clear() +{ + TREE_MAP_ENTRY_CLASS cur; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + // break references for garbage collection + cur = root; + while (cur != null) { + if (destroyKeyOnRemove) { + cur.destroyKey(); + } + if (destroyValueOnRemove) { + cur.destroyValue(); + } + + if (cur.left != null) { + cur = cur.left; + } + else if (cur.right != null) { + cur = cur.right; + } + else { + TREE_MAP_ENTRY_CLASS parent = cur.parent; + + if (parent == null) { + root = null; + } + else if (parent.left == cur) { + parent.left = null; + } + else { + parent.right = null; + } + cur.parent = null; + + cur = parent; + } + } + + count = 0; +} + +function Set TREE_MAP_CLASS::entrySet() +{ + TREE_MAP_ENTRY_SET_CLASS treeMapEntrySet = new(this); + entrySet = treeMapEntrySet; +} + +function MAP_ENTRY_CLASS TREE_MAP_CLASS::findKey(KEY_TYPE key) +{ + TREE_MAP_ENTRY_CLASS entry; + + entry = root; + while (entry != null) { + integer res; + + res = keyComp.compare(key, entry.key); + if (res == 0) { + break; + } + else if (res < 0) { + entry = entry.left; + } + else { + entry = entry.right; + } + } + + findKey = entry; +} + +function KEY_SET_CLASS TREE_MAP_CLASS::keySet() +{ + TREE_MAP_KEY_SET_CLASS treeMapKeySet = new(this); + keySet = treeMapKeySet; +} + +task TREE_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + TREE_MAP_ENTRY_CLASS entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.put(%s, %s)", + getObjectName(), KEY_DUMP_STRING(key), VALUE_DUMP_STRING(value))) + + if (root == null) { + root = new(key, value, null); + ++count; + } + + entry = root; + while (entry != null) { + integer res; + + res = keyComp.compare(key, entry.key); + if (res == 0) { + if (destroyValueOnRemove) { + VALUE_TYPE victim = entry.value; + VALUE_DESTROY(victim); + } + entry.value = value; + break; + } + else if (res < 0) { + if (entry.left != null) { + entry = entry.left; + } + else { + entry.left = new(key, value, entry); + ++count; + + fixAfterInsert(entry.left); + break; + } + } + else { + if (entry.right != null) { + entry = entry.right; + } + else { + entry.right = new(key, value, entry); + ++count; + + fixAfterInsert(entry.right); + break; + } + } + } +} + +task TREE_MAP_CLASS::remove(KEY_TYPE key) +{ + TREE_MAP_ENTRY_CLASS entry; + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), KEY_DUMP_STRING(key))) + + cast_assign(entry, findKey(key)); + if (entry != null) { + removeEntry(entry); + } +} + +function integer TREE_MAP_CLASS::size() +{ + size = count; +} + +function VALUE_COLLECTION_CLASS TREE_MAP_CLASS::values() +{ + TREE_MAP_VALUE_COLLECTION_CLASS treeMapValues = new(this); + values = treeMapValues; +} + +function KEY_COMPARATOR_CLASS TREE_MAP_CLASS::comparator() +{ + comparator = keyComp; +} + +function KEY_TYPE TREE_MAP_CLASS::firstKey() +{ + TREE_MAP_ENTRY_CLASS entry = firstEntry(); + + assert(entry != null); + + firstKey = entry.key; +} + +function KEY_TYPE TREE_MAP_CLASS::lastKey() +{ + TREE_MAP_ENTRY_CLASS entry = lastEntry(); + + assert(entry != null); + + lastKey = entry.key; +} + +function SORTED_MAP_CLASS TREE_MAP_CLASS::subMap(KEY_TYPE fromKey, KEY_TYPE toKey) +{ + TREE_MAP_SUB_MAP_CLASS theSubMap = new(this, fromKey, 1, toKey, 1); + + subMap = theSubMap; +} + +function SORTED_MAP_CLASS TREE_MAP_CLASS::headMap(KEY_TYPE toKey) +{ + TREE_MAP_SUB_MAP_CLASS theSubMap = new(this, KEY_NULL, 0, toKey, 1); + + headMap = theSubMap; +} + +function SORTED_MAP_CLASS TREE_MAP_CLASS::tailMap(KEY_TYPE fromKey) +{ + TREE_MAP_SUB_MAP_CLASS theSubMap = new(this, fromKey, 1, KEY_NULL, 0); + + tailMap = theSubMap; +} + +task TREE_MAP_CLASS::new(KEY_COMPARATOR_CLASS _keyComp = null) +{ + setClassName("TreeMap"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%s)", + getObjectName(), OBJECT_NAME(_keyComp))) + + if (_keyComp == null) { + DEFAULT_KEY_COMPARATOR_CLASS defKeyComp = new; + _keyComp = defKeyComp; + } + + keyComp = _keyComp; + count = 0; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::firstEntry() +{ + TREE_MAP_ENTRY_CLASS entry; + + entry = root; + if (entry != null) { + while (entry.left != null) { + entry = entry.left; + } + } + + firstEntry = entry; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::lastEntry() +{ + TREE_MAP_ENTRY_CLASS entry; + + entry = root; + if (entry != null) { + while (entry.right != null) { + entry = entry.right; + } + } + + lastEntry = entry; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::predecessor(TREE_MAP_ENTRY_CLASS entry) +{ + if (entry.left != null) { + // predecessor is left child's leftmost descendent + entry = entry.left; + while (entry.right != null) { + entry = entry.right; + } + } + else { + TREE_MAP_ENTRY_CLASS child; + + // predecessor is first ancestor of which we are a right descendent + child = entry; + entry = entry.parent; + while (entry != null && child == entry.left) { + child = entry; + entry = entry.parent; + } + } + + predecessor = entry; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::successor(TREE_MAP_ENTRY_CLASS entry) +{ + if (entry.right != null) { + // successor is right child's leftmost descendent + entry = entry.right; + while (entry.left != null) { + entry = entry.left; + } + } + else { + TREE_MAP_ENTRY_CLASS child; + + // successor is first ancestor of which we are a left descendent + child = entry; + entry = entry.parent; + while (entry != null && child == entry.right) { + child = entry; + entry = entry.parent; + } + } + + successor = entry; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::findEntryLT(KEY_TYPE key) +{ + TREE_MAP_ENTRY_CLASS entry; + + entry = root; + while (entry != null) { + integer res; + + res = keyComp.compare(key, entry.key); + if (res <= 0) { + if (entry.left != null) { + entry = entry.left; + } else { + entry = predecessor(entry); + break; + } + } + else { + if (entry.right != null) { + entry = entry.right; + } else { + break; + } + } + } + + findEntryLT = entry; +} + +function TREE_MAP_ENTRY_CLASS TREE_MAP_CLASS::findEntryGE(KEY_TYPE key) +{ + TREE_MAP_ENTRY_CLASS entry; + + entry = root; + while (entry != null) { + integer res; + + res = keyComp.compare(key, entry.key); + if (res == 0) { + break; + } + else if (res < 0) { + if (entry.left != null) { + entry = entry.left; + } else { + break; + } + } + else { + if (entry.right != null) { + entry = entry.right; + } else { + entry = successor(entry); + break; + } + } + } + + findEntryGE = entry; +} + +task TREE_MAP_CLASS::removeEntry(TREE_MAP_ENTRY_CLASS entry) +{ + TREE_MAP_ENTRY_CLASS repl; + + if (destroyKeyOnRemove) { + entry.destroyKey(); + } + if (destroyValueOnRemove) { + entry.destroyValue(); + } + + --count; + + // if node is internal, copy successor to node and remove successor + // (since successor of internal node has at most a right child) + if (entry.left != null && entry.right != null) { + TREE_MAP_ENTRY_CLASS succ; + + succ = successor(entry); + entry.key = succ.key; + entry.value = succ.value; + entry = succ; + } + + // select replacement node (entry now has at most one child) + if (entry.left != null) { + repl = entry.left; + + // break reference for garbage collection + entry.left = null; + } else { + repl = entry.right; + + // break reference for garbage collection + entry.right = null; + } + + if (repl != null) { + // link replacement to parent + repl.parent = entry.parent; + if (entry.parent == null) { + // entry was root + root = repl; + } + else if (entry == entry.parent.left) { + // entry was left child + entry.parent.left = repl; + + // break reference for garbage collection + entry.parent = null; + } + else { + // entry was right child + entry.parent.right = repl; + + // break reference for garbage collection + entry.parent = null; + } + + // fix replacement + if (entry.color == BLACK) { + fixAfterDelete(repl); + } + } + else if (entry.parent == null) { + // entry was only node + root = null; + } + else { + // no children: use entry as phantom replacement and unlink + if (entry.color == BLACK) { + fixAfterDelete(entry); + } + + if (entry.parent != null) { + if (entry == entry.parent.left) { + // entry was left child + entry.parent.left = null; + } + else { + // entry was right child + entry.parent.right = null; + } + + // break reference for garbage collection + entry.parent = null; + } + } +} + +local function TREE_MAP_ENTRY_CLASS parentOf(TREE_MAP_ENTRY_CLASS entry) +{ + parentOf = (entry != null) ? entry.parent : null; +} + +local function TREE_MAP_ENTRY_CLASS leftOf(TREE_MAP_ENTRY_CLASS entry) +{ + leftOf = (entry != null) ? entry.left : null; +} + +local function TREE_MAP_ENTRY_CLASS rightOf(TREE_MAP_ENTRY_CLASS entry) +{ + rightOf = (entry != null) ? entry.right : null; +} + +local function bit colorOf(TREE_MAP_ENTRY_CLASS entry) +{ + colorOf = (entry != null) ? entry.color : BLACK; +} + +local task setColor(TREE_MAP_ENTRY_CLASS entry, bit color) +{ + if (entry != null) entry.color = color; +} + +task TREE_MAP_CLASS::rotateLeft(TREE_MAP_ENTRY_CLASS entry) +{ + TREE_MAP_ENTRY_CLASS r; + + r = entry.right; + entry.right = r.left; + if (r.left != null) { + r.left.parent = entry; + } + r.parent = entry.parent; + if (entry.parent == null) { + root = r; + } + else if (entry.parent.left == entry) { + entry.parent.left = r; + } + else { + entry.parent.right = r; + } + r.left = entry; + entry.parent = r; +} + +task TREE_MAP_CLASS::rotateRight(TREE_MAP_ENTRY_CLASS entry) +{ + TREE_MAP_ENTRY_CLASS l; + + l = entry.left; + entry.left = l.right; + if (l.right != null) { + l.right.parent = entry; + } + l.parent = entry.parent; + if (entry.parent == null) { + root = l; + } + else if (entry.parent.right == entry) { + entry.parent.right = l; + } + else { + entry.parent.left = l; + } + l.right = entry; + entry.parent = l; +} + +task TREE_MAP_CLASS::fixAfterInsert(TREE_MAP_ENTRY_CLASS entry) +{ + entry.color = RED; + + while (entry != null && entry != root && entry.parent.color == RED) { + TREE_MAP_ENTRY_CLASS y; + + if (parentOf(entry) == leftOf(parentOf(parentOf(entry)))) { + y = rightOf(parentOf(parentOf(entry))); + if (colorOf(y) == RED) { + setColor(parentOf(entry), BLACK); + setColor(y, BLACK); + setColor(parentOf(parentOf(entry)), RED); + entry = parentOf(parentOf(entry)); + } + else { + if (entry == rightOf(parentOf(entry))) { + entry = parentOf(entry); + rotateLeft(entry); + } + setColor(parentOf(entry), BLACK); + setColor(parentOf(parentOf(entry)), RED); + if (parentOf(parentOf(entry)) != null) { + rotateRight(parentOf(parentOf(entry))); + } + } + } + else { + // symmetric + y = leftOf(parentOf(parentOf(entry))); + if (colorOf(y) == RED) { + setColor(parentOf(entry), BLACK); + setColor(y, BLACK); + setColor(parentOf(parentOf(entry)), RED); + entry = parentOf(parentOf(entry)); + } + else { + if (entry == leftOf(parentOf(entry))) { + entry = parentOf(entry); + rotateRight(entry); + } + setColor(parentOf(entry), BLACK); + setColor(parentOf(parentOf(entry)), RED); + if (parentOf(parentOf(entry)) != null) { + rotateLeft(parentOf(parentOf(entry))); + } + } + } + } + + root.color = BLACK; +} + +task TREE_MAP_CLASS::fixAfterDelete(TREE_MAP_ENTRY_CLASS entry) +{ + while (entry != root && colorOf(entry) == BLACK) { + TREE_MAP_ENTRY_CLASS sib; + + if (entry == leftOf(parentOf(entry))) { + sib = rightOf(parentOf(entry)); + if (colorOf(sib) == RED) { + setColor(sib, BLACK); + setColor(parentOf(entry), RED); + rotateLeft(parentOf(entry)); + sib = rightOf(parentOf(entry)); + } + if (colorOf(leftOf(sib)) == BLACK && + colorOf(rightOf(sib)) == BLACK) { + setColor(sib, RED); + entry = parentOf(entry); + } + else { + if (colorOf(rightOf(sib)) == BLACK) { + setColor(leftOf(sib), BLACK); + setColor(sib, RED); + rotateRight(sib); + sib = rightOf(parentOf(entry)); + } + setColor(sib, colorOf(parentOf(entry))); + setColor(parentOf(entry), BLACK); + setColor(rightOf(sib), BLACK); + rotateLeft(parentOf(entry)); + entry = root; + } + } + else { + // symmetric + sib = leftOf(parentOf(entry)); + if (colorOf(sib) == RED) { + setColor(sib, BLACK); + setColor(parentOf(entry), RED); + rotateRight(parentOf(entry)); + sib = leftOf(parentOf(entry)); + } + if (colorOf(rightOf(sib)) == BLACK && + colorOf(leftOf(sib)) == BLACK) { + setColor(sib, RED); + entry = parentOf(entry); + } + else { + if (colorOf(leftOf(sib)) == BLACK) { + setColor(rightOf(sib), BLACK); + setColor(sib, RED); + rotateLeft(sib); + sib = leftOf(parentOf(entry)); + } + setColor(sib, colorOf(parentOf(entry))); + setColor(parentOf(entry), BLACK); + setColor(leftOf(sib), BLACK); + rotateRight(parentOf(entry)); + entry = root; + } + } + } + + setColor(entry, BLACK); +} + +//////////////////////////////////////////////////////////// +// TreeMapEntry +//////////////////////////////////////////////////////////// + +class TREE_MAP_ENTRY_CLASS +extends MAP_ENTRY_CLASS +{ + TREE_MAP_ENTRY_CLASS parent; + TREE_MAP_ENTRY_CLASS left; + TREE_MAP_ENTRY_CLASS right; + bit color; + + task new(KEY_TYPE _key, VALUE_TYPE _value, TREE_MAP_ENTRY_CLASS _parent) + { + super.new(_key, _value); + + parent = _parent; + color = BLACK; + } +} + +//////////////////////////////////////////////////////////// +// TreeMapEntrySet +//////////////////////////////////////////////////////////// + +typedef class TREE_MAP_ENTRY_ITERATOR_CLASS; + +local class TREE_MAP_ENTRY_SET_CLASS +extends Set +{ + local TREE_MAP_CLASS treeMap; + + // Collection + virtual task add(Object o); + virtual task clear(); + virtual function bit contains(Object o); + virtual function Iterator iterator(); + virtual task remove(Object o); + virtual function integer size(); + + // TreeMapEntrySet + task new(TREE_MAP_CLASS _treeMap); +} + +task TREE_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map entry sets") +} + +task TREE_MAP_ENTRY_SET_CLASS::clear() +{ + treeMap.clear(); +} + +function bit TREE_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = treeMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function Iterator TREE_MAP_ENTRY_SET_CLASS::iterator() +{ + TREE_MAP_ENTRY_ITERATOR_CLASS entryIter = new(treeMap, treeMap.firstEntry()); + + iterator = entryIter; +} + +task TREE_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry; + TREE_MAP_ENTRY_CLASS mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + cast_assign(mapEntry, treeMap.findKey(entry.key)); + if (mapEntry != null && mapEntry.equals(entry)) { + treeMap.removeEntry(mapEntry); + } +} + +function integer TREE_MAP_ENTRY_SET_CLASS::size() +{ + size = treeMap.size(); +} + +task TREE_MAP_ENTRY_SET_CLASS::new(TREE_MAP_CLASS _treeMap) +{ + treeMap = _treeMap; +} + +//////////////////////////////////////////////////////////// +// TreeMapKeySet +//////////////////////////////////////////////////////////// + +local class TREE_MAP_KEY_SET_CLASS +extends KEY_SET_CLASS +{ + local TREE_MAP_CLASS treeMap; + + // Collection + virtual task add(KEY_TYPE o); + virtual task clear(); + virtual function bit contains(KEY_TYPE o); + virtual function KEY_ITERATOR_CLASS iterator(); + virtual task remove(KEY_TYPE o); + virtual function integer size(); + + // TreeMapKeySet + task new(TREE_MAP_CLASS _treeMap); +} + +task TREE_MAP_KEY_SET_CLASS::add(KEY_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map key sets") +} + +task TREE_MAP_KEY_SET_CLASS::clear() +{ + treeMap.clear(); +} + +function bit TREE_MAP_KEY_SET_CLASS::contains(KEY_TYPE o) +{ + contains = treeMap.containsKey(o); +} + +function KEY_ITERATOR_CLASS TREE_MAP_KEY_SET_CLASS::iterator() +{ + TREE_MAP_ENTRY_ITERATOR_CLASS entryIter = new(treeMap, treeMap.firstEntry()); + ENTRY_SET_KEY_ITERATOR_CLASS keyIter = new(entryIter); + + iterator = keyIter; +} + +task TREE_MAP_KEY_SET_CLASS::remove(KEY_TYPE o) +{ + treeMap.remove(o); +} + +function integer TREE_MAP_KEY_SET_CLASS::size() +{ + size = treeMap.size(); +} + +task TREE_MAP_KEY_SET_CLASS::new(TREE_MAP_CLASS _treeMap) +{ + treeMap = _treeMap; +} + +//////////////////////////////////////////////////////////// +// TreeMapValueCollection +//////////////////////////////////////////////////////////// + +local class TREE_MAP_VALUE_COLLECTION_CLASS +extends VALUE_COLLECTION_CLASS +{ + local TREE_MAP_CLASS treeMap; + + // Collection + virtual task add(VALUE_TYPE o); + virtual task clear(); + virtual function bit contains(VALUE_TYPE o); + virtual function VALUE_ITERATOR_CLASS iterator(); + virtual function integer size(); + virtual function bit equals(Object o); + virtual function integer hashCode(); + + // TreeMapValueCollection + task new(TREE_MAP_CLASS _treeMap); +} + +function bit TREE_MAP_VALUE_COLLECTION_CLASS::equals(Object o) +{ + equals = 0; + LOG_MSG(logIntf, LS_FATAL, "equals() not supported on map value collections") +} + +function integer TREE_MAP_VALUE_COLLECTION_CLASS::hashCode() +{ + hashCode = 0; + LOG_MSG(logIntf, LS_FATAL, "hashCode() not supported on map value collections") +} + +task TREE_MAP_VALUE_COLLECTION_CLASS::add(VALUE_TYPE o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on map value collections") +} + +task TREE_MAP_VALUE_COLLECTION_CLASS::clear() +{ + treeMap.clear(); +} + +function bit TREE_MAP_VALUE_COLLECTION_CLASS::contains(VALUE_TYPE o) +{ + contains = treeMap.containsValue(o); +} + +function VALUE_ITERATOR_CLASS TREE_MAP_VALUE_COLLECTION_CLASS::iterator() +{ + TREE_MAP_ENTRY_ITERATOR_CLASS entryIter = new(treeMap, treeMap.firstEntry()); + ENTRY_SET_VALUE_ITERATOR_CLASS valueIter = new(entryIter); + + iterator = valueIter; +} + +function integer TREE_MAP_VALUE_COLLECTION_CLASS::size() +{ + size = treeMap.size(); +} + +task TREE_MAP_VALUE_COLLECTION_CLASS::new(TREE_MAP_CLASS _treeMap) +{ + treeMap = _treeMap; +} + +//////////////////////////////////////////////////////////// +// TreeMapEntryIterator +//////////////////////////////////////////////////////////// + +local class TREE_MAP_ENTRY_ITERATOR_CLASS +extends Iterator +{ + local TREE_MAP_CLASS treeMap; + local TREE_MAP_ENTRY_CLASS curEntry; + local TREE_MAP_ENTRY_CLASS nextEntry; + local TREE_MAP_ENTRY_CLASS stopEntry; + + task new(TREE_MAP_CLASS _treeMap, + TREE_MAP_ENTRY_CLASS _firstEntry, + TREE_MAP_ENTRY_CLASS _stopEntry = null); + + virtual function bit hasNext(); + virtual function Object next(); + virtual task remove(); +} + +task TREE_MAP_ENTRY_ITERATOR_CLASS::new(TREE_MAP_CLASS _treeMap, + TREE_MAP_ENTRY_CLASS _firstEntry, + TREE_MAP_ENTRY_CLASS _stopEntry = null) +{ + treeMap = _treeMap; + curEntry = null; + nextEntry = _firstEntry; + stopEntry = _stopEntry; +} + +function bit TREE_MAP_ENTRY_ITERATOR_CLASS::hasNext() +{ + hasNext = (nextEntry != stopEntry); +} + +function Object TREE_MAP_ENTRY_ITERATOR_CLASS::next() +{ + assert(nextEntry != stopEntry); + + curEntry = nextEntry; + nextEntry = treeMap.successor(curEntry); + next = curEntry; +} + +task TREE_MAP_ENTRY_ITERATOR_CLASS::remove() +{ + if (curEntry == null) { + LOG_MSG(logIntf, LS_FATAL, "No valid active element") + } + + // deleted entry becomes successor if internal + if (curEntry.left != null && curEntry.right != null) { + nextEntry = curEntry; + } + + treeMap.removeEntry(curEntry); + curEntry = null; +} + +//////////////////////////////////////////////////////////// +// TreeMapSubMap +//////////////////////////////////////////////////////////// + +typedef class TREE_MAP_SUB_MAP_ENTRY_SET_CLASS; + +class TREE_MAP_SUB_MAP_CLASS +extends SORTED_MAP_CLASS +{ + // For local use only! + TREE_MAP_CLASS treeMap; + KEY_TYPE fromKey; + bit fromValid; + KEY_TYPE toKey; + bit toValid; + + // Map + virtual function Set entrySet(); + virtual function MAP_ENTRY_CLASS findKey(KEY_TYPE key); + virtual task put(KEY_TYPE key, VALUE_TYPE value); + virtual task remove(KEY_TYPE key); + + // SortedMap + virtual function KEY_COMPARATOR_CLASS comparator(); + virtual function KEY_TYPE firstKey(); + virtual function KEY_TYPE lastKey(); + virtual function SORTED_MAP_CLASS subMap(KEY_TYPE fromKey, KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS headMap(KEY_TYPE toKey); + virtual function SORTED_MAP_CLASS tailMap(KEY_TYPE fromKey); + + // TreeMapSubMap + task new(TREE_MAP_CLASS _treeMap, + KEY_TYPE _fromKey, bit _fromValid, + KEY_TYPE _toKey, bit _toValid); + + local function bit inRange(KEY_TYPE key, bit includeToKey = 0); +} + +task TREE_MAP_SUB_MAP_CLASS::new(TREE_MAP_CLASS _treeMap, + KEY_TYPE _fromKey, bit _fromValid, + KEY_TYPE _toKey, bit _toValid) +{ + treeMap = _treeMap; + fromKey = _fromKey; + fromValid = _fromValid; + toKey = _toKey; + toValid = _toValid; + + assert(!fromValid || !toValid || + treeMap.keyComp.compare(fromKey, toKey) <= 0); +} + +function Set TREE_MAP_SUB_MAP_CLASS::entrySet() +{ + TREE_MAP_SUB_MAP_ENTRY_SET_CLASS subMapEntrySet = new(this); + entrySet = subMapEntrySet; +} + +function MAP_ENTRY_CLASS TREE_MAP_SUB_MAP_CLASS::findKey(KEY_TYPE key) +{ + if (inRange(key)) { + findKey = treeMap.findKey(key); + } +} + +task TREE_MAP_SUB_MAP_CLASS::put(KEY_TYPE key, VALUE_TYPE value) +{ + assert(inRange(key)); + treeMap.put(key, value); +} + +task TREE_MAP_SUB_MAP_CLASS::remove(KEY_TYPE key) +{ + if (inRange(key)) { + treeMap.remove(key); + } +} + +function KEY_COMPARATOR_CLASS TREE_MAP_SUB_MAP_CLASS::comparator() +{ + comparator = treeMap.keyComp; +} + +function KEY_TYPE TREE_MAP_SUB_MAP_CLASS::firstKey() +{ + TREE_MAP_ENTRY_CLASS entry; + + if (fromValid) { + entry = treeMap.findEntryGE(fromKey); + } else { + entry = treeMap.firstEntry(); + } + assert(entry != null); + + if (toValid) { + assert(treeMap.keyComp.compare(entry.key, toKey) < 0); + } + + firstKey = entry.key; +} + +function KEY_TYPE TREE_MAP_SUB_MAP_CLASS::lastKey() +{ + TREE_MAP_ENTRY_CLASS entry; + + if (toValid) { + entry = treeMap.findEntryLT(toKey); + } else { + entry = treeMap.lastEntry(); + } + assert(entry != null); + + if (fromValid) { + assert(treeMap.keyComp.compare(entry.key, fromKey) >= 0); + } + + lastKey = entry.key; +} + +function SORTED_MAP_CLASS TREE_MAP_SUB_MAP_CLASS::subMap(KEY_TYPE fromKey, KEY_TYPE toKey) +{ + assert(inRange(fromKey, 1)); + assert(inRange(toKey, 1)); + subMap = treeMap.subMap(fromKey, toKey); +} + +function SORTED_MAP_CLASS TREE_MAP_SUB_MAP_CLASS::headMap(KEY_TYPE toKey) +{ + assert(inRange(toKey, 1)); + headMap = treeMap.headMap(toKey); +} + +function SORTED_MAP_CLASS TREE_MAP_SUB_MAP_CLASS::tailMap(KEY_TYPE fromKey) +{ + assert(inRange(fromKey, 1)); + tailMap = treeMap.tailMap(fromKey); +} + +function bit TREE_MAP_SUB_MAP_CLASS::inRange(KEY_TYPE key, bit includeToKey = 0) +{ + inRange = (!fromValid || treeMap.keyComp.compare(key, fromKey) >= 0) && + (!toValid || treeMap.keyComp.compare(key, toKey) <= (includeToKey ? 0 : -1)); +} + +//////////////////////////////////////////////////////////// +// TreeMapSubMapEntrySet +//////////////////////////////////////////////////////////// + +local class TREE_MAP_SUB_MAP_ENTRY_SET_CLASS +extends Set +{ + local TREE_MAP_SUB_MAP_CLASS subMap; + + // Collection + virtual task add(Object o); + virtual function bit contains(Object o); + virtual function bit isEmpty(); + virtual function Iterator iterator(); + virtual task remove(Object o); + + // TreeMapSubMapEntrySet + task new(TREE_MAP_SUB_MAP_CLASS _subMap); +} + +task TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::add(Object o) +{ + LOG_MSG(logIntf, LS_FATAL, "add() not supported on sub-map entry sets") +} + +function bit TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::contains(Object o) +{ + MAP_ENTRY_CLASS entry, mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + contains = 0; + return; + } + + mapEntry = subMap.findKey(entry.key); + contains = (mapEntry != null && mapEntry.equals(entry)); +} + +function bit TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::isEmpty() +{ + Iterator i = iterator(); + isEmpty = !i.hasNext(); +} + +function Iterator TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::iterator() +{ + TREE_MAP_CLASS treeMap = subMap.treeMap; + TREE_MAP_ENTRY_ITERATOR_CLASS entryIter = new(treeMap, + subMap.fromValid ? treeMap.findEntryGE(subMap.fromKey) : treeMap.firstEntry(), + subMap.toValid ? treeMap.findEntryGE(subMap.toKey) : null); + + iterator = entryIter; +} + +task TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::remove(Object o) +{ + MAP_ENTRY_CLASS entry; + TREE_MAP_ENTRY_CLASS mapEntry; + + if (o == null || !cast_assign(entry, o, CHECK)) { + return; + } + + cast_assign(mapEntry, subMap.findKey(entry.key)); + if (mapEntry != null && mapEntry.equals(entry)) { + subMap.treeMap.removeEntry(mapEntry); + } +} + +task TREE_MAP_SUB_MAP_ENTRY_SET_CLASS::new(TREE_MAP_SUB_MAP_CLASS _subMap) +{ + subMap = _subMap; +} + diff --git a/java/juno-samples/xmlreader/src/collections/treeset_tmpl.vr b/java/juno-samples/xmlreader/src/collections/treeset_tmpl.vr new file mode 100644 index 0000000..d995d99 --- /dev/null +++ b/java/juno-samples/xmlreader/src/collections/treeset_tmpl.vr @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +//////////////////////////////////////////////////////////// +// TreeSet +//////////////////////////////////////////////////////////// + +class TREE_SET_CLASS +extends SORTED_SET_CLASS +{ + local TREE_SET_TREE_MAP_CLASS treeMap; + + // Collection + virtual task add(ELEMENT_TYPE o); + virtual task clear(); + virtual function bit contains(ELEMENT_TYPE o); + virtual function ITERATOR_CLASS iterator(); + virtual task remove(ELEMENT_TYPE o); + virtual task setDestroyOnRemove(bit value); + virtual function integer size(); + + // SortedSet + virtual function COMPARATOR_CLASS comparator(); + + // TreeSet + task new(COMPARATOR_CLASS _keyComp = null); +} + +task TREE_SET_CLASS::add(ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.add(%s)", + getObjectName(), DUMP_STRING(o))) + + treeMap.put(o, null); +} + +task TREE_SET_CLASS::clear() +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.clear()", + getObjectName())) + + treeMap.clear(); +} + +function bit TREE_SET_CLASS::contains(ELEMENT_TYPE o) +{ + contains = (treeMap.findKey(o) != null); +} + +function ITERATOR_CLASS TREE_SET_CLASS::iterator() +{ + SET_CLASS keySet; + + keySet = treeMap.keySet(); + iterator = keySet.iterator(); +} + +task TREE_SET_CLASS::remove(ELEMENT_TYPE o) +{ + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.remove(%s)", + getObjectName(), DUMP_STRING(o))) + + treeMap.remove(o); +} + +task TREE_SET_CLASS::setDestroyOnRemove(bit value) +{ + super.setDestroyOnRemove(value); + treeMap.setDestroyKeyOnRemove(value); +} + +function integer TREE_SET_CLASS::size() +{ + size = treeMap.size(); +} + +function COMPARATOR_CLASS TREE_SET_CLASS::comparator() +{ + comparator = treeMap.comparator(); +} + +task TREE_SET_CLASS::new(COMPARATOR_CLASS _keyComp = null) +{ + setClassName("TreeSet"); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new(%s)", + getObjectName(), OBJECT_NAME(_keyComp))) + + treeMap = new(_keyComp); + + LOG_MSG(logIntf, LS_DEBUG, psprintf("%s.new: treeMap=%s", + getObjectName(), OBJECT_NAME(treeMap))) +} + diff --git a/java/juno-samples/xmlreader/src/common/common.mak b/java/juno-samples/xmlreader/src/common/common.mak new file mode 100644 index 0000000..fadd243 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/common.mak @@ -0,0 +1,8 @@ +SRC_FILES := \ + property.vr \ + listparser.vr \ + rangeparser.vr \ + log.vr \ + randutil.vr \ + object.vr \ + miscutil.vr diff --git a/java/juno-samples/xmlreader/src/common/common.vri b/java/juno-samples/xmlreader/src/common/common.vri new file mode 100644 index 0000000..f4538bc --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/common.vri @@ -0,0 +1,36 @@ +#ifndef INC__COMMON_VRI +#define INC__COMMON_VRI + +#include + +//////////////////////////////////////////////////////////// +// Debugging definitions +//////////////////////////////////////////////////////////// + +#ifndef assertFailed +#define assertFailed error +#endif + +// Juno treats assert as a built-in function +#ifndef __JUNO__ +#define assert(expr) if ((!(expr)) !== 0) \ + assertFailed("Assertion failed (%s, line %0d): %s\n", __FILE__, __LINE__, "expr") +#endif + +//////////////////////////////////////////////////////////// +// Universal constants +//////////////////////////////////////////////////////////// + +#define TRUE 1'b1 +#define FALSE 1'b0 +#define UNDEFINED 1'bx + +//////////////////////////////////////////////////////////// +// Common typedefs +//////////////////////////////////////////////////////////// + +#define Byte bit[7:0] +#define Dword bit[31:0] +#define Qword bit[63:0] + +#endif // INC__COMMON_VRI diff --git a/java/juno-samples/xmlreader/src/common/listparser.vr b/java/juno-samples/xmlreader/src/common/listparser.vr new file mode 100644 index 0000000..cba5d3f --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/listparser.vr @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include + +//////////////////////////////////////////////////////////// +// ListParser +//////////////////////////////////////////////////////////// + +class ListParser +{ + local string str; + local integer len; + local integer pos; + + task new(string _str) + { + str = _str; + len = _str.len(); + pos = 0; + advance(1); + } + + function bit hasNext() + { + hasNext = pos < len; + } + + function string next() + { + integer start = pos; + advance(0); + next = str.substr(start, pos - 1); + advance(1); + } + + local task advance(bit skipSep) + { + while (pos < len) { + integer i = str.getc(pos); + // skip until comma (,) or semicolon (;) + if ((i != 44 && i != 59) == skipSep) break; + ++pos; + } + } + +} + diff --git a/java/juno-samples/xmlreader/src/common/log.vr b/java/juno-samples/xmlreader/src/common/log.vr new file mode 100644 index 0000000..5a68997 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/log.vr @@ -0,0 +1,626 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include +#include +#include "common.vri" +#include "property.vrh" + +enum LogSeverity = + LS_DEBUG2, + LS_DEBUG1, + LS_DEBUG, + LS_CONFIG, + LS_WARNING, + LS_ERROR, + LS_FATAL, + LS_SYSTEM; +#define LS_COUNT 8 + +//////////////////////////////////////////////////////////// +// LogFile +//////////////////////////////////////////////////////////// + +/// Provides object-oriented access to a log file that is opened +/// on the first write. +class LogFile +{ + local string filename; + local string mode; + local integer fd = 0; + local bit alwaysFlush = 0; + local integer startSeconds; + + task new(string _filename, (string _mode = "w")) + { + filename = _filename; + mode = _mode; + alwaysFlush = getPropBool("flush=", 0); + startSeconds = get_systime(); + } + + /// Returns the filename of this log file. + function string getFilename() + { + getFilename = filename; + } + + /// Builds a log string in the proper format. + function string formatString(string source, LogSeverity severity, string type, string msg) + { + string eol = (msg.getc(msg.len() - 1) != 10) ? "\n" : ""; + + formatString = psprintf("%0d,%s,%s,%s,%s,%s%s", + getTime64(), secsToStr(get_systime() - startSeconds), source, + sevToStr(severity), type, msg, eol); + } + + /// Prints a string to the log. + task printString(string str) + { + checkOpen(); + fprintf(fd, "%s", str); + if (alwaysFlush) { + fflush(fd); + } + } + + /// Opens the log file if it is not already open. + local task checkOpen() + { + if (!fd) { + printf("Opening log file: %s\n", filename); + if (filename == "stdout") { + fd = stdout; + } else { + fd = fopen(filename, mode); + if (!fd) { + error("Error opening log file: %s\n", filename); + } + } + } + } + + /// Flushes unwritten entries to the log file. + task flush() + { + // do nothing if not open + if (fd) { + fflush(fd); + } + } + + /// Closes the log file if it is currently open. + task close() + { + // do nothing if not open + if (fd) { + // close and invalidate file handle + fclose(fd); + fd = 0; + + // append to file if reopened + mode = "a"; + } + } + +} + +//////////////////////////////////////////////////////////// +// ErrorListener +//////////////////////////////////////////////////////////// + +/// Interface class for responding to error notification. +virtual class ErrorListener +{ + virtual task notify(LogSeverity severity); +} + +//////////////////////////////////////////////////////////// +// VeraList_ErrorListener +//////////////////////////////////////////////////////////// + +MakeVeraList(ErrorListener) + +//////////////////////////////////////////////////////////// +// ErrorManager +//////////////////////////////////////////////////////////// + +/// Provides global error counting and notification. +class ErrorManager +{ + local static LogFile defLogFile; + + local integer maxErrors; + local VeraList_ErrorListener listeners; + local bit notifying; + local integer sevCounts[LS_COUNT]; + + task new() + { + integer i; + + if (defLogFile == null) { + defLogFile = new(getPropStr("log_file=", "sim.out"), + getPropStr("log_open_mode=", "w")); + } + + maxErrors = getPropInt("max_errors=", 0); + listeners = new; + notifying = 0; + for (i = 0; i < LS_COUNT; ++i) { + sevCounts[i] = 0; + } + } + + /// Returns the default log file. + function LogFile getDefLogFile() + { + getDefLogFile = defLogFile; + } + + /// Adds an error notification listener. + task addListener(ErrorListener listener) + { + listeners.push_back(listener); + } + + /// Returns the number of error notifications of the given severity. + function integer getErrorCount(LogSeverity severity) + { + getErrorCount = sevCounts[severity]; + } + + /// Notifies the error manager of an error condition. + /// The error manager will notify all error listeners, + /// and then terminate the simulation if appropriate. + task notify(LogSeverity severity, string msg = null) + { + ++sevCounts[severity]; + + if (severity >= LS_WARNING && severity <= LS_FATAL) { + + // dump call stack on warnings and errors + defLogFile.printString(defLogFile.formatString( + "log", LS_SYSTEM, "trace", psprintf("%m"))); + + // upgrade error to fatal if maximum errors reached + if (severity == LS_ERROR && maxErrors >= 0 && sevCounts[severity] > maxErrors) { + defLogFile.printString(defLogFile.formatString( + "log", LS_SYSTEM, "msg", "Maximum errors exceeded")); + severity = LS_FATAL; + } + + if (!notifying) { + VeraListIterator_ErrorListener i, f; + + notifying = 1; + + i = listeners.start(); + f = listeners.finish(); + while (!i.eq(f)) { + ErrorListener listener = i.data(); + listener.notify(severity); + i.next(); + } + + notifying = 0; + } else { + msg = "Recursive error notification"; + abort(msg, msg); + } + + if (severity == LS_FATAL) { + abort("Fatal error encountered", msg); + } + } + } + + /// Logs a fatal error message, logs the finish message, + /// and aborts the simulation. + local task abort(string msg, string lastErrorMsg = null) + { + string logStr = defLogFile.formatString("log", LS_FATAL, "msg", msg); + + defLogFile.printString(logStr); + finish("abended", lastErrorMsg); + error("%s", logStr); + } + + /// Logs a "finish" message to the default log file, + /// containing the total count of errors and warnings. + task finish(string status, string lastErrorMsg = null) + { + string msg, rec; + + msg = psprintf("%s (%0d warnings, %0d errors)", + status, sevCounts[LS_WARNING], sevCounts[LS_ERROR] + sevCounts[LS_FATAL]); + if (lastErrorMsg != null) { + msg = { msg, ", last error: ", lastErrorMsg }; + } + rec = defLogFile.formatString("log", LS_SYSTEM, "finish", msg); + defLogFile.printString(rec); + printf("%s", rec); + } + +} + +//////////////////////////////////////////////////////////// +// LogInterface +//////////////////////////////////////////////////////////// + +/// Provides an interface to a shared log file that enforces a logging policy +/// and provides logging context. +class LogInterface +{ + local static ErrorManager errMgr; + local static bit msgWatchdog = FALSE; + + local string source; + local LogFile logFile; + local LogSeverity minSeverity; + local LogSeverity echoSeverity; + local integer startTime; + + local integer indentLevel; + local string indentString; + + task new(string _source, LogFile _logFile = null) + { + if (errMgr == null) { + errMgr = new; + } + + source = _source; + logFile = _logFile != null ? _logFile : errMgr.getDefLogFile(); + minSeverity = strToSev(getPropStr("log_level=", "config")); + echoSeverity = strToSev(getPropStr("log_echo_level=", "error")); + startTime = getPropInt("log_start_time=", 0); + + indentLevel = 0; + indentString = ""; + } + + /// Returns the global error manager. + function ErrorManager getErrorManager() + { + getErrorManager = errMgr; + } + + /// Returns the source name for this interface. + function string getSource() + { + getSource = source; + } + + /// Sets the source name for this interface. + task setSource(string _source) + { + source = _source; + } + + /// Returns the log file associated with this interface. + function LogFile getLogFile() + { + getLogFile = logFile; + } + + /// Returns the minimum severity for writing a message to the log. + function LogSeverity getMinSeverity() + { + getMinSeverity = minSeverity; + } + + /// Sets the minimum severity for writing a message to the log. + task setMinSeverity(LogSeverity _minSeverity) + { + minSeverity = _minSeverity; + } + + /// Returns the minimum severity for echoing a log message to the console. + function LogSeverity getEchoSeverity() + { + getEchoSeverity = echoSeverity; + } + + /// Sets the minimum severity for echoing a log message to the console. + task setEchoSeverity(LogSeverity _echoSeverity) + { + echoSeverity = _echoSeverity; + } + + /// Returns the time that logging should begin. + function integer getStartTime() + { + getStartTime = startTime; + } + + /// Sets the time that logging should begin. + task setStartTime(integer _startTime) + { + startTime = _startTime; + } + + /// Loads the log interface settings from command line arguments. + virtual task loadSettings(string prefix) + { + string s; + integer i; + + s = getPropStr({prefix, "_log="}, null); + if (s != null) { + minSeverity = strToSev(s); + if (minSeverity > LS_FATAL) { + minSeverity = LS_FATAL; + } + } + s = getPropStr({prefix, "_log_echo="}, null); + if (s != null) { + echoSeverity = strToSev(s); + } + i = getPropInt({prefix, "_log_start_time="}, -1); + if (i >= 0) { + startTime = i; + } + } + + /// Copies the log interface settings from another interface. + virtual task copySettings(LogInterface logIntf) + { + minSeverity = logIntf.minSeverity; + echoSeverity = logIntf.echoSeverity; + startTime = logIntf.startTime; + } + + /// Determines whether a message will actually be logged. + function bit wouldLog(LogSeverity severity) + { + wouldLog = (get_time(LO) >= startTime && + (severity >= minSeverity || severity >= echoSeverity)); + + if(wouldLog) { + msgWatchdog = TRUE; // Flag that a message was printed. + } + } + + /// Returns the current message indent level. + function integer getIndent() + { + getIndent = indentLevel; + } + + /// Sets the new message indent level. + task setIndent(integer level) + { + static string spaces = " !"; + + indentLevel = level; + indentString = spaces.substr(0, level - 1); + } + + /// Increases the message indent level. + task pushIndent() + { + setIndent(indentLevel + 2); + } + + /// Decreases the message indent level. + task popIndent() + { + setIndent(indentLevel - 2); + } + + /// Logs a message without checking logging policy (used internally). + task printLogUnchecked(LogSeverity severity, string type, string msg) + { + string logStr; + + logStr = logFile.formatString(source, severity, type, { indentString, msg }); + + if (severity >= minSeverity) { + logFile.printString(logStr); + } + if (severity >= echoSeverity) { + printf("%s", logStr); // ensure that "%" in logStr is ignored + } + } + + /// Logs a message, if the logging policy is met. + task printLog(LogSeverity severity, string type, string msg) + { + if (wouldLog(severity)) { + printLogUnchecked(severity, type, msg); + } + } + + /// Logs a message (of type "msg"), if the logging policy is met. + task printLogMsg(LogSeverity severity, string msg) + { + if (wouldLog(severity)) { + printLogUnchecked(severity, "msg", msg); + } + } + + /// Notifies the error manager of an error condition. + task signalError(LogSeverity severity, string msg = null) + { + errMgr.notify(severity, msg); + } + + /// Logs a message, if the logging policy is met, + /// and notifies the error manager of the severity. + task log(LogSeverity severity, string type, string msg) + { + printLog(severity, type, msg); + errMgr.notify(severity, msg); + } + + /// Logs a message (of type "msg"), if the logging policy is met, + /// and notifies the error manager of the severity. + task logMsg(LogSeverity severity, string msg) + { + printLogMsg(severity, msg); + errMgr.notify(severity, msg); + } + + /// Logs a "finish" message to the default log file. + task finish() + { + errMgr.finish("completed"); + } + + function bit getMsgWatchdog() + { + getMsgWatchdog = msgWatchdog; + msgWatchdog = FALSE; + } +} + +/// Creates a LogInterface that (optionally) inherits the name and settings +/// of a parent LogInterface. +function LogInterface newChildLogInterface( + string name, LogInterface parentLogIntf = null, string prefix = null) +{ + LogInterface logIntf; + + if (parentLogIntf != null) { + name = { parentLogIntf.getSource(), ".", name }; + } + logIntf = new(name); + if (parentLogIntf != null) { + logIntf.copySettings(parentLogIntf); + } + if (prefix != null) { + logIntf.loadSettings(prefix); + } + + newChildLogInterface = logIntf; +} + +//////////////////////////////////////////////////////////// +// Optimized logging wrapper macros +//////////////////////////////////////////////////////////// + +// Object creation in JavaDV does not affect the random state +#ifndef __JUNO__ + +#define SAVE_RANDOM_STATE VeraRandomState randomState; getstate(randomState); +#define RESTORE_RANDOM_STATE setstate(randomState); + +#else + +#define SAVE_RANDOM_STATE +#define RESTORE_RANDOM_STATE + +#endif + +/// Calls printLog() if wouldLog() is true. +#define PRINT_LOG(intf,sev,type,_msg) \ + {if (intf.wouldLog(sev)) { SAVE_RANDOM_STATE intf.printLogUnchecked(sev, type, _msg); RESTORE_RANDOM_STATE }} + +/// Calls printLogMsg() if wouldLog() is true. +#define PRINT_LOG_MSG(intf,sev,_msg) \ + {if (intf.wouldLog(sev)) { SAVE_RANDOM_STATE intf.printLogUnchecked(sev, "msg", _msg); RESTORE_RANDOM_STATE }} + +/// Calls log() if wouldLog() is true. +#define LOG(intf,sev,type,_msg) \ + {if (intf.wouldLog(sev)) { SAVE_RANDOM_STATE intf.log(sev, type, _msg); RESTORE_RANDOM_STATE }} + +/// Calls logMsg() if wouldLog() is true. +#define LOG_MSG(intf,sev,_msg) \ + {if (intf.wouldLog(sev)) { SAVE_RANDOM_STATE intf.logMsg(sev, _msg); RESTORE_RANDOM_STATE }} + +//////////////////////////////////////////////////////////// +// Conversion helpers +//////////////////////////////////////////////////////////// + +/// Converts a string to a log severity. +function LogSeverity strToSev(string str) +{ + case (str) { + "debug2" : strToSev = LS_DEBUG2; + "debug1" : strToSev = LS_DEBUG1; + "debug" : strToSev = LS_DEBUG; + "config" : strToSev = LS_CONFIG; + "warning" : strToSev = LS_WARNING; + "error" : strToSev = LS_ERROR; + "fatal" : strToSev = LS_FATAL; + "system" : strToSev = LS_SYSTEM; + default : error("Unknown log severity %s!\n", str); + } +} + +/// Converts a log severity to a string. +function string sevToStr(LogSeverity sev) +{ + case (sev) { + LS_DEBUG2 : sevToStr = "debug2"; + LS_DEBUG1 : sevToStr = "debug1"; + LS_DEBUG : sevToStr = "debug"; + LS_CONFIG : sevToStr = "config"; + LS_WARNING : sevToStr = "warning"; + LS_ERROR : sevToStr = "error"; + LS_FATAL : sevToStr = "fatal"; + LS_SYSTEM : sevToStr = "system"; + default : error("Unknown log severity %s!\n", sev); + } +} + +/// Puts double quotes around a string if it contains any commas. +function string quoteMsg(string msg) +{ + if (msg.search(",") >= 0 && msg.search("\"") < 0) { + msg = { "\"", msg, "\"" }; + } + quoteMsg = msg; +} + +/// Converts a time in seconds to H:MM:SS format. +function string secsToStr(integer time) +{ + integer hours = time / 3600; + integer mins = (time % 3600) / 60; + integer secs = time % 60; + + // unfortunately, Vera does not have 0-padding for decimals + secsToStr = psprintf("%0d:%s%0d:%s%0d", hours, + mins < 10 ? "0" : "", mins, + secs < 10 ? "0" : "", secs); +} + +function Qword getTime64() +{ + getTime64 = { get_time(HI), get_time(LO) }; +} + +//////////////////////////////////////////////////////////// +// Assertion failure task +//////////////////////////////////////////////////////////// + +#ifdef assertFailed +#undef assertFailed +#endif + +task fatalError(string msg) +{ + LogInterface logIntf = new("log"); + logIntf.logMsg(LS_FATAL, msg); +} + +task assertFailed(string msg, string file, integer line, string expr) +{ + fatalError(psprintf(msg, file, line, expr)); +} + diff --git a/java/juno-samples/xmlreader/src/common/logtest/logtest.mak b/java/juno-samples/xmlreader/src/common/logtest/logtest.mak new file mode 100644 index 0000000..03c776b --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/logtest/logtest.mak @@ -0,0 +1,3 @@ +SRC_FILES := logtest.vr +LOAD_COMPS := common +RUNNABLE := 1 diff --git a/java/juno-samples/xmlreader/src/common/logtest/logtest.vr b/java/juno-samples/xmlreader/src/common/logtest/logtest.vr new file mode 100644 index 0000000..75a3a69 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/logtest/logtest.vr @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "log.vrh" + +class MyErrorListener +extends ErrorListener +{ + virtual task notify(LogSeverity severity) + { + printf("MyErrorListener::notify(%s)\n", severity); + } +} + +program main +{ + LogInterface logIntf; + ErrorManager errMgr; + MyErrorListener lsnr; + bit[63:0] x = 64'h1020304050607080; + + // create LogInterface + logIntf = new("test"); + logIntf.setMinSeverity(LS_DEBUG); + + // add error listener + errMgr = logIntf.getErrorManager(); + lsnr = new; + errMgr.addListener(lsnr); + + // do some logging + logIntf.log(LS_DEBUG, "msg", psprintf("dec x = %0d", x)); + // 0:0,test,debug,msg,dec x = 1161981756646125696 + logIntf.log(LS_DEBUG, "msg", psprintf("hex x = 'h%0h", x)); + // 0:0,test,debug,msg,hex x = 'h1020304050607080 + logIntf.log(LS_DEBUG, "msg", secsToStr(3661)); + // 0:0,test,error,msg,01:01:01 + logIntf.log(LS_DEBUG, "msg", secsToStr(7199)); + // 0:0,test,error,msg,01:59:59 + logIntf.log(LS_ERROR, "msg", "error!"); + // 0:0,test,error,msg,error! + // MyErrorListener::notify(LS_ERROR) + logIntf.finish(); + // 0:0,log,system,finish,"0 warnings, 1 errors" +} + diff --git a/java/juno-samples/xmlreader/src/common/miscutil.vr b/java/juno-samples/xmlreader/src/common/miscutil.vr new file mode 100644 index 0000000..62def06 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/miscutil.vr @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "common.vri" + +//////////////////////////////////////////////////////////// +// Memory size utilities +//////////////////////////////////////////////////////////// + +#define KB(n) ((n) << 10) +#define MB(n) ((n) << 20) +#define GB(n) ((n) << 30) + +function Qword strToMemSize(string str) +{ + if (str.match("^([0-9]+)([KMG]?)B?$")) { + string digits; + integer num; + integer shift; + + digits = str.backref(0); + num = digits.atoi(); + case (str.backref(1)) { + "K" : shift = 10; + "M" : shift = 20; + "G" : shift = 30; + default : shift = 0; + } + strToMemSize = num << shift; + } else { + error("Invalid memory size %s!\n", str); + } +} + +function string memSizeToStr(Qword value) +{ + string suffix; + + if (value > 0 && (value & (GB(1) - 1)) == 0) { + suffix = "G"; + value >>= 30; + } + else if (value > 0 && (value & (MB(1) - 1)) == 0) { + suffix = "M"; + value >>= 20; + } + else if (value > 0 && (value & (KB(1) - 1)) == 0) { + suffix = "K"; + value >>= 10; + } + else { + suffix = "B"; + } + + memSizeToStr = psprintf("%0d%s", value, suffix); +} + +//////////////////////////////////////////////////////////// +// Math utilities +//////////////////////////////////////////////////////////// + +function bit isPowerOf2(Qword x) +{ + isPowerOf2 = ((x & -x) == x); +} + +// returns the index of the highest (msb) bit set +// Example log2(8'b0011_1100) = 5, log2(8'b0010_0000) = 5 +function integer log2(Qword x) +{ + log2 = -1; + while (x > 0) { + x >>= 1; + ++log2; + } +} + +function integer bitCount(Qword x) +{ + bitCount = 0; + while (x != 0) { + bitCount += x & 1; + x >>= 1; + } +} + +function Qword maskCompress(Qword orig, Qword mask) +{ + integer ip, op; + + maskCompress = 0; + for (ip = 0, op = 0; ip < 64; ++ip) { + if (mask[ip]) maskCompress[op++] = orig[ip]; + } +} + +function Qword maskDecompress(Qword comp, Qword mask) +{ + integer ip, op; + + maskDecompress = 0; + for (ip = 0, op = 0; op < 64; ++op) { + if (mask[op]) maskDecompress[op] = comp[ip++]; + } +} + diff --git a/java/juno-samples/xmlreader/src/common/object.vr b/java/juno-samples/xmlreader/src/common/object.vr new file mode 100644 index 0000000..cbad53f --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/object.vr @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "common.vri" + +//////////////////////////////////////////////////////////// +// Object +//////////////////////////////////////////////////////////// + +#define OBJECT_ID(o) ((o != null) ? o.getObjectID() : 0) +#define OBJECT_NAME(o) ((o != null) ? o.getObjectName() : "(null)") + +#define OBJECT_DUMP_STRING(o) ((o != null) ? o.dumpString() : "(null)") +#define OBJECT_EQUALS(a,b) ((a != null) ? a.equals(b) : (b == null)) +#define OBJECT_HASH_CODE(o) ((o != null) ? o.hashCode() : 0) +#define OBJECT_DESTROY(o) if (o != null) { o.destroy(); o = null; } + +#define OBJECT_ASSOC_ARRAY_DESTROY(array) \ +{ \ + bit[63:0] index; \ + if (assoc_index(FIRST, array, index)) { \ + while (1) { \ + Object o = array[index]; \ + OBJECT_DESTROY(o) \ + if (!assoc_index(NEXT, array, index)) break; \ + } \ + } \ + assoc_index(DELETE, array); \ +} + +#define OBJECT_ARRAY_DESTROY(array,size) \ +{ \ + integer index; \ + for (index = 0; index < size; ++index) { \ + Object o = array[index]; \ + OBJECT_DESTROY(o) \ + array[index] = null; \ + } \ +} + +#define OBJECT_ARRAY_NULL(array,size) \ +{ \ + integer index; \ + for (index = 0; index < size; ++index) { \ + array[index] = null; \ + } \ +} + +class Object +{ + local static integer nextObjectID = 1; + + local string className; + local integer objectID; + local string objectName; + + task new() + { + className = "Object"; + objectID = nextObjectID++; + objectName = null; + } + + function string getClassName() + { + getClassName = className; + } + + protected task setClassName(string name) + { + className = name; + } + + function integer getObjectID() + { + getObjectID = objectID; + } + + function string getObjectName() + { + getObjectName = (objectName != null) ? objectName : + psprintf("%s%0d", className, objectID); + } + + task setObjectName(string name) + { + objectName = name; + } + + virtual function string dumpString() + { + dumpString = getObjectName(); + } + + virtual function bit equals(Object o) + { + equals = (o == this); + } + + virtual function integer hashCode() + { + hashCode = objectID; + } + + virtual task destroy() + { + // overridden by subclasses to help garbage collection + } +} + diff --git a/java/juno-samples/xmlreader/src/common/property.vr b/java/juno-samples/xmlreader/src/common/property.vr new file mode 100644 index 0000000..1efab26 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/property.vr @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include + +function string getPropStr(string name, string def) +{ + if (get_plus_arg(CHECK, name)) { + bit[256*8-1:0] bit_str = get_plus_arg(STR, name); + getPropStr.bittostr(bit_str); + } else { + getPropStr = def; + } +} + +function integer getPropInt(string name, integer def) +{ + if (get_plus_arg(CHECK, name)) { + getPropInt = get_plus_arg(NUM, name); + } else { + getPropInt = def; + } +} + +function bit strToBool(string str) +{ + strToBool = (str == "true") || (str == "yes") || + (str == "on") || (str == "1"); +} + +function bit getPropBool(string name, bit def) +{ + string value = getPropStr(name, def ? "true" : "false"); + getPropBool = strToBool(value); +} + diff --git a/java/juno-samples/xmlreader/src/common/randutil.vr b/java/juno-samples/xmlreader/src/common/randutil.vr new file mode 100644 index 0000000..40ad808 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/randutil.vr @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "log.vrh" + +// generates a random integer in the half interval [base,limit) +// DEPRECATED: use urandom_range(limit-1, base) +function bit[31:0] urandomRange(bit[31:0] base, bit[31:0] limit) +{ + urandomRange = random() % (limit - base) + base; +} + +#define RANDOM_MASK_BITS 128 +#define RandomMask bit[RANDOM_MASK_BITS-1:0] + +// Randomly selects a bit index based on a mask +// +// Given a mask with some bits set, this routine returns the index of one of those set bits. +// +// Example: +// mask = 1100_1010 +// count = 4 +// return value = {1, 3, 6, 7} +// +// mask - a bit mask +// count - the number of set bits to choose from. +// return value - the index of of one of the set bits chosen randomly. +// +function integer randomFromMask(RandomMask mask, integer count) +{ + integer i, j; + + assert(mask != 0 && count != 0); + + // pick random index in [0,count) + i = urandom_range(count-1, 0); + + // find i'th set bit in mask + j = 0; + while (1) { + // scan for next set bit in mask + while (!mask[j]) ++j; + + // break on i'th set bit + if (i == 0) break; + + --i; + ++j; + } + + randomFromMask = j; +} + +// Iterates randomly through the specified bits +// +// Given a mask with some bits set, this routine returns the index of one of those set bits. +// It also changes the count and mask to eliminate that bit from the next iteration. +// +// Example: +// 1st iteration: +// mask = 1100_1010 +// count = 4 +// return value = 3, from potential values {1, 3, 6, 7} +// +// 2nd iteration: +// mask = 1100_0010 +// count = 3 +// return value = 7, from potential values {1, 6, 7} +// +// mask - a bit mask +// count - the number of set bits too choose from. +// return value - the index of of one of the set bits chosen randomly. +// +function integer randomIterate(var RandomMask mask, var integer count) +{ + integer index = randomFromMask(mask, count); + mask[index] = 0; + --count; + randomIterate = index; +} + +// Generates a mask containing the given number of bits randomly set to 1s and 0s. +// +// Example: +// count = 8 +// return value = {8'b0000_0001, 8'b0000_0010, ..., 8'b1111_1111} +// +// count - the effective size of the mask returned. +// return value - a mask with an effective width of count +// +function RandomMask randomBits(integer count) +{ + integer pos; + + randomBits = 0; + for (pos = 0; pos < count; pos += 32) { + bit[31:0] rand32; + + rand32 = urandom(); + if (count - pos < 32) { + rand32[31:count - pos] = 0; + } + randomBits[pos + 31:pos] = rand32; + } +} + +// Generates a value, "count" bits wide, with [minSet..maxSet] bits randomly set +// +// Example: +// minSet = 2 +// maxSet = 5 +// count = 16 +// return value = {16'h8110, 16'h0c0e, 16'h4005, ...} +// number of bits set = {2, 3, 5, 6} +// +// count - the width of the resultant bit mask. +// minSet - the lowest number of bits that will be set. +// maxSet - the highest number of bits that will be set. +// return value - a bit mask that is 'count' bits wide and has between minSet and maxSet bits set, inclusive. +// +function RandomMask randomMask(integer count, integer minSet, integer maxSet) +{ + randomMask = randomMaskSubset(-1, count, minSet, maxSet); +} + +// Generates a random subset of a mask with a constrained number of bits set +// +// Example: +// mask = 16'b0110_1100_0000_1010 +// minSet = 1 +// maxSet = 2 +// count = 4 +// number of bits set = {1, 2} +// +// 0110_1100_0000_1010 <- mask +// 0000_1000_0000_0010 <- potential result, 2 bits set +// 0000_0000_0000_1000 <- potential result, 1 bit set +// +// mask - a starting mask with some set of bits set. +// count - the number of bits in "mask" that can be used to choose from, starting with the lowest bit set. +// minSet - the lowest number of bits that will be set. +// maxSet - the highest number of bits that will be set. +// return value - a bit mask that is has between minSet and maxSet bits set, inclusive. If a bit was set +// in the input mask it can be set in the return value. +// +function RandomMask randomMaskSubset(RandomMask mask, integer count, + integer minSet, integer maxSet) +{ + integer toSet, i; + + assert(0 <= minSet && minSet <= maxSet && maxSet <= count); + + randomMaskSubset = 0; + toSet = urandom_range(maxSet, minSet); + for (i = 0; i < toSet; ++i) { + randomMaskSubset[randomIterate(mask, count)] = 1; + } +} + diff --git a/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.mak b/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.mak new file mode 100644 index 0000000..52d000d --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.mak @@ -0,0 +1,2 @@ +LOAD_COMPS := common +RUNNABLE := 1 diff --git a/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.vr b/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.vr new file mode 100644 index 0000000..4bb342b --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/randutiltest/randutiltest.vr @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "randutil.vrh" +#include "miscutil.vrh" + +program main +{ + RandomMask mask, mask2; + integer count, count2; + + mask = randomBits(0); + printf("randomBits(0) = %x\n", mask); + assert(mask == 0); + + mask = randomBits(1); + printf("randomBits(1) = %x\n", mask); + assert(mask <= 64'h1); + + mask = randomBits(32); + printf("randomBits(32) = %x\n", mask); + assert(mask <= 64'hFFFFFFFF); + + mask = randomBits(33); + printf("randomBits(33) = %x\n", mask); + assert(mask <= 64'h1FFFFFFFF); + + mask = randomBits(64); + printf("randomBits(64) = %x\n\n", mask); + + mask = randomMask(24, 8, 16); + count = bitCount(mask); + printf("randomMask(24, 8, 16) = %x (%0d set)\n", mask, count); + assert(8 <= count && count <= 16); + mask = randomMask(24, 8, 16); + count = bitCount(mask); + printf("randomMask(24, 8, 16) = %x (%0d set)\n", mask, count); + assert(8 <= count && count <= 16); + mask = randomMask(24, 8, 16); + count = bitCount(mask); + printf("randomMask(24, 8, 16) = %x (%0d set)\n\n", mask, count); + assert(8 <= count && count <= 16); + + mask = randomMask(64, 24, 40); + count = bitCount(mask); + printf("randomMask(64, 24, 40) = %x (%0d set)\n", mask, count); + assert(24 <= count && count <= 40); + mask = randomMask(64, 24, 40); + count = bitCount(mask); + printf("randomMask(64, 24, 40) = %x (%0d set)\n", mask, count); + assert(24 <= count && count <= 40); + mask = randomMask(64, 24, 40); + count = bitCount(mask); + printf("randomMask(64, 24, 40) = %x (%0d set)\n\n", mask, count); + assert(24 <= count && count <= 40); + + mask = randomMask(64, 24, 40); + count = bitCount(mask); + mask2 = randomMaskSubset(mask, count, count - 8, count - 4); + count2 = bitCount(mask2); + printf("randomMaskSubset(%x, %0d, %0d, %0d) = %x (%0d set)\n\n", + mask, count, count - 8, count - 4, mask2, count2); + assert(count - 8 <= count2 && count2 <= count - 4); + assert((mask2 & ~mask) == 0); +} + diff --git a/java/juno-samples/xmlreader/src/common/rangeparser.vr b/java/juno-samples/xmlreader/src/common/rangeparser.vr new file mode 100644 index 0000000..a5537f4 --- /dev/null +++ b/java/juno-samples/xmlreader/src/common/rangeparser.vr @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "listparser.vrh" + +//////////////////////////////////////////////////////////// +// RangeParser +//////////////////////////////////////////////////////////// + +class RangeParser +{ + local ListParser lp; + local integer cur; + local integer high; + + task new(string _str) + { + lp = new(_str); + cur = 0; + high = -1; + } + + function bit hasNext() + { + hasNext = cur <= high || lp.hasNext(); + } + + function integer next() + { + if (cur <= high) { + next = cur++; + } else { + string term = lp.next(); + if (term.match("([0-9]+)-([0-9]+)")) { + string lowStr = term.backref(0); + string highStr = term.backref(1); + cur = lowStr.atoi(); + high = highStr.atoi(); + next = cur++; + } else { + next = term.atoi(); + } + } + } + +} + diff --git a/java/juno-samples/xmlreader/src/sax/sax.mak b/java/juno-samples/xmlreader/src/sax/sax.mak new file mode 100644 index 0000000..a5981e4 --- /dev/null +++ b/java/juno-samples/xmlreader/src/sax/sax.mak @@ -0,0 +1,2 @@ +SRC_FILES := sax.vr +LOAD_COMPS := streams diff --git a/java/juno-samples/xmlreader/src/sax/sax.vr b/java/juno-samples/xmlreader/src/sax/sax.vr new file mode 100644 index 0000000..1344a12 --- /dev/null +++ b/java/juno-samples/xmlreader/src/sax/sax.vr @@ -0,0 +1,240 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "object.vrh" +#include "streams.vrh" + +//////////////////////////////////////////////////////////// +// SaxInputSource +//////////////////////////////////////////////////////////// + +virtual class SaxInputSource +{ + // Get the character stream for this input source. + virtual function InputStream getStream(); + + // Get the character encoding for a byte stream or URI. + virtual function string getEncoding(); + + // Get the public identifier for this input source. + virtual function string getPublicId(); + + // Get the system identifier for this input source. + virtual function string getSystemId(); +} + +//////////////////////////////////////////////////////////// +// SaxLocator +//////////////////////////////////////////////////////////// + +virtual class SaxLocator +{ + // Return the public identifier for the current document event. + virtual function string getPublicId(); + + // Return the system identifier for the current document event. + virtual function string getSystemId(); + + // Return the line number where the current document event ends. + virtual function integer getLineNumber(); + + // Return the column number where the current document event ends. + virtual function integer getColumnNumber(); +} + +//////////////////////////////////////////////////////////// +// SaxAttributes +//////////////////////////////////////////////////////////// + +virtual class SaxAttributes +{ + // Look up the index of an attribute by XML 1.0 qualified name. + virtual function integer getIndexByQName(string qName); + + // Look up the index of an attribute by Namespace name. + virtual function integer getIndexByNSName(string uri, string localName); + + // Return the number of attributes in the list. + virtual function integer getLength(); + + // Look up an attribute's local name by index. + virtual function string getLocalName(integer index); + + // Look up an attribute's XML 1.0 qualified name by index. + virtual function string getQName(integer index); + + // Look up an attribute's type by index. + virtual function string getType(integer index); + + // Look up an attribute's type by XML 1.0 qualified name. + virtual function string getTypeByQName(string qName); + + // Look up an attribute's type by Namespace name. + virtual function string getTypeByNSName(string uri, string localName); + + // Look up an attribute's Namespace URI by index. + virtual function string getURI(integer index); + + // Look up an attribute's value by index. + virtual function string getValue(integer index); + + // Look up an attribute's value by XML 1.0 qualified name. + virtual function string getValueByQName(string qName); + + // Look up an attribute's value by Namespace name. + virtual function string getValueByNSName(string uri, string localName); +} + +//////////////////////////////////////////////////////////// +// SaxContentHandler +//////////////////////////////////////////////////////////// + +class SaxContentHandler +{ + // Receive notification of character data. + virtual task characters(string chars) { } + + // Receive notification of the end of a document. + virtual task endDocument() { } + + // Receive notification of the end of an element. + virtual task endElement(string namespaceURI, string localName, string qName) { } + + // End the scope of a prefix-URI mapping. + virtual task endPrefixMapping(string prefix) { } + + // Receive notification of ignorable whitespace in element content. + virtual task ignorableWhitespace(string chars) { } + + // Receive notification of a processing instruction. + virtual task processingInstruction(string target, string data) { } + + // Receive an object for locating the origin of SAX document events. + virtual task setDocumentLocator(SaxLocator locator) { } + + // Receive notification of a skipped entity. + virtual task skippedEntity(string name) { } + + // Receive notification of the beginning of a document. + virtual task startDocument() { } + + // Receive notification of the beginning of an element. + virtual task startElement(string namespaceURI, string localName, string qName, SaxAttributes atts) { } + + // Begin the scope of a prefix-URI Namespace mapping. + virtual task startPrefixMapping(string prefix, string uri) { } +} + +//////////////////////////////////////////////////////////// +// SaxDTDHandler +//////////////////////////////////////////////////////////// + +class SaxDTDHandler +{ + // Receive notification of a notation declaration event. + virtual task notationDecl(string name, string publicId, string systemId) { } + + // Receive notification of an unparsed entity declaration event. + virtual task unparsedEntityDecl(string name, string publicId, string systemId, string notationName) { } +} + +//////////////////////////////////////////////////////////// +// SaxEntityResolver +//////////////////////////////////////////////////////////// + +class SaxEntityResolver +{ + // Allow the application to resolve external entities. + virtual function SaxInputSource resolveEntity(string publicId, string systemId) { } +} + +//////////////////////////////////////////////////////////// +// SaxError +//////////////////////////////////////////////////////////// + +virtual class SaxError +{ + // Returns the message describing the error. + virtual function string getMessage(); + + // Returns the document location of the error. + virtual function SaxLocator getLocation(); + + // Returns a string containing the message and location of the error. + virtual function string toString(); +} + +//////////////////////////////////////////////////////////// +// SaxErrorHandler +//////////////////////////////////////////////////////////// + +class SaxErrorHandler +{ + // Receive notification of a warning. + virtual task warning(SaxError exception) { } + + // Receive notification of a recoverable error. + virtual task nonfatalError(SaxError exception) { } + + // Receive notification of a non-recoverable error. + virtual task fatalError(SaxError exception) { } +} + +//////////////////////////////////////////////////////////// +// SaxXMLReader +//////////////////////////////////////////////////////////// + +virtual class SaxXMLReader +{ + // Return the current content handler. + virtual function SaxContentHandler getContentHandler(); + + // Return the current DTD handler. + virtual function SaxDTDHandler getDTDHandler(); + + // Return the current entity resolver. + virtual function SaxEntityResolver getEntityResolver(); + + // Return the current error handler. + virtual function SaxErrorHandler getErrorHandler(); + + // Look up the value of a feature. + virtual function bit getFeature(string name); + + // Look up the value of a property. + virtual function Object getProperty(string name); + + // Parse an XML document. + virtual task parse(SaxInputSource source); + + // Allow an application to register a content event handler. + virtual task setContentHandler(SaxContentHandler handler); + + // Allow an application to register a DTD event handler. + virtual task setDTDHandler(SaxDTDHandler handler); + + // Allow an application to register an entity resolver. + virtual task setEntityResolver(SaxEntityResolver resolver); + + // Allow an application to register an error event handler. + virtual task setErrorHandler(SaxErrorHandler handler); + + // Set the state of a feature. + virtual task setFeature(string name, bit value); + + // Set the value of a property. + virtual task setProperty(string name, Object value); +} + diff --git a/java/juno-samples/xmlreader/src/streams/filestreams.vr b/java/juno-samples/xmlreader/src/streams/filestreams.vr new file mode 100644 index 0000000..3d0798b --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/filestreams.vr @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "streams.vrh" + +//////////////////////////////////////////////////////////// +// FileInputStream +//////////////////////////////////////////////////////////// + +class FileInputStream +extends InputStream +{ + local string filename; + local integer fd; + local string buffer; + local integer len; + local integer pos; + local string eol; + + task new(string _filename) + { + filename = _filename; + if (filename == "stdin") { + fd = stdin; + } else { + fd = fopen(filename, "r"); + if (!fd) { + error("Error opening file: %s\n", filename); + } + } + len = 0; + pos = 0; + eol.bittostr(8'h0A); + } + + function string getFilename() + { + getFilename = filename; + } + + local task fillBuffer() + { + assert(fd); + buffer = freadstr(fd, RAWIN); + if (buffer != null) { + buffer = { buffer, eol }; + len = buffer.len(); + } else { + len = -1; + } + pos = 0; + } + + virtual function integer read() + { + if (pos == len) fillBuffer(); + if (pos < len) { + read = buffer.getc(pos); + ++pos; + } else { + read = -1; + } + } + + virtual function string readLine() + { + if (pos == len) fillBuffer(); + if (pos < len) { + readLine = buffer.substr(pos); + pos = len; + } else { + readLine = null; + } + } + + virtual task close() + { + if (fd) { + fclose(fd); + fd = 0; + } + } +} + +//////////////////////////////////////////////////////////// +// FileOutputStream +//////////////////////////////////////////////////////////// + +class FileOutputStream +extends OutputStream +{ + local string filename; + local integer fd; + + task new(string _filename, string _mode = "w") + { + filename = _filename; + if (filename == "stdout") { + fd = stdout; + } else { + fd = fopen(filename, _mode); + if (!fd) { + error("Error opening file: %s\n", filename); + } + } + } + + function string getFilename() + { + getFilename = filename; + } + + virtual task write(integer b) + { + assert(fd); + fprintf(fd, "%s", b); + } + + virtual task writeLine(string s) + { + assert(fd); + fprintf(fd, "%s\n", s); + } + + virtual task flush() + { + assert(fd); + fflush(fd); + } + + virtual task close() + { + if (fd) { + fclose(fd); + fd = 0; + } + } +} + diff --git a/java/juno-samples/xmlreader/src/streams/lineposstreams.vr b/java/juno-samples/xmlreader/src/streams/lineposstreams.vr new file mode 100644 index 0000000..0ed7298 --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/lineposstreams.vr @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "streams.vrh" + +//////////////////////////////////////////////////////////// +// LinePosInputStream +//////////////////////////////////////////////////////////// + +class LinePosInputStream +extends InputStream +{ + local InputStream stream; + local integer line; + local integer column; + + task new(InputStream _stream) + { + stream = _stream; + line = 1; + column = 1; + } + + function integer getLineNumber() + { + getLineNumber = line; + } + + function integer getColumnNumber() + { + getColumnNumber = column; + } + + virtual function integer read() + { + read = stream.read(); + if (read == 8'h0A) { + ++line; + column = 1; + } + else if (read != -1) { + ++column; + } + } + + virtual function string readLine() + { + readLine = stream.readLine(); + if (readLine != null) { + ++line; + column = 1; + } + } + + virtual task close() + { + stream.close(); + } +} + +//////////////////////////////////////////////////////////// +// LinePosOutputStream +//////////////////////////////////////////////////////////// + +class LinePosOutputStream +extends OutputStream +{ + local OutputStream stream; + local integer line; + local integer column; + + task new(OutputStream _stream) + { + stream = _stream; + line = 1; + column = 1; + } + + function integer getLineNumber() + { + getLineNumber = line; + } + + function integer getColumnNumber() + { + getColumnNumber = column; + } + + virtual task write(integer b) + { + stream.write(b); + if (b == 8'h0A) { + ++line; + column = 1; + } + else { + ++column; + } + } + + virtual task writeLine(string s) + { + stream.writeLine(s); + ++line; + column = 1; + } + + virtual task flush() + { + stream.flush(); + } + + virtual task close() + { + stream.close(); + } +} + diff --git a/java/juno-samples/xmlreader/src/streams/parsestream.vr b/java/juno-samples/xmlreader/src/streams/parsestream.vr new file mode 100644 index 0000000..990638a --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/parsestream.vr @@ -0,0 +1,300 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "log.vrh" +#include "lineposstreams.vrh" + +//////////////////////////////////////////////////////////// +// ParseStream +//////////////////////////////////////////////////////////// + +#define PARSE_BUFFER_SIZE 64 +#define MAX_PARSE_PUSHBACK 32 +#define MAX_PARSE_FILL (PARSE_BUFFER_SIZE - MAX_PARSE_PUSHBACK) +#define MAX_PARSE_GROUPS 4 + +class ParseStream +extends InputStream +{ + local LogInterface logIntf; + + local LinePosInputStream stream; + local bit eof; + + local string injectStr; + local integer injectLine; + local integer injectColumn; + local integer injectPos; + + local integer buffer[PARSE_BUFFER_SIZE]; + local integer lines[PARSE_BUFFER_SIZE]; + local integer columns[PARSE_BUFFER_SIZE]; + local integer count; + local integer readPos; + local integer writePos; + + local integer groupPos[MAX_PARSE_GROUPS]; + local integer groups; + + local bit capturing; + local string capture; + + task new(InputStream _stream) + { + logIntf = new("parsestream"); + // by default, only log warnings and above (regardless of +log_level) + logIntf.setMinSeverity(LS_WARNING); + logIntf.loadSettings("parsestream"); + + stream = new(_stream); + eof = 0; + injectStr = null; + count = 0; + readPos = 0; + writePos = 0; + groups = 0; + capturing = 0; + } + + function integer peek(integer distance = 0) + { + assert(distance < PARSE_BUFFER_SIZE); + if (count <= distance) fillBuffer(); + if (count > distance) { + peek = buffer[advance(readPos, distance)]; + LOG_MSG(logIntf, LS_DEBUG1, psprintf("peek(%0d) = '%s'", distance, peek)) + } else { + peek = -1; + LOG_MSG(logIntf, LS_DEBUG1, psprintf("peek(%0d) = -1", distance)) + } + } + + function bit lookahead(string s, integer distance = 0) + { + integer len, i; + + len = s.len(); + for (i = 0; i < len; ++i) { + integer ch1 = s.getc(i); + integer ch2 = peek(i + distance); + + if (ch1 != ch2) { + break; + } + } + + lookahead = (i >= len); + LOG_MSG(logIntf, LS_DEBUG, psprintf("lookahead('%s', %0d) = %b", + s, distance, lookahead)) + } + + function integer read() + { + if (count == 0) fillBuffer(); + if (count > 0) { + read = buffer[readPos]; + if (capturing) { + string temp; + + temp.bittostr(read); + capture = { capture, temp }; + } + readPos = advance(readPos); + --count; + LOG_MSG(logIntf, LS_DEBUG, psprintf("read() = '%s'", read)) + } else { + read = -1; + LOG_MSG(logIntf, LS_DEBUG, "read() = -1") + } + } + + function string readString(integer len) + { + integer i; + string s; + + for (i = 0; i < len; ++i) { + integer ch; + string temp; + + ch = read(); + if (ch == -1) break; + temp.bittostr(ch); + s = { s, temp }; + } + if (capturing) { + capture = { capture, s }; + } + readString = s; + LOG_MSG(logIntf, LS_DEBUG, psprintf("readString(%0d) = '%s'", len, s)) + } + + function integer getLineNumber() + { + getLineNumber = (count > 0) ? lines[readPos] : stream.getLineNumber(); + } + + function integer getColumnNumber() + { + getColumnNumber = (count > 0) ? columns[readPos] : stream.getColumnNumber(); + } + + task beginGroup() + { + assert(groups < MAX_PARSE_GROUPS); + groupPos[groups] = readPos; + ++groups; + + LOG_MSG(logIntf, LS_DEBUG, + psprintf("beginGroup(): groups=%0d, readPos=%0d", + groups, readPos)) + } + + task endGroup(bit accept = 1) + { + assert(!capturing); + assert(groups > 0); + --groups; + if (!accept) { + integer savePos, delta; + + savePos = groupPos[groups]; + delta = readPos - savePos; + if (delta < 0) delta += PARSE_BUFFER_SIZE; + readPos = savePos; + count += delta; + } + + LOG_MSG(logIntf, LS_DEBUG, + psprintf("endGroup(%b): groups=%0d, readPos=%0d", + accept, groups, readPos)) + } + + task beginCapture() + { + assert(!capturing); + capturing = 1; + capture = ""; + + LOG_MSG(logIntf, LS_DEBUG, "beginCapture()") + } + + function string endCapture(bit accept = 1) + { + assert(capturing); + capturing = 0; + endCapture = accept ? capture : null; + + LOG_MSG(logIntf, LS_DEBUG, + psprintf("endCapture(%b) = '%s'", + accept, endCapture)) + } + + task inject(string s) + { + LOG_MSG(logIntf, LS_DEBUG, psprintf("inject('%s')", s)) + + if (s != null && s.len() > 0) { + string temp; + + injectLine = getLineNumber(); + injectColumn = getColumnNumber(); + + // read existing buffer onto end of new string + while (count > 0) { + temp.bittostr(buffer[readPos]); + s = { s, temp }; + readPos = advance(readPos); + --count; + } + + // concatenate new string and unused existing injection string + if (injectStr != null) { + injectStr = { s, injectStr.substr(injectPos) }; + } else { + injectStr = s; + } + LOG_MSG(logIntf, LS_DEBUG1, psprintf("injectStr = '%s'", injectStr)) + + // reset injection position + injectPos = 0; + } + } + + task close() + { + stream.close(); + injectStr = null; + eof = 1; + count = 0; + } + + local function integer advance(integer ofs, integer distance = 1) + { + ofs += distance; + if (ofs >= PARSE_BUFFER_SIZE) ofs -= PARSE_BUFFER_SIZE; + advance = ofs; + } + + local task fillBuffer() + { + integer injectCount; + + injectCount = (injectStr != null) ? injectStr.len() - injectPos : 0; + + LOG_MSG(logIntf, LS_DEBUG1, + psprintf("fillBuffer(): enter: eof=%b, injectCount=%0d, count=%0d, writePos=%0d", + eof, injectCount, count, writePos)) + + while (count < MAX_PARSE_FILL && (!eof || injectCount > 0)) { + integer ch; + integer line; + integer column; + string source; + + if (injectCount > 0) { + source = "injection buffer"; + line = injectLine; + column = injectColumn; + ch = injectStr.getc(injectPos++); + if (--injectCount == 0) { + injectStr = null; + } + } else { + source = "underlying stream"; + line = stream.getLineNumber(); + column = stream.getColumnNumber(); + ch = stream.read(); + } + if (ch != -1) { + LOG_MSG(logIntf, LS_DEBUG2, + psprintf("read from %s: ch='%s', line=%0d, column=%0d", + source, ch, line, column)) + lines[writePos] = line; + columns[writePos] = column; + buffer[writePos] = ch; + writePos = advance(writePos); + ++count; + } else { + eof = 1; + } + } + + LOG_MSG(logIntf, LS_DEBUG1, + psprintf("fillBuffer(): exit: eof=%b, injectCount=%0d, count=%0d, writePos=%0d", + eof, injectCount, count, writePos)) + } +} + diff --git a/java/juno-samples/xmlreader/src/streams/streams.mak b/java/juno-samples/xmlreader/src/streams/streams.mak new file mode 100644 index 0000000..fd58339 --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/streams.mak @@ -0,0 +1,7 @@ +SRC_FILES := \ + streams.vr \ + stringstreams.vr \ + filestreams.vr \ + lineposstreams.vr \ + parsestream.vr +LOAD_COMPS := common diff --git a/java/juno-samples/xmlreader/src/streams/streams.vr b/java/juno-samples/xmlreader/src/streams/streams.vr new file mode 100644 index 0000000..b366d1a --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/streams.vr @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "common.vri" + +//////////////////////////////////////////////////////////// +// InputStream +//////////////////////////////////////////////////////////// + +virtual class InputStream +{ + // Reads the next byte of data from the input stream. + virtual function integer read(); + + // Reads the next line of data from the input stream. + virtual function string readLine() + { + string s; + + while (1) { + integer b; + string temp; + + b = read(); + if (b == -1 || b == 8'h0A) break; + temp.bittostr(b); + s = { s, temp }; + } + readLine = s; + } + + // Skips over and discards n bytes of data from this input stream. + virtual function integer skip(integer n) + { + integer i; + + for (i = 0; i < n; ++i) { + integer b; + + b = read(); + if (b == -1) break; + } + skip = i; + } + + // Closes this input stream and releases any system resources associated with the stream. + virtual task close() {} +} + +//////////////////////////////////////////////////////////// +// OutputStream +//////////////////////////////////////////////////////////// + +virtual class OutputStream +{ + // Writes the specified byte to this output stream. + virtual task write(integer b); + + // Writes the specified line to this output stream. + virtual task writeLine(string s) + { + integer len, i; + + len = s.len(); + for (i = 0; i < len; ++i) { + write(s.getc(i)); + } + write(8'h0A); + } + + // Flushes this output stream and forces any buffered output bytes to be written out. + virtual task flush() {} + + // Closes this output stream and releases any system resources associated with this stream. + virtual task close() {} +} + diff --git a/java/juno-samples/xmlreader/src/streams/stringstreams.vr b/java/juno-samples/xmlreader/src/streams/stringstreams.vr new file mode 100644 index 0000000..81609ed --- /dev/null +++ b/java/juno-samples/xmlreader/src/streams/stringstreams.vr @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "streams.vrh" + +//////////////////////////////////////////////////////////// +// StringInputStream +//////////////////////////////////////////////////////////// + +class StringInputStream +extends InputStream +{ + local string buffer; + local integer pos; + + task new(string s) + { + buffer = s; + pos = 0; + } + + virtual function integer read() + { + if (buffer != null && pos < buffer.len()) { + read = buffer.getc(pos); + ++pos; + } else { + read = -1; + } + } + + virtual task close() + { + buffer = null; + } +} + +//////////////////////////////////////////////////////////// +// StringOutputStream +//////////////////////////////////////////////////////////// + +class StringOutputStream +extends OutputStream +{ + local string buffer; + + task new() + { + } + + function string getString() + { + getString = buffer; + } + + virtual task write(integer b) + { + string temp; + temp.bittostr(b); + buffer = { buffer, temp }; + } + + virtual task writeLine(string s) + { + sprintf(buffer, "%s%s\n", buffer, s); + } + + virtual task close() + { + buffer = null; + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/uri.vr b/java/juno-samples/xmlreader/src/xmlreader/uri.vr new file mode 100644 index 0000000..c51d865 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/uri.vr @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "common.vri" + +//////////////////////////////////////////////////////////// +// URI +//////////////////////////////////////////////////////////// + +class URI +{ + string protocol; + string host; + string path; + + task new(string s = null) + { + if (s != null) void = parse(s); + } + + function bit parse(string s) + { + parse = s.match("^(([^:]+):)?(//([^/]+))?([^ ]*)$"); + if (parse) { + protocol = s.backref(1); + host = s.backref(3); + path = s.backref(4); + } + } + + function string toString() + { + if (protocol != null) { + toString = { protocol, ":" }; + } + if (host != null) { + toString = { toString, "//", host }; + } + toString = { toString, path }; + } +} + +function string resolveRelativeURI(string rel, string base) +{ + URI relURI = new; + URI baseURI = new; + + if (relURI.parse(rel) && + relURI.protocol == null && + relURI.host == null && + relURI.path != null && + baseURI.parse(base)) { + + URI absURI = new; + + absURI.protocol = baseURI.protocol; + absURI.host = baseURI.host; + if (!relURI.path.match("^/") && baseURI.path.match("(.*/)[^/]*$")) { + absURI.path = { baseURI.path.backref(0), relURI.path }; + } + else { + absURI.path = relURI.path; + } + + resolveRelativeURI = absURI.toString(); + } else { + resolveRelativeURI = rel; + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xincludefilter.vr b/java/juno-samples/xmlreader/src/xmlreader/xincludefilter.vr new file mode 100644 index 0000000..925c2e9 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xincludefilter.vr @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "xmlreader.vrh" +#include "xmlinputsource.vrh" +#include "uri.vrh" + +//////////////////////////////////////////////////////////// +// XIncludeContentFilter +//////////////////////////////////////////////////////////// + +typedef class XIncludeLocator; + +class XIncludeContentFilter +extends SaxContentHandler +{ + local SaxXMLReader baseReader; + local SaxContentHandler baseHandler; + local SaxErrorHandler errorHandler; + local integer includeNesting; + local bit topLevel; + local XIncludeLocator xiLocator; + + task new(SaxXMLReader _baseReader, SaxContentHandler _baseHandler, + SaxErrorHandler _errorHandler = null) + { + baseReader = _baseReader; + baseHandler = _baseHandler; + errorHandler = (_errorHandler != null) ? _errorHandler : + baseReader.getErrorHandler(); + includeNesting = 0; + topLevel = 1; + } + + // Receive notification of character data. + virtual task characters(string chars) + { + if (includeNesting == 0) { + baseHandler.characters(chars); + } + } + + // Receive notification of the end of a document. + virtual task endDocument() + { + assert(includeNesting == 0); + if (topLevel) { + baseHandler.endDocument(); + } + } + + // Receive notification of the end of an element. + virtual task endElement(string namespaceURI, string localName, string qName) + { + if (includeNesting == 0) { + baseHandler.endElement(namespaceURI, localName, qName); + } else { + --includeNesting; + } + } + + // End the scope of a prefix-URI mapping. + virtual task endPrefixMapping(string prefix) + { + if (includeNesting == 0) { + baseHandler.endPrefixMapping(prefix); + } + } + + // Receive notification of ignorable whitespace in element content. + virtual task ignorableWhitespace(string chars) + { + if (includeNesting == 0) { + baseHandler.ignorableWhitespace(chars); + } + } + + // Receive notification of a processing instruction. + virtual task processingInstruction(string target, string data) + { + if (includeNesting == 0) { + baseHandler.processingInstruction(target, data); + } + } + + // Receive an object for locating the origin of SAX document events. + virtual task setDocumentLocator(SaxLocator _locator) + { + if (topLevel) { + xiLocator = new(_locator); + baseHandler.setDocumentLocator(xiLocator); + } + else if (xiLocator != null) { + xiLocator.base = _locator; + } + } + + // Receive notification of a skipped entity. + virtual task skippedEntity(string name) + { + if (includeNesting == 0) { + baseHandler.skippedEntity(name); + } + } + + // Receive notification of the beginning of a document. + virtual task startDocument() + { + assert(includeNesting == 0); + if (topLevel) { + baseHandler.startDocument(); + } + } + + // Receive notification of the beginning of an element. + virtual task startElement(string namespaceURI, string localName, string qName, SaxAttributes atts) + { + if (includeNesting == 0) { + if (namespaceURI == "http://www.w3.org/2001/XInclude") { + case (localName) { + "include" : { + string href = atts.getValueByNSName(null, "href"); + if (href != null) { + XmlReader reader; + XIncludeContentFilter filter; + string uri; + XmlInputSource source; + SaxLocator realLocator; + + reader = new; + reader.inheritHandlers(baseReader); + + filter = new(baseReader, baseHandler, errorHandler); + filter.topLevel = 0; + filter.xiLocator = xiLocator; + reader.setContentHandler(filter); + + if (xiLocator != null) { + uri = resolveRelativeURI(href, xiLocator.getSystemId()); + realLocator = xiLocator.base; + } else { + uri = href; + } + source = getXmlInputSource(uri); + + reader.parse(source); + + if (xiLocator != null) { + xiLocator.base = realLocator; + } + } else { + fatalError("XInclude: href not specified for include"); + } + } + "fallback" : { + fatalError("XInclude: fallback outside of include"); + } + default : { + fatalError({ "XInclude: Unknown element: ", localName }); + } + } + ++includeNesting; + } else { + baseHandler.startElement(namespaceURI, localName, qName, atts); + } + } + else { + warning(psprintf("XInclude: Ignoring nested element: %s", qName)); + } + } + + // Begin the scope of a prefix-URI Namespace mapping. + virtual task startPrefixMapping(string prefix, string uri) + { + if (includeNesting == 0) { + baseHandler.startPrefixMapping(prefix, uri); + } + } + + local task warning(string msg) + { + XmlError e = new(msg, xiLocator); + errorHandler.warning(e); + } + + local task fatalError(string msg) + { + XmlError e = new(msg, xiLocator); + errorHandler.fatalError(e); + } +} + +//////////////////////////////////////////////////////////// +// XIncludeLocator +//////////////////////////////////////////////////////////// + +class XIncludeLocator +extends SaxLocator +{ + SaxLocator base; + + task new(SaxLocator _base) + { + base = _base; + } + + // Return the public identifier for the current document event. + virtual function string getPublicId() + { + getPublicId = base.getPublicId(); + } + + // Return the system identifier for the current document event. + virtual function string getSystemId() + { + getSystemId = base.getSystemId(); + } + + // Return the line number where the current document event ends. + virtual function integer getLineNumber() + { + getLineNumber = base.getLineNumber(); + } + + // Return the column number where the current document event ends. + virtual function integer getColumnNumber() + { + getColumnNumber = base.getColumnNumber(); + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xml-grammar.txt b/java/juno-samples/xmlreader/src/xmlreader/xml-grammar.txt new file mode 100644 index 0000000..1903ec8 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xml-grammar.txt @@ -0,0 +1,83 @@ +[1] document ::= prolog element Misc* +[2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] +[3] S ::= (#x20 | #x9 | #xD | #xA)+ +[4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender +[5] Name ::= (Letter | '_' | ':') (NameChar)* +[6] Names ::= Name (S Name)* +[7] Nmtoken ::= (NameChar)+ +[8] Nmtokens ::= Nmtoken (S Nmtoken)* +[9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' | "'" ([^%&'] | PEReference | Reference)* "'" +[10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'" +[11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") +[12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" +[13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] +[14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) +[15] Comment ::= '' +[16] PI ::= '' Char*)))? '?>' +[17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) +[18] CDSect ::= CDStart CData CDEnd +[19] CDStart ::= '' Char*)) +[21] CDEnd ::= ']]>' +[22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)? +[23] XMLDecl ::= '' +[24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"') +[25] Eq ::= S? '=' S? +[26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+ +[27] Misc ::= Comment | PI | S +[28] doctypedecl ::= '' +[28a] DeclSep ::= PEReference | S +[29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment +[30] extSubset ::= TextDecl? extSubsetDecl +[31] extSubsetDecl ::= ( markupdecl | conditionalSect | DeclSep)* +[32] SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"')) +[39] element ::= EmptyElemTag | STag content ETag +[40] STag ::= '<' Name (S Attribute)* S? '>' +[41] Attribute ::= Name Eq AttValue +[42] ETag ::= '' +[43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)* +[44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' +[45] elementdecl ::= '' +[46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children +[47] children ::= (choice | seq) ('?' | '*' | '+')? +[48] cp ::= (Name | choice | seq) ('?' | '*' | '+')? +[49] choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')' +[50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')' +[51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' +[52] AttlistDecl ::= '' +[53] AttDef ::= S Name S AttType S DefaultDecl +[54] AttType ::= StringType | TokenizedType | EnumeratedType +[55] StringType ::= 'CDATA' +[56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS' +[57] EnumeratedType ::= NotationType | Enumeration +[58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' +[59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' +[60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue) +[61] conditionalSect ::= includeSect | ignoreSect +[62] includeSect ::= '' +[63] ignoreSect ::= '' +[64] ignoreSectContents ::= Ignore ('' Ignore)* +[65] Ignore ::= Char* - (Char* ('') Char*) +[66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' +[67] Reference ::= EntityRef | CharRef +[68] EntityRef ::= '&' Name ';' +[69] PEReference ::= '%' Name ';' +[70] EntityDecl ::= GEDecl | PEDecl +[71] GEDecl ::= '' +[72] PEDecl ::= '' +[73] EntityDef ::= EntityValue | (ExternalID NDataDecl?) +[74] PEDef ::= EntityValue | ExternalID +[75] ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral +[76] NDataDecl ::= S 'NDATA' S Name +[77] TextDecl ::= '' +[78] extParsedEnt ::= TextDecl? content +[80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) +[81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')* +[82] NotationDecl ::= '' +[83] PublicID ::= 'PUBLIC' S PubidLiteral +[84] Letter ::= BaseChar | Ideographic +[85] BaseChar ::= [#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | [#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | [#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | [#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | [#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | [#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | [#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | [#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | [#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | [#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | [#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | [#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | [#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | [#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | [#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | [#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | [#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | [#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | [#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | [#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | [#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | [#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | [#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | [#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | [#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | [#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | [#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | [#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | [#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | #x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | #x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | #x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | [#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | [#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | #x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | [#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | [#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | [#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | [#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | [#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | #x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | [#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | [#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | [#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | [#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3] +[86] Ideographic ::= [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] +[87] CombiningChar ::= [#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | [#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | [#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | [#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | #x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | [#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | [#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | #x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | [#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | [#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | #x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | [#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | [#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | [#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | [#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | [#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | #x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | [#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | #x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | [#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | [#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | #x3099 | #x309A +[88] Digit ::= [#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | [#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | [#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | [#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29] +[89] Extender ::= #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE] diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlattributes.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlattributes.vr new file mode 100644 index 0000000..0cd4a9c --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlattributes.vr @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "sax.vrh" +#include "arraylist.vrh" +#include "strhashmap.vrh" +#include "xmlnamescope.vrh" + +//////////////////////////////////////////////////////////// +// XmlAttribute +//////////////////////////////////////////////////////////// + +class XmlAttribute +extends Object +{ + string prefix; + string localName; + string qname; + string uri; + string type; + string value; + integer index; + + task new(string _prefix, string _localName, string _qname, + string _type, string _value, integer _index) + { + prefix = _prefix; + localName = _localName; + qname = _qname; + uri = null; + type = _type; + value = _value; + index = _index; + } +} + +//////////////////////////////////////////////////////////// +// XmlAttributes +//////////////////////////////////////////////////////////// + +class XmlAttributes +extends SaxAttributes +{ + local ArrayList attrList; + local StrHashMap qnameMap; + local StrHashMap nsnameMap; + + task new() + { + attrList = new; + qnameMap = new; + nsnameMap = new; + } + + // Adds a new attribute to the list. + task addAttr(string prefix, string localName, string type, string value) + { + string qname; + XmlAttribute attr; + + qname = (prefix != null) ? { prefix, ":", localName } : localName; + attr = new(prefix, localName, qname, type, value, attrList.size()); + attrList.add(attr); + qnameMap.put(qname, attr); + } + + // Resolves the URIs of each attribute using the given scope. + task resolveURIs(XmlNameScope scope) + { + Iterator i; + + nsnameMap.clear(); + i = attrList.iterator(); + while (i.hasNext()) { + XmlAttribute attr; + + cast_assign(attr, i.next()); + if (scope != null && attr.prefix != null) { + attr.uri = scope.lookupURI(attr.prefix); + } + nsnameMap.put({ attr.uri, ":", attr.localName }, attr); + } + } + + // Free resources associated with this object. + task destroy() + { + attrList.destroy(); + qnameMap.destroy(); + nsnameMap.destroy(); + } + + // Look up the index of an attribute by XML 1.0 qualified name. + virtual function integer getIndexByQName(string qname) + { + XmlAttribute attr; + + cast_assign(attr, qnameMap.get(qname)); + getIndexByQName = (attr != null) ? attr.index : -1; + } + + // Look up the index of an attribute by Namespace name. + virtual function integer getIndexByNSName(string uri, string localName) + { + XmlAttribute attr; + + cast_assign(attr, nsnameMap.get({ uri, ":", localName })); + getIndexByNSName = (attr != null) ? attr.index : -1; + } + + // Return the number of attributes in the list. + virtual function integer getLength() + { + getLength = attrList.size(); + } + + // Look up an attribute's local name by index. + virtual function string getLocalName(integer index) + { + XmlAttribute attr; + + cast_assign(attr, attrList.get(index)); + getLocalName = attr.localName; + } + + // Look up an attribute's XML 1.0 qualified name by index. + virtual function string getQName(integer index) + { + XmlAttribute attr; + string qname; + + cast_assign(attr, attrList.get(index)); + getQName = attr.qname; + } + + // Look up an attribute's type by index. + virtual function string getType(integer index) + { + XmlAttribute attr; + + cast_assign(attr, attrList.get(index)); + getType = attr.type; + } + + // Look up an attribute's type by XML 1.0 qualified name. + virtual function string getTypeByQName(string qname) + { + XmlAttribute attr; + + cast_assign(attr, qnameMap.get(qname)); + getTypeByQName = (attr != null) ? attr.type : null; + } + + // Look up an attribute's type by Namespace name. + virtual function string getTypeByNSName(string uri, string localName) + { + XmlAttribute attr; + + cast_assign(attr, nsnameMap.get({ uri, ":", localName })); + getTypeByNSName = (attr != null) ? attr.type : null; + } + + // Look up an attribute's Namespace URI by index. + virtual function string getURI(integer index) + { + XmlAttribute attr; + + cast_assign(attr, attrList.get(index)); + getURI = attr.uri; + } + + // Look up an attribute's value by index. + virtual function string getValue(integer index) + { + XmlAttribute attr; + + cast_assign(attr, attrList.get(index)); + getValue = attr.value; + } + + // Look up an attribute's value by XML 1.0 qualified name. + virtual function string getValueByQName(string qname) + { + XmlAttribute attr; + + cast_assign(attr, qnameMap.get(qname)); + getValueByQName = (attr != null) ? attr.value : null; + } + + // Look up an attribute's value by Namespace name. + virtual function string getValueByNSName(string uri, string localName) + { + XmlAttribute attr; + + cast_assign(attr, nsnameMap.get({ uri, ":", localName })); + getValueByNSName = (attr != null) ? attr.value : null; + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmldoctypeinfo.vr b/java/juno-samples/xmlreader/src/xmlreader/xmldoctypeinfo.vr new file mode 100644 index 0000000..5279b09 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmldoctypeinfo.vr @@ -0,0 +1,159 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strhashmap.vrh" + +//////////////////////////////////////////////////////////// +// XmlNotationInfo +//////////////////////////////////////////////////////////// + +class XmlNotationInfo +extends Object +{ + string name; + string publicId; + string systemId; + + task new(string _name, string _publicId, string _systemId) + { + name = _name; + publicId = _publicId; + systemId = _systemId; + } +} + +//////////////////////////////////////////////////////////// +// XmlEntityInfo +//////////////////////////////////////////////////////////// + +class XmlEntityInfo +extends Object +{ + string name; + string value; + string publicId; + string systemId; + string ndata; + + task new(string _name, string _value, string _publicId, string _systemId, string _ndata) + { + name = _name; + value = _value; + publicId = _publicId; + systemId = _systemId; + ndata = _ndata; + } + + function bit isExternal() + { + isExternal = (systemId != null); + } + + function bit isUnparsed() + { + isUnparsed = (ndata != null); + } +} + +//////////////////////////////////////////////////////////// +// XmlDocTypeInfo +//////////////////////////////////////////////////////////// + +class XmlDocTypeInfo +{ + local StrHashMap notations; + local StrHashMap genEntities; + local StrHashMap paramEntities; + + task new() + { + XmlEntityInfo entity; + string doubleQuote; + + notations = new; + genEntities = new; + paramEntities = new; + + // predefined entities + entity = new("lt", "<", null, null, null); + genEntities.put(entity.name, entity); + + entity = new("gt", ">", null, null, null); + genEntities.put(entity.name, entity); + + entity = new("amp", "&", null, null, null); + genEntities.put(entity.name, entity); + + entity = new("apos", "'", null, null, null); + genEntities.put(entity.name, entity); + + doubleQuote.bittostr(8'h22); + entity = new("quot", doubleQuote, null, null, null); + genEntities.put(entity.name, entity); + } + + task destroy() + { + notations.destroy(); + genEntities.destroy(); + paramEntities.destroy(); + } + + task addNotation(string name, string publicId, string systemId) + { + XmlNotationInfo notation = new(name, publicId, systemId); + notations.put(name, notation); + } + + function XmlNotationInfo lookupNotation(string name) + { + cast_assign(lookupNotation, notations.get(name)); + } + + task addGenEntity(string name, string value) + { + XmlEntityInfo entity = new(name, value, null, null, null); + genEntities.put(name, entity); + } + + task addGenEntityExt(string name, string publicId, string systemId, string ndata) + { + XmlEntityInfo entity = new(name, null, publicId, systemId, ndata); + genEntities.put(name, entity); + } + + function XmlEntityInfo lookupGenEntity(string name) + { + cast_assign(lookupGenEntity, genEntities.get(name)); + } + + task addParamEntity(string name, string value) + { + XmlEntityInfo entity = new(name, value, null, null, null); + paramEntities.put(name, entity); + } + + task addParamEntityExt(string name, string publicId, string systemId) + { + XmlEntityInfo entity = new(name, null, publicId, systemId, null); + paramEntities.put(name, entity); + } + + function XmlEntityInfo lookupParamEntity(string name) + { + cast_assign(lookupParamEntity, paramEntities.get(name)); + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlerror.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlerror.vr new file mode 100644 index 0000000..80668b9 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlerror.vr @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "log.vrh" +#include "sax.vrh" +#include "xmllocator.vrh" + +//////////////////////////////////////////////////////////// +// XmlError +//////////////////////////////////////////////////////////// + +class XmlError +extends SaxError +{ + local string message; + local XmlStaticLocator location; + + task new(string _message, SaxLocator locator) + { + message = _message; + if (locator != null) { + location = new( + locator.getPublicId(), + locator.getSystemId(), + locator.getLineNumber(), + locator.getColumnNumber()); + } + } + + // Returns the message describing the error. + virtual function string getMessage() + { + getMessage = message; + } + + // Returns the document location of the error. + virtual function SaxLocator getLocation() + { + getLocation = location; + } + + // Returns a string containing the message and location of the error. + virtual function string toString() + { + toString = message; + if (location != null) { + string publicId; + string systemId; + + publicId = location.getPublicId(); + systemId = location.getSystemId(); + if (publicId != null || systemId != null) { + toString = { toString, " in " }; + if (publicId != null && systemId != null) { + toString = { toString, publicId, " (", systemId, ")" }; + } + else if (publicId != null) { + toString = { toString, publicId }; + } + else { + toString = { toString, systemId }; + } + } + + toString = { toString, psprintf(" at line %0d, column %0d", + location.getLineNumber(), location.getColumnNumber()) }; + } + } +} + +//////////////////////////////////////////////////////////// +// XmlErrorHandler +//////////////////////////////////////////////////////////// + +class XmlErrorHandler +extends SaxErrorHandler +{ + local LogInterface logIntf; + + task new(LogInterface _logIntf) + { + logIntf = _logIntf; + } + + // Receive notification of a warning. + virtual task warning(SaxError exception) + { + logIntf.logMsg(LS_WARNING, exception.toString()); + } + + // Receive notification of a recoverable error. + virtual task error(SaxError exception) + { + logIntf.logMsg(LS_ERROR, exception.toString()); + } + + // Receive notification of a non-recoverable error. + virtual task fatalError(SaxError exception) + { + logIntf.logMsg(LS_FATAL, exception.toString()); + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlinputsource.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlinputsource.vr new file mode 100644 index 0000000..d9bfaa9 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlinputsource.vr @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "sax.vrh" +#include "filestreams.vrh" + +//////////////////////////////////////////////////////////// +// XmlInputSource +//////////////////////////////////////////////////////////// + +class XmlInputSource +extends SaxInputSource +{ + local InputStream stream; + local string encoding; + local string publicId; + local string systemId; + + task new(InputStream _stream) + { + stream = _stream; + encoding = "ASCII"; + } + + // Get the character stream for this input source. + virtual function InputStream getStream() + { + getStream = stream; + } + + // Get the character encoding for a byte stream or URI. + virtual function string getEncoding() + { + getEncoding = encoding; + } + + // Get the public identifier for this input source. + virtual function string getPublicId() + { + getPublicId = publicId; + } + + // Get the system identifier for this input source. + virtual function string getSystemId() + { + getSystemId = systemId; + } + + // Set the public identifier for this input source. + task setPublicId(string _publicId) + { + publicId = _publicId; + } + + // Set the system identifier for this input source. + task setSystemId(string _systemId) + { + systemId = _systemId; + } +} + +local function XmlInputSource getFileInputSource(string filename) +{ + FileInputStream stream; + XmlInputSource source; + + stream = new(filename); + + source = new(stream); + source.setSystemId(filename); + + getFileInputSource = source; +} + +function XmlInputSource getXmlInputSource(string uri) +{ + static integer tempseq = 0; + string proto; + string hostpath; + + if (uri.match("^([A-Za-z]+)://")) { + proto = uri.backref(0); + hostpath = uri.postmatch(); + } else { + proto = "file"; + hostpath = uri; + } + + case (proto) { + "file" : { + getXmlInputSource = getFileInputSource(hostpath); + } + "http", "ftp" : { + string tempfile; + integer res; + + tempfile = psprintf("wget%0d.tmp", tempseq++); + res = os_command(psprintf("wget -q -O %s %s", tempfile, uri)); + if (res == 0) { + getXmlInputSource = getFileInputSource(tempfile); + } else { + error("Error retrieving %s to %s\n", uri, tempfile); + } + } + default : { + error("Unsupported protocol: %s\n", proto); + } + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmllocator.vr b/java/juno-samples/xmlreader/src/xmlreader/xmllocator.vr new file mode 100644 index 0000000..acc87f3 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmllocator.vr @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "sax.vrh" +#include "parsestream.vrh" + +//////////////////////////////////////////////////////////// +// XmlStaticLocator +//////////////////////////////////////////////////////////// + +class XmlStaticLocator +extends SaxLocator +{ + local string publicId; + local string systemId; + local integer line; + local integer column; + + task new(string _publicId, string _systemId, integer _line, integer _column) + { + publicId = _publicId; + systemId = _systemId; + line = _line; + column = _column; + } + + // Return the public identifier for the current document event. + virtual function string getPublicId() + { + getPublicId = publicId; + } + + // Return the system identifier for the current document event. + virtual function string getSystemId() + { + getSystemId = systemId; + } + + // Return the line number where the current document event ends. + virtual function integer getLineNumber() + { + getLineNumber = line; + } + + // Return the column number where the current document event ends. + virtual function integer getColumnNumber() + { + getColumnNumber = column; + } +} + +//////////////////////////////////////////////////////////// +// XmlActiveLocator +//////////////////////////////////////////////////////////// + +class XmlActiveLocator +extends SaxLocator +{ + local ParseStream parseStream; + local string publicId; + local string systemId; + + task new(ParseStream _parseStream) + { + parseStream = _parseStream; + } + + // Return the public identifier for the current document event. + virtual function string getPublicId() + { + getPublicId = publicId; + } + + // Return the system identifier for the current document event. + virtual function string getSystemId() + { + getSystemId = systemId; + } + + // Return the line number where the current document event ends. + virtual function integer getLineNumber() + { + getLineNumber = parseStream.getLineNumber(); + } + + // Return the column number where the current document event ends. + virtual function integer getColumnNumber() + { + getColumnNumber = parseStream.getColumnNumber(); + } + + // Set the public identifier for this input source. + task setPublicId(string _publicId) + { + publicId = _publicId; + } + + // Set the system identifier for this input source. + task setSystemId(string _systemId) + { + systemId = _systemId; + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlnamescope.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlnamescope.vr new file mode 100644 index 0000000..15536a2 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlnamescope.vr @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "strstrhashmap.vrh" + +//////////////////////////////////////////////////////////// +// XmlNameScope +//////////////////////////////////////////////////////////// + +class XmlNameScope +{ + local XmlNameScope parent; + local StrStrHashMap namespaceMap; + + task new(XmlNameScope _parent = null) + { + parent = _parent; + namespaceMap = new; + } + + task destroy() + { + namespaceMap.destroy(); + } + + task addURI(string prefix, string uri) + { + namespaceMap.put(prefix, uri); + } + + function string lookupURI(string prefix) + { + if (prefix == "xml") { + lookupURI = "http://www.w3.org/XML/1998/namespace"; + } else { + XmlNameScope scope = this; + + while (scope != null) { + lookupURI = namespaceMap.get(prefix); + if (lookupURI != null) break; + scope = scope.parent; + } + } + } + + function StrSet getPrefixes() + { + getPrefixes = namespaceMap.keySet(); + } +} + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlreader.mak b/java/juno-samples/xmlreader/src/xmlreader/xmlreader.mak new file mode 100644 index 0000000..5aefdf4 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlreader.mak @@ -0,0 +1,11 @@ +SRC_FILES := \ + uri.vr \ + xmlattributes.vr \ + xmldoctypeinfo.vr \ + xmlerror.vr \ + xmlinputsource.vr \ + xmllocator.vr \ + xmlnamescope.vr \ + xmlreader.vr \ + xincludefilter.vr +LOAD_COMPS := sax collections diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlreader.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlreader.vr new file mode 100644 index 0000000..85436d3 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlreader.vr @@ -0,0 +1,2213 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include "log.vrh" +#include "sax.vrh" +#include "parsestream.vrh" +#include "xmlattributes.vrh" +#include "xmldoctypeinfo.vrh" +#include "xmlerror.vrh" +#include "xmlinputsource.vrh" +#include "xmllocator.vrh" + +//////////////////////////////////////////////////////////// +// XmlReader +//////////////////////////////////////////////////////////// + +typedef class XmlParseContext; +typedef class XmlParser; + +class XmlReader +extends SaxXMLReader +{ + LogInterface logIntf; + SaxContentHandler contentHandler; + SaxDTDHandler dtdHandler; + SaxEntityResolver entityResolver; + SaxErrorHandler errorHandler; + + task new() + { + XmlErrorHandler errImpl; + + logIntf = new("xmlreader"); + logIntf.loadSettings("xmlreader"); + + contentHandler = new; + dtdHandler = new; + entityResolver = new; + errImpl = new(logIntf); + errorHandler = errImpl; + } + + task inheritHandlers(SaxXMLReader reader) + { + contentHandler = reader.getContentHandler(); + dtdHandler = reader.getDTDHandler(); + entityResolver = reader.getEntityResolver(); + errorHandler = reader.getErrorHandler(); + } + + // Return the current content handler. + virtual function SaxContentHandler getContentHandler() + { + getContentHandler = contentHandler; + } + + // Return the current DTD handler. + virtual function SaxDTDHandler getDTDHandler() + { + getDTDHandler = dtdHandler; + } + + // Return the current entity resolver. + virtual function SaxEntityResolver getEntityResolver() + { + getEntityResolver = entityResolver; + } + + // Return the current error handler. + virtual function SaxErrorHandler getErrorHandler() + { + getErrorHandler = errorHandler; + } + + // Look up the value of a feature. + virtual function bit getFeature(string name) + { + // not implemented + getFeature = 0; + } + + // Look up the value of a property. + virtual function Object getProperty(string name) + { + // not implemented + getProperty = null; + } + + // Parse an XML document. + virtual task parse(SaxInputSource source) + { + XmlParseContext ctx = new; + XmlParser parser = new(this, ctx, source); + parser.parse(); + } + + // Allow an application to register a content event handler. + virtual task setContentHandler(SaxContentHandler handler) + { + assert(handler != null); + contentHandler = handler; + } + + // Allow an application to register a DTD event handler. + virtual task setDTDHandler(SaxDTDHandler handler) + { + assert(handler != null); + dtdHandler = handler; + } + + // Allow an application to register an entity resolver. + virtual task setEntityResolver(SaxEntityResolver resolver) + { + assert(resolver != null); + entityResolver = resolver; + } + + // Allow an application to register an error event handler. + virtual task setErrorHandler(SaxErrorHandler handler) + { + assert(handler != null); + errorHandler = handler; + } + + // Set the state of a feature. + virtual task setFeature(string name, bit value) + { + // not implemented + } + + // Set the value of a property. + virtual task setProperty(string name, Object value) + { + // not implemented + } +} + +//////////////////////////////////////////////////////////// +// XmlParseContext +//////////////////////////////////////////////////////////// + +// Context information shared by the entire document, +// including all external subsets. +local class XmlParseContext +{ + XmlDocTypeInfo docType; + XmlNameScope lastScope; + bit gotFatalError; + + task new() + { + docType = new; + lastScope = null; + gotFatalError = 0; + } +} + +//////////////////////////////////////////////////////////// +// XmlParser +//////////////////////////////////////////////////////////// + +enum XmlEntityAction = + XEA_Included, + XEA_Forbidden, + XEA_Notify, + XEA_Bypassed, + XEA_IncludedAsPE; + +// Parses a single source/subset of a document. +local class XmlParser +{ + local XmlReader reader; + local XmlParseContext ctx; + local ParseStream parseStream; + local XmlActiveLocator locator; + local string doubleQuote; + +//LOCAL +#if 0 + local integer nesting = 0; + #define ENTER(name) { \ + string indent; \ + indent = { nesting { " " } }; \ + reader.logIntf.printLogMsg(LS_DEBUG, \ + { indent, "ENTER: name" }); \ + ++nesting; } + #define EXIT(name) { \ + string indent; \ + --nesting; \ + indent = { nesting { " " } }; \ + reader.logIntf.printLogMsg(LS_DEBUG, \ + { indent, psprintf("EXIT: name (%b)", matched) }); } +#else + #define ENTER(name) + #define EXIT(name) +#endif +//END_LOCAL + + task new(XmlReader _reader, XmlParseContext _ctx, SaxInputSource _source); + task parse(); + + local function bit parseDocument(); + local function bit parseS(); + local function bit parseNameChar(); + local function bit parseName(var string name); + local function bit parseNmtoken(var string nmtoken); + local function bit parseEntityValue(var string value); + local function bit parseAttValue(var string value); + local function bit parseSystemLiteral(var string systemId); + local function bit parsePubidLiteral(var string publicId); + local function bit parsePubidChar(); + local function bit parseCharData(var string data); + local function bit parseComment(); + local function bit parsePI(); + local function bit parsePITarget(var string target); + local function bit parseCDSect(var string data); + local function bit parseCDStart(); + local function bit parseCData(var string data); + local function bit parseCDEnd(); + local function bit parseProlog(); + local function bit parseXMLDecl(); + local function bit parseVersionInfo(var string ver); + local function bit parseEq(); + local function bit parseVersionNum(var string ver); + local function bit parseMisc(); + local function bit parseDoctypedecl(); + local function bit parseDeclSep(); + local function bit parseMarkupdecl(); + local function bit parseExtSubset(); + local function bit parseExtSubsetDecl(); + local function bit parseSDDecl(var bit standalone); + local function bit parseYesNo(var bit yes); + local function bit parseElement(); + local function bit parseAttribute(XmlAttributes attrs, var XmlNameScope elemScope); + local function bit parseETag(var string prefix, var string localName); + local function bit parseContent(); + local function bit parseElementdecl(); + local function bit parseContentspec(); + local function bit parseChildren(); + local function bit parseCp(); + local function bit parseChoice(); + local function bit parseSeq(); + local function bit parseMixed(); + local function bit parseAttlistDecl(); + local function bit parseAttDef(); + local function bit parseAttType(); + local function bit parseStringType(var string type); + local function bit parseTokenizedType(var string type); + local function bit parseEnumeratedType(); + local function bit parseNotationType(); + local function bit parseEnumeration(); + local function bit parseDefaultDecl(); + local function bit parseConditionalSect(); + local function bit parseIgnoreSectContents(); + local function bit parseIgnore(); + local function bit parseCharRef(var string char); + local function bit parseEntityRef(var string name); + local function string expandEntityRef(string name); + local function bit parsePEReference(var string name); + local function string expandPEReference(string name); + local function bit parseEntityDecl(); + local function bit parseEntityDef(string name); + local function bit parsePEDef(string name); + local function bit parseExternalID(var string publicId, var string systemId); + local function bit parseNDataDecl(var string ndata); + local function bit parseTextDecl(); + local function bit parseExtParsedEnt(); + local function bit parseEncodingDecl(var string encName); + local function bit parseEncName(var string encName); + local function bit parseNotationDecl(); + local function bit parsePublicID(var string publicId); + local function bit parseNSAttName(var string name); + local function bit parseNCName(var string name); + local function bit parseNCNameChar(); + local function bit parseQName(var string prefix, var string localName); + local function bit parseEOF(); + local function bit parseLiteral(string s, bit required = 0); + local task warning(string msg); + local task nonfatalError(string msg); + local task fatalError(string msg); + local function bit require(bit matched, string prodName); +} + +task XmlParser::new(XmlReader _reader, XmlParseContext _ctx, SaxInputSource _source) +{ + reader = _reader; + ctx = _ctx; + + parseStream = new(_source.getStream()); + locator = new(parseStream); + locator.setPublicId(_source.getPublicId()); + locator.setSystemId(_source.getSystemId()); + + doubleQuote.bittostr(8'h22); +} + +task XmlParser::parse() +{ + bit matched; + + reader.contentHandler.setDocumentLocator(locator); + reader.contentHandler.startDocument(); + + matched = require(parseDocument(), "") && + require(parseEOF(), ""); + + if (matched) { + reader.contentHandler.endDocument(); + } +} + +function bit XmlParser::parseDocument() +{ + // [1] Document ::= Prolog Element Misc* + bit matched; + + ENTER(Document) + matched = parseProlog() && + require(parseElement(), ""); + if (matched) { + while (parseMisc()) {} + matched = !ctx.gotFatalError; + } + parseDocument = matched; + EXIT(Document) +} + +function bit XmlParser::parseS() +{ + // [3] S ::= (#x20 | #x9 | #xD | #xA)+ + bit matched = 0; + + ENTER(S) + while (1) { + integer ch; + + ch = parseStream.peek(); + if ((ch == 8'h09 || ch == 8'h0A || ch == 8'h0D || ch == 8'h20)) { + void = parseStream.skip(1); + matched = 1; + } else { + break; + } + } + parseS = matched; + EXIT(S) +} + +function bit XmlParser::parseNameChar() +{ + // [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender + bit matched; + integer ch; + + ch = parseStream.peek(); + matched = + (ch >= 8'h41 && ch <= 8'h5A) || // "A"-"Z" + (ch >= 8'h61 && ch <= 8'h7A) || // "a"-"z" + (ch >= 8'h30 && ch <= 8'h39) || // "0"-"9" + (ch == 8'h2E) || // "." + (ch == 8'h2D) || // "-" + (ch == 8'h5F) || // "_" + (ch == 8'h3A); // ":" + if (matched) { + void = parseStream.skip(1); + } + parseNameChar = matched; +} + +function bit XmlParser::parseName(var string name) +{ + // [5] Name ::= (Letter | '_' | ':') (NameChar)* + bit matched; + integer ch; + + ENTER(Name) + ch = parseStream.peek(); + matched = + (ch >= 8'h41 && ch <= 8'h5A) || // "A"-"Z" + (ch >= 8'h61 && ch <= 8'h7A) || // "a"-"z" + (ch == 8'h5F) || // "_" + (ch == 8'h3A); // ":" + if (matched) { + parseStream.beginCapture(); + void = parseStream.skip(1); + while (parseNameChar()) {} + name = parseStream.endCapture(matched); + } + parseName = matched; + EXIT(Name) +} + +function bit XmlParser::parseNmtoken(var string nmtoken) +{ + // [7] Nmtoken ::= (NameChar)+ + bit matched; + + ENTER(Nmtoken) + parseStream.beginCapture(); + matched = parseNameChar(); + if (matched) { + while (parseNameChar()) {} + } + nmtoken = parseStream.endCapture(matched); + parseNmtoken = matched; + EXIT(Nmtoken) +} + +function bit XmlParser::parseEntityValue(var string value) +{ + // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' | + // "'" ([^%&'] | PEReference | Reference)* "'" + // [67] Reference ::= EntityRef | CharRef + bit matched = 0; + string delim; + + ENTER(EntityValue) + if (parseLiteral(doubleQuote)) { + delim = doubleQuote; + matched = 1; + } + else if (parseLiteral("'")) { + delim = "'"; + matched = 1; + } + if (matched) { + integer delimCh; + + delimCh = delim.getc(0); + while (1) { + string term; + string name; + integer ch; + + matched = 0; + parseStream.beginCapture(); + while (1) { + ch = parseStream.peek(); + if (ch != -1 && ch != 8'h25 && ch != 8'h26 && ch != delimCh) { + void = parseStream.skip(1); + matched = 1; + } else { + break; + } + } + term = parseStream.endCapture(matched); + + if (!matched && parsePEReference(name)) { + term = expandPEReference(name); + matched = !ctx.gotFatalError; + } + else if (!matched && !ctx.gotFatalError && parseCharRef(term)) { + matched = 1; + } + else if (!matched && !ctx.gotFatalError && parseEntityRef(name)) { + term = { "&", name, ";" }; + matched = 1; + } + + if (matched) { + value = { value, term }; + } else { + break; + } + } + matched = !ctx.gotFatalError && parseLiteral(delim, 1); + } + parseEntityValue = matched; + EXIT(EntityValue) +} + +function bit XmlParser::parseAttValue(var string value) +{ + // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | + // "'" ([^<&'] | Reference)* "'" + // [67] Reference ::= EntityRef | CharRef + bit matched = 0; + string delim; + + ENTER(AttValue) + if (parseLiteral(doubleQuote)) { + delim = doubleQuote; + matched = 1; + } + else if (parseLiteral("'")) { + delim = "'"; + matched = 1; + } + if (matched) { + integer delimCh; + + delimCh = delim.getc(0); + while (1) { + string term; + string name; + integer ch; + + matched = 0; + parseStream.beginCapture(); + while (1) { + ch = parseStream.peek(); + if (ch != -1 && ch != 8'h3C && ch != 8'h26 && ch != delimCh) { + void = parseStream.skip(1); + matched = 1; + } else { + break; + } + } + term = parseStream.endCapture(matched); + + if (!matched && parseCharRef(term)) { + matched = 1; + } + else if (!matched && !ctx.gotFatalError && parseEntityRef(name)) { + XmlEntityInfo entity = ctx.docType.lookupGenEntity(name); + if (entity != null) { + if (!entity.isExternal()) { + term = entity.value; + matched = 1; + } else { + fatalError({ "Illegal reference to external entity ", name }); + } + } else { + nonfatalError({ "Reference to undefined entity ", name }); + term = ""; + matched = 1; + } + } + + if (matched) { + value = { value, term }; + } else { + break; + } + } + matched = !ctx.gotFatalError && parseLiteral(delim, 1); + } + parseAttValue = matched; + EXIT(AttValue) +} + +function bit XmlParser::parseSystemLiteral(var string systemId) +{ + // [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") + bit matched = 0; + string delim; + + ENTER(SystemLiteral) + if (parseLiteral(doubleQuote)) { + delim = doubleQuote; + matched = 1; + } + else if (parseLiteral("'")) { + delim = "'"; + matched = 1; + } + if (matched) { + integer delimCh; + + delimCh = delim.getc(0); + parseStream.beginCapture(); + while (1) { + integer ch = parseStream.peek(); + if (ch != -1 && ch != delimCh) { + void = parseStream.skip(1); + continue; + } + break; + } + systemId = parseStream.endCapture(); + matched = parseLiteral(delim, 1); + } + parseSystemLiteral = matched; + EXIT(SystemLiteral) +} + +function bit XmlParser::parsePubidLiteral(var string publicId) +{ + // [12] PubidLiteral ::= '"' PubidChar* '"' | + // "'" (PubidChar - "'")* "'" + bit matched = 0; + + ENTER(PubidLiteral) + if (parseLiteral(doubleQuote)) { + parseStream.beginCapture(); + while (parsePubidChar()) {} + publicId = parseStream.endCapture(); + matched = parseLiteral(doubleQuote, 1); + } + else if (parseLiteral("'")) { + parseStream.beginCapture(); + while (1) { + integer ch = parseStream.peek(); + if (ch == 8'h27 || !parsePubidChar()) break; + } + publicId = parseStream.endCapture(); + matched = parseLiteral("'", 1); + } + parsePubidLiteral = matched; + EXIT(PubidLiteral) +} + +function bit XmlParser::parsePubidChar() +{ + // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] + bit matched; + integer ch; + + ch = parseStream.peek(); + matched = + (ch == 8'h20) || + (ch == 8'h0D) || + (ch == 8'h0A) || + (ch >= 8'h61 && ch <= 8'h7A) || // "a"-"z" + (ch >= 8'h41 && ch <= 8'h5A) || // "A"-"Z" + (ch >= 8'h30 && ch <= 8'h39) || // "0"-"9" + (ch == 8'h2D) || // "-" + (ch == 8'h27) || // "'" + (ch == 8'h28) || // "(" + (ch == 8'h29) || // ")" + (ch == 8'h2B) || // "+" + (ch == 8'h2C) || // "," + (ch == 8'h2E) || // "." + (ch == 8'h2F) || // "/" + (ch == 8'h3A) || // ":" + (ch == 8'h3D) || // "=" + (ch == 8'h3F) || // "?" + (ch == 8'h3B) || // ";" + (ch == 8'h21) || // "!" + (ch == 8'h2A) || // "*" + (ch == 8'h23) || // "#" + (ch == 8'h40) || // "@" + (ch == 8'h24) || // "$" + (ch == 8'h5F) || // "_" + (ch == 8'h25); // "%" + if (matched) { + void = parseStream.skip(1); + } + parsePubidChar = matched; +} + +function bit XmlParser::parseCharData(var string data) +{ + // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) + bit matched = 1; + integer ch; + + ENTER(CharData) + parseStream.beginCapture(); + while (1) { + ch = parseStream.peek(); + if (ch == -1 || ch == 8'h3C || ch == 8'h26 || parseStream.lookahead("]]>")) { + break; + } + void = parseStream.skip(1); + } + data = parseStream.endCapture(matched); + parseCharData = matched; + EXIT(CharData) +} + +function bit XmlParser::parseComment() +{ + // [15] Comment ::= '' + bit matched; + + ENTER(Comment) + matched = parseLiteral(" + + + + + &example; + This sample shows a &tricky; method. + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/test2.xml b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/test2.xml new file mode 100644 index 0000000..b428f65 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/test2.xml @@ -0,0 +1,4 @@ + + + elem2 text + diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.mak b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.mak new file mode 100644 index 0000000..3050156 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.mak @@ -0,0 +1,2 @@ +LOAD_COMPS := xmlreader +RUNNABLE := 1 diff --git a/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.vr b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.vr new file mode 100644 index 0000000..c987fb1 --- /dev/null +++ b/java/juno-samples/xmlreader/src/xmlreader/xmlreadertest/xmlreadertest.vr @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +#include +#include "xmlreader.vrh" +#include "xmlinputsource.vrh" +#include "xincludefilter.vrh" +#include "property.vrh" + +class MyContentHandler +extends SaxContentHandler +{ + local LogInterface logIntf; + local SaxLocator locator; + + task new(LogInterface _logIntf) + { + logIntf = _logIntf; + } + + // Receive notification of character data. + virtual task characters(string chars) + { + dump(psprintf("characters: %s", chars)); + } + + // Receive notification of the end of a document. + virtual task endDocument() + { + dump("endDocument"); + } + + // Receive notification of the end of an element. + virtual task endElement(string namespaceURI, string localName, string qName) + { + dump(psprintf("endElement: namespaceURI=%s localName=%s qName=%s", + namespaceURI, localName, qName)); + } + + // End the scope of a prefix-URI mapping. + virtual task endPrefixMapping(string prefix) + { + dump(psprintf("endPrefixMapping: %s", prefix)); + } + + // Receive notification of ignorable whitespace in element content. + virtual task ignorableWhitespace(string chars) + { + dump(psprintf("ignorableWhitespace: %s", chars)); + } + + // Receive notification of a processing instruction. + virtual task processingInstruction(string target, string data) + { + dump(psprintf("processingInstruction: target=%s data=%s", target, data)); + } + + // Receive an object for locating the origin of SAX document events. + virtual task setDocumentLocator(SaxLocator _locator) + { + locator = _locator; + dump("setDocumentLocator"); + } + + // Receive notification of a skipped entity. + virtual task skippedEntity(string name) + { + dump(psprintf("skippedEntity: %s", name)); + } + + // Receive notification of the beginning of a document. + virtual task startDocument() + { + dump("startDocument"); + } + + // Receive notification of the beginning of an element. + virtual task startElement(string namespaceURI, string localName, string qName, SaxAttributes atts) + { + integer count, i; + + dump(psprintf("startElement: namespaceURI=%s localName=%s qName=%s", + namespaceURI, localName, qName)); + + count = atts.getLength(); + for (i = 0; i < count; ++i) { + dump(psprintf(" attribute[%0d]: namespaceURI=%s localName=%s qName=%s type=%s value=%s", + i, atts.getURI(i), atts.getLocalName(i), atts.getQName(i), atts.getType(i), atts.getValue(i))); + } + } + + // Begin the scope of a prefix-URI Namespace mapping. + virtual task startPrefixMapping(string prefix, string uri) + { + dump(psprintf("startPrefixMapping: prefix=%s uri=%s", prefix, uri)); + } + + local task dump(string msg) + { + string loc; + + if (locator != null) { + sprintf(loc, "line %0d, column %0d: ", + locator.getLineNumber(), locator.getColumnNumber()); + } + logIntf.printLogMsg(LS_DEBUG, { loc, msg }); + } +} + +program main +{ + LogInterface logIntf; + MyContentHandler handler; + string filename; + XmlInputSource source; + XmlReader reader; + XIncludeContentFilter xinclude; + + logIntf = new("xmlreadertest"); + logIntf.setMinSeverity(LS_DEBUG); + logIntf.setEchoSeverity(LS_DEBUG); + + handler = new(logIntf); + + filename = getPropStr("filename=", "src/xmlreader/xmlreadertest/test.xml"); + source = getXmlInputSource(filename); + + reader = new; +#ifndef NO_XINCLUDE + xinclude = new(reader, handler); + reader.setContentHandler(xinclude); +#else + reader.setContentHandler(handler); +#endif + reader.parse(source); +} + diff --git a/java/juno/build.xml b/java/juno/build.xml new file mode 100644 index 0000000..9a5a405 --- /dev/null +++ b/java/juno/build.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/juno/manifest.mf b/java/juno/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/juno/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/juno/src/com/newisys/juno/JunoPPHandler.java b/java/juno/src/com/newisys/juno/JunoPPHandler.java new file mode 100644 index 0000000..36fe37c --- /dev/null +++ b/java/juno/src/com/newisys/juno/JunoPPHandler.java @@ -0,0 +1,357 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.IOException; +import java.io.StringReader; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import com.newisys.langsource.SourceObject; +import com.newisys.langsource.vera.MacroDecl; +import com.newisys.parser.util.IncludeLocation; +import com.newisys.parser.util.Macro; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.util.PreprocessedToken; +import com.newisys.parser.util.Token; +import com.newisys.parser.vera.VeraParser; +import com.newisys.parser.vera.VeraParserBasePPHandler; +import com.newisys.parser.vera.VeraParserPPHandler; +import com.newisys.parser.vera.VeraParserReusableTokenManager; +import com.newisys.parser.vera.VeraParserTokenManager; +import com.newisys.parser.verapp.PathResolver; +import com.newisys.parser.verapp.VeraPPMacro; +import com.newisys.parser.verapp.VeraPPParser; +import com.newisys.schemabuilder.vera.VeraPreprocessorInfo; + +/** + * Juno translator parser handler for Vera preprocessor callbacks. + * Extends VeraParserPPHandler with translator-specific capabilities, like + * attempting to parse #define macros and resolving included header (.vrh) + * files to the source (.vr) file. + * + * @author Trevor Robinson + */ +public class JunoPPHandler + extends VeraParserPPHandler + implements VeraPreprocessorInfo +{ + private static final Logger logger = Logger + .getLogger("JunoPPHandler"); + + private final PathResolver importPathResolver; + private final Set headerSourceFiles = new HashSet(); + private boolean inHeaderSource; + private boolean inLocal; + private Map localDefines; + + public JunoPPHandler(VeraParserTokenManager tm) + { + super(tm); + importPathResolver = new PathResolver(); + } + + public void addImportPath(String path) + { + importPathResolver.addSearchPath(path); + } + + public Set getImportPaths() + { + return importPathResolver.getSearchPaths(); + } + + public boolean isFromHeader(SourceObject obj) + { + String filename = obj.getBeginFilename(); + if (headerSourceFiles.contains(filename)) return true; + + IncludeLocation loc = obj.getIncludeLocation(); + while (loc != null) + { + filename = loc.filename; + if (headerSourceFiles.contains(filename)) return true; + loc = loc.includedFrom; + } + + return false; + } + + public String getCompilationUnit(SourceObject obj) + { + String filename = obj.getBeginFilename(); + if (!isIncludedSource(filename)) return filename; + + IncludeLocation loc = obj.getIncludeLocation(); + while (loc != null) + { + filename = loc.filename; + if (!isIncludedSource(filename)) return filename; + loc = loc.includedFrom; + } + + return filename; + } + + private boolean isIncludedSource(String filename) + { + return filename.endsWith(".vr") + && !headerSourceFiles.contains(filename); + } + + public MacroDecl parseMacro(Macro macro) + { + MacroDecl expansionDecl = null; + String expansion = macro.expand(); + + VeraParserReusableTokenManager tm = new VeraParserReusableTokenManager(); + VeraParserBasePPHandler handler = new VeraParserBasePPHandler(tm, + getDefines()); + VeraPPParser macroPPParser = new VeraPPParser(new StringReader( + expansion), handler); + try + { + // preprocess the macro expansion into the token manager + macroPPParser.file(); + + // attempt to parse the preprocessed macro expansion + VeraParser macroParser = new VeraParser(tm); + expansionDecl = macroParser.macro_defn(); + } + catch (ParseException e) + { + // ignored; could be preprocessor encountering a Verilog-style + // reference to an undefined macro, or the parser not recognizing + // a supported macro form (statement, expression, range, type) + } + + return expansionDecl; + } + + @Override + public void addDefine(VeraPPMacro macro) + { + if (localDefines != null) + { + localDefines.put(macro.getName(), macro); + } + if (!inLocal) + { + super.addDefine(macro); + } + } + + @Override + public void removeDefine(String name) + { + if (localDefines != null) + { + localDefines.remove(name); + } + if (!inLocal) + { + super.removeDefine(name); + } + } + + @Override + public VeraPPMacro getDefine(String name) + { + if (localDefines != null) + { + return localDefines.get(name); + } + else + { + return super.getDefine(name); + } + } + + @Override + public void processComment(VeraPPParser parser, PreprocessedToken t) + { + boolean specialComment = false; + if (inHeaderSource) + { + if (t.image.startsWith("//LOCAL")) + { + logger.fine("//LOCAL" + getLocationMsg(parser, t)); + if (!inLocal) + { + inLocal = true; + markDefinesLocal = true; + if (localDefines == null) + { + localDefines = copyDefines(); + } + } + else + { + doWarning("Ignoring nested //LOCAL"); + } + specialComment = true; + } + else if (t.image.startsWith("//END_LOCAL")) + { + logger.fine("//END_LOCAL" + getLocationMsg(parser, t)); + if (inLocal) + { + inLocal = false; + markDefinesLocal = false; + } + else + { + doWarning("//END_LOCAL without //LOCAL"); + } + specialComment = true; + } + } + if (!specialComment) + { + super.processComment(parser, t); + } + } + + private static String getLocationMsg(VeraPPParser parser, Token t) + { + return " at " + parser.getFilename() + ", line " + t.beginLine; + } + + @Override + public void processInclude( + VeraPPParser parser, + String path, + boolean sysPath, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + if (!isSkipped()) + { + // remember whether we were in header source before this include + boolean wasInHeaderSource = inHeaderSource; + boolean wasMarkVerilogImport = markVerilogImport; + + boolean found = false; + String sourcePath = null; + boolean popLocalDefines = false; + search: try + { + String foundPath; + + // try to resolve using imported include + if (!sysPath) + { + foundPath = importPathResolver.resolve(path); + if (foundPath != null) + { + path = foundPath; + found = true; + markVerilogImport = true; + break search; + } + } + + // try to resolve path normally + foundPath = resolvePath(path, sysPath); + if (foundPath != null) + { + path = foundPath; + found = true; + markVerilogImport = false; + break search; + } + + // try to resolve user .vrh files using the source .vr file + if (!sysPath && path.endsWith(".vrh")) + { + // search for .vr file in user search paths + sourcePath = path.substring(0, path.length() - 1); + foundPath = userPathResolver.resolve(sourcePath); + if (foundPath != null) + { + path = foundPath; + found = true; + markVerilogImport = false; + + // do nothing if we have already included this file + if (headerSourceFiles.contains(path)) + { + logger.fine("Skipping included source path: " + + path); + return; + } + + // use .vr file as include file + logger.fine("Adding included source path: " + path); + headerSourceFiles.add(path); + inHeaderSource = true; + + // if including source for a header, and local defines + // are not already active, pop them on completion of + // this file + popLocalDefines = (localDefines == null); + } + } + } + catch (IOException e) + { + throw new ParseException("Error resolving include path: " + + e.getMessage()); + } + + if (!found) + { + System.err.println("Include file not found: " + path); + if (!sysPath) + { + System.err.println(" Searched imported include paths: " + + importPathResolver.getSearchPaths()); + System.err.println(" Searched user include paths: " + + userPathResolver.getSearchPaths()); + } + System.err.println(" Searched system include paths: " + + sysPathResolver.getSearchPaths()); + if (sourcePath != null) + { + System.err.println(" Searched user include paths " + + "for source file: " + sourcePath); + } + } + + doInclude(parser, path); + + // pop local defines if they were established for this file + if (popLocalDefines && localDefines != null) + { + localDefines = null; + if (inLocal) + { + doWarning("//LOCAL without //END_LOCAL"); + inLocal = false; + } + } + + // restore file flags + inHeaderSource = wasInHeaderSource; + markVerilogImport = wasMarkVerilogImport; + } + } +} diff --git a/java/juno/src/com/newisys/juno/JunoTranslator.java b/java/juno/src/com/newisys/juno/JunoTranslator.java new file mode 100644 index 0000000..c47790b --- /dev/null +++ b/java/juno/src/com/newisys/juno/JunoTranslator.java @@ -0,0 +1,682 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.*; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.newisys.dv.ifgen.schema.IfgenPackage; +import com.newisys.dv.ifgen.schema.IfgenSchema; +import com.newisys.dv.ifgen.schema.IfgenSchemaMember; +import com.newisys.dv.ifgen.schemaprinter.IfgenSchemaPrinter; +import com.newisys.juno.runtime.TestbenchFactory; +import com.newisys.langschema.java.JavaPackage; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.langschema.vera.VeraClass; +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraNameKind; +import com.newisys.langschema.vera.VeraProgram; +import com.newisys.langschema.vera.VeraSchema; +import com.newisys.parser.make.MakeParseException; +import com.newisys.parser.make.MakeVariable; +import com.newisys.parser.make.MakeVariableOrigin; +import com.newisys.parser.util.ParseException; +import com.newisys.schemaanalyzer.juno.VeraSchemaAnalyzer; +import com.newisys.schemabuilder.juno.DefaultFactoryCallBuilder; +import com.newisys.schemabuilder.juno.PackageNamer; +import com.newisys.schemabuilder.juno.JunoSchemaBuilder; +import com.newisys.schemaprinter.jove.JoveSchemaPrinter; +import com.newisys.schemaprinter.vera.VeraSchemaPrinter; +import com.newisys.util.cmdline.AbstractArg; +import com.newisys.util.cmdline.AbstractArgDef; +import com.newisys.util.cmdline.CmdLine; +import com.newisys.util.cmdline.CmdLineDef; +import com.newisys.util.cmdline.OptionArg; +import com.newisys.util.cmdline.OptionArgDef; +import com.newisys.util.cmdline.StringArg; +import com.newisys.util.cmdline.StringArgDef; +import com.newisys.util.cmdline.ValidationException; +import com.newisys.util.logging.IndentLogger; + +/** + * Main program for Juno. + * + * @author Trevor Robinson + */ +public class JunoTranslator +{ + private static class MyCmdLineDef + extends CmdLineDef + { + public final OptionArgDef helpOpt; + + public final OptionArgDef veraRootOpt; + public final StringArgDef veraRootArg; + + public final OptionArgDef veraCompOpt; + public final StringArgDef veraCompArg; + + public final OptionArgDef compVarOpt; + public final StringArgDef compVarNameArg; + public final StringArgDef compVarValueArg; + + public final OptionArgDef noDepsOpt; + + public final OptionArgDef veraFileOpt; + public final StringArgDef veraFileArg; + + public final OptionArgDef sysPathOpt; + public final StringArgDef sysPathArg; + + public final OptionArgDef veraSchemaDryRunOpt; + + public final OptionArgDef veraSchemaDumpOpt; + public final StringArgDef veraSchemaDumpArg; + + public final OptionArgDef veraSchemaLoadOpt; + public final StringArgDef veraSchemaLoadArg; + + public final OptionArgDef javaRootOpt; + public final StringArgDef javaRootArg; + + public final OptionArgDef javaPkgOpt; + public final StringArgDef javaPkgArg; + + public final OptionArgDef compClassMapOpt; + public final StringArgDef compClassMapArg; + + public final OptionArgDef debugOpt; + + public MyCmdLineDef() + { + super("juno"); + + helpOpt = new OptionArgDef("help", + "Display usage information and exit", 0, 1); + addArgDef(helpOpt); + + veraRootOpt = new OptionArgDef("veraroot", + "Root of Vera source tree", 0, 1); + veraRootArg = new StringArgDef("path"); + veraRootOpt.addArgDef(veraRootArg); + addArgDef(veraRootOpt); + + veraCompOpt = new OptionArgDef("veracomp", + "Vera component(s) to translate", 0, 1); + veraCompArg = new StringArgDef("name", null, 1, + AbstractArgDef.UNBOUNDED); + veraCompOpt.addArgDef(veraCompArg); + addArgDef(veraCompOpt); + + compVarOpt = new OptionArgDef("compvar", + "Define make variable for component makefiles", 0, + AbstractArgDef.UNBOUNDED); + compVarNameArg = new StringArgDef("name"); + compVarOpt.addArgDef(compVarNameArg); + compVarValueArg = new StringArgDef("value"); + compVarOpt.addArgDef(compVarValueArg); + addArgDef(compVarOpt); + + noDepsOpt = new OptionArgDef("nodeps", + "Do not translate prerequisite components", 0, 1); + addArgDef(noDepsOpt); + + veraFileOpt = new OptionArgDef("verafile", + "Vera file(s) to translate", 0, 1); + veraFileArg = new StringArgDef("file", null, 1, + AbstractArgDef.UNBOUNDED); + veraFileOpt.addArgDef(veraFileArg); + addArgDef(veraFileOpt); + + sysPathOpt = new OptionArgDef("syspath", "Add system include path"); + sysPathArg = new StringArgDef("path"); + sysPathOpt.addArgDef(sysPathArg); + addArgDef(sysPathOpt); + + veraSchemaDryRunOpt = new OptionArgDef("veraschemadryrun", + "Process all the Vera components without reading any files", 0, + 1); + addArgDef(veraSchemaDryRunOpt); + + veraSchemaDumpOpt = new OptionArgDef("veraschemadump", + "Dump the Vera schema to the given file", 0, 1); + veraSchemaDumpArg = new StringArgDef("path"); + veraSchemaDumpOpt.addArgDef(veraSchemaDumpArg); + addArgDef(veraSchemaDumpOpt); + + veraSchemaLoadOpt = new OptionArgDef("veraschemaload", + "Load the Vera schema from the given file", 0, 1); + veraSchemaLoadArg = new StringArgDef("path"); + veraSchemaLoadOpt.addArgDef(veraSchemaLoadArg); + addArgDef(veraSchemaLoadOpt); + + javaRootOpt = new OptionArgDef("javaroot", + "Root of Java source tree to generate", 1, 1); + javaRootArg = new StringArgDef("path"); + javaRootOpt.addArgDef(javaRootArg); + addArgDef(javaRootOpt); + + javaPkgOpt = new OptionArgDef("javapkg", + "Base package for Java classes", 0, 1); + javaPkgArg = new StringArgDef("pkg"); + javaPkgOpt.addArgDef(javaPkgArg); + addArgDef(javaPkgOpt); + + compClassMapOpt = new OptionArgDef("compclassmap", + "Generate mapping of Vera components to Java classes", 0, 1); + compClassMapArg = new StringArgDef("path"); + compClassMapOpt.addArgDef(compClassMapArg); + addArgDef(compClassMapOpt); + + debugOpt = new OptionArgDef("debug", "Output debug information", 0, + 1); + addArgDef(debugOpt); + } + } + + private static final MyCmdLineDef cmdLineDef = new MyCmdLineDef(); + + public static void main(String[] args) + { + try + { + CmdLine cmdLine = cmdLineDef.processCmdLine(args); + JunoTranslator v2j = new JunoTranslator(cmdLine); + v2j.run(); + + // exit with success + System.exit(0); + } + catch (ValidationException e) + { + System.err.println(e.getMessage()); + cmdLineDef.dumpUsage(System.err); + } + catch (Exception e) + { + e.printStackTrace(); + } + + // exit with error + System.exit(1); + } + + private final CmdLine cmdLine; + private final IndentLogger log; + + public JunoTranslator(CmdLine cmdLine) + { + this.cmdLine = cmdLine; + log = new IndentLogger(System.out); + } + + public void run() + throws ClassNotFoundException, IOException, MakeParseException, + InterruptedException, ParseException, ValidationException + { + final int SCHEMA_DUMP_VERSION = 1; + + final String veraRootPath; + final String veraSrcPath; + final VeraComponentMap compMap; + + // replace final modifier for veraSchema when the following javac + // bug is fixed (it is present as of 1.5.0_05) + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6328007 + VeraSchema veraSchema; + + final String loadPath = cmdLine.getOptionArgValue( + cmdLineDef.veraSchemaLoadOpt, cmdLineDef.veraSchemaLoadArg); + final String veraRootArg = cmdLine.getOptionArgValue( + cmdLineDef.veraRootOpt, cmdLineDef.veraRootArg); + if ((loadPath != null) == (veraRootArg != null)) + { + throw new ValidationException( + "Must specify -veraroot or -veraschemaload"); + } + + if (loadPath != null) + { + log.println("Loading Vera schema from " + loadPath); + FileInputStream fis = new FileInputStream(loadPath); + BufferedInputStream bis = new BufferedInputStream(fis); + ObjectInputStream ois = new ObjectInputStream(bis); + int version = ois.readInt(); + assert (version == SCHEMA_DUMP_VERSION); + veraRootPath = ois.readUTF(); + veraSrcPath = ois.readUTF(); + compMap = (VeraComponentMap) ois.readObject(); + veraSchema = (VeraSchema) ois.readObject(); + ois.close(); + log.println("Vera schema loaded"); + } + else + { + compMap = new VeraComponentMap(); + + // determine Vera tree root and src directories; + // if src directory does not exist in root, use root as src + final File veraRootFile = new File(veraRootArg).getCanonicalFile(); + veraRootPath = veraRootFile.getPath(); + File veraSrcFile = new File(veraRootFile, "src"); + if (veraSrcFile.isDirectory()) + { + veraSrcPath = veraSrcFile.getPath(); + } + else + { + veraSrcFile = veraRootFile; + veraSrcPath = veraRootPath; + } + + // build ordered list of components to process + final Set compList = new LinkedHashSet(); + final List veraCompOpts = cmdLine + .getArgsForDef(cmdLineDef.veraCompOpt); + if (veraCompOpts != null) + { + buildVeraComponentMap(compMap, veraRootFile, veraSrcFile); + buildCompList(compMap, veraCompOpts, compList); + } + final List veraFileOpts = cmdLine + .getArgsForDef(cmdLineDef.veraFileOpt); + if (veraFileOpts != null) + { + final VeraComponent comp = new VeraComponent("$default$", + veraSrcPath); + for (AbstractArg veraFileOpt : veraFileOpts) + { + final List veraFileArgs = ((OptionArg) veraFileOpt) + .getArgsForDef(cmdLineDef.veraFileArg); + for (StringArg veraFileArg : veraFileArgs) + { + final String argPath = veraFileArg.getValue(); + final File argFile = new File(argPath); + final File veraFile; + if (argFile.isAbsolute()) + veraFile = argFile; + else + veraFile = new File(veraSrcFile, argPath); + comp.addSourceFile(veraFile.getPath()); + } + } + compMap.addComponent(comp); + compList.add(comp); + } + if (compList.isEmpty()) + { + throw new ValidationException( + "No components specified; please specify -veracomp or -verafile"); + } + + // build Vera schema according to component list + final VeraFileProcessor fp = new VeraFileProcessor(); + final boolean veraSchemaDryRun = cmdLine + .getArgsForDef(cmdLineDef.veraSchemaDryRunOpt) != null; + buildVeraSchema(compList, fp, veraSchemaDryRun); + if (veraSchemaDryRun) return; + veraSchema = fp.getSchema(); + + final String dumpPath = cmdLine.getOptionArgValue( + cmdLineDef.veraSchemaDumpOpt, cmdLineDef.veraSchemaDumpArg); + if (dumpPath != null) + { + log.println("Dumping Vera schema to " + dumpPath); + File dumpFile = new File(dumpPath); + File dumpDir = dumpFile.getParentFile(); + if (dumpDir != null && !dumpDir.exists()) + { + log.println(" (Creating directory " + dumpDir.getPath() + + ")"); + dumpDir.mkdirs(); + } + FileOutputStream fos = new FileOutputStream(dumpFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + ObjectOutputStream oos = new ObjectOutputStream(bos); + oos.writeInt(SCHEMA_DUMP_VERSION); + oos.writeUTF(veraRootPath); + oos.writeUTF(veraSrcPath); + oos.writeObject(compMap); + oos.writeObject(veraSchema); + oos.close(); + log.println("Vera schema written"); + } + } + + if (false) + { + VeraSchemaPrinter vsp = new VeraSchemaPrinter(); + vsp.print(veraSchema, new OutputStreamWriter(System.out)); + } + + log.println("Performing global analysis of Vera schema"); + log.incIndent(); + VeraSchemaAnalyzer analyzer = new VeraSchemaAnalyzer(log); + analyzer.analyze(veraSchema); + log.decIndent(); + log.println("Global analysis complete"); + analyzer.dumpCounts(); + + JoveSchema javaSchema = new JoveSchema(); + IfgenSchema ifSchema = new IfgenSchema(); + PackageNamer packageNamer = new PackageNamer(veraSrcPath); + String javaPkgArg = cmdLine.getOptionArgValue(cmdLineDef.javaPkgOpt, + cmdLineDef.javaPkgArg); + if (javaPkgArg != null) + { + packageNamer.setBasePackage(javaPkgArg); + packageNamer.setExternalPackage(javaPkgArg + ".external"); + } + JunoSchemaBuilder jsb = new JunoSchemaBuilder(veraSchema, javaSchema, + ifSchema, analyzer, packageNamer, log); + JavaRawClass tbFactoryClass = (JavaRawClass) javaSchema + .getTypeForClass(TestbenchFactory.class.getName()); + DefaultFactoryCallBuilder tbFactoryBuilder = new DefaultFactoryCallBuilder( + javaSchema, jsb.getTypes(), jsb.getExprConv(), tbFactoryClass, null); + Iterator iter = compMap.getComponents().iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof VeraComponent) + { + VeraComponent comp = (VeraComponent) obj; + if (comp.isTestcaseTemplate()) + { + jsb.addFactory(comp.getAbstractTestbenchClass(), + tbFactoryBuilder); + } + } + } + jsb.build(); + + // write Java source + JoveSchemaPrinter printer = new JoveSchemaPrinter(); + JavaPackage basePkg = javaSchema.getPackage(packageNamer + .getBasePackage(), true); + String javaRootPath = cmdLine.getOptionArgValue(cmdLineDef.javaRootOpt, + cmdLineDef.javaRootArg); + File javaRoot = new File(javaRootPath); + printer.print(basePkg, javaRoot); + + // write Ifgen source + IfgenSchemaPrinter ifPrinter = new IfgenSchemaPrinter(); + printIfgenPackage(ifPrinter, null, ifSchema.getMembers(), javaRoot); + + // write component->class map + final String ccmPath = cmdLine.getOptionArgValue( + cmdLineDef.compClassMapOpt, cmdLineDef.compClassMapArg); + if (ccmPath != null) + { + writeComponentClassMap(ccmPath, veraSrcPath, compMap, veraSchema, + jsb); + } + } + + private void printIfgenPackage( + IfgenSchemaPrinter printer, + IfgenPackage pkg, + List< ? extends IfgenSchemaMember> members, + File srcRoot) + throws IOException + { + final List nonPackageMembers = new LinkedList(); + for (IfgenSchemaMember member : members) + { + if (member instanceof IfgenPackage) + { + IfgenPackage pkgMember = (IfgenPackage) member; + printIfgenPackage(printer, pkgMember, pkgMember.getMembers(), + srcRoot); + } + else + { + nonPackageMembers.add(member); + } + } + if (!nonPackageMembers.isEmpty()) + { + File ifPkgRoot = IfgenSchemaPrinter.getPackageRoot(pkg, srcRoot); + String pkgName = (pkg != null) ? pkg.getName().getIdentifier() + : "default"; + File file = new File(ifPkgRoot, pkgName + ".if"); + printer.printFile(nonPackageMembers, pkg, file); + } + } + + private void buildVeraComponentMap( + final VeraComponentMap cm, + final File veraRootFile, + final File veraSrcFile) + throws IOException, MakeParseException + { + final NewisysComponentMapBuilder cmb = new NewisysComponentMapBuilder( + cm, veraRootFile, veraSrcFile); + + // add user-defined make variables to component map builder + final List compVarOpts = cmdLine.getArgsForDef(cmdLineDef.compVarOpt); + if (compVarOpts != null) + { + Iterator compVarOptIter = compVarOpts.iterator(); + while (compVarOptIter.hasNext()) + { + OptionArg opt = (OptionArg) compVarOptIter.next(); + String name = opt.getArgValue(cmdLineDef.compVarNameArg); + String value = opt.getArgValue(cmdLineDef.compVarValueArg); + MakeVariable var = new MakeVariable(name, + MakeVariableOrigin.DEFAULT, false); + var.setValue(value); + cmb.addComponentVariable(var); + } + } + + // define all components + final List veraCompOpts = cmdLine.getArgsForDef(cmdLineDef.veraCompOpt); + if (veraCompOpts != null) + { + Iterator veraCompOptIter = veraCompOpts.iterator(); + while (veraCompOptIter.hasNext()) + { + OptionArg opt = (OptionArg) veraCompOptIter.next(); + List veraCompArgs = opt.getArgsForDef(cmdLineDef.veraCompArg); + Iterator veraCompArgIter = veraCompArgs.iterator(); + while (veraCompArgIter.hasNext()) + { + StringArg arg = (StringArg) veraCompArgIter.next(); + String compName = arg.getValue(); + cmb.addComponent(compName); + } + } + } + } + + private void buildVeraSchema( + final Set compSet, + final VeraFileProcessor fp, + final boolean dryRun) + throws IOException, InterruptedException, ParseException, + ValidationException + { + final VeraComponentProcessor cp = new VeraComponentProcessor(fp); + cp.setDryRun(dryRun); + + // build list of system paths from command line arguments + final List sysPathOpts = cmdLine.getArgsForDef(cmdLineDef.sysPathOpt); + if (sysPathOpts != null) + { + Iterator sysPathOptIter = sysPathOpts.iterator(); + while (sysPathOptIter.hasNext()) + { + OptionArg opt = (OptionArg) sysPathOptIter.next(); + String path = opt.getArgValue(cmdLineDef.sysPathArg); + cp.addSysPath(path); + } + } + + // process all components + Iterator compSetIter = compSet.iterator(); + while (compSetIter.hasNext()) + { + VeraComponent comp = (VeraComponent) compSetIter.next(); + cp.processVeraComponent(comp); + } + } + + private Set buildCompList( + final VeraComponentMap compMap, + final List veraCompOpts, + final Set compList) + { + log.println("Building ordered component list:"); + boolean deps = cmdLine.getArgsForDef(cmdLineDef.noDepsOpt) == null; + Iterator veraCompOptIter = veraCompOpts.iterator(); + while (veraCompOptIter.hasNext()) + { + OptionArg opt = (OptionArg) veraCompOptIter.next(); + List veraCompArgs = opt.getArgsForDef(cmdLineDef.veraCompArg); + Iterator veraCompArgIter = veraCompArgs.iterator(); + while (veraCompArgIter.hasNext()) + { + StringArg arg = (StringArg) veraCompArgIter.next(); + String compName = arg.getValue(); + VeraAbsComponent comp = compMap.getComponent(compName); + + if (deps) + { + Set depComps = comp.getFullDependencies(); + Iterator depIter = depComps.iterator(); + while (depIter.hasNext()) + { + VeraAbsComponent depComp = (VeraAbsComponent) depIter + .next(); + addComponent(depComp, compList); + } + } + + addComponent(comp, compList); + } + } + return compList; + } + + private void addComponent( + VeraAbsComponent depComp, + Set compSet) + { + if (depComp instanceof VeraComponent) + { + if (compSet.add(depComp)) + { + log.println(" " + depComp.getName()); + } + } + } + + private void writeComponentClassMap( + String outputPath, + String veraSrcPath, + VeraComponentMap compMap, + VeraSchema veraSchema, + JunoSchemaBuilder javaSchemaBuilder) + throws FileNotFoundException + { + log.println("Writing component->class mapping: " + outputPath); + final PrintWriter out = new PrintWriter( + new FileOutputStream(outputPath)); + + final Iterator schemaMemberIter = veraSchema.getMembers().iterator(); + while (schemaMemberIter.hasNext()) + { + Object schemaMember = schemaMemberIter.next(); + if (schemaMember instanceof VeraCompilationUnit) + { + final VeraCompilationUnit compUnit = (VeraCompilationUnit) schemaMember; + + // determine name of containing component + final String srcPath = compUnit.getSourcePath(); + // out.println("# file: " + srcPath); + if (srcPath.startsWith(veraSrcPath)) + { + final String relPath = srcPath.substring(veraSrcPath + .length() + 1); + int lastSepPos = relPath.lastIndexOf(File.separatorChar); + if (lastSepPos < 0) + { + lastSepPos = relPath.lastIndexOf('/'); + } + final String compName = relPath.substring(0, lastSepPos); + + VeraAbsComponent absComp = compMap.getComponent(compName); + if (absComp instanceof VeraComponent) + { + // out.println("# comp: " + compName); + VeraComponent comp = (VeraComponent) absComp; + + // look up translated testbench class, if present + String tbClass = comp.getTestbenchClass(); + if (tbClass != null) + { + Iterator tbClassIter = compUnit.lookupObjects( + tbClass, VeraNameKind.TYPE); + if (tbClassIter.hasNext()) + { + VeraClass veraTBClass = (VeraClass) tbClassIter + .next(); + JavaRawClass javaTBClass = (JavaRawClass) javaSchemaBuilder + .getTranslatedObject(veraTBClass); + out.println(compName + " := " + + javaTBClass.getName()); + } + } + + // look for programs in compilation unit + // (ignore non-source files) + else if (comp.getSourceFiles().contains(srcPath)) + { + final Iterator cuMemberIter = compUnit.getMembers() + .iterator(); + while (cuMemberIter.hasNext()) + { + Object cuMember = cuMemberIter.next(); + if (cuMember instanceof VeraProgram) + { + VeraProgram veraProgram = (VeraProgram) cuMember; + JavaRawClass javaProgramClass = (JavaRawClass) javaSchemaBuilder + .getTranslatedObject(veraProgram); + out.println(compName + " := " + + javaProgramClass.getName()); + } + } + } + else + { + // out.println("# not a source file"); + } + } + } + // out.println(); + } + } + + out.close(); + } +} diff --git a/java/juno/src/com/newisys/juno/NewisysComponentMapBuilder.java b/java/juno/src/com/newisys/juno/NewisysComponentMapBuilder.java new file mode 100644 index 0000000..975316b --- /dev/null +++ b/java/juno/src/com/newisys/juno/NewisysComponentMapBuilder.java @@ -0,0 +1,330 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.parser.make.MakeDatabase; +import com.newisys.parser.make.MakeFileInfo; +import com.newisys.parser.make.MakeParseException; +import com.newisys.parser.make.MakeParser; +import com.newisys.parser.make.MakeStaticRule; +import com.newisys.parser.make.MakeVariable; +import com.newisys.parser.make.MakeVariableOrigin; + +/** + * Populates the given Vera component map with definitions of the given + * components based on makefiles in the given Vera source tree. The makefiles + * and components are expected to follow the conventions of the Newisys Vera + * Make System; they are not arbitrary makefiles. Briefly, the expectations + * are: + *

    • + * $VERA_ROOT/makefile contains make rules describing component dependencies. + * For example, if component foo depends on component bar, then this makefile + * should include the rule "foo: bar". + *
    • + * For each component, $VERA_ROOT/src/$COMP_NAME/$COMP_ROOT.mak should exist. + * Here, COMP_NAME is the full name of the component, which may contain slashes + * to indicate subcomponents, and COMP_ROOT is the last segment of the name. + * For example, if COMP_NAME is tests/test1, then COMP_ROOT is test1. + *
    • + * If $COMP_ROOT.mak exists, it may contain the following variable assignments: + * + * + * + * + * + * + * + * + * + *
      SRC_FILESlist of .vr source files
      IMPORT_HDR_FILESexternal header files to import (relative to VERA_ROOT)
      TESTBENCH_CLASSname of the abstract testbench implementation class
      VSHELL_SRC_FILEsource file that generates Verilog shell
      TESTCASE_TEMPLATE_FILEtestcase template file, for multi-testbench testcases
      ABSTRACT_TESTBENCH_HEADERabstract testbench header file for testcase template
      ABSTRACT_TESTBENCH_CLASSabstract testbench class name for testcase template
      DEFAULT_TESTBENCHdefault testbench component for testcase template
      + *
    • + * If $COMP_ROOT.mak does not exist, the component is treated as if it existed + * and contained "SRC_FILES = $COMP_ROOT.vr". + *
    • + * + * @author Trevor Robinson + */ +public final class NewisysComponentMapBuilder +{ + private final VeraComponentMap compMap; + private final File veraRoot; + private final File veraSrcRoot; + private final MakeDatabase makeDatabase; + private final List compVars = new LinkedList(); + + public NewisysComponentMapBuilder( + VeraComponentMap compMap, + File veraRoot, + File veraSrcRoot) throws IOException, MakeParseException + { + this.compMap = compMap; + + this.veraRoot = veraRoot; + this.veraSrcRoot = veraSrcRoot; + + makeDatabase = new MakeDatabase(); + File makeFile = new File(veraRoot, "makefile"); + MakeParser makeParser = new MakeParser(makeDatabase, makeFile.getPath()); + makeParser.parse(); + makeDatabase.applySpecialTargets(); + } + + public VeraComponentMap getComponentMap() + { + return compMap; + } + + public void addComponentVariable(MakeVariable var) + { + compVars.add(var); + } + + public VeraAbsComponent addComponent(String target) + throws IOException, MakeParseException + { + MakeFileInfo targetFileInfo = makeDatabase.getOrCreateFile(target); + return processComponentRule(targetFileInfo); + } + + private VeraAbsComponent processComponentRule(MakeFileInfo targetFileInfo) + throws IOException, MakeParseException + { + String targetName = targetFileInfo.getPath(); + + // check whether component has already been processed + VeraAbsComponent resultComp = compMap.getComponent(targetName); + if (resultComp != null) + { + return resultComp; + } + + System.out.println("Defining component: " + targetName); + + // look up rule for component target + MakeStaticRule targetRule = makeDatabase.getRuleForFile(targetFileInfo); + if (targetRule == null) + { + throw new RuntimeException("No rule to build component target: " + + targetName); + } + + // define new component object, possibly from component makefile + resultComp = defineComponent(targetName, targetFileInfo.isPhony()); + + // process dependency components + Iterator iter = targetRule.getDependencies().iterator(); + while (iter.hasNext()) + { + MakeFileInfo depFileInfo = (MakeFileInfo) iter.next(); + VeraAbsComponent depComp = processComponentRule(depFileInfo); + resultComp.addDependency(depComp); + } + + return resultComp; + } + + private VeraAbsComponent defineComponent(String targetName, boolean isPhony) + throws IOException, MakeParseException + { + // check whether component has already been processed + VeraAbsComponent resultComp = compMap.getComponent(targetName); + if (resultComp != null) + { + return resultComp; + } + + // groups are represented by phony targets + // (also treat generated testcases as groups) + if (isPhony || targetName.startsWith("gen/testcases/")) + { + VeraComponentGroup group = new VeraComponentGroup(targetName); + resultComp = group; + } + else + { + File compRoot = new File(veraSrcRoot, targetName); + + VeraComponent comp = new VeraComponent(targetName, compRoot + .getPath()); + resultComp = comp; + + // process the component makefile, if present + boolean gotSrcFiles = false; + File compMakeFile = new File(compRoot, compRoot.getName() + ".mak"); + if (compMakeFile.exists()) + { + MakeDatabase compMakeDatabase = new MakeDatabase(); + + // define VERA_SRC_DIR (normally provided by top-level makefile) + MakeVariable veraSrc = new MakeVariable("VERA_SRC_DIR", + MakeVariableOrigin.DEFAULT, false); + veraSrc.setValue(veraSrcRoot.getCanonicalPath() + "/"); + compMakeDatabase.addVariable(veraSrc); + + // add user-defined variables to component makefile database + Iterator iter = compVars.iterator(); + while (iter.hasNext()) + { + MakeVariable var = (MakeVariable) iter.next(); + compMakeDatabase.addVariable(var); + } + + // parse the component makefile + MakeParser compMakeParser = new MakeParser(compMakeDatabase, + compMakeFile.getPath()); + compMakeParser.parse(); + + String srcFiles = getVar(compMakeDatabase, "SRC_FILES"); + if (srcFiles != null) + { + addFilesToList(srcFiles, comp.getSourceFiles(), compRoot, + compMakeDatabase); + gotSrcFiles = true; + } + + String testcaseTemplate = getVar(compMakeDatabase, + "TESTCASE_TEMPLATE_FILE"); + templateLabel: if (testcaseTemplate != null) + { + final String absTBHeaderVarName = "ABSTRACT_TESTBENCH_HEADER"; + String absTBHeader = getVar(compMakeDatabase, + absTBHeaderVarName); + if (absTBHeader == null) + { + System.err.println("Warning: " + absTBHeaderVarName + + " not specified for testcase template component"); + break templateLabel; + } + + final String absTBClassVarName = "ABSTRACT_TESTBENCH_CLASS"; + String absTBClass = getVar(compMakeDatabase, + absTBClassVarName); + if (absTBClass == null) + { + System.err.println("Warning: " + absTBClassVarName + + " not specified for testcase template component"); + break templateLabel; + } + + addFilesToList(testcaseTemplate, comp.getSourceFiles(), + compRoot, compMakeDatabase); + comp.setTestcaseTemplate(true); + comp.setAbstractTestbenchHeader(absTBHeader); + comp.setAbstractTestbenchClass(absTBClass); + + final String defTBVarName = "DEFAULT_TESTBENCH"; + String defTB = getVar(compMakeDatabase, defTBVarName); + if (defTB != null) + { + comp.setDefaultTestbenchComponent(defTB); + } + else + { + System.err.println("Warning: " + defTBVarName + + " not specified for testcase template component"); + } + } + + String tbClass = getVar(compMakeDatabase, "TESTBENCH_CLASS"); + if (tbClass != null) + { + comp.setTestbenchClass(tbClass); + } + + String vshellSrcFile = getVar(compMakeDatabase, + "VSHELL_SRC_FILE"); + if (vshellSrcFile != null) + { + addFilesToList(vshellSrcFile, comp.getVshellSourceFiles(), + compRoot, compMakeDatabase); + } + + String importHdrFiles = getVar(compMakeDatabase, + "IMPORT_HDR_FILES"); + if (importHdrFiles != null) + { + addFilesToList(importHdrFiles, comp.getImportedIncludes(), + veraRoot, compMakeDatabase); + } + } + + // if there is no component makefile, or SRC_FILES is undefined, + // add the default source file: .vr + if (!gotSrcFiles) + { + File srcFile = new File(compRoot, compRoot.getName() + ".vr"); + comp.addSourceFile(srcFile.getCanonicalPath()); + } + } + compMap.addComponent(resultComp); + + return resultComp; + } + + private static String getVar(MakeDatabase db, String name) + { + MakeVariable var = db.getVariable(name); + if (var != null) + { + return var.getValue().trim(); + } + return null; + } + + private void addFilesToList( + String str, + Collection list, + File root, + MakeDatabase mdb) + throws IOException + { + String[] names = str.split("\\s+"); + for (int i = 0; i < names.length; ++i) + { + String name = names[i]; + if (name.length() > 0) + { + File f = new File(root, name); + vpathSearch: if (!f.exists()) + { + final List searchedPaths = new LinkedList(); + searchedPaths.add(root.getPath()); + final Iterator iter = mdb.searchVPaths(name); + while (iter.hasNext()) + { + String path = (String) iter.next(); + f = new File(path, name); + if (f.exists()) break vpathSearch; + searchedPaths.add(path); + } + throw new FileNotFoundException(name + " not found in " + + searchedPaths); + } + list.add(f.getCanonicalPath()); + } + } + } +} diff --git a/java/juno/src/com/newisys/juno/VeraAbsComponent.java b/java/juno/src/com/newisys/juno/VeraAbsComponent.java new file mode 100644 index 0000000..9f66009 --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraAbsComponent.java @@ -0,0 +1,187 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Represents an abstract Vera component, which may be an actual component or a + * grouping component. + * + * @author Trevor Robinson + */ +public abstract class VeraAbsComponent + implements Serializable +{ + private final String name; + private final Set dependencies = new LinkedHashSet(); + + /** + * Constructs a new abstract component. + * + * @param name the name of this component + */ + public VeraAbsComponent(String name) + { + this.name = name; + } + + /** + * Returns the name of this component. + * + * @return String + */ + public String getName() + { + return name; + } + + /** + * Returns the set of components that this component is dependent upon. + * + * @return Set of VeraAbsComponent + */ + public Set getDependencies() + { + return dependencies; + } + + /** + * Adds the given component to this list of components that this component + * depends upon. + * + * @param target VeraAbsComponent + */ + public void addDependency(VeraAbsComponent target) + { + dependencies.add(target); + } + + /** + * Returns all the dependencies for the this component, including transitive + * dependencies. The returned components are unique and in the order of a + * pre-order traversal of the dependency graph. Circular dependencies are + * ignored. + * + * @return Set of VeraAbsComponent + */ + public Set getFullDependencies() + { + Set fullDeps = new LinkedHashSet(); + Set activeDeps = new HashSet(); + addDependencies(fullDeps, activeDeps); + return fullDeps; + } + + /** + * Recursive helper function for getFullDependencies(). + * + * @param fullDeps the full dependency set being built + * @param activeDeps the dependencies currently recursed into + */ + private void addDependencies( + Set fullDeps, + Set activeDeps) + { + Set targetDeps = getDependencies(); + for (VeraAbsComponent dep : targetDeps) + { + if (!activeDeps.contains(dep)) + { + activeDeps.add(dep); + dep.addDependencies(fullDeps, activeDeps); + activeDeps.remove(dep); + } + fullDeps.add(dep); + } + } + + /** + * Returns the set of include paths for the this component. + * + * @return Set of String + */ + public Set getIncludePaths() + { + Set pathList = new LinkedHashSet(); + addIncludePaths(pathList); + + Set fullDeps = getFullDependencies(); + for (VeraAbsComponent dep : fullDeps) + { + dep.addIncludePaths(pathList); + } + + return pathList; + } + + /** + * Helper function for getIncludePaths(). Adds the include paths for this + * component to the given set. + * + * @param paths the set of paths to add to + */ + protected void addIncludePaths(Set paths) + { + // do nothing by default + } + + /** + * Returns the set of include paths for the this component. + * + * @return Set of String + */ + public Set getAllImportedIncludes() + { + Set pathList = new LinkedHashSet(); + addImportPaths(pathList); + + Set fullDeps = getFullDependencies(); + for (VeraAbsComponent dep : fullDeps) + { + dep.addImportPaths(pathList); + } + + return pathList; + } + + /** + * Helper function for getAllImportedIncludes(). Adds the include paths for + * this component to the given set. + * + * @param paths the set of paths to add to + */ + protected void addImportPaths(Set paths) + { + // do nothing by default + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() + { + return name; + } +} diff --git a/java/juno/src/com/newisys/juno/VeraComponent.java b/java/juno/src/com/newisys/juno/VeraComponent.java new file mode 100644 index 0000000..fb99b98 --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraComponent.java @@ -0,0 +1,253 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Represents an actual Vera component (not a grouping component). + * + * @author Trevor Robinson + */ +public final class VeraComponent + extends VeraAbsComponent +{ + private static final long serialVersionUID = 3546080276355627058L; + + private final String sourcePath; + private final Set sourceFiles = new LinkedHashSet(); + private final Set vshellSourceFiles = new LinkedHashSet(); + private final Set importedIncludes = new LinkedHashSet(); + + private String testbenchClass; + + private boolean testcaseTemplate; + private String abstractTestbenchHeader; + private String abstractTestbenchClass; + private String defaultTestbenchComponent; + + /** + * Constructs a new Vera component. + * + * @param name the name of this component + * @param sourcePath the source path for this component + */ + public VeraComponent(String name, String sourcePath) + { + super(name); + this.sourcePath = sourcePath; + } + + /** + * Returns the source path for this component. + * + * @return String + */ + public String getSourcePath() + { + return sourcePath; + } + + /** + * Returns the list of source files for this component. + * + * @return Set of String + */ + public Set getSourceFiles() + { + return sourceFiles; + } + + /** + * Adds the given filename to the list of source files. + * + * @param name the filename of the source file + */ + public void addSourceFile(String name) + { + sourceFiles.add(name); + } + + /** + * Returns the list of Verilog shell source files for this component. + * + * @return Set of String + */ + public Set getVshellSourceFiles() + { + return vshellSourceFiles; + } + + /** + * Adds the given filename to the list of Verilog shell source files. + * + * @param name the filename of the source file + */ + public void addVshellSourceFile(String name) + { + vshellSourceFiles.add(name); + } + + /** + * Returns the list of include files imported by this component. + * + * @return Set of String + */ + public Set getImportedIncludes() + { + return importedIncludes; + } + + /** + * Adds the given path to the list of imported include files. + * + * @param path the path to the include file to import + */ + public void addImportedInclude(String path) + { + importedIncludes.add(path); + } + + /** + * Returns the name of the abstract testbench implementation class in this + * component, or null if this component does not contain an abstract + * testbench implementation. + * + * @return the name of the testbench class + */ + public String getTestbenchClass() + { + return testbenchClass; + } + + /** + * Sets the name of the abstract testbench implementation class in this + * component. + * + * @param cls the name of the testbench class + */ + public void setTestbenchClass(String cls) + { + this.testbenchClass = cls; + } + + /** + * Returns whether this component represents a testcase template (i.e. has + * TESTCASE_TEMPLATE_FILE defined in its makefile). + * + * @return true iff this component is a testcase template + */ + public boolean isTestcaseTemplate() + { + return testcaseTemplate; + } + + /** + * Sets whether this component represents a testcase template. + * + * @param testcaseTemplate true iff this component is a testcase template + */ + public void setTestcaseTemplate(boolean testcaseTemplate) + { + this.testcaseTemplate = testcaseTemplate; + } + + /** + * Returns the header file containing the abstract testbench class for this + * testcase template. + * + * @return the abstract testbench header file + */ + public String getAbstractTestbenchHeader() + { + return abstractTestbenchHeader; + } + + /** + * Sets the header file containing the abstract testbench class for this + * testcase template. + * + * @param hdr the abstract testbench header file + */ + public void setAbstractTestbenchHeader(String hdr) + { + this.abstractTestbenchHeader = hdr; + } + + /** + * Returns the name of the abstract testbench class for this testcase + * template. + * + * @return the name of the abstract testbench class + */ + public String getAbstractTestbenchClass() + { + return abstractTestbenchClass; + } + + /** + * Sets the name of the abstract testbench class for this testcase template. + * + * @param cls the name of the abstract testbench class + */ + public void setAbstractTestbenchClass(String cls) + { + this.abstractTestbenchClass = cls; + } + + /** + * Returns the name of the default testbench component. + * + * @return the name of the default testbench component + */ + public String getDefaultTestbenchComponent() + { + return defaultTestbenchComponent; + } + + /** + * Sets the name of the default testbench component. + * + * @param comp the name of the default testbench component + */ + public void setDefaultTestbenchComponent(String comp) + { + this.defaultTestbenchComponent = comp; + } + + /* + * (non-Javadoc) + * @see com.newisys.juno.VeraAbsComponent#addIncludePaths(java.util.Set) + */ + @Override + protected void addIncludePaths(Set paths) + { + paths.add(sourcePath); + } + + /* + * (non-Javadoc) + * @see com.newisys.juno.VeraAbsComponent#addImportPaths(java.util.Set) + */ + @Override + protected void addImportPaths(Set paths) + { + paths.addAll(importedIncludes); + } +} diff --git a/java/juno/src/com/newisys/juno/VeraComponentGroup.java b/java/juno/src/com/newisys/juno/VeraComponentGroup.java new file mode 100644 index 0000000..33fe121 --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraComponentGroup.java @@ -0,0 +1,34 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +/** + * Represents a grouping component. + * + * @author Trevor Robinson + */ +public final class VeraComponentGroup + extends VeraAbsComponent +{ + private static final long serialVersionUID = 3258411746384294706L; + + public VeraComponentGroup(String name) + { + super(name); + } +} diff --git a/java/juno/src/com/newisys/juno/VeraComponentMap.java b/java/juno/src/com/newisys/juno/VeraComponentMap.java new file mode 100644 index 0000000..979d71f --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraComponentMap.java @@ -0,0 +1,77 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.Serializable; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Provides a name-indexed map of all the components in a Vera source tree. + * + * @author Trevor Robinson + */ +public class VeraComponentMap + implements Serializable +{ + private static final long serialVersionUID = 3690193248312440368L; + + private final Map components = new LinkedHashMap(); + + /** + * Constructs a new component map. + */ + public VeraComponentMap() + { + // do nothing + } + + /** + * Returns the component with the given name, or null if no such component + * exists. + * + * @param name the name of the component + * @return VeraAbsComponent + */ + public VeraAbsComponent getComponent(String name) + { + return components.get(name); + } + + /** + * Returns a collection of all components in this map. + * + * @return Collection of VeraAbsComponent + */ + public Collection getComponents() + { + return components.values(); + } + + /** + * Adds the given component to this component manager. If a component with + * the same name already exists, it will be replaced. + * + * @param component a component + */ + public void addComponent(VeraAbsComponent component) + { + components.put(component.getName(), component); + } +} diff --git a/java/juno/src/com/newisys/juno/VeraComponentProcessor.java b/java/juno/src/com/newisys/juno/VeraComponentProcessor.java new file mode 100644 index 0000000..1efbd02 --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraComponentProcessor.java @@ -0,0 +1,133 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.newisys.parser.util.ParseException; + +/** + * Processes the Vera files in the given Vera components using the given file + * processor. + * + * @author Trevor Robinson + */ +public final class VeraComponentProcessor +{ + private final VeraFileProcessor fp; + private boolean dryRun = false; + private final Set sysPaths = new LinkedHashSet(); + + public VeraComponentProcessor(VeraFileProcessor fp) + { + this.fp = fp; + } + + public boolean isDryRun() + { + return dryRun; + } + + public void setDryRun(boolean dryRun) + { + this.dryRun = dryRun; + } + + public void addSysPath(String path) + { + sysPaths.add(path); + } + + public void processVeraComponent(VeraComponent component) + throws IOException, InterruptedException, ParseException, + ParseException + { + showSystemState(); + System.out.println("Analyzing component: " + component.getName()); + + Set includePaths = component.getIncludePaths(); + Set importPaths = component.getAllImportedIncludes(); + + Set sourceFiles = component.getSourceFiles(); + for (String filename : sourceFiles) + { + System.out.println(" Analyzing file: " + filename); + if (!dryRun) + { + fp.processVeraFile(filename, component, sysPaths, includePaths, + importPaths, false); + } + } + + Set vshellSourceFiles = component.getVshellSourceFiles(); + for (String filename : vshellSourceFiles) + { + if (sourceFiles.contains(filename)) continue; + System.out.println(" Analyzing file: " + filename); + if (!dryRun) + { + fp.processVeraFile(filename, component, sysPaths, includePaths, + importPaths, true); + } + } + } + + private static DateFormat timeFormat = DateFormat.getTimeInstance(); + + private void showSystemState() + { + System.out.print("Time: " + timeFormat.format(new Date()) + ", "); + + System.gc(); + Runtime runtime = Runtime.getRuntime(); + long memTotal = runtime.totalMemory(); + long memUsed = memTotal - runtime.freeMemory(); + System.out.println("Memory: " + formatSize(memUsed) + " used / " + + formatSize(memTotal) + " heap / " + + formatSize(runtime.maxMemory()) + " max"); + } + + private String formatSize(long size) + { + int shifts = 0; + while (size > 10240) + { + size >>>= 10; + ++shifts; + } + double scaledSize; + if (size >= 1000) + { + scaledSize = (double) size / 1024; + ++shifts; + } + else + { + scaledSize = size; + } + String[] units = { "B", "KB", "MB", "GB", "TB", "PB", "XB" }; + NumberFormat format = NumberFormat.getNumberInstance(); + format.setMaximumFractionDigits(1); + return format.format(scaledSize) + units[shifts]; + } +} diff --git a/java/juno/src/com/newisys/juno/VeraFileProcessor.java b/java/juno/src/com/newisys/juno/VeraFileProcessor.java new file mode 100644 index 0000000..aeb05e3 --- /dev/null +++ b/java/juno/src/com/newisys/juno/VeraFileProcessor.java @@ -0,0 +1,294 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.juno; + +import java.io.File; +import java.io.IOException; +import java.util.Set; + +import com.newisys.langschema.vera.VeraSchema; +import com.newisys.langsource.vera.CompilationUnitDecl; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.vera.VeraParser; +import com.newisys.parser.vera.VeraParserBoundedTokenManager; +import com.newisys.parser.vera.VeraParserTokenManager; +import com.newisys.parser.verapp.VeraPPParser; +import com.newisys.parser.verapp.VeraPPStaticMacro; +import com.newisys.schemabuilder.vera.VeraSchemaBuilder; + +/** + * Processes the given Vera files into a schema. + * + * @author Trevor Robinson + */ +public final class VeraFileProcessor +{ + private final VeraSchemaBuilder veraSchemaBuilder = new VeraSchemaBuilder(); + + public VeraSchema getSchema() + { + return veraSchemaBuilder.getSchema(); + } + + public void processVeraFile( + String filename, + VeraComponent component, + Set sysPaths, + Set userPaths, + Set importPaths, + boolean wantShell) + throws IOException, InterruptedException, ParseException, + ParseException + { + final VeraParserTokenManager veraTokenMgr = new VeraParserBoundedTokenManager(); + + final JunoPPHandler ppCallbacks = new JunoPPHandler( + veraTokenMgr); + ppCallbacks.addDefine(new VeraPPStaticMacro("__JUNO__", "1")); + + // support for Newisys multi-testbench testcase templates + if (component.isTestcaseTemplate()) + { + String tbHeader = VeraPPParser.toStringLiteral(component + .getAbstractTestbenchHeader()); + ppCallbacks.addDefine(new VeraPPStaticMacro( + "ABSTRACT_TESTBENCH_HEADER", tbHeader)); + ppCallbacks.addDefine(new VeraPPStaticMacro("TESTBENCH_HEADER", + tbHeader)); + + String tbClass = component.getAbstractTestbenchClass(); + ppCallbacks.addDefine(new VeraPPStaticMacro( + "ABSTRACT_TESTBENCH_CLASS", tbClass)); + ppCallbacks.addDefine(new VeraPPStaticMacro("TESTBENCH_CLASS", + tbClass)); + } + + for (String path : sysPaths) + { + ppCallbacks.addSysPath(path); + } + + File file = new File(filename); + file = file.getCanonicalFile(); + ppCallbacks.addUserPath(file.getParent()); + + for (String path : userPaths) + { + ppCallbacks.addUserPath(path); + } + + for (String path : importPaths) + { + ppCallbacks.addImportPath(path); + } + + final String path = file.getPath(); + final VeraPPParser ppParser = new VeraPPParser(path, ppCallbacks); + + final ParserThreadState threadState = new ParserThreadState(); + + final Thread ppThread = new Thread(new Runnable() + { + public void run() + { + try + { + ppParser.file(); + } + catch (ParseException e) + { + threadState.ppThrew(e); + } + catch (RuntimeException e) + { + // VeraParserTokenManager wraps InterruptedException + // in a RuntimeException + if (!(e.getCause() instanceof InterruptedException)) + { + threadState.ppThrew(e); + } + } + catch (Error e) + { + threadState.ppThrew(e); + } + finally + { + synchronized (threadState) + { + threadState.ppDone(); + } + } + } + }, "Vera Preprocessor Thread"); + + final VeraParser veraParser = new VeraParser(veraTokenMgr); + final CompilationUnitDecl compUnit = new CompilationUnitDecl(path); + + final Thread veraThread = new Thread(new Runnable() + { + public void run() + { + try + { + veraParser.compilation_unit(compUnit); + } + catch (ParseException e) + { + threadState.veraThrew(e); + } + catch (RuntimeException e) + { + // VeraParserTokenManager wraps InterruptedException + // in a RuntimeException + if (!(e.getCause() instanceof InterruptedException)) + { + threadState.veraThrew(e); + } + } + catch (Error e) + { + threadState.ppThrew(e); + } + finally + { + synchronized (threadState) + { + threadState.veraDone(); + } + } + } + }, "Vera Parser Thread"); + + ppThread.start(); + veraThread.start(); + + try + { + while (true) + { + synchronized (threadState) + { + if (threadState.exceptionThrown()) + { + ppThread.interrupt(); + veraThread.interrupt(); + break; + } + if (threadState.done()) + { + break; + } + threadState.wait(); + } + } + ppThread.join(); + veraThread.join(); + } + catch (InterruptedException e) + { + ppThread.interrupt(); + veraThread.interrupt(); + throw e; + } + threadState.throwException(); + + veraSchemaBuilder.setPreprocInfo(ppCallbacks); + veraSchemaBuilder.setWantShell(wantShell); + veraSchemaBuilder.visit(compUnit); + } +} + +final class ParserThreadState +{ + private boolean ppDone; + private Throwable ppException; + private boolean veraDone; + private Throwable veraException; + + public synchronized void ppDone() + { + ppDone = true; + notify(); + } + + public synchronized void ppThrew(Throwable e) + { + ppException = e; + ppDone = true; + notify(); + } + + public synchronized void veraDone() + { + veraDone = true; + notify(); + } + + public synchronized void veraThrew(Throwable e) + { + veraException = e; + veraDone = true; + notify(); + } + + public boolean exceptionThrown() + { + return ppException != null || veraException != null; + } + + public boolean done() + { + return ppDone && veraDone; + } + + public void throwException() + throws ParseException, ParseException + { + if (ppException != null) + { + if (ppException instanceof ParseException) + { + throw (ParseException) ppException; + } + else if (ppException instanceof RuntimeException) + { + throw (RuntimeException) ppException; + } + else + { + throw (Error) ppException; + } + } + if (veraException != null) + { + if (veraException instanceof ParseException) + { + throw (ParseException) veraException; + } + else if (veraException instanceof RuntimeException) + { + throw (RuntimeException) veraException; + } + else + { + throw (Error) veraException; + } + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/AccessType.java b/java/juno/src/com/newisys/schemaanalyzer/juno/AccessType.java new file mode 100644 index 0000000..ff5f692 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/AccessType.java @@ -0,0 +1,75 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +/** + * Enumeration of data access types. + * + * @author Trevor Robinson + */ +final class AccessType +{ + public static final AccessType VOID = new AccessType(false, false); + public static final AccessType READ = new AccessType(true, false); + public static final AccessType WRITE = new AccessType(false, true); + public static final AccessType READ_WRITE = new AccessType(true, true); + + private final boolean read; + private final boolean write; + + private AccessType(final boolean read, final boolean write) + { + this.read = read; + this.write = write; + } + + public static AccessType getInstance(boolean read, boolean write) + { + if (read) + { + return write ? READ_WRITE : READ; + } + else + { + return write ? WRITE : VOID; + } + } + + public boolean isRead() + { + return read; + } + + public boolean isWrite() + { + return write; + } + + @Override + public String toString() + { + if (read) + { + return write ? "read/write" : "read"; + } + else + { + return write ? "write" : "void"; + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/AnalyzerModule.java b/java/juno/src/com/newisys/schemaanalyzer/juno/AnalyzerModule.java new file mode 100644 index 0000000..870bce2 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/AnalyzerModule.java @@ -0,0 +1,523 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.SchemaObject; +import com.newisys.langschema.StructuredTypeMember; +import com.newisys.langschema.vera.*; +import com.newisys.verilog.util.BitVector; + +/** + * Base class for Vera analyzer modules. Defines common methods used by the + * concrete analyzer classes. + * + * @author Trevor Robinson + */ +abstract class AnalyzerModule +{ + protected final VeraSchemaAnalyzer analyzer; + + public AnalyzerModule(VeraSchemaAnalyzer analyzer) + { + this.analyzer = analyzer; + } + + protected BlockAnalysis analyzeBlock( + VeraBlock block, + SchemaObject context, + VeraCompilationUnit compUnit, + VeraUserClass cls, + boolean isCtor, + DADUAnalysis dadu) + { + BlockAnalysis analysis; + if (block != null) + { + analysis = analyzeBlockMember(block, context, compUnit, cls, + isCtor, dadu); + analyzer.setBlockAnalysis(block, analysis); + } + else + { + analysis = new BlockAnalysis(dadu); + } + return analysis; + } + + protected BlockAnalysis analyzeBlockMember( + VeraBlockMember blockMember, + SchemaObject context, + VeraCompilationUnit compUnit, + VeraUserClass cls, + boolean isCtor, + DADUAnalysis dadu) + { + BlockAnalysis analysis = new BlockAnalysis(dadu); + BlockMemberAnalyzer bma = new BlockMemberAnalyzer(analyzer, analysis, + context, compUnit, cls, isCtor); + blockMember.accept(bma); + bma.finalizeAnalysis(); + return analysis; + } + + protected ExpressionAnalysis analyzeExpression( + VeraExpression expr, + AccessType accessType, + VeraCompilationUnit compUnit, + VeraUserClass cls, + SchemaObject context, + BlockAnalysis blockAnalysis, + DADUAnalysis daduAnalysis) + { + ExpressionAnalysis analysis = new ExpressionAnalysis(compUnit, cls, + context, blockAnalysis, daduAnalysis); + analyzeNestedExpression(expr, analysis, accessType, true); + return analysis; + } + + protected ExpressionAnalysis analyzeCondition( + VeraExpression expr, + VeraCompilationUnit compUnit, + VeraUserClass cls, + SchemaObject context, + BlockAnalysis blockAnalysis, + DADUAnalysis daduAnalysis) + { + ExpressionAnalysis analysis = new ExpressionAnalysis(compUnit, cls, + context, blockAnalysis, daduAnalysis); + analyzeNestedCondition(expr, analysis, AccessType.READ, true); + return analysis; + } + + protected void analyzeNestedExpression( + VeraExpression expr, + ExpressionAnalysis analysis, + AccessType accessType, + boolean propagateXZ) + { + ExpressionAnalyzer ea = new ExpressionAnalyzer(analyzer, analysis, + accessType, propagateXZ); + expr.accept(ea); + + analysis.mergeDADU(); + } + + protected void analyzeNestedCondition( + VeraExpression expr, + ExpressionAnalysis analysis, + AccessType accessType, + boolean propagateXZ) + { + ExpressionAnalyzer ea = new ExpressionAnalyzer(analyzer, analysis, + accessType, propagateXZ); + expr.accept(ea); + + boolean isLiteral; + boolean isTrue; + if (expr instanceof VeraBitVectorLiteral) + { + isLiteral = true; + BitVector value = ((VeraBitVectorLiteral) expr).getValue(); + isTrue = !value.containsXZ() && !value.isZero(); + } + else if (expr instanceof VeraIntegerLiteral) + { + isLiteral = true; + isTrue = ((VeraIntegerLiteral) expr).getValue() != 0; + } + else if (expr instanceof VeraEnumValueReference) + { + isLiteral = true; + isTrue = ((VeraEnumValueReference) expr).getElement().getValue() != 0; + } + else + { + isLiteral = false; + isTrue = false; + } + + if (isLiteral) + { + analysis.mergeDADU(); + DADUAnalysis liveDADU = analysis.daduUncond; + DADUAnalysis deadDADU = liveDADU.duplicate(); + deadDADU.markDead(); + if (isTrue) + { + analysis.daduWhenTrue = liveDADU; + analysis.daduWhenFalse = deadDADU; + } + else + { + analysis.daduWhenFalse = liveDADU; + analysis.daduWhenTrue = deadDADU; + } + } + else + { + analysis.splitDADU(); + } + } + + protected void analyzeInvokeArgs( + List actualArgs, + VeraFunction func, + ExpressionAnalysis analysis, + boolean propagateXZ, + boolean inlinedFunc) + { + // save X/Z analysis for invocation + XZSourceType savedUncondXZ = analysis.uncondXZType; + Set savedXZPropagatesFrom = analysis.xzPropagatesFrom; + + VeraFunctionType funcType = func.getType(); + List formalArgs = funcType.getArguments(); + Iterator formalIter = formalArgs.iterator(); + Iterator actualIter = actualArgs.iterator(); + while (actualIter.hasNext()) + { + VeraExpression argExpr = (VeraExpression) actualIter.next(); + + VeraFunctionArgument formalArg; + VariableAnalysis formalArgAnalysis; + boolean formalByRef; + if (formalIter.hasNext()) + { + formalArg = (VeraFunctionArgument) formalIter.next(); + formalArgAnalysis = analyzer.getOrCreateVariableAnalysis( + formalArg, func); + formalByRef = formalArg.isByRef(); + } + else + { + assert (funcType.isVarArgs()); + formalArg = null; + formalArgAnalysis = null; + formalByRef = funcType.isVarArgsByRef(); + } + + boolean actualByRef = formalByRef && isVariableReference(argExpr); + if (actualByRef) + { + if (!inlinedFunc) + { + // remember that this expression contains a by-ref argument + analysis.byRefArgument = true; + } + + VeraVariable var = getReferencedVariable(argExpr); + assert (var != null); + VariableAnalysis varAnalysis = analyzer + .getOrCreateVariableAnalysis(var, analysis.context); + if (formalArg != null) + { + if (!inlinedFunc) + { + // remember that this variable is passed by-ref to this + // formal argument + varAnalysis.addByRefArgUse(formalArg, analyzer); + } + + // if this function has a body to analyze, X/Z analysis for + // by-ref formal args propagates back to actual argument + // variables; otherwise, we must rely on the annotation + // associated with the function + if (func.getBody() != null) + { + varAnalysis.trackXZPropagation(formalArgAnalysis); + } + else if (formalArg.isReturnsXZ() + && !varAnalysis.isXZKnown()) + { + varAnalysis.markAssignedXZ(XZSourceType.EXTERNAL, null); + } + } + else + { + if (!inlinedFunc) + { + // remember that this variable is passed as a by-ref + // var-arg to this function + varAnalysis.addByRefVarArgUse(func, analyzer); + } + + // assume that by-ref var-args can always be assigned X/Z + // (sscanf is currently the only by-ref var-arg function, + // and it will return X/Z) + if (!varAnalysis.isXZKnown()) + { + varAnalysis.markAssignedXZ(XZSourceType.EXTERNAL, null); + } + } + } + + // clear X/Z analysis for argument + analysis.uncondXZType = null; + analysis.xzPropagatesFrom = null; + + analyzeNestedExpression(argExpr, analysis, actualByRef + ? AccessType.READ_WRITE : AccessType.READ, !inlinedFunc); + + // update X/Z propagation analysis for argument + if (formalArg != null && !inlinedFunc) + { + applyAssignAnalysis(formalArgAnalysis, analysis); + } + } + + // restore X/Z analysis for invocation + analysis.uncondXZType = savedUncondXZ; + analysis.xzPropagatesFrom = savedXZPropagatesFrom; + + // update X/Z propagation analysis for expression + if (propagateXZ) + { + VeraLocalVariable returnVar = func.getReturnVar(); + if (returnVar != null) + { + VariableAnalysis returnVarAnalysis = analyzer + .getOrCreateVariableAnalysis(returnVar, func); + analysis.addXZPropagatesFrom(returnVarAnalysis); + } + else if (funcType.isReturnsXZ()) + { + // for built-in functions, we have no return variable to + // propagate from; instead, we must rely on the annotation + // associated with the function + analysis.markUncondXZ(XZSourceType.EXTERNAL); + } + } + } + + protected static boolean isVariableReference(VeraExpression varExpr) + { + // if expression is array access, use array expression instead + VeraExpression varRef; + if (varExpr instanceof VeraArrayAccess) + { + varRef = ((VeraArrayAccess) varExpr).getArray(); + if (!(varRef.getResultType() instanceof VeraArrayType)) + { + // bit accesses are not considered variable references + return false; + } + } + else + { + varRef = varExpr; + } + + // get variable + if (varRef instanceof VeraVariableReference) + { + return true; + } + else if (varRef instanceof VeraMemberAccess) + { + StructuredTypeMember member = ((VeraMemberAccess) varRef) + .getMember(); + return member instanceof VeraVariable; + } + return false; + } + + protected static VeraVariable getReferencedVariable(VeraExpression varExpr) + { + // if expression is array access, use array expression instead + VeraExpression varRef; + if (varExpr instanceof VeraArrayAccess) + { + varRef = ((VeraArrayAccess) varExpr).getArray(); + } + else if (varExpr instanceof VeraBitSliceAccess) + { + varRef = ((VeraBitSliceAccess) varExpr).getArray(); + } + else + { + varRef = varExpr; + } + + // get variable; return null for signal, this, super, etc. + VeraVariable var = null; + if (varRef instanceof VeraVariableReference) + { + var = ((VeraVariableReference) varRef).getVariable(); + } + else if (varRef instanceof VeraMemberAccess) + { + StructuredTypeMember member = ((VeraMemberAccess) varRef) + .getMember(); + if (member instanceof VeraVariable) + { + var = (VeraVariable) member; + } + } + return var; + } + + protected void applyAssignAnalysis( + VeraExpression lhsExpr, + ExpressionAnalysis analysis) + { + // recursively apply to each term of left-hand concatenation + if (lhsExpr instanceof VeraConcatenation) + { + VeraConcatenation concat = (VeraConcatenation) lhsExpr; + Iterator iter = concat.getOperands().iterator(); + while (iter.hasNext()) + { + VeraExpression expr = (VeraExpression) iter.next(); + applyAssignAnalysis(expr, analysis); + } + } + else + { + // get variable referenced by expression (null for signals, etc.) + VeraVariable var = getReferencedVariable(lhsExpr); + if (var != null) + { + VariableAnalysis varAnalysis = analyzer + .getOrCreateVariableAnalysis(var, analysis.context); + applyAssignAnalysis(varAnalysis, analysis); + } + } + } + + protected void applyAssignAnalysis( + VariableAnalysis varAnalysis, + ExpressionAnalysis analysis) + { + // update X/Z propagation analysis + if (!varAnalysis.isXZKnown()) + { + if (analysis.isUncondXZ()) + { + varAnalysis.markAssignedXZ(analysis.uncondXZType, null); + } + else + { + Iterator iter = analysis.getXZPropagatesFrom().iterator(); + while (iter.hasNext()) + { + VariableAnalysis other = (VariableAnalysis) iter.next(); + varAnalysis.trackXZPropagation(other); + } + } + } + + // update write side-effects analysis + if (analysis.sideEffects) + { + varAnalysis.markWriteSideEffects(); + } + } + + protected static void finalizeLocalVars(Collection localVarAnalyses) + { + // mark local variables as out of scope + Iterator iter = localVarAnalyses.iterator(); + while (iter.hasNext()) + { + VariableAnalysis varAnalysis = (VariableAnalysis) iter.next(); + varAnalysis.markScopeComplete(); + iter.remove(); + } + } + + protected void initFunctionDADU(VeraFunction func, DADUAnalysis dadu) + { + // initialize DA/DU tracking for arguments + Iterator iter = func.getType().getArguments().iterator(); + while (iter.hasNext()) + { + VeraFunctionArgument arg = (VeraFunctionArgument) iter.next(); + + // create analysis object for this variable (to track context) + analyzer.getOrCreateVariableAnalysis(arg, func); + + // initialize DA/DU tracking for argument + int daduIndex = dadu.alloc(arg); + + // mark all arguments as assigned + dadu.markAssigned(daduIndex); + } + + // initialize DA/DU tracking for return variable (if any) + VeraLocalVariable returnVar = func.getReturnVar(); + if (returnVar != null) + { + dadu.alloc(returnVar); + } + } + + protected void finalizeFunctionDADU(VeraFunction func, DADUAnalysis dadu) + { + // simulate final read of return variable for DA/DU analysis + VeraLocalVariable returnVar = func.getReturnVar(); + if (returnVar != null && !dadu.isDA(returnVar)) + { + VariableAnalysis varAnalysis = analyzer + .getOrCreateVariableAnalysis(returnVar, func); + + varAnalysis.markReadUnassigned(); + + if (!varAnalysis.isXZKnown()) + { + varAnalysis.markAssignedXZ(XZSourceType.UNINIT, null); + } + } + } + + protected void initDefineDADU(VeraDefine define, DADUAnalysis dadu) + { + // initialize DA/DU tracking for arguments + Iterator iter = define.getArguments().iterator(); + while (iter.hasNext()) + { + VeraDefineArgument arg = (VeraDefineArgument) iter.next(); + + // create analysis object for this variable (to track context) + analyzer.getOrCreateVariableAnalysis(arg, define); + + // initialize DA/DU tracking for argument + int daduIndex = dadu.alloc(arg); + + // mark all arguments as assigned + dadu.markAssigned(daduIndex); + } + } + + protected static String getDescription(SchemaObject obj) + { + if (obj instanceof NamedObject) + { + return ((NamedObject) obj).getName().getCanonicalName(); + } + else + { + return obj.toDebugString(); + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/BlockAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/BlockAnalysis.java new file mode 100644 index 0000000..3017caf --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/BlockAnalysis.java @@ -0,0 +1,103 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.newisys.langschema.vera.VeraVariable; + +/** + * Contains the analysis state for a particular statement block. + * + * @author Trevor Robinson + */ +public final class BlockAnalysis +{ + private final BlockAnalysis outerAnalysis; + private final Map localAccessMap = new HashMap(); + private boolean needThreadContext; + DADUAnalysis dadu; + + public BlockAnalysis(DADUAnalysis dadu) + { + this.outerAnalysis = null; + this.dadu = dadu; + } + + public BlockAnalysis(BlockAnalysis outerAnalysis) + { + this.outerAnalysis = outerAnalysis; + this.dadu = outerAnalysis.dadu; + } + + private AccessType getAccess(VeraVariable var) + { + AccessType access = localAccessMap.get(var); + return access != null ? access : AccessType.VOID; + } + + public Set getLocalRefs() + { + return localAccessMap.keySet(); + } + + public boolean isLocalRead(VeraVariable var) + { + return getAccess(var).isRead(); + } + + public boolean isLocalWrite(VeraVariable var) + { + return getAccess(var).isWrite(); + } + + void addLocalAccess(VeraVariable var, boolean read, boolean write) + { + AccessType oldAccess = getAccess(var); + AccessType newAccess = AccessType.getInstance(read + || oldAccess.isRead(), write || oldAccess.isWrite()); + localAccessMap.put(var, newAccess); + + if (outerAnalysis != null) + { + outerAnalysis.addLocalAccess(var, read, write); + } + } + + void removeLocalAccess(VeraVariable var) + { + localAccessMap.remove(var); + + if (outerAnalysis != null) + { + outerAnalysis.removeLocalAccess(var); + } + } + + public boolean isNeedThreadContext() + { + return needThreadContext; + } + + void setNeedThreadContext(boolean needThreadContext) + { + this.needThreadContext = needThreadContext; + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/BlockMemberAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/BlockMemberAnalyzer.java new file mode 100644 index 0000000..3116d02 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/BlockMemberAnalyzer.java @@ -0,0 +1,991 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.BlockMember; +import com.newisys.langschema.JoinKind; +import com.newisys.langschema.SchemaObject; +import com.newisys.langschema.Statement; +import com.newisys.langschema.vera.*; + +/** + * Schema analyzer for block member objects. + * + * @author Trevor Robinson + */ +final class BlockMemberAnalyzer + extends AnalyzerModule + implements VeraBlockMemberVisitor +{ + private static class BlockExit + { + final VeraStatement stmt; + final DADUAnalysis dadu; + + public BlockExit(VeraStatement stmt, DADUAnalysis dadu) + { + this.stmt = stmt; + this.dadu = dadu.duplicate(); + } + } + + private final VeraCompilationUnit compUnit; + private final VeraUserClass cls; + private final SchemaObject context; + private final boolean isCtor; + private final BlockAnalysis analysis; + private List localVarAnalyses; + + private List curExitList = new LinkedList(); + private boolean loopPassTwo = false; + + public BlockMemberAnalyzer( + VeraSchemaAnalyzer analyzer, + BlockAnalysis analysis, + SchemaObject context, + VeraCompilationUnit compUnit, + VeraUserClass cls, + boolean isCtor) + { + super(analyzer); + this.compUnit = compUnit; + this.cls = cls; + this.context = context; + this.isCtor = isCtor; + this.analysis = analysis; + } + + // used to create forked statement analyzers + private BlockMemberAnalyzer( + BlockMemberAnalyzer enclosing, + BlockAnalysis analysis) + { + super(enclosing.analyzer); + this.compUnit = enclosing.compUnit; + this.cls = enclosing.cls; + this.context = enclosing.context; + this.isCtor = enclosing.isCtor; + this.analysis = analysis; + } + + private ExpressionAnalysis analyzeExpression( + VeraExpression expr, + AccessType accessType) + { + ExpressionAnalysis exprAnalysis = analyzeExpression(expr, accessType, + compUnit, cls, context, analysis, analysis.dadu); + analysis.dadu = exprAnalysis.daduUncond; + return exprAnalysis; + } + + private ExpressionAnalysis analyzeCondition(VeraExpression expr) + { + return analyzeCondition(expr, compUnit, cls, context, analysis, + analysis.dadu); + } + + private void recordExit(VeraStatement obj) + { + curExitList.add(new BlockExit(obj, analysis.dadu)); + analysis.dadu.markDead(); + } + + private void analyzeExits(Class stmtCls, List enclosingExitList) + { + final Iterator iter = curExitList.iterator(); + curExitList = enclosingExitList; + while (iter.hasNext()) + { + BlockExit exit = iter.next(); + if (stmtCls.isInstance(exit.stmt)) + { + analysis.dadu.merge(exit.dadu); + } + else + { + curExitList.add(exit); + } + } + } + + public void finalizeAnalysis() + { + // merge DA/DU states from any early returns + analyzeExits(VeraReturnStatement.class, new LinkedList()); + assert (curExitList.isEmpty()); + } + + public void visit(VeraLocalVariable obj) + { + ++analyzer.localVarCount; + + // create analysis object for this variable (to track context) + VariableAnalysis varAnalysis = analyzer.getOrCreateVariableAnalysis( + obj, context); + localVarAnalyses.add(varAnalysis); + + // initialize DA/DU tracking for variable + int daduIndex = analysis.dadu.alloc(obj); + + VeraExpression initExpr = obj.getInitializer(); + if (initExpr != null) + { + // analyze initializer + ExpressionAnalysis exprAnalysis = analyzeExpression(initExpr, + AccessType.READ); + applyAssignAnalysis(varAnalysis, exprAnalysis); + + // mark variable as assigned after initializer + analysis.dadu.markAssigned(daduIndex); + + // track initialization as write access + varAnalysis.markWriteAccess(); + if (exprAnalysis.sideEffects) varAnalysis.markWriteSideEffects(); + } + else + { + // treat fixed and associative arrays as always assigned + VeraType type = obj.getType(); + if (type instanceof VeraFixedArrayType + || type instanceof VeraAssocArrayType) + { + analysis.dadu.markAssigned(daduIndex); + } + } + } + + public void visit(VeraBlock obj) + { + // save existing local variable list and create new one + final List enclosingVarAnalyses = localVarAnalyses; + localVarAnalyses = new LinkedList(); + + // remember DA/DU variable index at start of block + final int blockIndex = analysis.dadu.beginBlock(); + + for (final VeraBlockMember member : obj.getMembers()) + { + member.accept(this); + } + + // restore DA/DU variable index + analysis.dadu.endBlock(blockIndex); + + // mark local variables as out of scope + finalizeLocalVars(localVarAnalyses); + localVarAnalyses = enclosingVarAnalyses; + } + + public void visit(VeraBreakpointStatement obj) + { + ++analyzer.statementCount; + } + + public void visit(VeraBreakStatement obj) + { + ++analyzer.statementCount; + + recordExit(obj); + } + + public void visit(VeraContinueStatement obj) + { + ++analyzer.statementCount; + + recordExit(obj); + } + + public void visit(VeraDriveSampleStatement obj) + { + ++analyzer.statementCount; + + VeraExpression delayExpr = obj.getDelay(); + if (delayExpr != null) + { + analyzeExpression(delayExpr, AccessType.READ); + } + + VeraExpression destExpr = obj.getDestination(); + analyzeExpression(destExpr, AccessType.WRITE); + + VeraExpression valueExpr = obj.getSource(); + ExpressionAnalysis exprAnalysis = analyzeExpression(valueExpr, + AccessType.READ); + applyAssignAnalysis(destExpr, exprAnalysis); + } + + public void visit(VeraExpectStatement obj) + { + ++analyzer.statementCount; + + final VeraExpression delayExpr = obj.getDelay(); + if (delayExpr != null) + { + analyzeExpression(delayExpr, AccessType.READ); + } + + final VeraExpression windowExpr = obj.getWindow(); + if (windowExpr != null) + { + analyzeExpression(windowExpr, AccessType.READ); + } + + for (final VeraExpectTerm term : obj.getExpectTerms()) + { + analyzeExpression(term.getSignal(), AccessType.READ); + analyzeExpression(term.getValue(), AccessType.READ); + } + } + + public void visit(VeraExpressionStatement obj) + { + ++analyzer.statementCount; + + VeraExpression expr = obj.getExpression(); + if (expr instanceof VeraFunctionInvocation) + { + VeraFunctionInvocation callExpr = (VeraFunctionInvocation) expr; + VeraExpression funcExpr = callExpr.getFunction(); + List actualArgs = callExpr.getArguments(); + if (isCtor && funcExpr instanceof VeraMemberAccess) + { + VeraMemberAccess memberExpr = (VeraMemberAccess) funcExpr; + VeraExpression objExpr = memberExpr.getObject(); + VeraMemberFunction func = (VeraMemberFunction) memberExpr + .getMember(); + + // call to super.new? + if (objExpr instanceof VeraSuperReference + && func.isConstructor()) + { + // analyze argument expressions + ExpressionAnalysis exprAnalysis = new ExpressionAnalysis( + compUnit, cls, context, analysis, analysis.dadu); + analyzeInvokeArgs(actualArgs, func, exprAnalysis, false, + false); + + // does any argument reference the instance or a local + // variable, or contain a construct requiring temporaries? + if (exprAnalysis.referencesInstance + || exprAnalysis.referencesLocalNonArg + || exprAnalysis.byRefArgument + || exprAnalysis.postIncDec) + { + // this class requires transformation of the super call + ClassAnalysis thisAnalysis = analyzer + .getClassAnalysis(cls); + analyzer.log + .println("Found complex super ctor call in " + + cls.getName()); + thisAnalysis.transformSuperCall = true; + + // any user base classes will need a default ctor + VeraClass baseCls = cls.getBaseClass(); + while (baseCls instanceof VeraUserClass) + { + ClassAnalysis superAnalysis = analyzer + .getOrCreateClassAnalysis((VeraUserClass) baseCls); + if (superAnalysis.needDefaultCtor) break; + analyzer.log.incIndent(); + analyzer.log + .println("Class requires default ctor: " + + baseCls.getName()); + analyzer.log.decIndent(); + superAnalysis.needDefaultCtor = true; + + baseCls = baseCls.getBaseClass(); + } + } + + // skip processing expression as a whole + return; + } + } + else if (funcExpr instanceof VeraFunctionReference) + { + VeraFunctionReference funcRef = (VeraFunctionReference) funcExpr; + VeraFunction func = funcRef.getFunction(); + String id = func.getName().getIdentifier(); + + // call to wait_var? + if (func instanceof VeraGlobalFunction && id.equals("wait_var")) + { + // analyze argument expressions + ExpressionAnalysis exprAnalysis = new ExpressionAnalysis( + compUnit, cls, context, analysis, analysis.dadu); + for (final VeraExpression argExpr : actualArgs) + { + analyzeNestedExpression(argExpr, exprAnalysis, + AccessType.READ, false); + + // mark variable as a wait_var target + VeraVariable var = getReferencedVariable(argExpr); + assert (var != null); + VariableAnalysis varAnalysis = analyzer + .getOrCreateVariableAnalysis(var, null); + varAnalysis.markWaitVar(analyzer); + } + + // skip processing expression as a whole + return; + } + + // call to wait_child? + if (func instanceof VeraGlobalFunction + && id.equals("wait_child")) + { + analyzer.log.println("Found wait_child() in " + + AnalyzerModule.getDescription(context)); + + // need to create thread context for enclosing block + analysis.setNeedThreadContext(true); + + // skip processing expression as a whole + return; + } + } + } + analyzeExpression(expr, AccessType.READ); + } + + public void visit(VeraForkStatement obj) + { + ++analyzer.statementCount; + + BlockAnalysis forkAnalysis = new BlockAnalysis(analysis); + Statement searchStmt = obj.getContainingStatement(); + + // DA/DU + final DADUAnalysis daduBeforeFork = analysis.dadu; + DADUAnalysis daduForks = null; + + final Iterator iter = obj.getForkedStatements() + .iterator(); + assert (iter.hasNext()); + while (iter.hasNext()) + { + VeraStatement stmt = iter.next(); + + // DA/DU: V is [un]assigned before each forked statement of the + // fork/join statement iff V is [un]assigned before the fork/join + // statement. + BlockAnalysis forkStmtAnalysis = new BlockAnalysis(forkAnalysis); + forkStmtAnalysis.dadu = daduBeforeFork.duplicate(); + BlockMemberAnalyzer bma = new BlockMemberAnalyzer(this, + forkStmtAnalysis); + stmt.accept((VeraStatementVisitor) bma); + + filterForkAnalysis(forkStmtAnalysis, searchStmt, false); + analyzer.setBlockAnalysis(stmt, forkStmtAnalysis); + + // DA/DU + if (daduForks != null) + { + daduForks.merge(forkStmtAnalysis.dadu); + } + else + { + daduForks = forkStmtAnalysis.dadu; + } + } + + filterForkAnalysis(forkAnalysis, searchStmt, true); + analyzer.setBlockAnalysis(obj, forkAnalysis); + + // DA/DU + final JoinKind joinKind = obj.getJoinKind(); + if (joinKind == JoinKind.ALL) + { + // DA/DU: V is [un]assigned after fork/join all iff V is + // [un]assigned after each forked statement. + analysis.dadu = daduForks; + } + else if (joinKind == JoinKind.ANY) + { + // DA/DU: V is [un]assigned after fork/join any iff V is + // [un]assigned before the fork and V is [un]assigned after each + // forked statement. + daduForks.merge(daduBeforeFork); + analysis.dadu = daduForks; + } + else + { + // DA/DU: V is [un]assigned after fork/join none iff V is + // [un]assigned before the fork. + assert (joinKind == JoinKind.NONE); + analysis.dadu = daduBeforeFork; + } + } + + private void filterForkAnalysis( + BlockAnalysis forkAnalysis, + Statement searchStmt, + boolean logReferences) + { + Set localRefs = forkAnalysis.getLocalRefs(); + Iterator iter = localRefs.iterator(); + while (iter.hasNext()) + { + VeraVariable var = iter.next(); + + String varKind; + if (var instanceof VeraLocalVariable) + { + // exclude local variables contained within forked statement + VeraLocalVariable localVar = (VeraLocalVariable) var; + if (!fromEnclosingStatement(localVar, searchStmt) + && !isReturnVar(localVar)) + { + iter.remove(); + continue; + } + varKind = "local"; + } + else if (var instanceof VeraFunctionArgument) + { + varKind = "argument"; + } + else if (var instanceof VeraMemberVariable) + { + varKind = "field"; + } + else + { + assert (var instanceof VeraGlobalVariable || var instanceof VeraBindVariable); + varKind = "global"; + } + + // flag forked reads/writes in variable analysis + VariableAnalysis varAnalysis = analyzer + .getOrCreateVariableAnalysis(var, context); + boolean isRead = forkAnalysis.isLocalRead(var); + boolean isWrite = forkAnalysis.isLocalWrite(var); + if (isRead) varAnalysis.markForkRead(); + if (isWrite) + { + // TODO: handle shadow variables properly; they should be cloned + // when referenced, since they are really a separate variable + // for the purposes of DA/DU and forked access analysis + if (var.hasModifier(VeraVariableModifier.SHADOW)) + { + analyzer.log.println("Analysis of write to shadow variable " + + var.getName() + " in fork not fully supported"); + } + varAnalysis.markForkWrite(); + } + + if (logReferences) + { + StringBuffer msg = new StringBuffer(80); + msg.append("Fork in " + AnalyzerModule.getDescription(context) + + " references " + varKind + " "); + msg.append(var.getName().getIdentifier()); + msg.append(" with "); + if (isRead && isWrite) + { + msg.append("read/write"); + } + else if (isWrite) + { + msg.append("write"); + } + else + { + msg.append("read"); + } + msg.append(" access"); + analyzer.log.println(msg.toString()); + } + } + } + + private boolean isReturnVar(VeraLocalVariable var) + { + return context instanceof VeraFunction + && var == ((VeraFunction) context).getReturnVar(); + } + + private static boolean fromEnclosingStatement( + BlockMember member, + Statement searchStmt) + { + Statement memberStmt = member.getContainingStatement(); + do + { + if (memberStmt == searchStmt) return true; + searchStmt = searchStmt.getContainingStatement(); + } + while (searchStmt != null); + return false; + } + + public void visit(VeraForStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: V is [un]assigned before the initialization part of the for + // statement iff V is [un]assigned before the for statement. + Iterator initIter = obj.getInitStatements().iterator(); + while (initIter.hasNext()) + { + VeraStatement stmt = (VeraStatement) initIter.next(); + stmt.accept((VeraStatementVisitor) this); + } + + List enclosingExitList = curExitList; + boolean enclosingLoopPassTwo = loopPassTwo; + DADUAnalysis daduAfterCond = null; + while (true) + { + curExitList = new LinkedList(); + + // DA/DU: V is definitely assigned before the condition part of the + // for statement iff V is definitely assigned after the + // initialization part of the for statement. + // DA/DU: V is definitely unassigned before the condition part of + // the for statement iff [a], [b], and [c]. + // [a] V is definitely unassigned after the initialization part of + // the for statement. + DADUAnalysis daduBeforeCond = null; + if (!loopPassTwo) + { + daduBeforeCond = analysis.dadu.duplicate(); + } + VeraExpression condExpr = (VeraExpression) obj.getCondition(); + if (condExpr != null) + { + ExpressionAnalysis condAnalysis = analyzeCondition(condExpr); + if (daduAfterCond == null) + { + daduAfterCond = condAnalysis.daduWhenFalse; + } + + // DA/DU: [1] A condition expression is present and V is + // [un]assigned after the condition expression when true. + analysis.dadu = condAnalysis.daduWhenTrue; + } + else + { + if (daduAfterCond == null) + { + daduAfterCond = analysis.dadu.duplicate(); + } + daduAfterCond.markDead(); + + // DA/DU: [2] No condition expression is present and V is + // [un]assigned after the initialization part of the for + // statement. + } + + // DA/DU: V is [un]assigned before the contained statement iff + // either [1] or [2]. + VeraStatement stmt = obj.getStatement(); + stmt.accept((VeraStatementVisitor) this); + + // DA/DU: [b] Assuming V is definitely unassigned before the + // condition part of the for statement, V is definitely unassigned + // after the contained statement. + // [c] Assuming V is definitely unassigned before the contained + // statement, V is definitely unassigned before every continue + // statement for which the for statement is the continue target. + analyzeExits(VeraContinueStatement.class, + new LinkedList()); + + // DA/DU: V is [un]assigned before the update part of the for + // statement iff V is [un]assigned after the contained statement + // and V is [un]assigned before every continue statement for which + // the for statement is the continue target. + for (VeraExpressionStatement updateStmt : obj.getUpdateStatements()) + { + updateStmt.accept((VeraStatementVisitor) this); + } + + // second pass ends here + if (loopPassTwo) break; + + // DU before condition - DU after update statements = vars possibly + // assigned in condition, contained statement, or update statements + daduBeforeCond.clearDU(analysis.dadu); + // skip pass two if no vars possibly assigned + if (!daduBeforeCond.containsDU()) break; + + // DA/DU: V is definitely unassigned after condition when true iff + // V is definitely unassigned after contained statement and update + // statements. + daduAfterCond.clearDU(daduBeforeCond); + + // make a second pass through the loop to detect variables that are + // possibly assigned multiple times + loopPassTwo = true; + } + loopPassTwo = enclosingLoopPassTwo; + + // DA/DU: V is definitely assigned after a for statement iff both of the + // following are true: + // [A] Either a condition expression is not present or V is definitely + // assigned after the condition expression when false. + // [B] V is definitely assigned before every break statement for which + // the for statement is the break target. + // DA/DU: V is definitely unassigned after a for statement iff both of + // the following are true: + // [A] Either a condition expression is not present or V is definitely + // unassigned after the condition expression when true. + // [B] V is definitely unassigned after S. + analysis.dadu = daduAfterCond; + analyzeExits(VeraBreakStatement.class, enclosingExitList); + } + + public void visit(VeraIfStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: V is [un]assigned before e iff V is [un]assigned before if (e) + // S [else T]. + VeraExpression condExpr = obj.getCondition(); + ExpressionAnalysis condAnalysis = analyzeCondition(condExpr); + DADUAnalysis daduAfterCondWhenFalse = condAnalysis.daduWhenFalse; + + // DA/DU: V is [un]assigned before S iff V is [un]assigned after e when + // true. + analysis.dadu = condAnalysis.daduWhenTrue; + VeraStatement thenStmt = obj.getThenStatement(); + thenStmt.accept((VeraStatementVisitor) this); + + VeraStatement elseStmt = obj.getElseStatement(); + if (elseStmt != null) + { + DADUAnalysis daduAfterThen = analysis.dadu.duplicate(); + + // DA/DU: V is [un]assigned before T iff V is [un]assigned after e + // when false. + analysis.dadu = daduAfterCondWhenFalse; + elseStmt.accept((VeraStatementVisitor) this); + + // DA/DU: V is [un]assigned after if (e) S else T iff V is + // [un]assigned after S and V is [un]assigned after T. + analysis.dadu.merge(daduAfterThen); + } + else + { + // DA/DU: V is [un]assigned after if (e) S iff V is [un]assigned + // after S and V is [un]assigned after e when false. + analysis.dadu.merge(daduAfterCondWhenFalse); + } + } + + public void visit(VeraRandCaseStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: V is [un]assigned before the first weight expression of the + // randcase statement iff V is [un]assigned before the randcase + // statement. + final DADUAnalysis daduWeightExprs = analysis.dadu; + DADUAnalysis daduCases = null; + + for (final VeraRandCase rc : obj.getCaseList()) + { + // DA/DU: V is [un]assigned before each subsequent weight expression + // iff V is [un]assigned after the previous weight expression in + // source order. + analysis.dadu = daduWeightExprs; + + VeraExpression weightExpr = rc.getWeight(); + analyzeExpression(weightExpr, AccessType.READ); + + // DA/DU: V is [un]assigned before each case statement iff V is + // [un]assigned after the corresponding weight expression. + analysis.dadu = analysis.dadu.duplicate(); + + VeraStatement stmt = rc.getStatement(); + stmt.accept((VeraStatementVisitor) this); + + // DA/DU + if (daduCases != null) + { + daduCases.merge(analysis.dadu); + } + else + { + daduCases = analysis.dadu; + } + } + + // DA/DU + if (daduCases == null) + { + // DA/DU: V is [un]assigned after a randcase statement with no cases + // iff V is [un]assigned before the randcase statement. + analysis.dadu = daduWeightExprs; + } + else + { + // DA/DU: V is [un]assigned after a randcase statement iff V is + // [un]assigned after each case. + analysis.dadu = daduCases; + } + } + + public void visit(VeraRepeatStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: repeat (e) S + List enclosingExitList = curExitList; + boolean enclosingLoopPassTwo = loopPassTwo; + DADUAnalysis daduAfterCond = null; + while (true) + { + curExitList = new LinkedList(); + + // DA/DU: V is definitely assigned before e iff V is definitely + // assigned before the repeat statement. + // DA/DU: V is definitely unassigned before e iff [a], [b], and [c]. + // [a] V is definitely unassigned before the repeat statement. + DADUAnalysis daduBeforeCond = null; + if (!loopPassTwo) + { + daduBeforeCond = analysis.dadu.duplicate(); + } + VeraExpression condExpr = obj.getCondition(); + analyzeExpression(condExpr, AccessType.READ); + if (daduAfterCond == null) + { + daduAfterCond = analysis.dadu; + } + + // DA/DU: V is [un]assigned before S iff V is [un]assigned after e. + VeraStatement stmt = obj.getStatement(); + stmt.accept((VeraStatementVisitor) this); + + // DA/DU: [b] Assuming V is definitely unassigned before e, V is + // definitely unassigned after S. + // [c] Assuming V is definitely unassigned before e, V is definitely + // unassigned before every continue statement for which the repeat + // statement is the continue target. + analyzeExits(VeraContinueStatement.class, + new LinkedList()); + + // second pass ends here + if (loopPassTwo) break; + + // DU before e - DU after S = vars possibly assigned in e or S + daduBeforeCond.clearDU(analysis.dadu); + // skip pass two if no vars assigned in e or S + if (!daduBeforeCond.containsDU()) break; + + // DA/DU: V is definitely unassigned after e when true iff V is + // definitely unassigned after S. + daduAfterCond.clearDU(daduBeforeCond); + + // make a second pass through the loop to detect variables that are + // possibly assigned multiple times + loopPassTwo = true; + } + loopPassTwo = enclosingLoopPassTwo; + + // DA/DU: V is definitely assigned after repeat (e) S iff V is + // definitely assigned after e when false and V is definitely assigned + // before every break statement for which the repeat statement is the + // break target. + // DA/DU: V is definitely unassigned after repeat (e) S iff V is + // definitely unassigned after e when true and V is definitely + // unassigned after S. + analysis.dadu = daduAfterCond; + analyzeExits(VeraBreakStatement.class, enclosingExitList); + } + + public void visit(VeraReturnStatement obj) + { + ++analyzer.statementCount; + + recordExit(obj); + } + + public void visit(VeraSwitchStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: V is [un]assigned before the switch expression iff V is + // [un]assigned before the switch statement. + VeraExpression selExpr = obj.getSelector(); + analyzeExpression(selExpr, AccessType.READ); + + // DA/DU: V is [un]assigned before the first case expression of the + // switch statement iff V is [un]assigned after the switch expression. + final DADUAnalysis daduCaseExprs = analysis.dadu; + DADUAnalysis daduCases = null; + + boolean hasDefault = false; + final Iterator iter = obj.getCases().iterator(); + while (iter.hasNext()) + { + VeraSwitchCase sc = iter.next(); + + // DA/DU: V is [un]assigned before each subsequent case expression + // iff V is [un]assigned after the previous case expression in + // source order. + analysis.dadu = daduCaseExprs; + + if (sc instanceof VeraSwitchValueCase) + { + VeraSwitchValueCase svc = (VeraSwitchValueCase) sc; + for (final VeraExpression valueExpr : svc.getValues()) + { + analyzeExpression(valueExpr, AccessType.READ); + } + } + else + { + assert (sc instanceof VeraSwitchDefaultCase); + hasDefault = true; + assert (!iter.hasNext()); + } + + // DA/DU: V is [un]assigned before each case statement iff V is + // [un]assigned after the corresponding case expression. + analysis.dadu = analysis.dadu.duplicate(); + + VeraStatement stmt = sc.getStatement(); + stmt.accept((VeraStatementVisitor) this); + + // DA/DU + if (daduCases != null) + { + daduCases.merge(analysis.dadu); + } + else + { + daduCases = analysis.dadu; + } + } + + // DA/DU + if (daduCases == null) + { + // DA/DU: V is [un]assigned after a switch statement with no cases + // iff V is [un]assigned after the switch expression. + analysis.dadu = daduCaseExprs; + } + else if (!hasDefault) + { + // DA/DU: V is [un]assigned after a switch statement without a + // default case iff V is [un]assigned after the switch and case + // expressions and V is [un]assigned after each case statement. + daduCases.merge(daduCaseExprs); + analysis.dadu = daduCases; + } + else + { + // DA/DU: V is [un]assigned after a switch statement with a default + // case iff V is [un]assigned after each case. + analysis.dadu = daduCases; + } + } + + public void visit(VeraSyncStatement obj) + { + ++analyzer.statementCount; + + for (final VeraSyncTerm term : obj.getTerms()) + { + VeraExpression signalExpr = term.getSignal(); + analyzeExpression(signalExpr, AccessType.READ); + } + } + + public void visit(VeraTerminateStatement obj) + { + ++analyzer.statementCount; + } + + public void visit(VeraWhileStatement obj) + { + ++analyzer.statementCount; + + // DA/DU: while (e) S + List enclosingExitList = curExitList; + boolean enclosingLoopPassTwo = loopPassTwo; + DADUAnalysis daduAfterCond = null; + while (true) + { + curExitList = new LinkedList(); + + // DA/DU: V is definitely assigned before e iff V is definitely + // assigned before the while statement. + // DA/DU: V is definitely unassigned before e iff [a], [b], and [c]. + // [a] V is definitely unassigned before the while statement. + DADUAnalysis daduBeforeCond = null; + if (!loopPassTwo) + { + daduBeforeCond = analysis.dadu.duplicate(); + } + VeraExpression condExpr = obj.getCondition(); + ExpressionAnalysis condAnalysis = analyzeCondition(condExpr); + if (daduAfterCond == null) + { + daduAfterCond = condAnalysis.daduWhenFalse; + } + + // DA/DU: V is [un]assigned before S iff V is [un]assigned after e + // when true. + analysis.dadu = condAnalysis.daduWhenTrue; + VeraStatement stmt = obj.getStatement(); + stmt.accept((VeraStatementVisitor) this); + + // DA/DU: [b] Assuming V is definitely unassigned before e, V is + // definitely unassigned after S. + // [c] Assuming V is definitely unassigned before e, V is definitely + // unassigned before every continue statement for which the while + // statement is the continue target. + analyzeExits(VeraContinueStatement.class, + new LinkedList()); + + // second pass ends here + if (loopPassTwo) break; + + // DU before e - DU after S = vars possibly assigned in e or S + daduBeforeCond.clearDU(analysis.dadu); + // skip pass two if no vars possibly assigned + if (!daduBeforeCond.containsDU()) break; + + // DA/DU: V is definitely unassigned after e when true iff V is + // definitely unassigned after S. + daduAfterCond.clearDU(daduBeforeCond); + + // make a second pass through the loop to detect variables that are + // possibly assigned multiple times + loopPassTwo = true; + } + loopPassTwo = enclosingLoopPassTwo; + + // DA/DU: V is definitely assigned after while (e) S iff V is definitely + // assigned after e when false and V is definitely assigned before every + // break statement for which the while statement is the break target. + // DA/DU: V is definitely unassigned after while (e) S iff V is + // definitely unassigned after e when true and V is definitely + // unassigned after S. + analysis.dadu = daduAfterCond; + analyzeExits(VeraBreakStatement.class, enclosingExitList); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/ClassAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/ClassAnalysis.java new file mode 100644 index 0000000..5f0c297 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/ClassAnalysis.java @@ -0,0 +1,54 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import com.newisys.langschema.vera.VeraUserClass; + +/** + * Contains the analysis state for a particular user class. + * + * @author Trevor Robinson + */ +public final class ClassAnalysis +{ + final VeraUserClass cls; + + boolean hasDefaultCtor; + boolean needDefaultCtor; + boolean transformSuperCall; + + public ClassAnalysis(VeraUserClass cls) + { + this.cls = cls; + } + + public boolean hasDefaultCtor() + { + return hasDefaultCtor; + } + + public boolean needDefaultCtor() + { + return needDefaultCtor; + } + + public boolean transformSuperCall() + { + return transformSuperCall; + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/ClassMemberAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/ClassMemberAnalyzer.java new file mode 100644 index 0000000..f49c31a --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/ClassMemberAnalyzer.java @@ -0,0 +1,232 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.vera.*; + +/** + * Schema analyzer for class member objects. This class expects the following + * types of objects to be analyzed in the given order: variables, constructor, + * methods/constraints. Other types of objects may be freely interspersed among + * those and are ignored. + * + * @author Trevor Robinson + */ +final class ClassMemberAnalyzer + extends AnalyzerModule + implements VeraClassMemberVisitor +{ + private final VeraUserClass cls; + private final ClassAnalysis analysis; + private final List localVarAnalyses = new LinkedList(); + private DADUAnalysis dadu = new DADUAnalysis(); + private boolean gotCtor = false; + private boolean gotMethod = false; + + public ClassMemberAnalyzer( + VeraSchemaAnalyzer analyzer, + VeraUserClass cls, + ClassAnalysis analysis) + { + super(analyzer); + this.cls = cls; + this.analysis = analysis; + } + + public void ctorsComplete() + { + // mark fields not definitely assigned as unassigned after ctor + final int nextIndex = dadu.getNextIndex(); + for (int index = 0; index < nextIndex; ++index) + { + if (!dadu.isDA(index)) + { + final VeraVariable var = dadu.getVariable(index); + final VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(var); + varAnalysis.markFieldUnassignedInCtor(); + } + } + } + + public void finalizeAnalysis() + { + // mark local variables as out of scope + finalizeLocalVars(localVarAnalyses); + } + + public void visit(VeraClassConstraint obj) + { + ++analyzer.constraintCount; + + // analyze constraint expressions + final Iterator iter = obj.getExprs().iterator(); + while (iter.hasNext()) + { + VeraExpression expr = (VeraExpression) iter.next(); + analyzeExpression(expr, AccessType.READ, cls.getCompilationUnit(), + cls, obj, null, dadu); + } + } + + public void visit(VeraEnumeration obj) + { + ++analyzer.enumCount; + } + + public void visit(VeraEnumerationElement obj) + { + // ignored + } + + public void visit(VeraMemberFunction obj) + { + ++analyzer.methodCount; + + // determine whether method is a constructor + final boolean isCtor = obj.isConstructor(); + if (isCtor) + { + // check member type ordering + assert (!gotMethod); + gotCtor = true; + + // remember whether class has a default constructor + if (obj.getType().getArguments().size() == 0) + { + analysis.hasDefaultCtor = true; + } + } + else + { + gotMethod = true; + + // two override analyses: + // 1) track direct method overrides + // 2) check for override of a non-virtual method; + // requires method renaming in Java + final FunctionAnalysis funcAnalysis = analyzer + .getOrCreateFunctionAnalysis(obj); + final boolean visibleNonVirtual = isVisibleNonVirtual(obj); + final String id = obj.getName().getIdentifier(); + boolean foundBaseFunc = false; + VeraClass baseCls = cls.getBaseClass(); + while (baseCls != null) + { + Iterator iter = baseCls + .lookupObjects(id, VeraNameKind.NON_TYPE); + while (iter.hasNext()) + { + Object baseObj = iter.next(); + if (baseObj instanceof VeraMemberFunction) + { + VeraMemberFunction baseFunc = (VeraMemberFunction) baseObj; + FunctionAnalysis baseFuncAnalysis = analyzer + .getOrCreateFunctionAnalysis(baseFunc); + // analysis 1 + if (!foundBaseFunc) + { + funcAnalysis.setOverridden(baseFuncAnalysis); + baseFuncAnalysis.addDirectOverride(funcAnalysis); + } + // analysis 2 + if (visibleNonVirtual && isVisibleNonVirtual(baseFunc)) + { + baseFuncAnalysis.markNonVirtualOverride(); + } + foundBaseFunc = true; + } + } + baseCls = baseCls.getBaseClass(); + } + // analysis 2 + if (visibleNonVirtual && foundBaseFunc) + { + funcAnalysis.markNonVirtualOverride(); + } + } + + // analyze method body + final VeraBlock body = obj.getBody(); + if (body != null) + { + final int blockIndex = dadu.beginBlock(); + initFunctionDADU(obj, dadu); + BlockAnalysis blockAnalysis = analyzeBlock(body, obj, cls + .getCompilationUnit(), cls, isCtor, dadu); + dadu = blockAnalysis.dadu; + finalizeFunctionDADU(obj, dadu); + dadu.endBlock(blockIndex); + } + } + + private boolean isVisibleNonVirtual(VeraMemberFunction func) + { + return !func.isVirtual() + && func.getVisibility() != VeraVisibility.LOCAL; + } + + public void visit(VeraMemberVariable obj) + { + ++analyzer.fieldCount; + + // check member type ordering + assert (!gotCtor && !gotMethod); + + // create analysis object for this variable (to track context) + VariableAnalysis varAnalysis = analyzer.getOrCreateVariableAnalysis( + obj, cls); + if (obj.getVisibility() == VeraVisibility.LOCAL) + { + localVarAnalyses.add(varAnalysis); + } + + // initialize DA/DU tracking for variable + int daduIndex = dadu.alloc(obj); + + VeraExpression initExpr = obj.getInitializer(); + if (initExpr != null) + { + // analyze initializer + ExpressionAnalysis exprAnalysis = analyzeExpression(initExpr, + AccessType.READ, cls.getCompilationUnit(), cls, cls, null, dadu); + applyAssignAnalysis(varAnalysis, exprAnalysis); + + // mark variable as assigned after initializer + dadu.markAssigned(daduIndex); + + // track initialization as write access + varAnalysis.markWriteAccess(); + if (exprAnalysis.sideEffects) varAnalysis.markWriteSideEffects(); + } + else + { + // treat fixed and associative arrays as always assigned + VeraType type = obj.getType(); + if (type instanceof VeraFixedArrayType + || type instanceof VeraAssocArrayType) + { + dadu.markAssigned(daduIndex); + } + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/CompUnitMemberAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/CompUnitMemberAnalyzer.java new file mode 100644 index 0000000..c2552c0 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/CompUnitMemberAnalyzer.java @@ -0,0 +1,182 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Iterator; + +import com.newisys.langschema.vera.*; + +/** + * Schema analyzer for compilation unit member objects. + * + * @author Trevor Robinson + */ +final class CompUnitMemberAnalyzer + extends AnalyzerModule + implements VeraCompilationUnitMemberVisitor +{ + private final VeraCompilationUnit compUnit; + + public CompUnitMemberAnalyzer( + VeraSchemaAnalyzer analyzer, + VeraCompilationUnit compUnit) + { + super(analyzer); + this.compUnit = compUnit; + } + + public void visit(VeraBindVariable obj) + { + ++analyzer.bindCount; + analyzer.bindSignalCount += obj.getMembers().size(); + } + + public void visit(VeraEnumeration obj) + { + ++analyzer.enumCount; + } + + public void visit(VeraEnumerationElement obj) + { + // ignored + } + + public void visit(VeraExpressionDefine obj) + { + ++analyzer.exprDefineCount; + + DADUAnalysis dadu = new DADUAnalysis(); + initDefineDADU(obj, dadu); + VeraExpression expr = obj.getExpression(); + analyzeExpression(expr, AccessType.READ, compUnit, null, obj, null, + dadu); + } + + public void visit(VeraGlobalFunction obj) + { + ++analyzer.globalFuncCount; + + DADUAnalysis dadu = new DADUAnalysis(); + initFunctionDADU(obj, dadu); + BlockAnalysis blockAnalysis = analyzeBlock(obj.getBody(), obj, + compUnit, null, false, dadu); + dadu = blockAnalysis.dadu; + finalizeFunctionDADU(obj, dadu); + } + + public void visit(VeraGlobalVariable obj) + { + ++analyzer.globalVarCount; + assert (obj.getInitializer() == null); + } + + public void visit(VeraHDLFunction obj) + { + ++analyzer.hdlFuncCount; + } + + public void visit(VeraInterfaceType obj) + { + ++analyzer.interfaceCount; + analyzer.interfaceSignalCount += obj.getMembers().size(); + } + + public void visit(VeraPortType obj) + { + ++analyzer.portCount; + analyzer.portSignalCount += obj.getMembers().size(); + } + + public void visit(VeraProgram obj) + { + ++analyzer.programCount; + DADUAnalysis dadu = new DADUAnalysis(); + analyzeBlock(obj.getBlock(), obj, compUnit, null, false, dadu); + } + + public void visit(VeraRangeDefine obj) + { + ++analyzer.rangeDefineCount; + + DADUAnalysis dadu = new DADUAnalysis(); + initDefineDADU(obj, dadu); + VeraExpression from = obj.getRange().getFrom(); + analyzeExpression(from, AccessType.READ, compUnit, null, obj, null, + dadu); + VeraExpression to = obj.getRange().getTo(); + analyzeExpression(to, AccessType.READ, compUnit, null, obj, null, dadu); + } + + public void visit(VeraStatementDefine obj) + { + ++analyzer.stmtDefineCount; + + DADUAnalysis dadu = new DADUAnalysis(); + initDefineDADU(obj, dadu); + VeraStatement stmt = obj.getStatement(); + analyzeBlockMember(stmt, obj, compUnit, null, false, dadu); + } + + public void visit(VeraTypeDefine obj) + { + ++analyzer.typeDefineCount; + } + + public void visit(VeraUDFFunction obj) + { + ++analyzer.udfFuncCount; + } + + public void visit(VeraUserClass obj) + { + ++analyzer.classCount; + ClassAnalysis analysis = analyzer.getOrCreateClassAnalysis(obj); + ClassMemberAnalyzer cma = new ClassMemberAnalyzer(analyzer, obj, + analysis); + // process members in three passes: + // pass 0: variables + // pass 1: constructors + // pass 2: anything else + for (int pass = 0; pass <= 2; ++pass) + { + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraClassMember member = (VeraClassMember) iter.next(); + int objPass; + if (member instanceof VeraMemberVariable) + { + objPass = 0; + } + else if (member instanceof VeraMemberFunction + && ((VeraMemberFunction) member).isConstructor()) + { + objPass = 1; + } + else + { + objPass = 2; + } + if (pass == objPass) member.accept(cma); + } + + if (pass == 1) cma.ctorsComplete(); + } + cma.finalizeAnalysis(); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAllocator.java b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAllocator.java new file mode 100644 index 0000000..0461123 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAllocator.java @@ -0,0 +1,95 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.ArrayList; +import java.util.HashMap; + +import com.newisys.langschema.vera.VeraVariable; + +/** + * Maintains a mapping of variables to integer indices used to reference DA/DU + * state for each variable (by DADUState). The indices are maintained as a + * stack: As DA/DU analysis descends into nested block scopes, indices are + * sequentially allocated to each variable encountered. Upon leaving a block + * scope, all variables from the scope are popped from the top of the stack. + * + * @author Trevor Robinson + */ +final class DADUAllocator +{ + private static final int INITIAL_CAPACITY = 32; + + private final ArrayList varArray = new ArrayList( + INITIAL_CAPACITY); + private final HashMap varIndexMap = new HashMap( + INITIAL_CAPACITY); + + public int getNextIndex() + { + return varArray.size(); + } + + public void revertToNextIndex(final int index) + { + int size = varArray.size(); + assert (index <= size); + while (size > index) + { + --size; + VeraVariable var = varArray.remove(size); + varIndexMap.remove(var); + } + } + + public int alloc(final VeraVariable var) + { + int index = varArray.size(); + varArray.add(var); + varIndexMap.put(var, index); + return index; + } + + public VeraVariable getVariable(final int index) + { + return varArray.get(index); + } + + public int getIndex(final VeraVariable var) + { + final Integer indexObj = varIndexMap.get(var); + return indexObj != null ? indexObj.intValue() : -1; + } + + @Override + public String toString() + { + final int size = varArray.size(); + final StringBuffer buf = new StringBuffer(size * 20); + for (int index = 0; index < size; ++index) + { + if (index > 0) buf.append(", "); + buf.append(index); + buf.append(':'); + final VeraVariable var = getVariable(index); + + buf.append(var.getName()); + } + return buf.toString(); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAnalysis.java new file mode 100644 index 0000000..ea4c96d --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUAnalysis.java @@ -0,0 +1,165 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import com.newisys.langschema.vera.VeraVariable; + +/** + * Manages the current state of a DA/DU analysis. The class is simply a facade + * around a DADUAllocator and a DADUState. It provides both index-based and + * variable reference-based access to the DA/DU state, to optimize cases where + * the index is known by the caller, and to simplify cases where it is not. + * When the DA/DU analysis is split, to analyze a branch, only the DADUState is + * duplicated; the same DADUAllocator is used by both instances. + * + * @author Trevor Robinson + */ +final class DADUAnalysis +{ + private final DADUAllocator allocator; + private final DADUState state; + + public DADUAnalysis() + { + allocator = new DADUAllocator(); + state = new DADUState(); + } + + private DADUAnalysis(DADUAnalysis other) + { + allocator = other.allocator; + state = other.state.duplicate(); + } + + public DADUAnalysis duplicate() + { + return new DADUAnalysis(this); + } + + public void merge(final DADUAnalysis other) + { + assert (other.allocator == allocator); + state.merge(other.state); + } + + public int beginBlock() + { + return allocator.getNextIndex(); + } + + public void endBlock(int index) + { + int nextIndex = allocator.getNextIndex(); + if (index < nextIndex) + { + allocator.revertToNextIndex(index); + state.clear(index, nextIndex); + } + } + + public int alloc(final VeraVariable var) + { + final int index = allocator.alloc(var); + state.init(index); + return index; + } + + public int getIndex(final VeraVariable var) + { + return allocator.getIndex(var); + } + + public VeraVariable getVariable(final int index) + { + return allocator.getVariable(index); + } + + public int getNextIndex() + { + return allocator.getNextIndex(); + } + + public void markAssigned(final int index) + { + state.markAssigned(index); + } + + public void markAssigned(final VeraVariable var) + { + final int index = allocator.getIndex(var); + assert (index >= 0); + state.markAssigned(index); + } + + public void markDead() + { + state.markDead(0, allocator.getNextIndex()); + } + + public void clearDU(final DADUAnalysis other) + { + state.clearDU(other.state); + } + + public boolean containsDU() + { + return state.containsDU(0); + } + + public boolean isDA(final int index) + { + return state.isDA(index); + } + + public boolean isDA(final VeraVariable var) + { + final int index = allocator.getIndex(var); + assert (index >= 0); + return state.isDA(index); + } + + public boolean isDU(final int index) + { + return state.isDU(index); + } + + public boolean isDU(final VeraVariable var) + { + final int index = allocator.getIndex(var); + assert (index >= 0); + return state.isDU(index); + } + + public String toString() + { + final StringBuffer buf = new StringBuffer(80); + final int nextIndex = allocator.getNextIndex(); + for (int index = 0; index < nextIndex; ++index) + { + if (index > 0) buf.append(", "); + final VeraVariable var = allocator.getVariable(index); + final boolean isDA = state.isDA(index); + boolean isDU = state.isDU(index); + buf.append(var.getName()); + buf.append('['); + buf.append(isDA ? (isDU ? "DEAD" : "DA") : (isDU ? "DU" : "?")); + buf.append(']'); + } + return buf.toString(); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/DADUState.java b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUState.java new file mode 100644 index 0000000..50e7feb --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/DADUState.java @@ -0,0 +1,112 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.BitSet; + +/** + * Compactly represents the current state of a DA/DU analysis. The interface of + * this class is in terms of integer indexes assigned (by DADUAllocator) to + * each variable in the analysis. + * + * @author Trevor Robinson + */ +final class DADUState +{ + private final BitSet daBits; + private final BitSet duBits; + + public DADUState() + { + daBits = new BitSet(); + duBits = new BitSet(); + } + + private DADUState(DADUState other) + { + daBits = (BitSet) other.daBits.clone(); + duBits = (BitSet) other.duBits.clone(); + } + + public DADUState duplicate() + { + return new DADUState(this); + } + + public void merge(final DADUState other) + { + daBits.and(other.daBits); + duBits.and(other.duBits); + } + + public void init(final int index) + { + daBits.clear(index); + duBits.set(index); + } + + public void clear(final int fromIndex, final int toIndex) + { + daBits.clear(fromIndex, toIndex); + duBits.clear(fromIndex, toIndex); + } + + public void markAssigned(final int index) + { + daBits.set(index); + duBits.clear(index); + } + + public void markDead(final int fromIndex, final int toIndex) + { + daBits.set(fromIndex, toIndex); + duBits.set(fromIndex, toIndex); + } + + public void clearDU(final DADUState other) + { + duBits.andNot(other.duBits); + } + + public void assignDU(final DADUState other) + { + duBits.clear(); + duBits.or(other.duBits); + } + + public boolean containsDU(final int fromIndex) + { + return duBits.nextSetBit(fromIndex) >= 0; + } + + public boolean isDA(final int index) + { + return daBits.get(index); + } + + public boolean isDU(final int index) + { + return duBits.get(index); + } + + @Override + public String toString() + { + return "DA:" + daBits + ", DU:" + duBits; + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalysis.java new file mode 100644 index 0000000..b5ae767 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalysis.java @@ -0,0 +1,118 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import com.newisys.langschema.SchemaObject; +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraUserClass; +import com.newisys.langschema.vera.VeraVariable; + +/** + * Contains the analysis state for a particular expression. + * + * @author Trevor Robinson + */ +final class ExpressionAnalysis +{ + final VeraCompilationUnit compUnit; + final VeraUserClass cls; + final SchemaObject context; + final BlockAnalysis blockAnalysis; + + boolean referencesInstance; + boolean referencesLocalNonArg; + boolean byRefArgument; + boolean postIncDec; + boolean sideEffects; + DADUAnalysis daduUncond; + DADUAnalysis daduWhenTrue; + DADUAnalysis daduWhenFalse; + + XZSourceType uncondXZType; + Set xzPropagatesFrom; + + public ExpressionAnalysis( + VeraCompilationUnit compUnit, + VeraUserClass cls, + SchemaObject context, + BlockAnalysis blockAnalysis, + DADUAnalysis daduAnalysis) + { + this.compUnit = compUnit; + this.cls = cls; + this.context = context; + this.blockAnalysis = blockAnalysis; + this.daduUncond = daduAnalysis; + } + + public void addLocalAccess(VeraVariable var, boolean read, boolean write) + { + if (blockAnalysis != null) + { + blockAnalysis.addLocalAccess(var, read, write); + } + } + + public void splitDADU() + { + if (daduUncond != null) + { + daduWhenTrue = daduUncond; + daduWhenFalse = daduUncond.duplicate(); + daduUncond = null; + } + } + + public void mergeDADU() + { + if (daduWhenTrue != null) + { + daduUncond = daduWhenTrue; + daduUncond.merge(daduWhenFalse); + daduWhenTrue = daduWhenFalse = null; + } + } + + public boolean isUncondXZ() + { + return uncondXZType != null; + } + + public void markUncondXZ(XZSourceType xzSourceType) + { + uncondXZType = xzSourceType; + xzPropagatesFrom = null; + } + + public void addXZPropagatesFrom(VariableAnalysis var) + { + if (xzPropagatesFrom == null) + xzPropagatesFrom = new HashSet(); + xzPropagatesFrom.add(var); + } + + public Set getXZPropagatesFrom() + { + if (xzPropagatesFrom == null) return Collections.emptySet(); + return xzPropagatesFrom; + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalyzer.java new file mode 100644 index 0000000..aaecf3c --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/ExpressionAnalyzer.java @@ -0,0 +1,904 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.io.File; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import com.newisys.langschema.CompilationUnit; +import com.newisys.langschema.Function; +import com.newisys.langschema.StructuredTypeMember; +import com.newisys.langschema.vera.*; + +/** + * Schema analyzer for expression objects. + * + * @author Trevor Robinson + */ +final class ExpressionAnalyzer + extends AnalyzerModule + implements VeraExpressionVisitor +{ + private final ExpressionAnalysis analysis; + private final AccessType accessType; + private final boolean propagateXZ; + + public ExpressionAnalyzer( + VeraSchemaAnalyzer analyzer, + ExpressionAnalysis analysis, + AccessType accessType, + boolean propagateXZ) + { + super(analyzer); + this.analysis = analysis; + this.accessType = accessType; + this.propagateXZ = propagateXZ; + } + + private static final int ASSIGN_NONE = 0; + private static final int ASSIGN_FIRST = 1; + private static final int ASSIGN_OP_FIRST = 2; + private static final int ASSIGN_ALL = 3; + + private static final int XZ_NONE = 0; + private static final int XZ_FIRST = 1; + private static final int XZ_ALL = 2; + + private void analyzeOperation( + VeraOperation operation, + int assignType, + int xzPropType, + boolean leftToRight) + { + VeraExpression assignExpr = null; + final List operands = operation.getOperands(); + final int startIndex = leftToRight ? 0 : operands.size(); + final ListIterator iter = operands + .listIterator(startIndex); + while (leftToRight ? iter.hasNext() : iter.hasPrevious()) + { + final VeraExpression expr; + final boolean isFirst; + if (leftToRight) + { + isFirst = !iter.hasPrevious(); + expr = iter.next(); + } + else + { + expr = iter.previous(); + isFirst = !iter.hasPrevious(); + } + final AccessType nestedAccessType; + switch (assignType) + { + case ASSIGN_NONE: + nestedAccessType = AccessType.READ; + break; + case ASSIGN_FIRST: + nestedAccessType = isFirst ? AccessType.WRITE : AccessType.READ; + if (isFirst) assignExpr = expr; + break; + case ASSIGN_OP_FIRST: + nestedAccessType = isFirst ? AccessType.READ_WRITE + : AccessType.READ; + if (isFirst) assignExpr = expr; + break; + case ASSIGN_ALL: + nestedAccessType = AccessType.WRITE; + break; + default: + throw new Error("Invalid access type"); + } + final boolean nestedPropagateXZ = propagateXZ + && nestedAccessType == AccessType.READ + && (xzPropType == XZ_ALL || (xzPropType == XZ_FIRST && isFirst)); + analyzeNestedExpression(expr, analysis, nestedAccessType, + nestedPropagateXZ); + } + if (assignExpr != null) + { + applyAssignAnalysis(assignExpr, analysis); + } + } + + public void visit(VeraAdd obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraAndReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraArithmeticNegative obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraArrayAccess obj) + { + // treat bit writes as read/writes + VeraExpression arrayExpr = obj.getArray(); + boolean bitAccess = arrayExpr.getResultType() instanceof VeraBitVectorType; + analyzeNestedExpression(arrayExpr, analysis, bitAccess ? AccessType + .getInstance(true, accessType.isWrite()) : AccessType.READ, false); + + Iterator iter = obj.getIndices().iterator(); + while (iter.hasNext()) + { + VeraExpression indexExpr = (VeraExpression) iter.next(); + analyzeNestedExpression(indexExpr, analysis, AccessType.READ, false); + } + + // update X/Z propagation analysis + if (propagateXZ) + { + analysis.markUncondXZ(XZSourceType.ARRAY); + } + } + + public void visit(VeraArrayCreation obj) + { + VeraExpression sizeExpr = obj.getSizeExpr(); + analyzeNestedExpression(sizeExpr, analysis, AccessType.READ, false); + + VeraExpression srcExpr = obj.getSourceExpr(); + if (srcExpr != null) + { + analyzeNestedExpression(srcExpr, analysis, AccessType.READ, false); + } + } + + public void visit(VeraArrayInitializer obj) + { + Iterator iter = obj.getElements().iterator(); + while (iter.hasNext()) + { + VeraExpression elemExpr = (VeraExpression) iter.next(); + analyzeNestedExpression(elemExpr, analysis, AccessType.READ, false); + } + } + + public void visit(VeraAssign obj) + { + analyzeOperation(obj, ASSIGN_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignAdd obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignAnd obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignAndNot obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignDivide obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignLeftShift obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignModulo obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignMultiply obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignOr obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignOrNot obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignRightShift obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignSubtract obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignXor obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraAssignXorNot obj) + { + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_ALL, false); + } + + public void visit(VeraBitSliceAccess obj) + { + // treat bit slice writes as read/writes + VeraExpression arrayExpr = obj.getArray(); + analyzeNestedExpression(arrayExpr, analysis, AccessType.getInstance( + true, accessType.isWrite()), propagateXZ); + + VeraRange range = obj.getRange(); + + VeraExpression highExpr = range.getFrom(); + analyzeNestedExpression(highExpr, analysis, AccessType.READ, false); + + VeraExpression lowExpr = range.getTo(); + analyzeNestedExpression(lowExpr, analysis, AccessType.READ, false); + } + + public void visit(VeraBitVectorLiteral obj) + { + // update X/Z propagation analysis + if (propagateXZ && obj.getValue().containsXZ()) + { + analysis.markUncondXZ(XZSourceType.LITERAL); + } + } + + public void visit(VeraBitwiseAnd obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseAndNot obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseNegative obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseOr obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseOrNot obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseReverse obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseXor obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraBitwiseXorNot obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraConcatenation obj) + { + analyzeOperation(obj, accessType.isWrite() ? ASSIGN_ALL : ASSIGN_NONE, + XZ_ALL, true); + } + + public void visit(VeraConditional obj) + { + VeraExpression condExpr = obj.getOperand(0); + analyzeNestedCondition(condExpr, analysis, AccessType.READ, false); + + DADUAnalysis daduBeforeElse = analysis.daduWhenFalse; + analysis.daduUncond = analysis.daduWhenTrue; + + VeraExpression trueExpr = obj.getOperand(1); + VeraExpression falseExpr = obj.getOperand(2); + if (trueExpr.getResultType().isIntegralConvertible() + && falseExpr.getResultType().isIntegralConvertible()) + { + analyzeNestedCondition(trueExpr, analysis, AccessType.READ, + propagateXZ); + + DADUAnalysis daduAfterThenWhenTrue = analysis.daduWhenTrue + .duplicate(); + DADUAnalysis daduAfterThenWhenFalse = analysis.daduWhenFalse + .duplicate(); + analysis.daduUncond = daduBeforeElse; + + analyzeNestedCondition(falseExpr, analysis, AccessType.READ, + propagateXZ); + + analysis.daduWhenTrue.merge(daduAfterThenWhenTrue); + analysis.daduWhenFalse.merge(daduAfterThenWhenFalse); + } + else + { + analyzeNestedExpression(trueExpr, analysis, AccessType.READ, + propagateXZ); + + DADUAnalysis daduAfterThen = analysis.daduUncond.duplicate(); + analysis.daduUncond = daduBeforeElse; + + analyzeNestedExpression(falseExpr, analysis, AccessType.READ, + propagateXZ); + + analysis.daduUncond.merge(daduAfterThen); + } + } + + public void visit(VeraConstraintSet obj) + { + // ignored for current analyses + } + + public void visit(VeraCopyCreation obj) + { + analysis.sideEffects = true; + + VeraExpression srcExpr = obj.getSource(); + if (srcExpr != null) + { + analyzeNestedExpression(srcExpr, analysis, AccessType.READ, false); + } + } + + public void visit(VeraDepthAccess obj) + { + VeraExpression signalExpr = obj.getSignal(); + analyzeNestedExpression(signalExpr, analysis, AccessType.READ, false); + } + + public void visit(VeraDistSet obj) + { + // ignored for current analyses + } + + public void visit(VeraDivide obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_FIRST, true); + } + + public void visit(VeraEnumValueReference obj) + { + // do nothing + } + + public void visit(VeraEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraExactEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraExactNotEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraFunctionInvocation obj) + { + analysis.sideEffects = true; + + VeraExpression funcExpr = obj.getFunction(); + analyzeNestedExpression(funcExpr, analysis, AccessType.READ, false); + + final VeraFunction func; + boolean inlinedFunc = false; + VeraVariable thisVar = null; + VariableAnalysis thisVarAnalysis = null; + boolean thisWrite = false; + if (funcExpr instanceof VeraFunctionReference) + { + VeraFunctionReference funcRef = (VeraFunctionReference) funcExpr; + func = funcRef.getFunction(); + String funcName = func.getName().getCanonicalName(); + if (funcName.equals("cast_assign") + || funcName.equals("assoc_index") || funcName.equals("sprintf")) + { + inlinedFunc = true; + } + } + else + { + assert (funcExpr instanceof VeraMemberAccess); + VeraMemberAccess memberExpr = (VeraMemberAccess) funcExpr; + StructuredTypeMember member = memberExpr.getMember(); + assert (member instanceof VeraMemberFunction); + func = (VeraMemberFunction) member; + + final VeraExpression thisExpr = memberExpr.getObject(); + final VeraType thisType = thisExpr.getResultType(); + if (thisType instanceof VeraStringType) + { + thisVar = getReferencedVariable(thisExpr); + thisVarAnalysis = analyzer.getOrCreateVariableAnalysis(thisVar, + null); + final String funcID = func.getName().getIdentifier(); + + if (funcID.startsWith("get_status") + || funcID.equals("prematch") || funcID.equals("postmatch") + || funcID.equals("thismatch") || funcID.equals("backref")) + { + thisVarAnalysis.markReadStringState(analyzer); + } + else if (funcID.equals("putc") || funcID.equals("match")) + { + thisVarAnalysis.markWriteStringState(analyzer); + } + + if (funcID.equals("putc") || funcID.equals("itoa") + || funcID.equals("bittostr")) + { + thisWrite = true; + } + } + } + + List actualArgs = obj.getArguments(); + analyzeInvokeArgs(actualArgs, func, analysis, propagateXZ, inlinedFunc); + + if (thisWrite) + { + processVarAccess(thisVar, thisVarAnalysis, false, true); + } + } + + public void visit(VeraFunctionReference obj) + { + Function func = obj.getFunction(); + if (func instanceof VeraMemberFunction) + { + analysis.referencesInstance = true; + } + } + + public void visit(VeraGreater obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraGreaterOrEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraIfElseConstraint obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraImplicationConstraint obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraInSet obj) + { + // ignored for current analyses + } + + public void visit(VeraInstanceCreation obj) + { + analysis.sideEffects = true; + + List actualArgs = obj.getArguments(); + if (actualArgs.size() > 0) + { + VeraClass cls = (VeraClass) obj.getType(); + Iterator iter = cls.lookupObjects("new", VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + VeraFunction func = (VeraFunction) iter.next(); + assert (!iter.hasNext()) : "Multiple new() tasks found"; + analyzeInvokeArgs(actualArgs, func, analysis, false, false); + } + else + { + assert false : "new() task not found"; + } + } + } + + public void visit(VeraIntegerLiteral obj) + { + // do nothing + } + + public void visit(VeraInterfaceReference obj) + { + // do nothing + } + + public void visit(VeraLeftShift obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_FIRST, true); + } + + public void visit(VeraLess obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraLessOrEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraLogicalAnd obj) + { + VeraExpression lhsExpr = obj.getOperand(0); + analyzeNestedCondition(lhsExpr, analysis, AccessType.READ, false); + + DADUAnalysis daduWhenFalseLHS = analysis.daduWhenFalse; + analysis.daduUncond = analysis.daduWhenTrue; + + VeraExpression rhsExpr = obj.getOperand(1); + analyzeNestedCondition(rhsExpr, analysis, AccessType.READ, false); + + analysis.daduWhenFalse.merge(daduWhenFalseLHS); + } + + public void visit(VeraLogicalNegative obj) + { + VeraExpression expr = obj.getOperand(0); + analyzeNestedCondition(expr, analysis, AccessType.READ, propagateXZ); + + DADUAnalysis swapTemp = analysis.daduWhenTrue; + analysis.daduWhenTrue = analysis.daduWhenFalse; + analysis.daduWhenFalse = swapTemp; + } + + public void visit(VeraLogicalOr obj) + { + VeraExpression lhsExpr = obj.getOperand(0); + analyzeNestedCondition(lhsExpr, analysis, AccessType.READ, false); + + DADUAnalysis daduWhenTrueLHS = analysis.daduWhenTrue; + analysis.daduUncond = analysis.daduWhenFalse; + + VeraExpression rhsExpr = obj.getOperand(1); + analyzeNestedCondition(rhsExpr, analysis, AccessType.READ, false); + + analysis.daduWhenTrue.merge(daduWhenTrueLHS); + } + + public void visit(VeraMemberAccess obj) + { + VeraExpression objExpr = obj.getObject(); + analyzeNestedExpression(objExpr, analysis, AccessType.READ, false); + + StructuredTypeMember member = obj.getMember(); + if (member instanceof VeraMemberVariable) + { + VeraMemberVariable memberVar = (VeraMemberVariable) member; + processVarAccess(memberVar, accessType.isRead(), accessType + .isWrite()); + } + else if (propagateXZ + && (member instanceof VeraInterfaceSignal || member instanceof VeraPortSignal)) + { + analysis.markUncondXZ(XZSourceType.SIGNAL); + } + } + + private boolean sameDir(String path1, String path2) + { + File f1 = new File(path1); + File f2 = new File(path2); + return f1.getParentFile().equals(f2.getParentFile()); + } + + public void visit(VeraModulo obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_FIRST, true); + } + + public void visit(VeraMultiply obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraNotAndReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraNotEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraNotInSet obj) + { + // ignored for current analyses + } + + public void visit(VeraNotOrReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraNotXorReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraNullLiteral obj) + { + // do nothing + } + + public void visit(VeraOrReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraPostDecrement obj) + { + analysis.postIncDec = true; + analysis.sideEffects = true; + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_NONE, true); + } + + public void visit(VeraPostIncrement obj) + { + analysis.postIncDec = true; + analysis.sideEffects = true; + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_NONE, true); + } + + public void visit(VeraPreDecrement obj) + { + analysis.sideEffects = true; + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_NONE, true); + } + + public void visit(VeraPreIncrement obj) + { + analysis.sideEffects = true; + analyzeOperation(obj, ASSIGN_OP_FIRST, XZ_NONE, true); + } + + public void visit(VeraReplication obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraRightShift obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_FIRST, true); + } + + public void visit(VeraSignalReference obj) + { + // update X/Z propagation analysis + if (propagateXZ) + { + analysis.markUncondXZ(XZSourceType.SIGNAL); + } + } + + public void visit(VeraStringLiteral obj) + { + // do nothing + } + + public void visit(VeraSubtract obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } + + public void visit(VeraSuperReference obj) + { + analysis.referencesInstance = true; + } + + public void visit(VeraSystemClockReference obj) + { + // do nothing + } + + public void visit(VeraThisReference obj) + { + analysis.referencesInstance = true; + } + + public void visit(VeraVariableReference obj) + { + final VeraVariable var = obj.getVariable(); + final boolean isRead = accessType.isRead(); + final boolean isWrite = accessType.isWrite(); + + // track variable references in block + analysis.addLocalAccess(var, isRead, isWrite); + + // update expression reference modes analysis + if (var instanceof VeraMemberVariable) + { + if (!var.getModifiers().contains(VeraVariableModifier.STATIC)) + { + analysis.referencesInstance = true; + } + } + else if (var instanceof VeraLocalVariable) + { + analysis.referencesLocalNonArg = true; + } + + processVarAccess(var, isRead, isWrite); + } + + private void processVarAccess( + final VeraVariable var, + final boolean isRead, + final boolean isWrite) + { + VariableAnalysis varAnalysis = analyzer.getOrCreateVariableAnalysis( + var, null); + processVarAccess(var, varAnalysis, isRead, isWrite); + } + + private void processVarAccess( + final VeraVariable var, + final VariableAnalysis varAnalysis, + final boolean isRead, + final boolean isWrite) + { + // required visibility analysis for fields and globals + CompilationUnit varCompUnit = null; + if (var instanceof VeraMemberVariable) + { + VeraMemberVariable memberVar = (VeraMemberVariable) var; + VeraUserClass varCls = (VeraUserClass) memberVar + .getStructuredType(); + boolean inCtor; + if (varCls != analysis.cls) + { + // isSuperclassOf(null) returns false + if (!varCls.isSuperclassOf(analysis.cls)) + { + varAnalysis.markFieldAccessOutsideSubClass(); + } + else + { + varAnalysis.markFieldAccessOutsideClass(); + } + + varCompUnit = varCls.getCompilationUnit(); + inCtor = false; + } + else + { + inCtor = analysis.context instanceof VeraMemberFunction + && ((VeraMemberFunction) analysis.context).isConstructor(); + } + if (isWrite && !inCtor) + { + varAnalysis.markFieldWriteOutsideCtor(); + } + } + else if (var instanceof VeraCompilationUnitMember) + { + VeraCompilationUnitMember member = (VeraCompilationUnitMember) var; + varCompUnit = member.getCompilationUnit(); + } + if (varCompUnit != null) + { + String varSrcPath = varCompUnit.getSourcePath(); + String srcPath = analysis.compUnit.getSourcePath(); + if (!sameDir(varSrcPath, srcPath)) + { + varAnalysis.markFieldAccessOutsideDirectory(); + } + } + + // update unread/unwritten variable analysis + if (isRead) + { + varAnalysis.markReadAccess(); + } + if (isWrite) + { + varAnalysis.markWriteAccess(); + } + + // update variable DA/DU analysis + final DADUAnalysis dadu = analysis.daduUncond; + final int varIndex = dadu.getIndex(var); + final boolean daduTracked = varIndex >= 0; + if (daduTracked) + { + if (isRead) + { + if (!dadu.isDA(varIndex)) + { + varAnalysis.markReadUnassigned(); + + if (!varAnalysis.isXZKnown()) + { + varAnalysis.markAssignedXZ(XZSourceType.UNINIT, null); + } + } + } + if (isWrite) + { + if (!dadu.isDU(varIndex)) + { + varAnalysis.markWriteAssigned(); + } + dadu.markAssigned(varIndex); + } + } + else + { + assert ((var instanceof VeraMemberVariable && ((VeraMemberVariable) var) + .getStructuredType() != analysis.cls) + || var instanceof VeraGlobalVariable || var instanceof VeraBindVariable); + } + + // update X/Z propagation analysis + if (propagateXZ) + { + analysis.addXZPropagatesFrom(varAnalysis); + } + } + + public void visit(VeraVoidLiteral obj) + { + // do nothing + } + + public void visit(VeraWildEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraWildNotEqual obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_NONE, true); + } + + public void visit(VeraXorReduction obj) + { + analyzeOperation(obj, ASSIGN_NONE, XZ_ALL, true); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/FunctionAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/FunctionAnalysis.java new file mode 100644 index 0000000..856e3c3 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/FunctionAnalysis.java @@ -0,0 +1,138 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.HashSet; +import java.util.Set; + +import com.newisys.langschema.vera.VeraFunction; + +/** + * Contains the analysis state for a particular function. + * + * @author Trevor Robinson + */ +public final class FunctionAnalysis +{ + final VeraSchemaAnalyzer analyzer; + final VeraFunction func; + + private FunctionAnalysis overridden; + private final Set directOverrides = new HashSet(); + private boolean returnXZInOverride; + private final boolean[] argXZInOverride; + private final boolean[] argStatefulStringInOverride; + private boolean nonVirtualOverride; // involved in non-virtual overriding + private boolean varArgsWaitVarAlias; // var args alias wait_var target + + public FunctionAnalysis(VeraSchemaAnalyzer analyzer, VeraFunction func) + { + this.analyzer = analyzer; + this.func = func; + final int argCount = func.getType().getArguments().size(); + argXZInOverride = new boolean[argCount]; + argStatefulStringInOverride = new boolean[argCount]; + } + + public int getArgumentCount() + { + return argXZInOverride.length; + } + + public FunctionAnalysis getOverridden() + { + return overridden; + } + + void setOverridden(FunctionAnalysis overridden) + { + this.overridden = overridden; + } + + public Set getDirectOverrides() + { + return directOverrides; + } + + void addDirectOverride(FunctionAnalysis func) + { + directOverrides.add(func); + } + + public boolean isReturnXZInOverride() + { + return returnXZInOverride; + } + + void setReturnXZInOverride(boolean returnXZInOverride) + { + this.returnXZInOverride = returnXZInOverride; + } + + public boolean isArgumentXZInOverride(int index) + { + return argXZInOverride[index]; + } + + void setArgumentXZInOverride(int index, boolean value) + { + this.argXZInOverride[index] = value; + } + + public boolean isArgumentStatefulStringInOverride(int index) + { + return argStatefulStringInOverride[index]; + } + + void setArgumentStatefulStringInOverride(int index, boolean value) + { + this.argStatefulStringInOverride[index] = value; + } + + public boolean isNonVirtualOverride() + { + return nonVirtualOverride; + } + + void markNonVirtualOverride() + { + if (!nonVirtualOverride) + { + analyzer.log.println("Function involved in non-virtual override: " + + func.getName()); + + nonVirtualOverride = true; + } + } + + public boolean isVarArgsWaitVarAlias() + { + return varArgsWaitVarAlias; + } + + void markVarArgsWaitVarAlias() + { + if (!varArgsWaitVarAlias) + { + analyzer.log.println("By-ref var-args alias wait_var target: " + + func.getName()); + + varArgsWaitVarAlias = true; + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/SchemaMemberAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/SchemaMemberAnalyzer.java new file mode 100644 index 0000000..26cb622 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/SchemaMemberAnalyzer.java @@ -0,0 +1,58 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.Iterator; + +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraCompilationUnitMember; +import com.newisys.langschema.vera.VeraGlobalFunction; +import com.newisys.langschema.vera.VeraSchemaMemberVisitor; + +/** + * Schema analyzer for top-level schema member objects (which includes only + * compilation units). + * + * @author Trevor Robinson + */ +final class SchemaMemberAnalyzer + extends AnalyzerModule + implements VeraSchemaMemberVisitor +{ + public SchemaMemberAnalyzer(VeraSchemaAnalyzer analyzer) + { + super(analyzer); + } + + public void visit(VeraCompilationUnit obj) + { + CompUnitMemberAnalyzer cuma = new CompUnitMemberAnalyzer(analyzer, obj); + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraCompilationUnitMember member = (VeraCompilationUnitMember) iter + .next(); + member.accept(cuma); + } + } + + public void visit(VeraGlobalFunction obj) + { + // ignore built-in functions + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/VariableAnalysis.java b/java/juno/src/com/newisys/schemaanalyzer/juno/VariableAnalysis.java new file mode 100644 index 0000000..55763cd --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/VariableAnalysis.java @@ -0,0 +1,762 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.newisys.io.IndentWriter; +import com.newisys.langschema.SchemaObject; +import com.newisys.langschema.Type; +import com.newisys.langschema.vera.VeraBitType; +import com.newisys.langschema.vera.VeraBitVectorType; +import com.newisys.langschema.vera.VeraFunction; +import com.newisys.langschema.vera.VeraFunctionArgument; +import com.newisys.langschema.vera.VeraIntegerType; +import com.newisys.langschema.vera.VeraSchemaObject; +import com.newisys.langschema.vera.VeraVariable; + +/** + * Contains the analysis state for a particular variable. + * + * @author Trevor Robinson + */ +public final class VariableAnalysis +{ + final VeraVariable var; + SchemaObject context; + + // indicates that all possible accesses have been seen + private boolean scopeComplete; + + // read/write usage analysis: + private boolean readAccess; // accessed for read + private boolean writeAccess; // accessed for write (including init) + private boolean writeSideEffects; // write/init expr has side effects + private boolean readUnassigned; // read when unassigned (X value observed) + private boolean writeAssigned; // written when assigned (not final) + + // X/Z analysis: + private final boolean xzType; + private boolean assignedXZ; // definitely assigned X/Z + private boolean notAssignedXZ; // definitely NOT assigned X/Z + private Set xzPropagatesFrom; // Set of VariableAnalysis + private Set xzPropagatesTo; // Set of VariableAnalysis + private XZSourceType xzSourceType; + private VariableAnalysis xzSource; + private Set xzDests; // Set of VariableAnalysis + + // string analysis: + private boolean readStringState; // get_status[_msg], (pre|post|this)match, backref + private boolean writeStringState; // putc, match + + // field usage analysis: + private boolean fieldAccessOutsideClass; // cannot be private + private boolean fieldAccessOutsideSubClass; // cannot be protected + private boolean fieldAccessOutsideDirectory; // cannot be default access + private boolean fieldUnassignedInCtor; // cannot be final + private boolean fieldWriteOutsideCtor; // cannot be final + + // by-ref argument usage: + private Set byRefArgUses; // arguments this variable is passed by-ref to + private Set byRefArgVars; // variables passed by-ref to this argument + private boolean passedByRefNVA; // passed by-ref to non-var-arg + + // fork usage: + private boolean forkRead; // read by forked thread + private boolean forkWrite; // written by forked thread + + // wait_var analysis: + private boolean waitVar; // target of wait_var + private boolean waitVarAlias; // by-ref argument alias of wait_var target + + private static final boolean debug = false; + private static final IndentWriter iw; + private static final PrintWriter pw; + static + { + if (debug) + { + final FileWriter fw; + try + { + fw = new FileWriter("var-analysis.log"); + } + catch (IOException e) + { + throw new Error(e); + } + iw = new IndentWriter(fw); + pw = new PrintWriter(iw, true); + } + else + { + iw = null; + pw = null; + } + } + + public VariableAnalysis(VeraVariable var, SchemaObject context) + { + this.var = var; + this.context = context; + + // immediately mark non-bit/integer variables as not X/Z + xzType = isXZType(var.getType()); + notAssignedXZ = !xzType; + } + + private boolean isXZType(Type type) + { + return type instanceof VeraBitType || type instanceof VeraBitVectorType + || type instanceof VeraIntegerType; + } + + private void dumpName(StringBuffer msg) + { + msg.append(var.getName().getIdentifier()); + if (context != null) + { + msg.append(" (in "); + msg.append(AnalyzerModule.getDescription(context)); + msg.append(")"); + } + } + + public boolean isScopeComplete() + { + return scopeComplete; + } + + void markScopeComplete() + { + if (debug) pw.println("markScopeComplete: " + this); + if (debug) iw.incIndent(); + + scopeComplete = true; + + checkClosure(); + + if (debug) iw.decIndent(); + } + + private void checkClosure() + { + if (!isXZKnown() && isXZPropagationClosed()) + { + markNotAssignedXZ(); + } + } + + private boolean checkingXZClosure; + + private boolean isXZPropagationClosed() + { + if (debug) pw.println("isXZPropagationClosed: " + this); + if (debug) iw.incIndent(); + + boolean closed = true; + + if (xzPropagatesFrom != null) + { + checkingXZClosure = true; + + Iterator iter = xzPropagatesFrom.iterator(); + while (iter.hasNext()) + { + VariableAnalysis other = (VariableAnalysis) iter.next(); + if (!other.scopeComplete + || (!other.checkingXZClosure && !other + .isXZPropagationClosed())) + { + if (debug) pw.println("not closed due to: " + other); + closed = false; + break; + } + } + + checkingXZClosure = false; + } + + if (debug) iw.decIndent(); + + return closed; + } + + public boolean isReadAccess() + { + return readAccess; + } + + void markReadAccess() + { + readAccess = true; + } + + public boolean isWriteAccess() + { + return writeAccess; + } + + void markWriteAccess() + { + writeAccess = true; + } + + public boolean isWriteSideEffects() + { + return writeSideEffects; + } + + void markWriteSideEffects() + { + writeSideEffects = true; + } + + public boolean isReadUnassigned() + { + return readUnassigned; + } + + void markReadUnassigned() + { + readUnassigned = true; + } + + public boolean isWriteAssigned() + { + return writeAssigned; + } + + void markWriteAssigned() + { + writeAssigned = true; + } + + public boolean isXZType() + { + return xzType; + } + + public boolean isAssignedXZ() + { + return assignedXZ; + } + + void markAssignedXZ(XZSourceType xzSourceType, VariableAnalysis xzSource) + { + if (debug) pw.println("markAssignedXZ: " + this); + if (debug) iw.incIndent(); + + assert (!isXZKnown()); + assignedXZ = true; + this.xzSourceType = xzSourceType; + this.xzSource = xzSource; + if (xzSource != null) xzSource.addXZDestination(this); + + // propagate X/Z assignment to linked variables + if (xzPropagatesTo != null) + { + // get iterator for current propagates-to list + Iterator iter = xzPropagatesTo.iterator(); + + // clear propagates-to list before recursion, for two reasons: + // a) in case circularites exist + // b) so linked variables will not modify our propagates-to list + xzPropagatesTo = null; + + // recursively propagate X/Z assignment + while (iter.hasNext()) + { + VariableAnalysis other = (VariableAnalysis) iter.next(); + if (!other.isXZKnown()) + { + other.markAssignedXZ(XZSourceType.ASSIGNMENT, this); + } + } + } + + clearXZPropagatesFrom(); + + if (debug) iw.decIndent(); + } + + public boolean isNotAssignedXZ() + { + return notAssignedXZ; + } + + void markNotAssignedXZ() + { + if (debug) pw.println("markNotAssignedXZ: " + this); + if (debug) iw.incIndent(); + + assert (!isXZKnown()); + notAssignedXZ = true; + + // remove self from other propagates-from lists + if (xzPropagatesTo != null) + { + Iterator iter = xzPropagatesTo.iterator(); + xzPropagatesTo = null; + while (iter.hasNext()) + { + VariableAnalysis other = (VariableAnalysis) iter.next(); + if (debug) + pw.println("removing dependency: " + other + " <- " + this); + + // propagates-from list might not exist for this dependency + // because it was marked not X/Z in determining the closure + // of a previous dependency + if (other.xzPropagatesFrom != null) + { + boolean removed = other.xzPropagatesFrom.remove(this); + assert (removed); + if (other.scopeComplete) other.checkClosure(); + } + } + } + + clearXZPropagatesFrom(); + + if (debug) iw.decIndent(); + } + + public boolean isXZKnown() + { + return assignedXZ || notAssignedXZ; + } + + public XZSourceType getXZSourceType() + { + return xzSourceType; + } + + public VariableAnalysis getXZSource() + { + return xzSource; + } + + public Set getXZDestinations() + { + return xzDests != null ? xzDests : Collections.EMPTY_SET; + } + + private void addXZDestination(VariableAnalysis dest) + { + if (xzDests == null) xzDests = new LinkedHashSet(); + xzDests.add(dest); + } + + void trackXZPropagation(VariableAnalysis from) + { + // ignore self-assignment + if (!isXZKnown() && from != this) + { + if (from.assignedXZ) + { + markAssignedXZ(XZSourceType.ASSIGNMENT, from); + } + else if (!from.notAssignedXZ) + { + if (debug) + pw.println("adding dependency: " + this + " <- " + from); + this.addXZPropagatesFrom(from); + from.addXZPropagatesTo(this); + } + } + } + + private void addXZPropagatesFrom(VariableAnalysis var) + { + // X/Z propagation need not be tracked when X/Z condition is known + assert (!isXZKnown()); + + if (xzPropagatesFrom == null) + xzPropagatesFrom = new HashSet(); + xzPropagatesFrom.add(var); + } + + private void clearXZPropagatesFrom() + { + // remove self from other propagates-to lists + if (xzPropagatesFrom != null) + { + Iterator iter = xzPropagatesFrom.iterator(); + xzPropagatesFrom = null; + while (iter.hasNext()) + { + VariableAnalysis other = (VariableAnalysis) iter.next(); + if (debug) + pw.println("removing dependency: " + this + " <- " + other); + + // propagates-to list will not exist for variables currently + // propagating to this variable + if (other.xzPropagatesTo != null) + { + // however, if the propagates-to list does exist, + // check that it maintains from/to propagation pairing + boolean removed = other.xzPropagatesTo.remove(this); + assert (removed); + } + } + } + } + + private void addXZPropagatesTo(VariableAnalysis var) + { + // X/Z propagation need not be tracked when X/Z condition is known + assert (!isXZKnown()); + + if (xzPropagatesTo == null) + xzPropagatesTo = new HashSet(); + xzPropagatesTo.add(var); + } + + public boolean isReadStringState() + { + return readStringState; + } + + void markReadStringState(VeraSchemaAnalyzer analyzer) + { + if (!readStringState) + { + readStringState = true; + markStringStateVars(analyzer, true, false); + } + } + + public boolean isWriteStringState() + { + return writeStringState; + } + + void markWriteStringState(VeraSchemaAnalyzer analyzer) + { + if (!writeStringState) + { + writeStringState = true; + markStringStateVars(analyzer, false, true); + } + } + + private void markStringStateVars( + VeraSchemaAnalyzer analyzer, + boolean read, + boolean write) + { + // mark any variables found so far that are aliased by this argument + if (byRefArgVars != null) + { + for (VeraVariable var : byRefArgVars) + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(var); + // only analyzed variables can be put in byRefArgVars + assert (varAnalysis != null); + if (read) varAnalysis.markReadStringState(analyzer); + if (write) varAnalysis.markWriteStringState(analyzer); + } + } + + // mark any by-ref arguments found so far that receive this variable + if (byRefArgUses != null) + { + for (Object obj : byRefArgUses) + { + if (obj instanceof VeraFunctionArgument) + { + VeraFunctionArgument arg = (VeraFunctionArgument) obj; + VariableAnalysis argAnalysis = analyzer + .getOrCreateVariableAnalysis(arg, arg.getFunction()); + if (read) argAnalysis.markReadStringState(analyzer); + if (write) argAnalysis.markWriteStringState(analyzer); + } + else + { + // ignore by-ref var-args uses + } + } + } + } + + public boolean isNeedStatefulString() + { + return (readStringState && writeStringState) || waitVar || waitVarAlias; + } + + public boolean isFieldAccessOutsideClass() + { + return fieldAccessOutsideClass; + } + + void markFieldAccessOutsideClass() + { + fieldAccessOutsideClass = true; + } + + public boolean isFieldAccessOutsideSubClass() + { + return fieldAccessOutsideSubClass; + } + + void markFieldAccessOutsideSubClass() + { + fieldAccessOutsideClass = true; + fieldAccessOutsideSubClass = true; + } + + public boolean isFieldAccessOutsideDirectory() + { + return fieldAccessOutsideDirectory; + } + + void markFieldAccessOutsideDirectory() + { + fieldAccessOutsideClass = true; + fieldAccessOutsideDirectory = true; + } + + public boolean isFieldUnassignedInCtor() + { + return fieldUnassignedInCtor; + } + + void markFieldUnassignedInCtor() + { + fieldUnassignedInCtor = true; + } + + public boolean isFieldWriteOutsideCtor() + { + return fieldWriteOutsideCtor; + } + + void markFieldWriteOutsideCtor() + { + fieldWriteOutsideCtor = true; + } + + public boolean isPassedByRef() + { + return byRefArgUses != null; + } + + public boolean isPassedByRefNVA() + { + return passedByRefNVA; + } + + public Set getByRefArgUses() + { + return (byRefArgUses != null) ? byRefArgUses : Collections.EMPTY_SET; + } + + void addByRefArgUse(VeraFunctionArgument arg, VeraSchemaAnalyzer analyzer) + { + // add the given argument to the set of by-ref arguments that alias + // this variable + if (byRefArgUses == null) + { + byRefArgUses = new HashSet(); + } + byRefArgUses.add(arg); + passedByRefNVA = true; + + // add this variable to the set of variables the given argument aliases + VariableAnalysis argAnalysis = analyzer.getOrCreateVariableAnalysis( + arg, arg.getFunction()); + argAnalysis.addByRefArgVar(var); + + // if this variable is a wait_var target or alias, + // mark the argument as a wait_var alias + if (waitVarAlias) + { + argAnalysis.markWaitVarAlias(analyzer); + } + + // if the argument is a wait_var target, + // mark this variable as a wait_var target + if (argAnalysis.isWaitVar()) + { + markWaitVar(analyzer); + } + + // propagate read/write string state analysis to argument + if (readStringState) argAnalysis.markReadStringState(analyzer); + if (writeStringState) argAnalysis.markWriteStringState(analyzer); + } + + void addByRefVarArgUse(VeraFunction func, VeraSchemaAnalyzer analyzer) + { + if (byRefArgUses == null) + { + byRefArgUses = new HashSet(); + } + byRefArgUses.add(func); + + // if this variable is a wait_var target or alias, + // mark the function as having wait_var alias var-args + FunctionAnalysis funcAnalysis = analyzer + .getOrCreateFunctionAnalysis(func); + if (waitVarAlias) + { + funcAnalysis.markVarArgsWaitVarAlias(); + } + } + + public Set getByRefArgVars() + { + return (byRefArgVars != null) ? byRefArgVars : Collections.EMPTY_SET; + } + + private void addByRefArgVar(VeraVariable var) + { + if (byRefArgVars == null) + { + byRefArgVars = new HashSet(); + } + byRefArgVars.add(var); + } + + public boolean isForkRead() + { + return forkRead; + } + + void markForkRead() + { + forkRead = true; + } + + public boolean isForkWrite() + { + return forkWrite; + } + + void markForkWrite() + { + forkWrite = true; + } + + public boolean isWaitVar() + { + return waitVar; + } + + void markWaitVar(VeraSchemaAnalyzer analyzer) + { + if (!waitVar) + { + StringBuffer msg = new StringBuffer(80); + msg.append("Found wait_var target: "); + dumpName(msg); + analyzer.log.println(msg.toString()); + + waitVar = true; + waitVarAlias = true; + + markWaitVars(analyzer); + markWaitVarAliases(analyzer); + } + } + + private void markWaitVars(VeraSchemaAnalyzer analyzer) + { + // mark any variables found so far that are aliased by this + // wait_var target argument + if (byRefArgVars != null) + { + for (VeraVariable var : byRefArgVars) + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(var); + // only analyzed variables can be put in byRefArgVars + assert (varAnalysis != null); + varAnalysis.markWaitVar(analyzer); + } + } + } + + public boolean isWaitVarAlias() + { + return waitVarAlias; + } + + private void markWaitVarAlias(VeraSchemaAnalyzer analyzer) + { + if (!waitVarAlias) + { + StringBuffer msg = new StringBuffer(80); + msg.append("Found alias for wait_var target: "); + dumpName(msg); + analyzer.log.println(msg.toString()); + + waitVarAlias = true; + + markWaitVarAliases(analyzer); + } + } + + private void markWaitVarAliases(VeraSchemaAnalyzer analyzer) + { + // mark any by-ref arguments/functions found so far that receive + // this variable as taking wait_var aliases + if (byRefArgUses != null) + { + for (Object obj : byRefArgUses) + { + if (obj instanceof VeraFunctionArgument) + { + VeraFunctionArgument arg = (VeraFunctionArgument) obj; + VariableAnalysis argAnalysis = analyzer + .getOrCreateVariableAnalysis(arg, arg.getFunction()); + argAnalysis.markWaitVarAlias(analyzer); + } + else + { + VeraFunction func = (VeraFunction) obj; + FunctionAnalysis funcAnalysis = analyzer + .getOrCreateFunctionAnalysis(func); + funcAnalysis.markVarArgsWaitVarAlias(); + } + } + } + } + + @Override + public String toString() + { + if (context != null) + { + return var.getName().getIdentifier() + " in " + + AnalyzerModule.getDescription(context); + } + else + { + return var.getName().getCanonicalName(); + } + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/VeraSchemaAnalyzer.java b/java/juno/src/com/newisys/schemaanalyzer/juno/VeraSchemaAnalyzer.java new file mode 100644 index 0000000..246b6ae --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/VeraSchemaAnalyzer.java @@ -0,0 +1,428 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import com.newisys.langschema.SchemaObject; +import com.newisys.langschema.vera.*; +import com.newisys.util.logging.IndentLogger; + +/** + * Performs various analyses on a Vera schema and provides access to the + * results. The analyses performed include the following: + *
        + *
      • variable read/write analysis (is a variable read/written, read when + * unassigned, written when assigned, initialized with side effects?)
      • + *
      • X/Z propagation (is a variable directly or indirectly assigned an X/Z + * or observed as X/Z?)
      • + *
      • string usage (is a string modified?, is its Vera error or matching + * metadata accessed?)
      • + *
      • field usage (what is the most restrictive scope of accesses to a + * field?, is a field definitely assigned in the constructor?, is it ever + * assigned outside the constructor?)
      • + *
      • by-reference argument usage (what variables are aliased by by-reference + * arguments?)
      • + *
      • fork analysis (what variables are read or written in a forked thread?)
      • + *
      • wait_var analysis (what variables are directly or indirectly the target + * of a wait_var call?)
      • + *
      • counting of schema object types
      • + *
      + * + * @author Trevor Robinson + */ +public final class VeraSchemaAnalyzer +{ + private final Map analyses = new HashMap(); + final IndentLogger log; + + int classCount = 0; + int fieldCount = 0; + int constraintCount = 0; + int methodCount = 0; + int enumCount = 0; + int globalVarCount = 0; + int globalFuncCount = 0; + int programCount = 0; + int interfaceCount = 0; + int interfaceSignalCount = 0; + int portCount = 0; + int portSignalCount = 0; + int bindCount = 0; + int bindSignalCount = 0; + int hdlFuncCount = 0; + int udfFuncCount = 0; + int localVarCount = 0; + int statementCount = 0; + int exprDefineCount = 0; + int rangeDefineCount = 0; + int stmtDefineCount = 0; + int typeDefineCount = 0; + + public VeraSchemaAnalyzer(IndentLogger log) + { + this.log = log; + } + + public void analyze(VeraSchema schema) + { + // analyze all members of schema + SchemaMemberAnalyzer sma = new SchemaMemberAnalyzer(this); + Iterator iter = schema.getMembers().iterator(); + while (iter.hasNext()) + { + VeraSchemaMember obj = (VeraSchemaMember) iter.next(); + obj.accept(sma); + } + + // mark scope complete for remaining variables + final boolean checkedCompletion = false; + iter = analyses.values().iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof VariableAnalysis) + { + VariableAnalysis varAnalysis = (VariableAnalysis) obj; + if (!varAnalysis.isXZKnown()) + { + if (!checkedCompletion) + { + varAnalysis.markNotAssignedXZ(); + } + else if (!varAnalysis.isScopeComplete()) + { + varAnalysis.markScopeComplete(); + } + } + } + } + if (checkedCompletion) + { + iter = analyses.values().iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof VariableAnalysis) + { + VariableAnalysis varAnalysis = (VariableAnalysis) obj; + assert varAnalysis.isAssignedXZ() != varAnalysis + .isNotAssignedXZ() : varAnalysis + ": isAssignedXZ{" + + varAnalysis.isAssignedXZ() + "} != isNotAssignedXZ{" + + varAnalysis.isNotAssignedXZ() + "}"; + } + } + } + + dumpXZAnalysis(); + + // resolve X/Z analysis among method overrides + iter = analyses.values().iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof FunctionAnalysis) + { + FunctionAnalysis funcAnalysis = (FunctionAnalysis) obj; + if (funcAnalysis.getOverridden() == null) + { + int argCount = funcAnalysis.getArgumentCount(); + for (int i = -1; i < argCount; ++i) + { + boolean xz = analyzeArgXZInOverride(funcAnalysis, i, + true); + if (xz) analyzeArgXZInOverride(funcAnalysis, i, false); + } + for (int i = 0; i < argCount; ++i) + { + boolean stateful = analyzeArgStatefulStringInOverride( + funcAnalysis, i, true); + if (stateful) + analyzeArgStatefulStringInOverride(funcAnalysis, i, + false); + } + } + } + } + } + + private void dumpXZAnalysis() + { + int notXZCount = 0, totalCount = 0; + int[] sourceTypeCount = new int[XZSourceType.NUM_CODES]; + + log.println("X/Z analysis summary:"); + log.incIndent(); + Iterator iter = analyses.values().iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof VariableAnalysis) + { + VariableAnalysis varAnalysis = (VariableAnalysis) obj; + if (varAnalysis.isXZType()) + { + if (varAnalysis.isNotAssignedXZ()) + { + ++notXZCount; + } + else + { + XZSourceType sourceType = varAnalysis.getXZSourceType(); + if (sourceType != XZSourceType.ASSIGNMENT) + { + int destCount = dumpXZSource(varAnalysis, + sourceType); + sourceTypeCount[sourceType.getCode()] += destCount; + } + } + ++totalCount; + } + } + } + log.decIndent(); + + for (int i = 1; i < XZSourceType.NUM_CODES; ++i) + { + log.println(sourceTypeCount[i] + " variables X/Z due to " + + XZSourceType.getInstance(i) + + " (or assignments from such variables)"); + } + log.println(notXZCount + " of " + totalCount + + " bit/integer variables provably not X/Z"); + } + + private int dumpXZSource( + VariableAnalysis varAnalysis, + XZSourceType sourceType) + { + log.println(varAnalysis + " can be X/Z due to " + sourceType); + int destCount = 1; + Set dests = varAnalysis.getXZDestinations(); + if (!dests.isEmpty()) + { + log.incIndent(); + Iterator iter = dests.iterator(); + while (iter.hasNext()) + { + VariableAnalysis destVar = (VariableAnalysis) iter.next(); + destCount += dumpXZSource(destVar, XZSourceType.ASSIGNMENT); + } + log.decIndent(); + } + return destCount; + } + + private boolean analyzeArgXZInOverride( + FunctionAnalysis funcAnalysis, + int index, + boolean check) + { + boolean xz = true; + if (check) + { + VeraFunctionType funcType = funcAnalysis.func.getType(); + if (index < 0) + { + VeraLocalVariable returnVar = funcAnalysis.func.getReturnVar(); + xz = funcType.isReturnsXZ(); + if (!xz && returnVar != null) + { + VariableAnalysis varAnalysis = getVariableAnalysis(returnVar); + xz = varAnalysis == null || !varAnalysis.isNotAssignedXZ(); + } + } + else + { + VeraFunctionArgument arg = funcType.getArguments().get(index); + xz = arg.isReturnsXZ(); + if (!xz) + { + VariableAnalysis varAnalysis = getVariableAnalysis(arg); + xz = varAnalysis == null || !varAnalysis.isNotAssignedXZ(); + } + } + if (xz) return true; + } + + for (FunctionAnalysis overrideAnalysis : funcAnalysis + .getDirectOverrides()) + { + xz |= analyzeArgXZInOverride(overrideAnalysis, index, check); + if (check && xz) break; + } + + if (!check) + { + if (index < 0) + { + funcAnalysis.setReturnXZInOverride(true); + } + else + { + funcAnalysis.setArgumentXZInOverride(index, true); + } + } + + return xz; + } + + private boolean analyzeArgStatefulStringInOverride( + FunctionAnalysis funcAnalysis, + int index, + boolean check) + { + assert (index >= 0); + boolean stateful = true; + if (check) + { + VeraFunctionType funcType = funcAnalysis.func.getType(); + VeraFunctionArgument arg = funcType.getArguments().get(index); + VariableAnalysis varAnalysis = getVariableAnalysis(arg); + stateful = varAnalysis != null + && varAnalysis.isNeedStatefulString(); + if (stateful) return true; + } + + for (FunctionAnalysis overrideAnalysis : funcAnalysis + .getDirectOverrides()) + { + stateful |= analyzeArgStatefulStringInOverride(overrideAnalysis, + index, check); + if (check && stateful) break; + } + + if (!check) + { + funcAnalysis.setArgumentStatefulStringInOverride(index, true); + } + + return stateful; + } + + public ClassAnalysis getClassAnalysis(VeraUserClass cls) + { + ClassAnalysis analysis = (ClassAnalysis) analyses.get(cls); + assert (analysis == null || analysis.cls == cls); + return analysis; + } + + ClassAnalysis getOrCreateClassAnalysis(VeraUserClass cls) + { + ClassAnalysis analysis = getClassAnalysis(cls); + if (analysis == null) + { + analysis = new ClassAnalysis(cls); + analyses.put(cls, analysis); + } + return analysis; + } + + public VariableAnalysis getVariableAnalysis(VeraVariable var) + { + VariableAnalysis analysis = (VariableAnalysis) analyses.get(var); + assert (analysis == null || analysis.var == var); + return analysis; + } + + VariableAnalysis getOrCreateVariableAnalysis( + VeraVariable var, + SchemaObject context) + { + VariableAnalysis analysis = getVariableAnalysis(var); + if (analysis == null) + { + analysis = new VariableAnalysis(var, context); + analyses.put(var, analysis); + } + else if (context != null && analysis.context == null) + { + analysis.context = context; + } + return analysis; + } + + public FunctionAnalysis getFunctionAnalysis(VeraFunction func) + { + FunctionAnalysis analysis = (FunctionAnalysis) analyses.get(func); + assert (analysis == null || analysis.func == func); + return analysis; + } + + FunctionAnalysis getOrCreateFunctionAnalysis(VeraFunction func) + { + FunctionAnalysis analysis = getFunctionAnalysis(func); + if (analysis == null) + { + analysis = new FunctionAnalysis(this, func); + analyses.put(func, analysis); + } + return analysis; + } + + public FunctionAnalysis getBaseFunctionAnalysis(VeraFunction func) + { + FunctionAnalysis analysis = getFunctionAnalysis(func); + while (analysis != null) + { + FunctionAnalysis baseAnalysis = analysis.getOverridden(); + if (baseAnalysis == null) break; + analysis = baseAnalysis; + } + return analysis; + } + + public BlockAnalysis getBlockAnalysis(VeraStatement stmt) + { + BlockAnalysis analysis = (BlockAnalysis) analyses.get(stmt); + return analysis; + } + + void setBlockAnalysis(VeraStatement stmt, BlockAnalysis analysis) + { + analyses.put(stmt, analysis); + } + + public void dumpCounts() + { + log.println("Classes: " + classCount + " [Fields: " + fieldCount + + ", Constraints: " + constraintCount + ", Methods: " + methodCount + + "]"); + log.println("Enums: " + enumCount); + log.println("Global variables: " + globalVarCount); + log.println("Global functions: " + globalFuncCount); + log.println("Program blocks: " + programCount); + log.println("Interfaces: " + interfaceCount + " [Signals: " + + interfaceSignalCount + "]"); + log.println("Ports: " + portCount + " [Signals: " + portSignalCount + + "]"); + log.println("Binds: " + bindCount + " [Signals: " + bindSignalCount + + "]"); + log.println("HDL functions: " + hdlFuncCount); + log.println("UDF functions: " + udfFuncCount); + log.println("Local variables: " + localVarCount); + log.println("Statements: " + statementCount); + log.println("Expression defines: " + exprDefineCount); + log.println("Range defines: " + rangeDefineCount); + log.println("Statement defines: " + stmtDefineCount); + log.println("Type defines: " + typeDefineCount); + } +} diff --git a/java/juno/src/com/newisys/schemaanalyzer/juno/XZSourceType.java b/java/juno/src/com/newisys/schemaanalyzer/juno/XZSourceType.java new file mode 100644 index 0000000..fbadfc9 --- /dev/null +++ b/java/juno/src/com/newisys/schemaanalyzer/juno/XZSourceType.java @@ -0,0 +1,90 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaanalyzer.juno; + +/** + * Enumeration of X/Z sources for a variable. + * + * @author Trevor Robinson + */ +public final class XZSourceType +{ + // assignment from X/Z variable + public static final XZSourceType ASSIGNMENT = new XZSourceType(0, + "assignment"); + + // read of uninitialized variable + public static final XZSourceType UNINIT = new XZSourceType(1, + "uninitialized read"); + + // bit vector literal containing X/Z + public static final XZSourceType LITERAL = new XZSourceType(2, "literal"); + + // read of array element + public static final XZSourceType ARRAY = new XZSourceType(3, "array access"); + + // read of Verilog signal + public static final XZSourceType SIGNAL = new XZSourceType(4, "signal read"); + + // built-in, HDL, or UDF function + public static final XZSourceType EXTERNAL = new XZSourceType(5, + "external function"); + + public static final int NUM_CODES = 6; + + private final int code; + private final String str; + + private XZSourceType(int code, String str) + { + this.code = code; + this.str = str; + } + + public static XZSourceType getInstance(int code) + { + switch (code) + { + case 0: + return ASSIGNMENT; + case 1: + return UNINIT; + case 2: + return LITERAL; + case 3: + return ARRAY; + case 4: + return SIGNAL; + case 5: + return EXTERNAL; + default: + throw new IllegalArgumentException("Illegal code: " + code); + } + } + + public int getCode() + { + return code; + } + + @Override + public String toString() + { + return str; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ArithmeticOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/ArithmeticOperationBuilder.java new file mode 100644 index 0000000..49bc983 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ArithmeticOperationBuilder.java @@ -0,0 +1,68 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; + +/** + * Interface for building various Java arithmetic operation expressions. + * + * @author Trevor Robinson + */ +interface ArithmeticOperationBuilder +{ + JavaExpression add(JavaExpression op1, JavaExpression op2); + + JavaExpression subtract(JavaExpression op1, JavaExpression op2); + + JavaExpression multiply(JavaExpression op1, JavaExpression op2); + + JavaExpression divide(JavaExpression op1, JavaExpression op2); + + JavaExpression mod(JavaExpression op1, JavaExpression op2); + + JavaExpression negate(JavaExpression op1); + + JavaExpression and(JavaExpression op1, JavaExpression op2); + + JavaExpression andNot(JavaExpression op1, JavaExpression op2); + + JavaExpression or(JavaExpression op1, JavaExpression op2); + + JavaExpression orNot(JavaExpression op1, JavaExpression op2); + + JavaExpression xor(JavaExpression op1, JavaExpression op2); + + JavaExpression xorNot(JavaExpression op1, JavaExpression op2); + + JavaExpression not(JavaExpression op1); + + JavaExpression reverse(JavaExpression op1); + + JavaExpression reductiveAnd(JavaExpression op1); + + JavaExpression reductiveAndNot(JavaExpression op1); + + JavaExpression reductiveOr(JavaExpression op1); + + JavaExpression reductiveOrNot(JavaExpression op1); + + JavaExpression reductiveXor(JavaExpression op1); + + JavaExpression reductiveXorNot(JavaExpression op1); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ArrayLHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/ArrayLHSTranslator.java new file mode 100644 index 0000000..6cc3717 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ArrayLHSTranslator.java @@ -0,0 +1,347 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; +import java.util.List; + +import com.newisys.langschema.java.JavaAbstractClass; +import com.newisys.langschema.java.JavaArrayAccess; +import com.newisys.langschema.java.JavaArrayType; +import com.newisys.langschema.java.JavaAssign; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.jove.JoveAssocArrayType; +import com.newisys.langschema.vera.VeraArrayAccess; +import com.newisys.langschema.vera.VeraExpression; + +/** + * LHS translator for array elements, including individual bit vector bits. + * + * @author Trevor Robinson + */ +final class ArrayLHSTranslator + extends BaseLHSTranslator +{ + private final JavaType arrayType; + private final boolean isDrive; + private final JavaType elementType; + private final JavaExpression updateEvent; + private final JavaExpression arrayOnceExpr; + private final JavaExpression signalOnceExpr; + private final JavaExpression objectOnceExpr; + private final JavaExpression indexOnceExpr; + + public ArrayLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext, + VeraArrayAccess obj, + boolean readAccess, + boolean writeAccess) + { + super(exprXlat, exprContext); + + // translate the array expression + final VeraExpression veraArrayExpr = obj.getArray(); + final JavaExpression arrayExpr = translateExpr(veraArrayExpr, + "lhs_obj", writeAccess ? types.outputSignalType : null); + arrayType = arrayExpr.getResultType(); + isDrive = exprConv.isOutputSignal(arrayType); + final boolean bitVector = isDrive || schema.isBitVector(arrayType); + + // translate the indices + final List veraIndices = obj.getIndices(); + final int indexCount = veraIndices.size(); + final JavaExpression[] indexExprs = new JavaExpression[indexCount]; + JavaExpression updateEvent; + if (arrayType instanceof JavaArrayType) + { + JavaArrayType realArrayType = (JavaArrayType) arrayType; + elementType = realArrayType.getElementType(); + + // native Java array: translate multiple int indexes + int curIndex = 0; + final Iterator iter = veraIndices.iterator(); + while (iter.hasNext()) + { + VeraExpression veraIndexExpr = (VeraExpression) iter.next(); + JavaExpression indexExpr = exprConv.toInt(translateExpr( + veraIndexExpr, "lhs_index" + curIndex, schema.intType)); + indexExprs[curIndex++] = indexExpr; + } + } + else + { + // BitVector bit access or associative array access: single + // index + assert (indexCount == 1); + final VeraExpression veraIndexExpr = (VeraExpression) veraIndices + .get(0); + if (bitVector) + { + elementType = schema.bitType; + + // BitVector bit access: int index + indexExprs[0] = exprConv.toInt(translateExpr(veraIndexExpr, + "lhs_index", schema.intType)); + } + else + { + // associative array access: BitVector or String index + assert (arrayType instanceof JoveAssocArrayType); + final JoveAssocArrayType assocType = (JoveAssocArrayType) arrayType; + elementType = assocType.getElementType(); + + JavaExpression indexExpr = translateExpr(veraIndexExpr, + "lhs_index", null); + final JavaAbstractClass baseClass = assocType.getBaseClass(); + if (types.bitAssocArrayType.isSuperclassOf(baseClass)) + { + // BitVector-indexed associative array + indexExpr = exprConv.toUnsizedBitVector(indexExpr); + } + else + { + // String-indexed associative array + assert (types.stringAssocArrayType + .isSuperclassOf(baseClass)); + indexExpr = exprConv.toJavaString(indexExpr, false); + } + indexExprs[0] = indexExpr; + } + } + + // check for wait_var update event + updateEvent = getWaitVarEventRef(arrayExpr); + + // check the Java type of the array + boolean multiAccess = (readAccess && writeAccess) + || (updateEvent != null); + if (arrayType instanceof JavaArrayType) + { + // native Java array + JavaExpression lhs = buildNativeArrayAccess(arrayExpr, indexExprs); + arrayOnceExpr = EvalOnceExprBuilder.evalLHSExpr(lhs, exprContext, + "lhs", multiAccess); + signalOnceExpr = null; + objectOnceExpr = null; + indexOnceExpr = null; + if (updateEvent != null) + { + updateEvent = buildNativeArrayAccess(updateEvent, indexExprs); + } + } + else + { + // associative array or bit vector + arrayOnceExpr = null; + if (isDrive) + { + signalOnceExpr = EvalOnceExprBuilder.evalLHSExpr(arrayExpr, + exprContext, "lhs_signal", multiAccess); + if (readAccess) + { + objectOnceExpr = EvalOnceExprBuilder.evalLHSExpr( + ExpressionBuilder.memberCall(signalOnceExpr, + "sampleAsync"), exprContext, "lhs_bv", true); + } + else + { + objectOnceExpr = null; + } + } + else + { + signalOnceExpr = null; + objectOnceExpr = EvalOnceExprBuilder.evalLHSExpr(arrayExpr, + exprContext, "lhs_obj", multiAccess + || (writeAccess && bitVector)); + } + indexOnceExpr = EvalOnceExprBuilder.evalConstExpr(indexExprs[0], + exprContext, "lhs_index", multiAccess); + if (updateEvent != null && !bitVector) + { + updateEvent = buildAssocArrayGet(updateEvent, + types.junoEventType, indexOnceExpr, true); + } + } + this.updateEvent = updateEvent; + } + + private JavaExpression buildNativeArrayAccess( + JavaExpression array, + JavaExpression[] indices) + { + // normal Java array + final JavaArrayAccess access = new JavaArrayAccess(array); + for (int i = 0; i < indices.length; ++i) + { + access.addIndex(indices[i]); + } + return access; + } + + private JavaExpression buildAssocArrayGet( + JavaExpression array, + JavaType elementType, + JavaExpression index, + boolean forWrite) + { + // associative array get + // Vera: x = foo[2]; + // Java: x = (Integer) foo.get(new BitVector(32, 2)); + return ExpressionBuilder.checkDowncast(ExpressionBuilder.memberCall( + array, forWrite ? "getOrCreate" : "get", index), elementType); + } + + private JavaExpression buildAssocArraySet( + JavaExpression array, + JavaType elementType, + JavaExpression index, + JavaExpression value) + { + // associative array set + // Vera: foo[2] = 42; + // Java: foo.put(new BitVector(32, 2), new Integer(42)); + return ExpressionBuilder.memberCall(array, "put", index, exprConv + .toObject(value)); + } + + private JavaExpression buildBitGet( + JavaExpression array, + JavaExpression index) + { + // BitVector bit get + // Vera: x = foo[2]; + // Java: x = foo.getBit(2); + return ExpressionBuilder.memberCall(array, "getBit", index); + } + + private JavaExpression buildBitSet( + JavaExpression array, + JavaExpression index, + JavaExpression value) + { + // BitVector bit set + // Vera: foo[2] = 1'b1; + // Java: foo = foo.setBit(2, Bit.ONE); + JavaExpression setExpr = ExpressionBuilder.memberCall(array, "setBit", + index, exprConv.toBit(value)); + return new JavaAssign(schema, array, setExpr); + } + + private JavaExpression buildBitDrive( + JavaExpression signal, + JavaExpression index, + JavaExpression value) + { + // BitVector bit slice set + // Vera: foo[2] = 1'b1; + // Java: foo.driveRange(2, 2, new BitVector("1'b1")); + return ExpressionBuilder.memberCall(signal, "driveRange", + new JavaExpression[] { index, index, exprConv.toObject(value) }, + null); + } + + public JavaType getResultType() + { + return elementType; + } + + public JavaExpression getUpdateEvent() + { + return updateEvent; + } + + public JavaExpression getReadExpression() + { + if (arrayOnceExpr != null) + { + return arrayOnceExpr; + } + else + { + if (schema.isBitVector(arrayType)) + { + return buildBitGet(objectOnceExpr, indexOnceExpr); + } + else + { + return buildAssocArrayGet(objectOnceExpr, elementType, + indexOnceExpr, false); + } + } + } + + public ConvertedExpression getWriteExpression(JavaExpression value) + { + ConvertedExpression result = new ConvertedExpression(exprContext); + if (arrayOnceExpr != null) + { + getAssignWriteExpression(result, elementType, arrayOnceExpr, value, + updateEvent); + } + else if (isDrive) + { + result.setResultExpr(buildBitDrive(signalOnceExpr, indexOnceExpr, + value)); + } + else if (schema.isBitVector(arrayType)) + { + if (updateEvent != null) + { + value = EvalOnceExprBuilder.evalConstExpr(value, result, + "new_value", true); + } + result.setResultExpr(buildBitSet(objectOnceExpr, indexOnceExpr, + value)); + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor("old_value", + buildBitGet(objectOnceExpr, indexOnceExpr), true); + checkUpdate(result, oldValue, value, false, updateEvent); + } + } + else if (hasValueSemantics(elementType)) + { + JavaExpression destExpr = buildAssocArrayGet(objectOnceExpr, + elementType, indexOnceExpr, true); + result.setResultExpr(getValueWriteExpression(elementType, destExpr, + value)); + } + else + { + if (updateEvent != null) + { + value = EvalOnceExprBuilder.evalConstExpr(value, result, + "new_value", true); + } + result.setResultExpr(buildAssocArraySet(objectOnceExpr, + elementType, indexOnceExpr, value)); + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor("old_value", + buildAssocArrayGet(objectOnceExpr, elementType, + indexOnceExpr, false), true); + checkUpdate(result, oldValue, value, false, updateEvent); + } + } + return result; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BaseLHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/BaseLHSTranslator.java new file mode 100644 index 0000000..c23fdda --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BaseLHSTranslator.java @@ -0,0 +1,107 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaAssign; +import com.newisys.langschema.java.JavaCastExpression; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaNullType; +import com.newisys.langschema.java.JavaPrimitiveType; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.VeraExpression; + +/** + * Base class for LHS translators. Provides common state and utility methods. + * + * @author Trevor Robinson + */ +abstract class BaseLHSTranslator + extends TranslatorModule + implements LHSTranslator +{ + protected final ExpressionTranslator exprXlat; + protected final ConvertedExpression exprContext; + + public BaseLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext) + { + super(exprXlat); + this.exprXlat = exprXlat; + this.exprContext = exprContext; + } + + protected final JavaExpression translateExpr( + VeraExpression veraExpr, + String tempID, + JavaType typeContext) + { + ConvertedExpression convExpr = exprXlat.translateNewExpr(veraExpr, + typeContext); + convExpr.flatten(tempID); + return convExpr.mergeIntoResult(exprContext); + } + + protected final boolean hasValueSemantics(JavaType lhsType) + { + // JunoString has value semantics + return lhsType == types.junoStringType; + } + + protected final JavaExpression getValueWriteExpression( + JavaType lhsType, + JavaExpression destExpr, + JavaExpression value) + { + // JunoString is the only assignable object type with value semantics + assert (lhsType == types.junoStringType); + + // JunoString: str.assign(value) + if (value.getResultType() instanceof JavaNullType) + { + // avoid ambiguous method invocation: str.assign((String) null) + value = new JavaCastExpression(types.stringType, value); + } + return ExpressionBuilder.memberCall(destExpr, "assign", value); + } + + protected final void getAssignWriteExpression( + ConvertedExpression result, + JavaType lhsType, + JavaExpression lhs, + JavaExpression value, + JavaExpression updateEvent) + { + if (hasValueSemantics(lhsType)) + { + result.setResultExpr(getValueWriteExpression(lhsType, lhs, value)); + } + else + { + result.setResultExpr(new JavaAssign(schema, lhs, value)); + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor("old_value", lhs, + true); + checkUpdate(result, oldValue, lhs, + lhsType instanceof JavaPrimitiveType, updateEvent); + } + } + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BitOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/BitOperationBuilder.java new file mode 100644 index 0000000..5b32c36 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BitOperationBuilder.java @@ -0,0 +1,180 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaEqual; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaNotEqual; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds various operation expressions for Bit-type operands. + * + * @author Trevor Robinson + */ +final class BitOperationBuilder + extends TranslatorModule + implements ArithmeticOperationBuilder, EqualityOperationBuilder +{ + public BitOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + private JavaExpression doBitOpCall( + String methodID, + JavaExpression arg1, + JavaExpression arg2) + { + return ExpressionBuilder.staticCall(types.bitOpType, methodID, arg1, + arg2); + } + + public JavaExpression add(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "xor", op2); + } + + public JavaExpression subtract(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "xor", op2); + } + + public JavaExpression multiply(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "and", op2); + } + + public JavaExpression divide(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("divide", op1, op2); + } + + public JavaExpression mod(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("mod", op1, op2); + } + + public JavaExpression negate(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "ztox"); + } + + public JavaExpression and(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "and", op2); + } + + public JavaExpression andNot(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "and", op2), "not"); + } + + public JavaExpression or(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "or", op2); + } + + public JavaExpression orNot(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "or", op2), "not"); + } + + public JavaExpression xor(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "xor", op2); + } + + public JavaExpression xorNot(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "xor", op2), "not"); + } + + public JavaExpression not(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "not"); + } + + public JavaExpression reverse(JavaExpression op1) + { + return op1; + } + + public JavaExpression reductiveAnd(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "ztox"); + } + + public JavaExpression reductiveAndNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "not"); + } + + public JavaExpression reductiveOr(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "ztox"); + } + + public JavaExpression reductiveOrNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "not"); + } + + public JavaExpression reductiveXor(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "ztox"); + } + + public JavaExpression reductiveXorNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "not"); + } + + public JavaExpression equal(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("equal", op1, op2); + } + + public JavaExpression notEqual(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("notEqual", op1, op2); + } + + public JavaExpression exactEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaEqual(schema, op1, op2); + } + + public JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaNotEqual(schema, op1, op2); + } + + public JavaExpression wildEqual(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("wildEqual", op1, op2); + } + + public JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2) + { + return doBitOpCall("wildNotEqual", op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BitSliceLHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/BitSliceLHSTranslator.java new file mode 100644 index 0000000..fa249ea --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BitSliceLHSTranslator.java @@ -0,0 +1,302 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaAssign; +import com.newisys.langschema.java.JavaClassMember; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaFunction; +import com.newisys.langschema.java.JavaFunctionInvocation; +import com.newisys.langschema.java.JavaFunctionReference; +import com.newisys.langschema.java.JavaMemberVariable; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.JavaVariableReference; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.VeraBitSliceAccess; +import com.newisys.langschema.vera.VeraDefineReference; +import com.newisys.langschema.vera.VeraExpression; +import com.newisys.langschema.vera.VeraRange; +import com.newisys.langschema.vera.VeraRangeDefine; + +/** + * LHS translator for bit vector slices. + * + * @author Trevor Robinson + */ +final class BitSliceLHSTranslator + extends BaseLHSTranslator +{ + private final JavaType resultType; + private final boolean isDrive; + private final JavaExpression updateEvent; + private final JavaExpression signalOnceExpr; + private final JavaExpression bvOnceExpr; + private final JavaExpression rangeExpr; + private final JavaExpression highOnceExpr; + private final JavaExpression lowOnceExpr; + + public BitSliceLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext, + VeraBitSliceAccess obj, + boolean readAccess, + boolean writeAccess) + { + super(exprXlat, exprContext); + + // convert the array expression + final VeraExpression veraArrayExpr = obj.getArray(); + final JavaExpression arrayExpr = translateExpr(veraArrayExpr, + "lhs_obj", writeAccess ? types.outputSignalType : null); + final JavaType arrayType = arrayExpr.getResultType(); + isDrive = exprConv.isOutputSignal(arrayType); + if (isDrive) + { + resultType = schema.bitVectorType; + } + else + { + assert (schema.isBitVector(arrayType)); + resultType = arrayType; + } + + final VeraRange range = obj.getRange(); + + // check for range define reference + JavaExpression rangeExpr = null; + final VeraDefineReference defineRef = range + .getDefineRef(); + if (defineRef != null) + { + final VeraRangeDefine define = defineRef.getDefine(); + final JavaClassMember member = translateRangeDefine(define); + if (member != null) + { + if (member instanceof JavaMemberVariable) + { + rangeExpr = new JavaVariableReference( + (JavaMemberVariable) member); + } + else + { + rangeExpr = new JavaFunctionInvocation( + new JavaFunctionReference((JavaFunction) member)); + } + } + } + this.rangeExpr = rangeExpr; + + // convert the high index expression + final VeraExpression veraHighExpr = range.getFrom(); + final JavaExpression highExpr = exprConv.toInt(translateExpr( + veraHighExpr, "lhs_high", schema.intType)); + + // convert the low index expression + final VeraExpression veraLowExpr = range.getTo(); + final JavaExpression lowExpr = exprConv.toInt(translateExpr( + veraLowExpr, "lhs_low", schema.intType)); + + // check for wait_var update event + updateEvent = getWaitVarEventRef(arrayExpr); + + // create single-evaluation expressions for sub-expressions + boolean multiAccess = (readAccess && writeAccess) + || (updateEvent != null); + if (isDrive) + { + signalOnceExpr = EvalOnceExprBuilder.evalLHSExpr(arrayExpr, + exprContext, "lhs_signal", multiAccess); + if (readAccess) + { + bvOnceExpr = EvalOnceExprBuilder.evalLHSExpr(ExpressionBuilder + .memberCall(signalOnceExpr, "sampleAsync"), exprContext, + "lhs_bv", true); + } + else + { + bvOnceExpr = null; + } + } + else + { + signalOnceExpr = null; + bvOnceExpr = EvalOnceExprBuilder.evalLHSExpr(arrayExpr, + exprContext, "lhs_bv", multiAccess || writeAccess); + } + highOnceExpr = EvalOnceExprBuilder.evalConstExpr(highExpr, exprContext, + "lhs_high", multiAccess); + lowOnceExpr = EvalOnceExprBuilder.evalConstExpr(lowExpr, exprContext, + "lhs_low", multiAccess); + } + + private JavaExpression buildBitSliceGet( + JavaExpression array, + JavaExpression high, + JavaExpression low) + { + // BitVector bit slice get + // Vera: x = foo[4:2]; + // Java: x = BitVectorOp.getBits(foo, 4, 2); + return ExpressionBuilder.staticCall(types.bitVectorOpType, "getBits", + new JavaExpression[] { array, high, low }, null); + } + + private JavaExpression buildBitSliceGet( + JavaExpression array, + JavaExpression range) + { + // BitVector bit slice get + // Vera: x = foo[RANGE]; + // Java: x = foo.getBits(RANGE); + return ExpressionBuilder.memberCall(array, "getBits", range); + } + + private JavaExpression buildBitSliceSet( + JavaExpression array, + JavaExpression high, + JavaExpression low, + JavaExpression value) + { + // BitVector bit slice set + // Vera: foo[4:2] = 3'b101; + // Java: foo = BitVectorOp.setBits(foo, 4, 2, new BitVector("3'b101")); + int size = schema.getBitVectorSize(array.getResultType()); + JavaExpression setExpr = ExpressionBuilder.staticCall( + types.bitVectorOpType, "setBits", new JavaExpression[] { array, + high, low, exprConv.toBitVector(value, size, false) }, null); + return new JavaAssign(schema, array, setExpr); + } + + private JavaExpression buildBitSliceSet( + JavaExpression array, + JavaExpression range, + JavaExpression value) + { + // BitVector bit slice set + // Vera: foo[RANGE] = 3'b101; + // Java: foo = foo.setBits(RANGE, new BitVector("3'b101")); + int size = schema.getBitVectorSize(array.getResultType()); + JavaExpression setExpr = ExpressionBuilder.memberCall(array, "setBits", + range, exprConv.toBitVector(value, size, false)); + return new JavaAssign(schema, array, setExpr); + } + + private JavaExpression buildBitSliceDrive( + JavaExpression signal, + JavaExpression high, + JavaExpression low, + JavaExpression value) + { + // BitVector bit slice set + // Vera: foo[4:2] = 3'b101; + // Java: foo.driveRange(4, 2, new BitVector("3'b101")); + return ExpressionBuilder.memberCall(signal, "driveRange", + new JavaExpression[] { high, low, exprConv.toObject(value) }, null); + } + + private JavaExpression buildBitSliceDrive( + JavaExpression signal, + JavaExpression range, + JavaExpression value) + { + // BitVector bit slice set + // Vera: foo[RANGE] = 3'b101; + // Java: foo.driveRange(RANGE, new BitVector("3'b101")); + return ExpressionBuilder.memberCall(signal, "driveRange", range, + exprConv.toObject(value)); + } + + public JavaType getResultType() + { + return resultType; + } + + public JavaExpression getUpdateEvent() + { + return updateEvent; + } + + public JavaExpression getRangeExpression() + { + return rangeExpr; + } + + public JavaExpression getHighExpression() + { + return highOnceExpr; + } + + public JavaExpression getLowExpression() + { + return lowOnceExpr; + } + + public JavaExpression getReadExpression() + { + JavaExpression getExpr; + if (rangeExpr != null) + { + getExpr = buildBitSliceGet(bvOnceExpr, rangeExpr); + } + else + { + getExpr = buildBitSliceGet(bvOnceExpr, highOnceExpr, lowOnceExpr); + } + return getExpr; + } + + public ConvertedExpression getWriteExpression(JavaExpression value) + { + ConvertedExpression result = new ConvertedExpression(exprContext); + if (isDrive) + { + JavaExpression driveExpr; + if (rangeExpr != null) + { + driveExpr = buildBitSliceDrive(signalOnceExpr, rangeExpr, value); + } + else + { + driveExpr = buildBitSliceDrive(signalOnceExpr, highOnceExpr, + lowOnceExpr, value); + } + result.setResultExpr(driveExpr); + } + else + { + JavaExpression setExpr; + if (rangeExpr != null) + { + setExpr = buildBitSliceSet(bvOnceExpr, rangeExpr, value); + } + else + { + setExpr = buildBitSliceSet(bvOnceExpr, highOnceExpr, + lowOnceExpr, value); + } + result.setResultExpr(setExpr); + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor("old_value", + bvOnceExpr, true); + checkUpdate(result, oldValue, bvOnceExpr, false, updateEvent); + } + } + return result; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BitVectorOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/BitVectorOperationBuilder.java new file mode 100644 index 0000000..290994b --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BitVectorOperationBuilder.java @@ -0,0 +1,253 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaFunctionInvocation; +import com.newisys.langschema.java.JavaLogicalNot; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds various operation expressions for BitVector-type operands. + * + * @author Trevor Robinson + */ +final class BitVectorOperationBuilder + extends TranslatorModule + implements ArithmeticOperationBuilder, ShiftOperationBuilder, + EqualityOperationBuilder, RelationalOperationBuilder +{ + public BitVectorOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + public JavaExpression memberOpSame(JavaExpression op1, String methodID) + { + JavaFunctionInvocation invoke = ExpressionBuilder.memberCall(op1, + methodID); + JavaType type1 = op1.getResultType(); + invoke.setResultType(type1); + return invoke; + } + + public JavaExpression memberOpFirst( + JavaExpression op1, + String methodID, + JavaExpression op2) + { + JavaFunctionInvocation invoke = ExpressionBuilder.memberCall(op1, + methodID, op2); + JavaType type1 = op1.getResultType(); + invoke.setResultType(type1); + return invoke; + } + + public JavaExpression memberOpLargest( + JavaExpression op1, + String methodID, + JavaExpression op2) + { + JavaFunctionInvocation invoke = ExpressionBuilder.memberCall(op1, + methodID, op2); + JavaType type1 = op1.getResultType(); + JavaType type2 = op2.getResultType(); + int len1 = schema.getBitVectorSize(type1); + int len2 = schema.getBitVectorSize(type2); + if (len1 > 0 && len2 > 0) + { + invoke.setResultType(len2 > len1 ? type2 : type1); + } + return invoke; + } + + private JavaExpression doBitVectorOpCall( + String methodID, + JavaExpression op1, + JavaExpression op2) + { + return ExpressionBuilder.staticCall(types.bitVectorOpType, methodID, + op1, op2); + } + + public JavaExpression add(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "add", op2); + } + + public JavaExpression subtract(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "subtract", op2); + } + + public JavaExpression multiply(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "multiply", op2); + } + + public JavaExpression divide(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "divide", op2); + } + + public JavaExpression mod(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "mod", op2); + } + + public JavaExpression negate(JavaExpression op1) + { + return memberOpSame(op1, "negate"); + } + + public JavaExpression and(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "and", op2); + } + + public JavaExpression andNot(JavaExpression op1, JavaExpression op2) + { + return memberOpSame(memberOpLargest(op1, "and", op2), "not"); + } + + public JavaExpression or(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "or", op2); + } + + public JavaExpression orNot(JavaExpression op1, JavaExpression op2) + { + return memberOpSame(memberOpLargest(op1, "or", op2), "not"); + } + + public JavaExpression xor(JavaExpression op1, JavaExpression op2) + { + return memberOpLargest(op1, "xor", op2); + } + + public JavaExpression xorNot(JavaExpression op1, JavaExpression op2) + { + return memberOpSame(memberOpLargest(op1, "xor", op2), "not"); + } + + public JavaExpression not(JavaExpression op1) + { + return memberOpSame(op1, "not"); + } + + public JavaExpression reverse(JavaExpression op1) + { + return memberOpSame(op1, "reverse"); + } + + public JavaExpression reductiveAnd(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "reductiveAnd"); + } + + public JavaExpression reductiveAndNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "reductiveAnd"), "not"); + } + + public JavaExpression reductiveOr(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "reductiveOr"); + } + + public JavaExpression reductiveOrNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "reductiveOr"), "not"); + } + + public JavaExpression reductiveXor(JavaExpression op1) + { + return ExpressionBuilder.memberCall(op1, "reductiveXor"); + } + + public JavaExpression reductiveXorNot(JavaExpression op1) + { + return ExpressionBuilder.memberCall(ExpressionBuilder.memberCall(op1, + "reductiveXor"), "not"); + } + + public JavaExpression shiftLeft(JavaExpression op1, JavaExpression op2) + { + return memberOpFirst(op1, "shiftLeft", op2); + } + + public JavaExpression shiftRight(JavaExpression op1, JavaExpression op2) + { + return memberOpFirst(op1, "shiftRight", op2); + } + + public JavaExpression equal(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("equal", op1, op2); + } + + public JavaExpression notEqual(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("notEqual", op1, op2); + } + + public JavaExpression exactEqual(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "equalsExact", op2); + } + + public JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, ExpressionBuilder.memberCall(op1, + "equalsExact", op2)); + } + + public JavaExpression wildEqual(JavaExpression op1, JavaExpression op2) + { + return ExpressionBuilder.memberCall(op1, "equalsWild", op2); + } + + public JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, ExpressionBuilder.memberCall(op1, + "equalsWild", op2)); + } + + public JavaExpression greater(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("greater", op1, op2); + } + + public JavaExpression greaterOrEqual(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("greaterOrEqual", op1, op2); + } + + public JavaExpression less(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("less", op1, op2); + } + + public JavaExpression lessOrEqual(JavaExpression op1, JavaExpression op2) + { + return doBitVectorOpCall("lessOrEqual", op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BlockMemberTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/BlockMemberTranslator.java new file mode 100644 index 0000000..48338f6 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BlockMemberTranslator.java @@ -0,0 +1,1408 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.Annotation; +import com.newisys.langschema.JoinKind; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.*; +import com.newisys.schemaanalyzer.juno.BlockAnalysis; +import com.newisys.verilog.EdgeSet; + +/** + * Schema translator for block members. + * + * @author Trevor Robinson + */ +final class BlockMemberTranslator + extends TranslatorModule + implements VeraBlockMemberVisitor +{ + private final JavaBlock block; + private final TempBlockScope tempScope; + private VarInfoMap varInfoMap; + private final JavaLocalVariable returnVar; + private final JavaRawAbstractClass containingClass; + private final JavaClassMember assocMember; + private final BlockMemberTranslator outerXlat; + + private boolean transformSuperNewCall; + private boolean translatingLoop; + private boolean translatingSwitch; + private JavaLabeledStatement loopLabelStmt; + + public BlockMemberTranslator( + TranslatorModule xlatContext, + JavaBlock block, + TempBlockScope tempScope, + VarInfoMap varInfoMap, + JavaLocalVariable returnVar, + JavaRawAbstractClass containingClass, + JavaClassMember assocMember) + { + super(xlatContext); + this.block = block; + this.tempScope = tempScope; + this.varInfoMap = varInfoMap; + this.returnVar = returnVar; + this.containingClass = containingClass; + this.assocMember = assocMember; + this.outerXlat = null; + } + + private BlockMemberTranslator( + BlockMemberTranslator outerXlat, + JavaBlock block, + TempBlockScope tempScope, + VarInfoMap varInfoMap, + JavaLocalVariable returnVar, + JavaRawAbstractClass containingClass, + JavaClassMember assocMember) + { + super(outerXlat); + this.block = block; + this.tempScope = tempScope; + this.varInfoMap = varInfoMap; + this.returnVar = returnVar; + this.containingClass = containingClass; + this.assocMember = assocMember; + this.outerXlat = outerXlat; + } + + public void setTransformSuperNewCall(boolean transformSuperNewCall) + { + this.transformSuperNewCall = transformSuperNewCall; + } + + public void translateBlockMembers(VeraBlock veraBlock) + { + final List members = veraBlock.getMembers(); + final Iterator iter = members.iterator(); + while (iter.hasNext()) + { + VeraBlockMember member = (VeraBlockMember) iter.next(); + member.accept(this); + } + } + + private JavaBlock translateBlock(VeraBlock veraBlock) + { + final JavaBlock subBlock = new JavaBlock(schema); + subBlock.addAnnotations(veraBlock.getAnnotations()); + + final BlockMemberTranslator subXlat = new BlockMemberTranslator(this, + subBlock, new TempBlockScope(tempScope), varInfoMap, returnVar, + containingClass, assocMember); + subXlat.translateBlockMembers(veraBlock); + + return subBlock; + } + + private JavaStatement translateStatement(VeraStatement veraStmt) + { + final JavaBlock subBlock = new JavaBlock(schema); + + translateStatementInto(veraStmt, subBlock, varInfoMap, containingClass); + + if (!(veraStmt instanceof VeraBlock)) + { + List members = subBlock.getMembers(); + if (members.size() == 1) + { + Object member = members.get(0); + if (member instanceof JavaStatement) + { + return (JavaStatement) member; + } + } + } + return subBlock; + } + + private void translateStatementInto( + VeraStatement veraStmt, + JavaBlock block, + VarInfoMap varInfoMap, + JavaRawAbstractClass containingClass) + { + final BlockMemberTranslator subXlat = new BlockMemberTranslator(this, + block, new TempBlockScope(tempScope), varInfoMap, returnVar, + containingClass, assocMember); + if (veraStmt instanceof VeraBlock) + { + subXlat.translateBlockMembers((VeraBlock) veraStmt); + } + else + { + veraStmt.accept((VeraStatementVisitor) subXlat); + } + } + + private ConvertedExpression translateExpr( + VeraExpression veraExpr, + JavaType desiredResultType) + { + return translateExpr(veraExpr, tempScope, containingClass, varInfoMap, + returnVar, null, desiredResultType); + } + + private JavaExpression translateIntExpr( + VeraExpression veraExpr, + String tempID) + { + ConvertedExpression convExpr = translateExpr(veraExpr, schema.intType); + convExpr.convertResultExpr(schema.intType, exprConv); + return convExpr.toBlockExpr(block, tempID); + } + + private ConvertedExpression translateCondition(VeraExpression veraCond) + { + ConvertedExpression condInfo = translateExpr(veraCond, + schema.booleanType); + condInfo.setResultExpr(exprConv.toBoolean(condInfo.getResultExpr(), + false, false)); + return condInfo; + } + + public void visit(VeraLocalVariable obj) + { + translateLocalVariable(obj, false, containingClass, assocMember, block, + tempScope, returnVar, varInfoMap); + } + + public void visit(VeraBlock obj) + { + JavaBlock subBlock = translateBlock(obj); + + // remove unnecessary sub-blocks containing only statements + // (i.e. no local variable declarations or classes) + boolean containsNonStmt = false; + List members = subBlock.getMembers(); + for (Iterator iter = members.iterator(); iter.hasNext();) + { + if (!(iter.next() instanceof JavaStatement)) + { + containsNonStmt = true; + break; + } + } + if (!containsNonStmt) + { + // transfer any annotations from block to first member + List annotations = subBlock.getAnnotations(); + if (!annotations.isEmpty() && !members.isEmpty()) + { + JavaBlockMember member0 = (JavaBlockMember) members.get(0); + member0.addAnnotations(0, annotations); + } + + // add all sub-block members directly to containing block + block.addMembers(members); + } + else + { + block.addMember(subBlock); + } + } + + public void visit(VeraBreakpointStatement obj) + { + // TODO: translate VeraBreakpointStatement + } + + public void visit(VeraBreakStatement obj) + { + JavaLabeledStatement target = null; + BlockMemberTranslator cur = outerXlat; + boolean inSwitch = false; + while (cur != null) + { + if (cur.translatingLoop) + { + if (inSwitch) + { + // intervening switch statement; generate labeled break + target = cur.loopLabelStmt; + if (target == null) + { + target = new JavaLabeledStatement(schema, VarBuilder + .uniquifyID(tempScope, "loop", JavaNameKind.LABEL)); + cur.loopLabelStmt = target; + } + } + else + { + // no intervening switch statement; generate simple break + } + break; + } + else if (cur.translatingSwitch) + { + inSwitch = true; + } + cur = cur.outerXlat; + } + JavaBreakStatement breakStmt = new JavaBreakStatement(schema, target); + breakStmt.addAnnotations(obj.getAnnotations()); + block.addMember(breakStmt); + } + + public void visit(VeraContinueStatement obj) + { + JavaContinueStatement contStmt = new JavaContinueStatement(schema); + contStmt.addAnnotations(obj.getAnnotations()); + block.addMember(contStmt); + } + + public void visit(VeraDriveSampleStatement obj) + { + // translate destination + VeraExpression veraDest = obj.getDestination(); + final JavaExpression highExpr, lowExpr; + if (veraDest instanceof VeraArrayAccess) + { + VeraArrayAccess aa = (VeraArrayAccess) veraDest; + veraDest = aa.getArray(); + List indices = aa.getIndices(); + assert (indices.size() == 1); + VeraExpression veraIndex = (VeraExpression) indices.get(0); + JavaExpression indexExpr = translateIntExpr(veraIndex, "index"); + // FIXME: translate index as eval-once + highExpr = indexExpr; + lowExpr = highExpr; + } + else if (veraDest instanceof VeraBitSliceAccess) + { + VeraBitSliceAccess bsa = (VeraBitSliceAccess) veraDest; + veraDest = bsa.getArray(); + VeraRange range = bsa.getRange(); + VeraExpression veraHigh = range.getFrom(); + VeraExpression veraLow = range.getTo(); + highExpr = translateIntExpr(veraHigh, "high"); + lowExpr = translateIntExpr(veraLow, "low"); + } + else + { + highExpr = null; + lowExpr = null; + } + JavaExpression destExpr = translateExpr(veraDest, + types.outputSignalType).toBlockExpr(block, "dest"); + boolean isDrive = exprConv.isOutputSignal(destExpr.getResultType()); + + VeraExpression veraValue = obj.getSource(); + final JavaExpression stmtExpr; + if (veraValue instanceof VeraVoidLiteral) + { + if (isDrive) + { + // void drive + VeraExpression veraDelay = obj.getDelay(); + if (veraDelay != null) + { + stmtExpr = ExpressionBuilder.memberCall(destExpr, + "syncDriveDelay", translateIntExpr(veraDelay, "delay")); + } + else + { + stmtExpr = ExpressionBuilder.memberCall(destExpr, + "syncDrive"); + } + } + else + { + // void assignment; ignored + stmtExpr = null; + } + } + else + { + if (isDrive) + { + // build drive method name and argument list + StringBuffer methodID = new StringBuffer(30); + LinkedList argList = new LinkedList(); + methodID.append("drive"); + if (highExpr != null) + { + methodID.append("Range"); + argList.add(highExpr); + argList.add(lowExpr); + } + if (obj.isAsync()) + { + methodID.append("Async"); + } + else + { + VeraExpression veraDelay = obj.getDelay(); + if (veraDelay != null) + { + methodID.append("Delay"); + argList.addFirst(translateIntExpr(veraDelay, "delay")); + } + } + if (obj.isSoft()) + { + methodID.append("Soft"); + } + if (obj.isNonBlocking() && !obj.isAsync()) + { + methodID.append("NB"); + } + + // translate value + JavaExpression valueExpr = translateExpr(veraValue, null) + .toBlockExpr(block, "value"); + argList.add(exprConv.toObject(valueExpr)); + + // build drive call + JavaExpression[] argArray = new JavaExpression[argList.size()]; + argList.toArray(argArray); + stmtExpr = ExpressionBuilder.memberCall(destExpr, methodID + .toString(), argArray, null); + } + else + { + // build sample assignment + ConvertedExpression result = new ConvertedExpression(schema, + tempScope); + ExpressionTranslator exprXlat = new ExpressionTranslator(this, + containingClass, varInfoMap, returnVar, null, + schema.voidType, result); + exprXlat.setAssignSampleAsync(obj.isAsync()); + exprXlat.buildAssignOp(veraDest, veraValue); + stmtExpr = result.toBlockExpr(block, null); + } + } + + if (stmtExpr != null) + { + JavaExpressionStatement stmt = new JavaExpressionStatement(stmtExpr); + stmt.addAnnotations(obj.getAnnotations()); + block.addMember(stmt); + } + } + + public void visit(VeraExpectStatement obj) + { + // TODO: only simple expects are supported + assert (obj.getExpectKind() == VeraExpectKind.SIMPLE); + + // TODO: expect window is not supported + assert (obj.getWindow() == null); + + // TODO: async expect is not supported + assert (!obj.isAsync()); + + // TODO: only single-term expects are supported + final List terms = obj.getExpectTerms(); + assert (terms.size() == 1); + final VeraExpectTerm term = (VeraExpectTerm) terms.get(0); + + // TODO: only void expects are supported + assert (term.getValue() instanceof VeraVoidLiteral); + assert (term.isEqual()); + + // translate signal expression of expect term + final JavaExpression signalExpr = translateExpr(term.getSignal(), + types.inputSignalType).toBlockExpr(block, "signal"); + // TODO: signal required on LHS of expect term? + assert (exprConv.isInputSignal(signalExpr.getResultType())); + + // void expect + final JavaExpression stmtExpr; + final VeraExpression veraDelay = obj.getDelay(); + if (veraDelay != null) + { + stmtExpr = ExpressionBuilder.memberCall(signalExpr, + "syncSampleDelay", translateIntExpr(veraDelay, "delay")); + } + else + { + stmtExpr = ExpressionBuilder.memberCall(signalExpr, "syncSample"); + } + JavaExpressionStatement stmt = new JavaExpressionStatement(stmtExpr); + stmt.addAnnotations(obj.getAnnotations()); + block.addMember(stmt); + } + + public void visit(VeraExpressionStatement obj) + { + VeraExpression veraExpr = obj.getExpression(); + ConvertedExpression convExpr = translateExpr(veraExpr, schema.voidType); + JavaExpression expr = convExpr.getResultExpr(); + + // is super() call? + JavaBlockMember stmt; + if (expr instanceof JavaConstructorInvocation) + { + // need to transform super() call? + if (transformSuperNewCall) + { + JavaConstructorInvocation ctorCallExpr = (JavaConstructorInvocation) expr; + List callArgs = ctorCallExpr.getArguments(); + + // ignore no-arg super() call + if (callArgs.size() == 0) return; + + // call super.init(...) + JavaSuperReference superRef = new JavaSuperReference( + containingClass); + expr = ExpressionBuilder.memberCall(superRef, "init", + getArgArray(callArgs), containingClass); + stmt = new JavaExpressionStatement(expr); + block.addMember(stmt); + } + else + { + // make sure super() call goes at top of block + assert (!convExpr.hasInitMembers()); + stmt = new JavaExpressionStatement(expr); + block.addMemberAt(stmt, 0); + } + } + else + { + stmt = convExpr.toBlockStmt(block); + } + if (stmt != null) + { + stmt.addAnnotations(obj.getAnnotations()); + } + } + + public void visit(VeraForkStatement obj) + { + JavaVariableReference simRef = new JavaVariableReference(types.dvType + .getField("simulation")); + + // create final copies of shadow variables + VarInfoMap outerVarInfoMap = new VarInfoMap(varInfoMap); + BlockAnalysis forkAnalysis = analyzer.getBlockAnalysis(obj); + if (forkAnalysis != null) + { + // iterate local variables referenced in fork + Iterator varIter = forkAnalysis.getLocalRefs().iterator(); + while (varIter.hasNext()) + { + VeraVariable veraVar = (VeraVariable) varIter.next(); + JavaVariable var = translateVariable(veraVar); + VarInfo varInfo = varInfoMap != null ? varInfoMap.getInfo(var) + : null; + boolean varIsHolder = varInfo != null && varInfo.isHolderVar(); + JavaType varType = var.getType(); + boolean needsClone = false; + if (veraVar.hasModifier(VeraVariableModifier.SHADOW) + && (!var.hasModifier(JavaVariableModifier.FINAL) + || (needsClone = needsClone(varType)) || varIsHolder)) + { + // for shadow variable "Foo foo", create temporary: + // final Foo forked_foo = foo; + // use reference to determine type, in case of holder vars + JavaExpression varRef = ExpressionTranslator + .translateVarRef(veraVar, var, schema, outerVarInfoMap, + null); + JavaType varRefType = varRef.getResultType(); + String id = var.getName().getIdentifier(); + id = id.replace("_holder", ""); + JavaLocalVariable forkVar = VarBuilder.createLocalVar( + tempScope, "forked_" + id, varRefType); + tempScope.addObject(forkVar); + forkVar.addModifier(JavaVariableModifier.FINAL); + if (needsClone) varRef = getCloneExpr(varRef); + forkVar.setInitializer(varRef); + block.addMember(forkVar); + + // translate variable references to forked variable + outerVarInfoMap.addInfo(new VarInfo(schema, veraVar, + forkVar, false)); + } + } + } + + // translate Vera fork statements into DVSimulation.fork() calls + List forkCalls = new LinkedList(); + JavaType threadType = null; + List veraForkStmts = obj.getForkedStatements(); + Iterator iter = veraForkStmts.iterator(); + while (iter.hasNext()) + { + VeraStatement veraStmt = (VeraStatement) iter.next(); + + // create anonymous Runnable class + JavaRawClass anonClass = new JavaRawClass(containingClass); + anonClass.setBaseClass(types.objectType); + anonClass.addBaseInterface(types.runnableType); + + // implement Runnable.run() + JavaFunction runMethod = anonClass + .newMethod("run", schema.voidType); + runMethod.setVisibility(JavaVisibility.PUBLIC); + JavaBlock body = new JavaBlock(schema); + + // create non-final copies of written shadow variables + VarInfoMap innerVarInfoMap = new VarInfoMap(outerVarInfoMap); + BlockAnalysis forkStmtAnalysis = analyzer + .getBlockAnalysis(veraStmt); + if (forkStmtAnalysis != null) + { + // iterate local variables referenced in forked statement + Iterator varIter = forkStmtAnalysis.getLocalRefs().iterator(); + while (varIter.hasNext()) + { + VeraVariable veraVar = (VeraVariable) varIter.next(); + JavaVariable var = translateVariable(veraVar); + JavaType varType = var.getType(); + // duplicate shadow variables that are written but have not + // been cloned for the forked statement + if (veraVar.hasModifier(VeraVariableModifier.SHADOW) + && forkStmtAnalysis.isLocalWrite(veraVar) + && !needsClone(varType)) + { + // for shadow variable "forked_foo", create temporary: + // Foo foo = forked_foo; + // use reference to determine type, in case of holder + // vars + JavaExpression forkVarRef = ExpressionTranslator + .translateVarRef(veraVar, var, schema, + outerVarInfoMap, null); + JavaType forkVarRefType = forkVarRef.getResultType(); + String id = var.getName().getIdentifier(); + id = id.replace("_holder", ""); + JavaLocalVariable shadowVar = VarBuilder + .createLocalVar(tempScope, id, forkVarRefType); + tempScope.addObject(shadowVar); + shadowVar.setInitializer(forkVarRef); + body.addMember(shadowVar); + + // translate variable references to forked variable + innerVarInfoMap.addInfo(new VarInfo(schema, veraVar, + shadowVar, false)); + } + } + } + + // translated Vera statement into run() body + translateStatementInto(veraStmt, body, innerVarInfoMap, anonClass); + body = checkThreadContext(body, forkStmtAnalysis); + runMethod.setBody(body); + + // instantiate the anonymous class + JavaInstanceCreation newExpr = new JavaInstanceCreation( + types.runnableType, null); + newExpr.setAnonymousClass(anonClass); + + // generate fork call: Vera.fork("func", new Runnable() {}) + JavaExpression forkCall = ExpressionBuilder.staticCall( + types.junoType, "fork", new JavaStringLiteral(schema, + describeClassMember(assocMember)), newExpr); + forkCalls.add(forkCall); + + // get returned thread type on first fork + if (threadType == null) + { + threadType = forkCall.getResultType(); + } + } + + JavaStatement stmt = null; + JoinKind joinKind = obj.getJoinKind(); + if (joinKind == JoinKind.NONE) + { + // not joined; add fork calls directly to block + iter = forkCalls.iterator(); + while (iter.hasNext()) + { + JavaExpression forkCall = (JavaExpression) iter.next(); + JavaStatement forkStmt = new JavaExpressionStatement(forkCall); + block.addMember(forkStmt); + if (stmt == null) stmt = forkStmt; + } + } + else + { + // build array initializer with fork calls + JavaArrayType threadArrayType = schema.getArrayType(threadType, 1); + JavaArrayInitializer arrayInit = new JavaArrayInitializer( + threadArrayType); + iter = forkCalls.iterator(); + while (iter.hasNext()) + { + JavaExpression forkCall = (JavaExpression) iter.next(); + arrayInit.addElement(forkCall); + } + + // create new array of threads + JavaArrayCreation arrayNew = new JavaArrayCreation(threadArrayType); + arrayNew.setInitializer(arrayInit); + + // generate join call + String joinMethodID = (joinKind == JoinKind.ANY) ? "joinAny" + : "joinAll"; + JavaExpression joinCall = ExpressionBuilder.memberCall(simRef, + joinMethodID, arrayNew); + stmt = new JavaExpressionStatement(joinCall); + block.addMember(stmt); + } + stmt.addAnnotations(obj.getAnnotations()); + } + + public void visit(VeraForStatement obj) + { + translatingLoop = true; + + // translate init statements + List veraInitStmts = obj.getInitStatements(); + JavaBlock initBlock = new JavaBlock(schema); + boolean gotInitOrUpdate = processForStmts(veraInitStmts, initBlock); + + // translate condition expression + VeraExpression veraCond = (VeraExpression) obj.getCondition(); + ConvertedExpression condInfo = null; + if (veraCond != null) + { + condInfo = translateCondition(veraCond); + gotInitOrUpdate |= condInfo.hasInitExprs() + || condInfo.hasUpdateMembers(); + } + + // translate update statements + List veraUpdateStmts = obj.getUpdateStatements(); + JavaBlock updateBlock = new JavaBlock(schema); + gotInitOrUpdate |= processForStmts(veraUpdateStmts, updateBlock); + + VeraStatement veraStmt = obj.getStatement(); + + // if any statements or expressions have initialization or update + // statements, for-statement must be transformed to a + // while(true)-break-statement + JavaStatement loopStmt; + if (gotInitOrUpdate) + { + // append init members to containing block + block.addMembers(initBlock.getMembers()); + + // create statement block for while-loop + JavaBlock stmtBlock = new JavaBlock(schema); + + // append guard statement to while-block + if (condInfo != null) + { + JavaExpression guardExpr = condInfo.toBlockExpr(stmtBlock, + "guard"); + stmtBlock.addMember(new JavaIfStatement(getNotExpr(guardExpr), + new JavaBreakStatement(schema))); + } + + // translate Vera statement into while-block + translateStatementInto(veraStmt, stmtBlock, varInfoMap, + containingClass); + + // append update members to while-block + stmtBlock.addMembers(updateBlock.getMembers()); + + // append while-statement to containing block + JavaExpression condExpr = new JavaBooleanLiteral(schema, true); + loopStmt = new JavaWhileStatement(condExpr, stmtBlock); + } + else + { + // append for-statement to containing block + JavaForStatement forStmt = new JavaForStatement(schema); + forStmt.addInitStatements(initBlock.getMembers()); + if (condInfo != null) + { + forStmt.setCondition(condInfo.toBlockExpr(block, "guard")); + } + for (JavaBlockMember updateMember : updateBlock.getMembers()) + { + forStmt + .addUpdateStatement((JavaExpressionStatement) updateMember); + } + forStmt.setStatement(translateStatement(veraStmt)); + loopStmt = forStmt; + } + + // put loop statement in labeled statement if necessary + if (loopLabelStmt != null) + { + loopLabelStmt.setStatement(loopStmt); + loopStmt = loopLabelStmt; + } + + loopStmt.addAnnotations(obj.getAnnotations()); + + // append loop to containing block + block.addMember(loopStmt); + + translatingLoop = false; + } + + private boolean processForStmts(List veraStmts, JavaBlock tempBlock) + { + boolean gotInitOrUpdate = false; + Iterator iter = veraStmts.iterator(); + while (iter.hasNext()) + { + VeraExpressionStatement veraStmt = (VeraExpressionStatement) iter + .next(); + VeraExpression veraExpr = veraStmt.getExpression(); + ConvertedExpression exprInfo = translateExpr(veraExpr, tempScope, + containingClass, varInfoMap, returnVar, null, schema.voidType); + gotInitOrUpdate |= exprInfo.hasInitExprs() + || exprInfo.hasUpdateMembers(); + tempBlock.addMembers(exprInfo.getInitMembers()); + tempBlock.addMember(new JavaExpressionStatement(exprInfo + .getResultExpr())); + tempBlock.addMembers(exprInfo.getUpdateMembers()); + } + return gotInitOrUpdate; + } + + public void visit(VeraIfStatement obj) + { + // translate condition + VeraExpression veraCond = obj.getCondition(); + ConvertedExpression condInfo = translateCondition(veraCond); + JavaExpression condExpr = condInfo.toBlockExpr(block, "guard"); + + // translate then-statement + VeraStatement veraThen = obj.getThenStatement(); + JavaStatement thenStmt = translateStatement(veraThen); + + // translate else-statement (if present) + VeraStatement veraElse = obj.getElseStatement(); + JavaStatement elseStmt = (veraElse != null) + ? translateStatement(veraElse) : null; + + // append if-statement to containing block + JavaIfStatement stmt = new JavaIfStatement(condExpr, thenStmt, elseStmt); + stmt.addAnnotations(obj.getAnnotations()); + block.addMember(stmt); + } + + public void visit(VeraRandCaseStatement obj) + { + translatingSwitch = true; + + // create temp variable containing randcase weights + JavaArrayType intArrayType = schema.getArrayType(schema.intType, 1); + JavaLocalVariable weightsVar = VarBuilder.createLocalVar(tempScope, + "weights", intArrayType); + tempScope.addObject(weightsVar); + weightsVar.addModifier(JavaVariableModifier.FINAL); + JavaArrayInitializer initExpr = new JavaArrayInitializer(intArrayType); + weightsVar.setInitializer(initExpr); + + // create call to Vera.randcase() + JavaFunctionReference funcRef = new JavaFunctionReference( + types.junoType.getMethod("randcase", + new JavaType[] { intArrayType })); + JavaFunctionInvocation funcCall = new JavaFunctionInvocation(funcRef); + funcCall.addArgument(new JavaVariableReference(weightsVar)); + + // create switch statement to decode randcase index + JavaSwitchStatement switchStmt = new JavaSwitchStatement(funcCall); + switchStmt.addAnnotations(obj.getAnnotations()); + + // process cases into array initializer and switch statement + List cases = obj.getCaseList(); + Iterator iter = cases.iterator(); + int index = 0; + while (iter.hasNext()) + { + VeraRandCase randCase = (VeraRandCase) iter.next(); + + // translate weight + ConvertedExpression weightInfo = translateExpr( + randCase.getWeight(), schema.intType); + weightInfo.convertResultExpr(schema.intType, exprConv); + JavaExpression weightExpr = weightInfo.toBlockExpr(block, "weight"); + initExpr.addElement(weightExpr); + + // translate statement + JavaStatement stmt = translateStatement(randCase.getStatement()); + + // create switch case + if (iter.hasNext()) + { + JavaSwitchValueCase _case = switchStmt.newValueCase(); + _case.addValue(new JavaIntLiteral(schema, index++)); + _case.addMember(stmt); + _case.addMember(new JavaBreakStatement(schema)); + } + else + { + // make last case default for DA/DU analysis + JavaSwitchCase _case = switchStmt.newDefaultCase(); + _case.addMember(stmt); + } + } + + // add variable and switch to block (after any weight inits/updates) + block.addMember(weightsVar); + block.addMember(switchStmt); + + translatingSwitch = false; + } + + public void visit(VeraRepeatStatement obj) + { + translatingLoop = true; + + // translate condition + VeraExpression veraCond = obj.getCondition(); + ConvertedExpression condInfo = translateExpr(veraCond, schema.intType); + condInfo.convertResultExpr(schema.intType, exprConv); + JavaExpression condExpr = condInfo.toEvalOnceExpr(block, "count"); + + // create loop variable + JavaLocalVariable loopVar = VarBuilder.createLocalVar(tempScope, "i", + schema.intType); + tempScope.addObject(loopVar); + loopVar.setInitializer(new JavaIntLiteral(schema, 0)); + JavaVariableReference loopVarRef = new JavaVariableReference(loopVar); + + // translate statement + VeraStatement veraStmt = obj.getStatement(); + JavaStatement stmt = translateStatement(veraStmt); + + // build for-loop + JavaForStatement forStmt = new JavaForStatement(schema); + forStmt.addInitStatement(loopVar); + forStmt.setCondition(new JavaLess(schema, loopVarRef, condExpr)); + forStmt.addUpdateStatement(new JavaExpressionStatement( + new JavaPreIncrement(schema, loopVarRef))); + forStmt.setStatement(stmt); + + // put loop statement in labeled statement if necessary + JavaStatement loopStmt = forStmt; + if (loopLabelStmt != null) + { + loopLabelStmt.setStatement(loopStmt); + loopStmt = loopLabelStmt; + } + + loopStmt.addAnnotations(obj.getAnnotations()); + + // append for-loop to containing block + block.addMember(loopStmt); + + translatingLoop = false; + } + + public void visit(VeraReturnStatement obj) + { + JavaType returnType = null; + if (returnVar != null) + { + JavaFunction func = (JavaFunction) assocMember; + returnType = func.getType().getReturnType(); + } + JavaReturnStatement stmt = addReturnStatement(block, returnVar, + returnType, varInfoMap); + stmt.addAnnotations(obj.getAnnotations()); + } + + public void visit(VeraSwitchStatement obj) + { + // translate selector expression + VeraExpression veraSel = obj.getSelector(); + ConvertedExpression selInfo = translateExpr(veraSel, null); + + // translate cases into temporary CaseInfo list + List caseInfos = new LinkedList(); + VeraCaseKind kind = obj.getCaseKind(); + boolean useJavaSwitch = (kind == VeraCaseKind.NORMAL); + List veraCases = obj.getCases(); + Iterator caseIter = veraCases.iterator(); + while (caseIter.hasNext()) + { + CaseInfo caseInfo = new CaseInfo(); + caseInfos.add(caseInfo); + + VeraSwitchCase _case = (VeraSwitchCase) caseIter.next(); + if (_case instanceof VeraSwitchValueCase) + { + // translate case value expressions + VeraSwitchValueCase valueCase = (VeraSwitchValueCase) _case; + List veraValues = valueCase.getValues(); + Iterator valueIter = veraValues.iterator(); + while (valueIter.hasNext()) + { + // translate value expression + VeraExpression veraValue = (VeraExpression) valueIter + .next(); + ConvertedExpression valueInfo = translateExpr(veraValue, + null); + caseInfo.valueInfos.add(valueInfo); + + // cannot use Java switch if value has initialization or + // update statements + useJavaSwitch &= !valueInfo.hasInitExprs() + && !valueInfo.hasUpdateMembers(); + if (useJavaSwitch) + { + // cannot use Java switch if value is not a constant + // int/char/short/byte expression + JavaExpression value = valueInfo.getResultExpr(); + useJavaSwitch &= JavaSwitchValueCase + .isValidValue(value); + } + } + } + else + { + assert (_case instanceof VeraSwitchDefaultCase); + } + + // get case statement (but wait to translate it) + caseInfo.veraStmt = _case.getStatement(); + } + + // determine whether to use switch-statement or if-else chain + if (useJavaSwitch) + { + translatingSwitch = true; + + JavaExpression selExpr = selInfo.toBlockExpr(block, "selector"); + + // selector must be int, since translator does not generate + // char/short/byte + // FIXME: should select default case if selector is undefined; + // toInt() generates code that will throw a RuntimeException + selExpr = exprConv.toInt(selExpr); + + JavaSwitchStatement switchStmt = new JavaSwitchStatement(selExpr); + switchStmt.addAnnotations(obj.getAnnotations()); + + // generate switch cases for each CaseInfo + caseIter = caseInfos.iterator(); + while (caseIter.hasNext()) + { + CaseInfo caseInfo = (CaseInfo) caseIter.next(); + JavaSwitchCase _case; + if (!caseInfo.valueInfos.isEmpty()) + { + // generate value cases + JavaSwitchValueCase valueCase = switchStmt.newValueCase(); + Iterator valueIter = caseInfo.valueInfos.iterator(); + while (valueIter.hasNext()) + { + ConvertedExpression valueInfo = (ConvertedExpression) valueIter + .next(); + JavaExpression valueExpr = valueInfo.toBlockExpr(block, + "value"); + valueCase.addValue(valueExpr); + } + _case = valueCase; + } + else + { + // default case; must be last case + assert (!caseIter.hasNext()); + _case = switchStmt.newDefaultCase(); + } + + // add statement to case, followed by break-statement + JavaStatement stmt = translateStatement(caseInfo.veraStmt); + _case.addMember(stmt); + if (canCompleteNormally(stmt)) + { + _case.addMember(new JavaBreakStatement(schema)); + } + } + + block.addMember(switchStmt); + + translatingSwitch = false; + } + else + { + // get simple selector expression + // FIXME: if the case values are primarily of a different type, + // it might be best to convert the selector type + JavaExpression selExpr = selInfo.toEvalOnceExpr(block, "selector"); + + // determine operation to use in comparisons + // FIXME: casex/casez both use =?= + int opcode = (kind == VeraCaseKind.NORMAL) + ? ExpressionTranslator.OP_EXACT_EQ + : ExpressionTranslator.OP_WILD_EQ; + + // generate if-else statements for each CaseInfo + JavaStatement switchStmt = null; + JavaIfStatement prevIfStmt = null; + caseIter = caseInfos.iterator(); + while (caseIter.hasNext()) + { + JavaIfStatement ifStmt = null; + JavaStatement caseStmt; + CaseInfo caseInfo = (CaseInfo) caseIter.next(); + if (!caseInfo.valueInfos.isEmpty()) + { + // build equality test expression for this case: + // selector == value1 || selector == value2 || ... + JavaExpression testExpr = null; + Iterator valueIter = caseInfo.valueInfos.iterator(); + while (valueIter.hasNext()) + { + ConvertedExpression valueInfo = (ConvertedExpression) valueIter + .next(); + // FIXME: init/update statements should probably not + // be added directly to the top-level block + JavaExpression valueExpr = valueInfo.toBlockExpr(block, + "value"); + JavaExpression eqExpr = buildCaseEqualityExpr(selExpr, + valueExpr, opcode); + if (testExpr != null) + { + testExpr = new JavaConditionalOr(schema, testExpr, + eqExpr); + } + else + { + testExpr = eqExpr; + } + } + + // build if-statement for this case + JavaStatement stmt = translateStatement(caseInfo.veraStmt); + ifStmt = new JavaIfStatement(testExpr, stmt); + caseStmt = ifStmt; + } + else + { + // default case; must be last case + assert (!caseIter.hasNext()); + caseStmt = translateStatement(caseInfo.veraStmt); + } + + if (prevIfStmt != null) + { + // chain this statement onto the previous statement + prevIfStmt.setElseStatement(caseStmt); + } + else + { + // add first statement to block when done + switchStmt = caseStmt; + } + prevIfStmt = ifStmt; + } + + assert (switchStmt != null); + switchStmt.addAnnotations(obj.getAnnotations()); + block.addMember(switchStmt); + } + } + + private boolean canCompleteNormally(JavaStatement stmt) + { + // poor man's liveness checking + if (stmt instanceof JavaBlock) + { + // does every statement in block complete normally? + JavaBlock block = (JavaBlock) stmt; + List members = block.getMembers(); + Iterator iter = members.iterator(); + while (iter.hasNext()) + { + Object member = iter.next(); + if (member instanceof JavaStatement) + { + JavaStatement memberStmt = (JavaStatement) member; + if (!canCompleteNormally(memberStmt)) return false; + } + } + return true; + } + else if (stmt instanceof JavaBreakStatement + || stmt instanceof JavaContinueStatement + || stmt instanceof JavaReturnStatement) + { + // break, continue, return never complete normally + return false; + } + else + { + return true; + } + } + + private JavaExpression buildCaseEqualityExpr( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + ConvertedExpression result = new ConvertedExpression(schema, tempScope); + ExpressionTranslator exprXlat = new ExpressionTranslator(this, + containingClass, varInfoMap, returnVar, null, schema.booleanType, + result); + exprXlat.buildEquality(op1, op2, opcode); + result.convertResultExpr(schema.booleanType, exprConv); + return result.toBlockExpr(block, "temp"); + } + + private static class CaseInfo + { + final List valueInfos = new LinkedList(); + VeraStatement veraStmt; + } + + public void visit(VeraSyncStatement obj) + { + final JavaExpression syncExpr; + final List terms = obj.getTerms(); + if (terms.size() == 1) + { + // build syncXXX() call for single signal + final VeraSyncTerm term = (VeraSyncTerm) terms.get(0); + syncExpr = getSyncExpr(term, false); + } + else + { + // build array expression of getXXXEvent() calls + final JavaArrayInitializer arrayInit = new JavaArrayInitializer( + types.eventArrayType); + final Iterator iter = terms.iterator(); + while (iter.hasNext()) + { + VeraSyncTerm term = (VeraSyncTerm) iter.next(); + arrayInit.addElement(getSyncExpr(term, true)); + } + final JavaArrayCreation arrayNew = new JavaArrayCreation( + types.eventArrayType); + arrayNew.setInitializer(arrayInit); + + // wait on sync events + final JavaVariableReference simRef = new JavaVariableReference( + types.dvType.getField("simulation")); + syncExpr = ExpressionBuilder.memberCall(simRef, "waitForAny", + arrayNew); + } + JavaExpressionStatement stmt = new JavaExpressionStatement(syncExpr); + stmt.addAnnotations(obj.getAnnotations()); + block.addMember(stmt); + } + + private JavaExpression getSyncExpr(VeraSyncTerm term, boolean wantEvent) + { + // extract sync signal and bit range + final VeraExpression veraSyncExpr = term.getSignal(); + final VeraExpression veraSignal; + final VeraExpression veraHighBit, veraLowBit; + if (veraSyncExpr instanceof VeraArrayAccess) + { + VeraArrayAccess aa = (VeraArrayAccess) veraSyncExpr; + veraSignal = aa.getArray(); + List indices = aa.getIndices(); + assert (indices.size() == 1); + veraHighBit = (VeraExpression) indices.get(0); + veraLowBit = null; + } + else if (veraSyncExpr instanceof VeraBitSliceAccess) + { + VeraBitSliceAccess bsa = (VeraBitSliceAccess) veraSyncExpr; + veraSignal = bsa.getArray(); + VeraRange range = bsa.getRange(); + veraHighBit = range.getFrom(); + veraLowBit = range.getTo(); + } + else + { + veraSignal = veraSyncExpr; + veraHighBit = null; + veraLowBit = null; + } + + // translate signal + assert (veraSignal instanceof VeraMemberAccess + || veraSignal instanceof VeraSignalReference || veraSignal instanceof VeraSystemClockReference); + final JavaExpression signalExpr = translateExpr(veraSignal, + types.inputSignalType).toBlockExpr(block, "signal"); + assert (exprConv.isInputSignal(signalExpr.getResultType())); + + // generate call to appropriate sync method + final JavaExpression syncExpr; + final EdgeSet edgeSet = term.getEdgeSet(); + boolean async = term.isAsync(); + if (edgeSet.equals(EdgeSet.ANYEDGE)) + { + // generate value change mask, if any + JavaExpression maskExpr = null; + if (veraHighBit != null) + { + final JavaExpression highBitExpr = translateIntExpr( + veraHighBit, "high"); + if (veraLowBit != null) + { + final JavaExpression lowBitExpr = translateIntExpr( + veraLowBit, "low"); + maskExpr = ExpressionBuilder.staticCall( + types.bitVectorOpType, "getMask", highBitExpr, + lowBitExpr); + } + else + { + maskExpr = ExpressionBuilder.staticCall( + types.bitVectorOpType, "getMask", highBitExpr); + } + } + + if (wantEvent) + { + if (maskExpr == null) + { + maskExpr = new JavaNullLiteral(schema); + } + syncExpr = ExpressionBuilder.memberCall(signalExpr, + "getChangeEvent", maskExpr, new JavaBooleanLiteral(schema, + async)); + } + else if (maskExpr != null) + { + syncExpr = ExpressionBuilder.memberCall(signalExpr, async + ? "syncChangeAsync" : "syncChange", maskExpr); + } + else + { + syncExpr = ExpressionBuilder.memberCall(signalExpr, async + ? "syncChangeAsync" : "syncChange"); + } + } + else + { + final JavaExpression edgeExpr = getEdgeExpr(edgeSet); + + // generate edge bit index, if any + JavaExpression bitExpr = null; + if (veraHighBit != null) + { + final JavaExpression highBitExpr = translateIntExpr( + veraHighBit, "high"); + if (veraLowBit != null) + { + final JavaExpression lowBitExpr = translateIntExpr( + veraLowBit, "low"); + bitExpr = ExpressionBuilder.staticCall(types.mathType, + "min", highBitExpr, lowBitExpr); + } + else + { + bitExpr = highBitExpr; + } + } + + if (wantEvent) + { + if (bitExpr == null) + { + bitExpr = new JavaIntLiteral(schema, 0); + } + syncExpr = ExpressionBuilder.memberCall(signalExpr, + "getEdgeEvent", new JavaExpression[] { edgeExpr, bitExpr, + new JavaBooleanLiteral(schema, async) }, null); + } + else if (bitExpr != null) + { + syncExpr = ExpressionBuilder.memberCall(signalExpr, async + ? "syncEdgeAsync" : "syncEdge", edgeExpr, bitExpr); + } + else + { + syncExpr = ExpressionBuilder.memberCall(signalExpr, async + ? "syncEdgeAsync" : "syncEdge", edgeExpr); + } + } + return syncExpr; + } + + public void visit(VeraTerminateStatement obj) + { + JavaVariableReference simRef = new JavaVariableReference(types.dvType + .getField("simulation")); + JavaExpression terminateCall = ExpressionBuilder.memberCall(simRef, + "terminate"); + JavaExpressionStatement stmt = new JavaExpressionStatement( + terminateCall); + stmt.addAnnotations(obj.getAnnotations()); + block.addMember(stmt); + } + + public void visit(VeraWhileStatement obj) + { + translatingLoop = true; + + // translate condition + VeraExpression veraCond = obj.getCondition(); + ConvertedExpression condInfo = translateCondition(veraCond); + + VeraStatement veraStmt = obj.getStatement(); + + // if condition has initialization or update statements, while(cond) + // must be transformed to while(true) { if (!cond) break; } + JavaExpression condExpr; + JavaStatement stmt; + if (condInfo.hasInitExprs() || condInfo.hasUpdateMembers()) + { + // create statement block for while-loop + JavaBlock stmtBlock = new JavaBlock(schema); + + // append guard statement to while-block + JavaExpression guardExpr = condInfo.toBlockExpr(stmtBlock, "guard"); + stmtBlock.addMember(new JavaIfStatement(getNotExpr(guardExpr), + new JavaBreakStatement(schema))); + + // translate Vera statement into while-block + translateStatementInto(veraStmt, stmtBlock, varInfoMap, + containingClass); + + // use true-literal for while-condition + condExpr = new JavaBooleanLiteral(schema, true); + stmt = stmtBlock; + } + else + { + // translate condition and statement literally + condExpr = condInfo.toBlockExpr(block, "guard"); + stmt = translateStatement(veraStmt); + } + + // put loop statement in labeled statement if necessary + JavaStatement loopStmt = new JavaWhileStatement(condExpr, stmt); + if (loopLabelStmt != null) + { + loopLabelStmt.setStatement(loopStmt); + loopStmt = loopLabelStmt; + } + + loopStmt.addAnnotations(obj.getAnnotations()); + + // append while-loop to containing block + block.addMember(loopStmt); + + translatingLoop = false; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BooleanOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/BooleanOperationBuilder.java new file mode 100644 index 0000000..a3b1ceb --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BooleanOperationBuilder.java @@ -0,0 +1,149 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaAnd; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaLogicalNot; +import com.newisys.langschema.java.JavaOr; +import com.newisys.langschema.java.JavaXor; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds various operation expressions for boolean-type operands. + * + * @author Trevor Robinson + */ +final class BooleanOperationBuilder + extends TranslatorModule + implements ArithmeticOperationBuilder +{ + public BooleanOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + private JavaExpression doBooleanOpCall( + String methodID, + JavaExpression op1, + JavaExpression op2) + { + return ExpressionBuilder.staticCall(types.booleanOpType, methodID, op1, + op2); + } + + public JavaExpression add(JavaExpression op1, JavaExpression op2) + { + return new JavaXor(schema, op1, op2); + } + + public JavaExpression subtract(JavaExpression op1, JavaExpression op2) + { + return new JavaXor(schema, op1, op2); + } + + public JavaExpression multiply(JavaExpression op1, JavaExpression op2) + { + return new JavaAnd(schema, op1, op2); + } + + public JavaExpression divide(JavaExpression op1, JavaExpression op2) + { + return doBooleanOpCall("divide", op1, op2); + } + + public JavaExpression mod(JavaExpression op1, JavaExpression op2) + { + return doBooleanOpCall("mod", op1, op2); + } + + public JavaExpression negate(JavaExpression op1) + { + return op1; + } + + public JavaExpression and(JavaExpression op1, JavaExpression op2) + { + return new JavaAnd(schema, op1, op2); + } + + public JavaExpression andNot(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, new JavaAnd(schema, op1, op2)); + } + + public JavaExpression or(JavaExpression op1, JavaExpression op2) + { + return new JavaOr(schema, op1, op2); + } + + public JavaExpression orNot(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, new JavaOr(schema, op1, op2)); + } + + public JavaExpression xor(JavaExpression op1, JavaExpression op2) + { + return new JavaXor(schema, op1, op2); + } + + public JavaExpression xorNot(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, new JavaXor(schema, op1, op2)); + } + + public JavaExpression not(JavaExpression op1) + { + return new JavaLogicalNot(schema, op1); + } + + public JavaExpression reverse(JavaExpression op1) + { + return op1; + } + + public JavaExpression reductiveAnd(JavaExpression op1) + { + return op1; + } + + public JavaExpression reductiveAndNot(JavaExpression op1) + { + return new JavaLogicalNot(schema, op1); + } + + public JavaExpression reductiveOr(JavaExpression op1) + { + return op1; + } + + public JavaExpression reductiveOrNot(JavaExpression op1) + { + return new JavaLogicalNot(schema, op1); + } + + public JavaExpression reductiveXor(JavaExpression op1) + { + return op1; + } + + public JavaExpression reductiveXorNot(JavaExpression op1) + { + return new JavaLogicalNot(schema, op1); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslator.java new file mode 100644 index 0000000..778bc54 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslator.java @@ -0,0 +1,38 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.List; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.vera.VeraExpression; +import com.newisys.langschema.vera.VeraFunction; + +/** + * Interface for translating built-in task/function calls. + * + * @author Trevor Robinson + */ +interface BuiltinFunctionTranslator +{ + void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslatorMap.java b/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslatorMap.java new file mode 100644 index 0000000..8e86a95 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/BuiltinFunctionTranslatorMap.java @@ -0,0 +1,970 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.newisys.juno.runtime.Juno; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Schema; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.util.SemanticException; +import com.newisys.langschema.vera.*; + +/** + * Map of translators for built-in task/function calls. + * + * @author Trevor Robinson + */ +final class BuiltinFunctionTranslatorMap +{ + private final Map builtinFuncMap = new HashMap(); + + public BuiltinFunctionTranslatorMap(SchemaTypes types) + { + SimpleStaticTranslator veraStaticXlat = new SimpleStaticTranslator( + types.junoType); + + builtinFuncMap.put("alloc", veraStaticXlat); + builtinFuncMap.put("assert", new AssertTranslator()); + builtinFuncMap.put("assoc_index", new AssocIndexTranslator()); + builtinFuncMap.put("cast_assign", new CastAssignTranslator()); + builtinFuncMap.put("delay", veraStaticXlat); + builtinFuncMap.put("error", veraStaticXlat); + builtinFuncMap.put("error_mode", veraStaticXlat); + builtinFuncMap.put("exit", veraStaticXlat); + builtinFuncMap.put("fclose", veraStaticXlat); + builtinFuncMap.put("feof", veraStaticXlat); + builtinFuncMap.put("ferror", veraStaticXlat); + builtinFuncMap.put("fflush", veraStaticXlat); + builtinFuncMap.put("flag", veraStaticXlat); + builtinFuncMap.put("fopen", veraStaticXlat); + builtinFuncMap.put("fprintf", veraStaticXlat); + builtinFuncMap.put("freadb", veraStaticXlat); + builtinFuncMap.put("freadh", veraStaticXlat); + builtinFuncMap.put("freadstr", veraStaticXlat); + builtinFuncMap.put("get_coverage", null); + builtinFuncMap.put("get_cycle", new GetCycleTranslator()); + builtinFuncMap.put("get_inst_coverage", null); + builtinFuncMap.put("get_plus_arg", veraStaticXlat); + builtinFuncMap.put("get_systime", veraStaticXlat); + builtinFuncMap.put("get_time", veraStaticXlat); + builtinFuncMap.put("get_time_unit", null); + builtinFuncMap.put("getstate", new GetStateTranslator()); + builtinFuncMap.put("initstate", null); + builtinFuncMap.put("lock_file", veraStaticXlat); + builtinFuncMap.put("mailbox_get", veraStaticXlat); + builtinFuncMap.put("mailbox_put", veraStaticXlat); + builtinFuncMap.put("os_command", veraStaticXlat); + builtinFuncMap.put("printf", veraStaticXlat); + builtinFuncMap.put("prodget", null); + builtinFuncMap.put("prodset", null); + builtinFuncMap.put("psprintf", veraStaticXlat); + builtinFuncMap.put("rand48", veraStaticXlat); + builtinFuncMap.put("random", veraStaticXlat); + builtinFuncMap.put("region_enter", veraStaticXlat); + builtinFuncMap.put("region_exit", veraStaticXlat); + builtinFuncMap.put("rewind", veraStaticXlat); + builtinFuncMap.put("semaphore_get", veraStaticXlat); + builtinFuncMap.put("semaphore_put", veraStaticXlat); + builtinFuncMap.put("setstate", new SetStateTranslator()); + builtinFuncMap.put("signal_connect", null); + builtinFuncMap.put("sprintf", new SprintfTranslator()); + builtinFuncMap.put("srandom", veraStaticXlat); + builtinFuncMap.put("sscanf", veraStaticXlat); + builtinFuncMap.put("stop", null); + builtinFuncMap.put("suspend_thread", new SuspendThreadTranslator()); + builtinFuncMap.put("sync", veraStaticXlat); + builtinFuncMap.put("timeout", null); + builtinFuncMap.put("trace", null); + builtinFuncMap.put("trigger", veraStaticXlat); + builtinFuncMap.put("unlock_file", veraStaticXlat); + builtinFuncMap.put("urand48", veraStaticXlat); + builtinFuncMap.put("urandom", veraStaticXlat); + builtinFuncMap.put("urandom_range", veraStaticXlat); + builtinFuncMap.put("vca", null); + builtinFuncMap.put("vera_bit_reverse", null); + builtinFuncMap.put("vera_crc", null); + builtinFuncMap.put("vera_get_clk_name", veraStaticXlat); + builtinFuncMap.put("vera_get_dir", veraStaticXlat); + builtinFuncMap.put("vera_get_ifc_name", veraStaticXlat); + builtinFuncMap.put("vera_get_in_depth", veraStaticXlat); + builtinFuncMap.put("vera_get_in_skew", veraStaticXlat); + builtinFuncMap.put("vera_get_in_type", veraStaticXlat); + builtinFuncMap.put("vera_get_name", veraStaticXlat); + builtinFuncMap.put("vera_get_out_skew", veraStaticXlat); + builtinFuncMap.put("vera_get_out_type", veraStaticXlat); + builtinFuncMap.put("vera_get_surrx_D", null); + builtinFuncMap.put("vera_get_surrx_F", null); + builtinFuncMap.put("vera_get_surrx_R", null); + builtinFuncMap.put("vera_get_surrx_Z", null); + builtinFuncMap.put("vera_get_width", veraStaticXlat); + builtinFuncMap.put("vera_has_surrx", null); + builtinFuncMap.put("vera_is_bound", veraStaticXlat); + builtinFuncMap.put("vera_pack", null); + builtinFuncMap.put("vera_pack_big_endian", null); + builtinFuncMap.put("vera_plot", null); + builtinFuncMap.put("vera_report_profile", veraStaticXlat); + builtinFuncMap.put("vera_unpack", null); + builtinFuncMap.put("vera_unpack_big_endian", null); + builtinFuncMap.put("vsv_call_func", null); + builtinFuncMap.put("vsv_call_task", null); + builtinFuncMap.put("vsv_close_conn", null); + builtinFuncMap.put("vsv_get_conn_err", null); + builtinFuncMap.put("vsv_make_client", null); + builtinFuncMap.put("vsv_make_server", null); + builtinFuncMap.put("vsv_up_connections", null); + builtinFuncMap.put("vsv_wait_for_done", null); + builtinFuncMap.put("vsv_wait_for_input", null); + builtinFuncMap.put("wait_child", veraStaticXlat); + builtinFuncMap.put("wait_var", new WaitVarTranslator()); + + SimpleMemberTranslator memberXlat = new SimpleMemberTranslator(); + + builtinFuncMap.put("::constraint_mode", memberXlat); + builtinFuncMap.put("::finalize", memberXlat); + builtinFuncMap.put("::object_compare", memberXlat); + builtinFuncMap.put("::object_copy", memberXlat); + builtinFuncMap.put("::object_print", memberXlat); + builtinFuncMap.put("::pack", memberXlat); + builtinFuncMap.put("::post_pack", memberXlat); + builtinFuncMap.put("::post_randomize", memberXlat); + builtinFuncMap.put("::post_unpack", memberXlat); + builtinFuncMap.put("::pre_pack", memberXlat); + builtinFuncMap.put("::pre_randomize", memberXlat); + builtinFuncMap.put("::pre_unpack", memberXlat); + builtinFuncMap.put("::rand_mode", memberXlat); + builtinFuncMap.put("::randomize", memberXlat); + builtinFuncMap.put("::unpack", memberXlat); + + StringMemberTranslator stringXlat = new StringMemberTranslator(); + + builtinFuncMap.put("string::atobin", stringXlat); + builtinFuncMap.put("string::atohex", stringXlat); + builtinFuncMap.put("string::atoi", stringXlat); + builtinFuncMap.put("string::atooct", stringXlat); + builtinFuncMap.put("string::backref", stringXlat); + builtinFuncMap.put("string::bittostr", stringXlat); + builtinFuncMap.put("string::compare", stringXlat); + builtinFuncMap.put("string::get_status", stringXlat); + builtinFuncMap.put("string::get_status_msg", stringXlat); + builtinFuncMap.put("string::getc", stringXlat); + builtinFuncMap.put("string::hash", stringXlat); + builtinFuncMap.put("string::icompare", stringXlat); + builtinFuncMap.put("string::itoa", stringXlat); + builtinFuncMap.put("string::len", stringXlat); + builtinFuncMap.put("string::match", stringXlat); + builtinFuncMap.put("string::postmatch", stringXlat); + builtinFuncMap.put("string::prematch", stringXlat); + builtinFuncMap.put("string::putc", stringXlat); + builtinFuncMap.put("string::search", stringXlat); + builtinFuncMap.put("string::substr", stringXlat); + builtinFuncMap.put("string::thismatch", stringXlat); + builtinFuncMap.put("string::tolower", stringXlat); + builtinFuncMap.put("string::toupper", stringXlat); + } + + public boolean isBuiltinFunction(VeraFunction func) + { + String name = func.getName().getCanonicalName(); + return builtinFuncMap.containsKey(name); + } + + public BuiltinFunctionTranslator getTranslator(VeraFunction func) + { + String name = func.getName().getCanonicalName(); + return builtinFuncMap.get(name); + } + + /** + * Translates a built-in task/function call to a Java static method call + * of the same name in the given class. + */ + private class SimpleStaticTranslator + implements BuiltinFunctionTranslator + { + private final JavaRawAbstractClass cls; + + public SimpleStaticTranslator(JavaRawAbstractClass cls) + { + this.cls = cls; + } + + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + String methodID = func.getName().getIdentifier(); + exprXlat.translateCall(func, cls, methodID, obj, veraArgExprs); + } + } + + /** + * Translates a built-in task/function call to a Java instance method call + * of the same name on the given object (if specified) or 'this'. + */ + private class SimpleMemberTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + JavaRawAbstractClass cls = (obj != null) + ? (JavaRawAbstractClass) obj.getResultType() + : (JavaRawAbstractClass) exprXlat.containingType; + String methodID = func.getName().getIdentifier(); + exprXlat.translateCall(func, cls, methodID, obj, veraArgExprs); + } + } + + /** + * Translates usage of the (user-defined) assert macro to a Java assertion + * statement. + */ + private class AssertTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + // Vera: assert(foo); + // Java: assert(foo); + int argCount = veraArgExprs.size(); + assert (argCount == 1); + VeraExpression veraTestExpr = veraArgExprs.get(0); + JavaExpression testExpr = exprXlat.translateNestedExpr( + veraTestExpr, exprXlat.schema.booleanType); + // NOTE: our Vera assert() macro is unfortunately defined as + // 'if (!(foo)) assertFailed()', which means that if foo is X/Z, + // the assert does not fail + testExpr = exprXlat.exprConv.toBoolean(testExpr, false, true); + exprXlat.result.addInitMember(new JavaAssertStatement(testExpr)); + } + } + + /** + * Translates calls to assoc_index. + */ + private class AssocIndexTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + int argCount = veraArgExprs.size(); + assert (argCount >= 2 && argCount <= 3); + + VeraExpression arg0 = veraArgExprs.get(0); + int op = ((VeraIntegerLiteral) arg0).getValue(); + + VeraExpression arg1 = veraArgExprs.get(1); + JavaExpression arrayExpr = exprXlat.translateNestedExpr(arg1, + "array"); + + JavaExpression result = null; + if (argCount == 2) + { + if (op == Juno.CHECK || op == Juno.DELETE) + { + // assoc_index(CHECK, array) -> array.check() + // assoc_index(DELETE, array) -> array.delete() + result = ExpressionBuilder.memberCall(arrayExpr, + op == Juno.CHECK ? "check" : "delete"); + } + else + { + throw new SemanticException("Invalid assoc_index opcode"); + } + } + else + { + JavaType arrayType = arrayExpr.getResultType(); + boolean isBitArray = exprXlat.types.bitAssocArrayType + .isAssignableFrom(arrayType); + JavaType formalIndexType = isBitArray + ? exprXlat.schema.bitVectorType : exprXlat.schema + .getStringType(); + VeraExpression arg2 = veraArgExprs.get(2); + if (op == Juno.CHECK || op == Juno.DELETE) + { + // assoc_index(CHECK, array, index) -> array.check(index) + // assoc_index(DELETE, array, index) -> array.delete(index) + JavaExpression indexExpr = exprXlat.translateNestedExpr( + arg2, "index", formalIndexType); + indexExpr = exprXlat.exprConv.toType(formalIndexType, + indexExpr); + result = ExpressionBuilder.memberCall(arrayExpr, + op == Juno.CHECK ? "check" : "delete", indexExpr); + } + else if (op == Juno.FIRST || op == Juno.NEXT) + { + // assoc_index(FIRST, array, index) + // (BitVector) -> !(index = array.first()).containsXZ() + // (Integer/String) -> (index = array.first()) != null + // (JunoString) -> !(index.assign(array.first())).equals(JunoString.NULL) + // assoc_index(NEXT, array, index) + // (BitVector) -> !(index = array.next(index)).containsXZ() + // (Integer/String) -> (index = array.next(index)) != null + // (JunoString) -> !(index.assign(array.next(index))).equals(JunoString.NULL) + // + // NOTE: These translations have a subtle difference from + // the most literal translation to Vera.assoc_index: the + // index expression is assigned to null/X when there is no + // first/next index instead of being left unassigned. + JavaExpression indexExpr = null; + JavaType actualIndexType = null; + int indexKind = 0; + if (exprXlat.hasJavaLHS(arg2)) + { + indexExpr = exprXlat.translateNestedExpr(arg2); + actualIndexType = indexExpr.getResultType(); + if (exprXlat.schema.isBitVector(actualIndexType)) + { + indexKind = 1; + } + else if (actualIndexType == exprXlat.schema.integerWrapperType + || actualIndexType == exprXlat.schema + .getStringType()) + { + indexKind = 2; + } + else if (actualIndexType == exprXlat.types.junoStringType) + { + indexKind = 3; + } + } + if (indexKind > 0) + { + LHSTranslator lhsXlat = new SimpleLHSTranslator( + exprXlat, exprXlat.result, indexExpr, + op == Juno.NEXT, true); + JavaExpression callExpr; + if (op == Juno.FIRST) + { + callExpr = ExpressionBuilder.memberCall(arrayExpr, + "first"); + } + else + { + JavaExpression prevIndexExpr = exprXlat.exprConv + .toType(formalIndexType, lhsXlat + .getReadExpression()); + callExpr = ExpressionBuilder.memberCall(arrayExpr, + "next", prevIndexExpr); + } + callExpr = exprXlat.convertRHS(callExpr, + formalIndexType, actualIndexType, false); + JavaExpression assignExpr = lhsXlat.getWriteExpression( + callExpr).getResultExpr(); + switch (indexKind) + { + case 1: + result = new JavaLogicalNot(exprXlat.schema, + ExpressionBuilder.memberCall(assignExpr, + "containsXZ")); + break; + case 2: + result = new JavaNotEqual(exprXlat.schema, + assignExpr, + new JavaNullLiteral(exprXlat.schema)); + break; + case 3: + result = new JavaLogicalNot(exprXlat.schema, + ExpressionBuilder.memberCall(assignExpr, + "equals", new JavaVariableReference( + exprXlat.types.junoStringType + .getField("NULL")))); + break; + default: + assert false; + } + } + else + { + // assoc_index(FIRST, array, index) + // -> Vera.assoc_index(Vera.FIRST, array, index_holder) + // assoc_index(NEXT, array, index) + // -> Vera.assoc_index(Vera.NEXT, array, index_holder) + exprXlat.translateCall(func, exprXlat.types.junoType, + "assoc_index", obj, veraArgExprs); + } + } + else + { + throw new SemanticException("Invalid assoc_index opcode"); + } + } + if (result != null) + { + exprXlat.result.setResultExpr(result); + } + } + } + + /** + * Translates calls to cast_assign. + */ + private class CastAssignTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + int argCount = veraArgExprs.size(); + assert (argCount >= 2 && argCount <= 3); + boolean checked = (argCount == 3); + VeraExpression veraDstExpr = veraArgExprs.get(0); + VeraExpression veraSrcExpr = veraArgExprs.get(1); + VeraType veraDstType = veraDstExpr.getResultType(); + VeraType veraSrcType = veraSrcExpr.getResultType(); + boolean voidContext = exprXlat.desiredResultType instanceof JavaVoidType; + + JavaExpression result = null; + boolean alwaysFail = false; + if (veraDstType.isAssignableFrom(veraSrcType)) + { + // identical types, + // string/enum/integer/bit to integer/bit, + // class upcast + + // handle as normal assignment: dst = src + exprXlat.buildAssignOp(veraDstExpr, veraSrcExpr); + + // flatten assignment expression into init statement + exprXlat.result.flatten(null); + } + else if (veraDstType instanceof VeraUserClass + && veraSrcType instanceof VeraUserClass) + { + VeraUserClass veraDstClass = (VeraUserClass) veraDstType; + VeraUserClass veraSrcClass = (VeraUserClass) veraSrcType; + if (veraSrcClass.isSuperclassOf(veraDstClass)) + { + // downcast + + // translate result class + JavaRawClass dstClass = exprXlat.translateClass( + veraDstClass, false); + + // translate source expression + JavaExpression srcExpr = exprXlat.translateNestedExpr( + veraSrcExpr, "src"); + if (checked) + { + // source will be evaluated twice if checked + srcExpr = EvalOnceExprBuilder.evalConstExpr(srcExpr, + exprXlat.result, "src", true); + } + + // build cast expression: (DstClass) src + JavaExpression castExpr = new JavaCastExpression(dstClass, + srcExpr); + JavaNullLiteral nullLiteral = null; + if (checked) + { + // conditional cast: + // src instanceof DstClass ? (DstClass) src : null + nullLiteral = new JavaNullLiteral(exprXlat.schema); + castExpr = new JavaConditional(new JavaTypeTest( + srcExpr, dstClass), castExpr, nullLiteral); + } + + // build assignment expression: dst = + LHSTranslator lhsXlat = exprXlat.translateLHS(veraDstExpr, + null, checked && !voidContext, true); + lhsXlat.getWriteExpression(castExpr).mergeIntoInit( + exprXlat.result); + + // build result expression: dst != null || src == null + if (checked && !voidContext) + { + result = new JavaConditionalOr( + exprXlat.schema, + new JavaNotEqual(exprXlat.schema, lhsXlat + .getReadExpression(), nullLiteral), + new JavaEqual(exprXlat.schema, srcExpr, nullLiteral)); + } + } + else + { + // fail (unrelated declared types) + alwaysFail = true; + } + } + else if (veraDstType.isIntegralConvertible() + && (veraSrcType.isIntegralConvertible() || veraSrcType instanceof VeraStringType)) + { + // translate source expression + JavaExpression srcExpr = exprXlat.translateNestedExpr( + veraSrcExpr, "src"); + if (checked && !voidContext + && veraDstType instanceof VeraEnumeration) + { + // source will be evaluated twice if checked, not in void + // context, and assigning to an enum + srcExpr = EvalOnceExprBuilder.evalConstExpr(srcExpr, + exprXlat.result, "src", true); + } + + JavaExpression intExpr; + if (veraSrcType instanceof VeraStringType) + { + // string to integer/bit/enum + srcExpr = exprXlat.exprConv.toJavaString(srcExpr, true); + if (veraDstType instanceof VeraBitVectorType) + { + // new BitVector(src.getBytes()) + JavaExpression bytesExpr = ExpressionBuilder + .memberCall(srcExpr, "getBytes"); + intExpr = ExpressionBuilder.newInstance( + exprXlat.schema.bitVectorType, bytesExpr); + } + else + { + // IntOp.toInt(src) + assert (veraDstType instanceof VeraIntegerType); + intExpr = ExpressionBuilder.staticCall( + exprXlat.types.intOpType, "toInt", srcExpr); + } + } + else + { + // enum/integer/bit to enum + assert (veraSrcType.isIntegralConvertible()); + intExpr = srcExpr; + } + + LHSTranslator lhsXlat = exprXlat.translateLHS(veraDstExpr, + null, checked && !voidContext, true); + + JavaExpression finalExpr; + if (veraDstType instanceof VeraEnumeration) + { + // convert source expression to Integer + JavaExpression integerExpr = exprXlat.exprConv + .toInteger(intExpr); + if (checked && !voidContext) + { + // source will be evaluated twice if checked + integerExpr = EvalOnceExprBuilder.evalConstExpr( + integerExpr, exprXlat.result, "src", true); + } + + // build enum conversion expression + VeraEnumeration veraEnum = (VeraEnumeration) veraDstType; + JavaEnum enumClass = exprXlat.translateEnum(veraEnum); + JavaBooleanLiteral checkedLiteral = new JavaBooleanLiteral( + exprXlat.schema, checked); + finalExpr = ExpressionBuilder.staticCall(enumClass, + "forValue", integerExpr, checkedLiteral); + + // build result expression: dst.isDefined() || src == null + if (checked && !voidContext) + { + result = new JavaConditionalOr(exprXlat.schema, + ExpressionBuilder.memberCall(lhsXlat + .getReadExpression(), "isDefined"), + new JavaEqual(exprXlat.schema, integerExpr, + new JavaNullLiteral(exprXlat.schema))); + } + } + else + { + // string to integer/bit + finalExpr = intExpr; + } + + // build assignment expression: dst = + lhsXlat.getWriteExpression(finalExpr).mergeIntoInit( + exprXlat.result); + } + else + { + // fail + alwaysFail = true; + } + + if (alwaysFail) + { + if (checked) + { + // assign null/X to dst + LHSTranslator lhsXlat = exprXlat.translateLHS(veraDstExpr, + null, false, true); + JavaExpression undefValue = exprXlat.getInitValue(lhsXlat + .getResultType(), true, false); + lhsXlat.getWriteExpression(undefValue).mergeIntoInit( + exprXlat.result); + } + else + { + // throw exception for bad cast + exprXlat.result.addInitExpr(ExpressionBuilder.staticCall( + exprXlat.types.junoType, "badCast")); + } + + // return false + result = new JavaBooleanLiteral(exprXlat.schema, false); + } + else if (result == null && !voidContext) + { + // if result expression is not set, always return true + result = new JavaBooleanLiteral(exprXlat.schema, true); + } + + exprXlat.result.setOptionalResult(true); + exprXlat.result.setResultExpr(result); + } + } + + /** + * Translates calls to get_cycle. + */ + private class GetCycleTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + // Vera: foo = get_cycle(); + // Java: foo = Vera.systemClock.getCycleCount(); + // Vera: foo = get_cycle(signal); + // Java: foo = signal.getClock().getCycleCount(); + int argCount = veraArgExprs.size(); + assert (argCount >= 0 && argCount <= 1); + JavaExpression clockExpr; + if (argCount == 0) + { + clockExpr = new JavaVariableReference(exprXlat.types.junoType + .getField("systemClock")); + } + else + { + VeraExpression veraSignalExpr = veraArgExprs.get(0); + JavaExpression signalExpr = exprXlat.translateNestedExpr( + veraSignalExpr, "signal", exprXlat.types.signalType); + clockExpr = ExpressionBuilder + .memberCall(signalExpr, "getClock"); + } + JavaExpression getCycleCountCall = ExpressionBuilder.memberCall( + clockExpr, "getCycleCount"); + exprXlat.result.setResultExpr(getCycleCountCall); + } + } + + /** + * Translates calls to get_state. + * Not implemented, but not generally necessary with Java. + */ + private class GetStateTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + int argCount = veraArgExprs.size(); + assert (argCount >= 1 && argCount <= 2); + // TODO: translate type of VeraRandomState + if (true) return; + VeraExpression veraStateExpr = veraArgExprs.get(0); + LHSTranslator lhsXlat = exprXlat.translateLHS(veraStateExpr, null, + false, true); + if (argCount == 1) + { + // thread getstate() + // Vera: getstate(foo); + // Java: foo = DV.simulation.getRandom().clonePRNG(); + JavaVariableReference simRef = new JavaVariableReference( + exprXlat.types.dvType.getField("simulation")); + JavaExpression getRandomCall = ExpressionBuilder.memberCall( + simRef, "getRandom"); + JavaExpression clonePRNGCall = ExpressionBuilder.memberCall( + getRandomCall, "clonePRNG"); + lhsXlat.getWriteExpression(clonePRNGCall).mergeIntoResult( + exprXlat.result); + } + else + { + // TODO: object getstate() + assert false; + } + } + } + + /** + * Translates calls to set_state. + * Not implemented, but not generally necessary with Java. + */ + private class SetStateTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + int argCount = veraArgExprs.size(); + assert (argCount >= 1 && argCount <= 2); + // TODO: translate type of VeraRandomState + if (true) return; + VeraExpression veraStateExpr = veraArgExprs.get(0); + JavaExpression stateExpr = exprXlat.translateNestedExpr( + veraStateExpr, "state"); + if (argCount == 1) + { + // thread setstate() + // Vera: setstate(foo); + // Java: DV.simulation.setRandom(foo.clonePRNG()); + JavaVariableReference simRef = new JavaVariableReference( + exprXlat.types.dvType.getField("simulation")); + JavaExpression clonePRNGCall = ExpressionBuilder.memberCall( + stateExpr, "clonePRNG"); + JavaExpression setRandomCall = ExpressionBuilder.memberCall( + simRef, "setRandom", clonePRNGCall); + exprXlat.result.setResultExpr(setRandomCall); + } + else + { + // TODO: object setstate() + assert false; + } + } + } + + /** + * Translates calls to sprintf. + */ + private class SprintfTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + assert (veraArgExprs.size() > 0); + final VeraExpression veraResultArgExpr = veraArgExprs.get(0); + final JavaExpression resultArgExpr = exprXlat.translateNestedExpr( + veraResultArgExpr, "result"); + final JavaType resultType = resultArgExpr.getResultType(); + if (resultType == exprXlat.schema.getStringType()) + { + // result argument is String; translate as sprintf(foo, ...) as + // foo = psprintf(...) + final Schema veraSchema = func.getSchema(); + final Iterator< ? extends NamedObject> iter = veraSchema + .lookupObjects("psprintf", VeraNameKind.NON_TYPE); + assert (iter.hasNext()); + final VeraFunction psprintfFunc = (VeraFunction) iter.next(); + final List psprintfArgs = new LinkedList( + veraArgExprs); + psprintfArgs.remove(0); + exprXlat.translateCall(psprintfFunc, exprXlat.types.junoType, + "psprintf", null, psprintfArgs); + JavaExpression expr = exprXlat.result.getResultExpr(); + expr = new JavaAssign(exprXlat.schema, resultArgExpr, expr); + exprXlat.result.setResultExpr(expr); + } + else + { + // result argument should be JunoString + exprXlat.translateCall(func, exprXlat.types.junoType, + "sprintf", null, veraArgExprs); + } + } + } + + /** + * Translates calls to suspend_thread. + */ + private class SuspendThreadTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + // Vera: suspend_thread(); + // Java: DV.simulation.yield(); + assert (veraArgExprs.size() == 0); + JavaVariableReference simRef = new JavaVariableReference( + exprXlat.types.dvType.getField("simulation")); + JavaExpression yieldCall = ExpressionBuilder.memberCall(simRef, + "yield"); + exprXlat.result.setResultExpr(yieldCall); + } + } + + /** + * Translates calls to wait_var. + */ + private class WaitVarTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + // Vera: wait_var(var, ...); + // Java: Vera.sync(Vera.ANY, varevent, ...); + final int argCount = veraArgExprs.size(); + assert (argCount > 0); + JavaExpression[] javaArgExprs = new JavaExpression[argCount + 1]; + int argIndex = 0; + javaArgExprs[argIndex++] = new JavaVariableReference( + exprXlat.types.junoType.getField("ANY")); + for (VeraExpression veraExpr : veraArgExprs) + { + LHSTranslator lhsXlat = exprXlat.translateLHS(veraExpr, null, + true, false); + JavaExpression eventRef = lhsXlat.getUpdateEvent(); + if (eventRef == null) + { + exprXlat + .log("Warning: wait_var event not defined for variable: " + + veraExpr); + eventRef = new JavaNullLiteral(exprXlat.schema); + } + javaArgExprs[argIndex++] = eventRef; + } + JavaExpression syncCall = ExpressionBuilder.staticCall( + exprXlat.types.junoType, "sync", javaArgExprs, null); + exprXlat.result.setResultExpr(syncCall); + } + } + + /** + * Translates calls to string member functions. Primarily used when a + * Vera string is translated to a Java String; the implementation for + * translations to JunoString is trivial. + */ + private class StringMemberTranslator + implements BuiltinFunctionTranslator + { + public void translate( + ExpressionTranslator exprXlat, + VeraFunction func, + JavaExpression obj, + List veraArgExprs) + { + assert (obj != null); + JavaRawAbstractClass cls = (JavaRawAbstractClass) obj + .getResultType(); + String methodID = func.getName().getIdentifier(); + if (cls == exprXlat.types.junoStringType) + { + exprXlat.translateCall(func, cls, methodID, obj, veraArgExprs); + } + else + { + assert (cls == exprXlat.schema.getStringType()); + boolean writeBack = false; + boolean msg = false; + if (methodID.equals("tolower")) + { + // translate directly to String.toLowerCase + exprXlat.translateCall(func, cls, "toLowerCase", obj, + veraArgExprs); + } + else if (methodID.equals("toupper")) + { + // translate directly to String.toUpperCase + exprXlat.translateCall(func, cls, "toUpperCase", obj, + veraArgExprs); + } + else if (methodID.equals("itoa") || methodID.equals("bittostr")) + { + // translate to static StringOp call with assign to 'this' + // expression instead of passing it + writeBack = true; + exprXlat.translateCall(func, exprXlat.types.stringOpType, + methodID, null, veraArgExprs); + } + else if (methodID.equals("get_status") + || (msg = methodID.equals("get_status_msg"))) + { + // translate to JunoString.OK / StringOp.get_status_msg(OK) + // (since the analysis phase guarantees the status is OK) + JavaVariableReference okRef = new JavaVariableReference( + exprXlat.types.junoStringType.getField("OK")); + JavaExpression result = msg ? ExpressionBuilder.staticCall( + exprXlat.types.stringOpType, methodID, okRef) : okRef; + exprXlat.result.setResultExpr(result); + } + else if (methodID.equals("prematch") + || methodID.equals("postmatch") + || methodID.equals("thismatch") + || methodID.equals("backref")) + { + // these functions return the null string if no match + JavaVariableReference nullRef = new JavaVariableReference( + exprXlat.types.junoStringType.getField("NULL")); + exprXlat.result.setResultExpr(nullRef); + } + else + { + // only putc() requires write-back + writeBack = methodID.equals("putc"); + exprXlat.translateCallAsStatic(func, + exprXlat.types.stringOpType, methodID, obj, + veraArgExprs); + } + if (writeBack) + { + // potential multiple references to 'this' expression + // should be okay, since Vera requires it to be a variable + // reference or member variable access + JavaExpression expr = exprXlat.result.getResultExpr(); + expr = new JavaAssign(exprXlat.schema, obj, expr); + exprXlat.result.setResultExpr(expr); + } + } + } + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ClassMemberTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/ClassMemberTranslator.java new file mode 100644 index 0000000..fd0e07e --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ClassMemberTranslator.java @@ -0,0 +1,142 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.List; + +import com.newisys.langschema.Annotation; +import com.newisys.langschema.constraint.ConsExpression; +import com.newisys.langschema.java.JavaAnnotation; +import com.newisys.langschema.java.JavaAnnotationArrayInitializer; +import com.newisys.langschema.java.JavaAnnotationType; +import com.newisys.langschema.java.JavaArrayType; +import com.newisys.langschema.java.JavaFunction; +import com.newisys.langschema.java.JavaPackage; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaSchemaObject; +import com.newisys.langschema.java.JavaStringLiteral; +import com.newisys.langschema.vera.VeraClassConstraint; +import com.newisys.langschema.vera.VeraClassMemberVisitor; +import com.newisys.langschema.vera.VeraEnumeration; +import com.newisys.langschema.vera.VeraEnumerationElement; +import com.newisys.langschema.vera.VeraMemberFunction; +import com.newisys.langschema.vera.VeraMemberVariable; + +/** + * Schema translator for class members. + * + * @author Trevor Robinson + */ +final class ClassMemberTranslator + extends TranslatorModule + implements VeraClassMemberVisitor +{ + private final JavaPackage pkg; + private final JavaRawClass cls; + + public ClassMemberTranslator( + TranslatorModule xlatContext, + JavaPackage pkg, + JavaRawClass cls) + { + super(xlatContext); + this.pkg = pkg; + this.cls = cls; + } + + public void visit(VeraClassConstraint obj) + { + final String id = obj.getName().getIdentifier(); + logEnter("Translating constraint: " + id); + + // translate constraint expression + final ConsExpressionTranslator xlat = new ConsExpressionTranslator(this); + obj.accept(xlat); + final ConsExpression expr = xlat.getResult(); + + // get or create Randomizable annotation + JavaAnnotation randomizable = findAnnotation(cls, + types.randomizableType); + if (randomizable == null) + { + randomizable = new JavaAnnotation(types.randomizableType); + cls.addAnnotation(randomizable); + } + + // get or create constraint list element (Randomizable.value) + final JavaFunction valueElem = types.randomizableType + .getMethod("value"); + JavaAnnotationArrayInitializer consInit = (JavaAnnotationArrayInitializer) randomizable + .getAssignedElementValue(valueElem); + if (consInit == null) + { + final JavaArrayType consArrayType = schema.getArrayType( + types.constraintType, 1); + consInit = new JavaAnnotationArrayInitializer(consArrayType); + randomizable.setElementValue(valueElem, consInit); + } + + // add constraint to constraint list + final JavaAnnotation cons = new JavaAnnotation(types.constraintType); + cons.setElementValue("name", new JavaStringLiteral(schema, id)); + final String exprStr = ConsExpressionPrinter.print(expr, cls); + cons.setElementValue("expr", new JavaStringLiteral(schema, exprStr)); + consInit.addElement(cons); + + // copy comments from constraint + cons.addAnnotations(obj.getAnnotations()); + + logExit(); + } + + private JavaAnnotation findAnnotation( + JavaSchemaObject obj, + JavaAnnotationType annType) + { + final List< ? extends Annotation> anns = obj.getAnnotations(); + for (final Annotation ann : anns) + { + if (ann instanceof JavaAnnotation) + { + JavaAnnotation jann = (JavaAnnotation) ann; + if (jann.getType() == annType) return jann; + } + } + return null; + } + + public void visit(VeraEnumeration obj) + { + translateEnum(obj, pkg, cls); + } + + public void visit(VeraEnumerationElement obj) + { + // ignored; processed as part of enumeration + } + + public void visit(VeraMemberFunction obj) + { + translateMemberFunctionOrCtor(obj, cls); + } + + public void visit(VeraMemberVariable obj) + { + translateMemberVariable(obj, cls); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/CompUnitMemberTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/CompUnitMemberTranslator.java new file mode 100644 index 0000000..dbc1948 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/CompUnitMemberTranslator.java @@ -0,0 +1,260 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.newisys.dv.ifgen.schema.*; +import com.newisys.langschema.CompilationUnit; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.*; + +/** + * Schema translator for compilation unit members. + * + * @author Trevor Robinson + */ +final class CompUnitMemberTranslator + extends TranslatorModule + implements VeraCompilationUnitMemberVisitor +{ + private final JavaPackage pkg; + + public CompUnitMemberTranslator( + TranslatorModule xlatContext, + JavaPackage pkg) + { + super(xlatContext); + this.pkg = pkg; + } + + public void visit(VeraBindVariable obj) + { + translateBind(obj, pkg); + } + + public void visit(VeraEnumeration obj) + { + translateEnum(obj, pkg, null); + } + + public void visit(VeraEnumerationElement obj) + { + // ignored; processed as part of enumeration + } + + public void visit(VeraExpressionDefine obj) + { + // lazy-translate Verilog import defines + if (!obj.isVerilogImport()) + { + translateExpressionDefine(obj, null, pkg); + } + } + + public void visit(VeraGlobalFunction obj) + { + translateGlobalFunction(obj, pkg); + } + + public void visit(VeraGlobalVariable obj) + { + translateGlobalVariable(obj, pkg); + } + + public void visit(VeraHDLFunction obj) + { + translateHDLFunction(obj, pkg); + } + + public void visit(VeraInterfaceType obj) + { + translateInterface(obj, pkg); + } + + public void visit(VeraPortType obj) + { + translatePort(obj, pkg); + } + + public void visit(VeraProgram obj) + { + String id = obj.getName().getIdentifier(); + logEnter("Translating program: " + obj.getName()); + + // uniquify program name by prefixing compilation unit + final CompilationUnit compUnit = obj.getCompilationUnit(); + id = buildID(getIDForCompUnit(compUnit, true), "Program"); + + // create the Java class + final JavaRawClass cls = new JavaRawClass(schema, id, pkg); + cls.addAnnotations(obj.getAnnotations()); + cls.setBaseClass(types.dvAppType); + cls.setVisibility(JavaVisibility.PUBLIC); + pkg.addMember(cls); + xlatObjMap.addJavaObject(obj, cls); + + // create constructor + { + final JavaFunctionType ctorType = new JavaFunctionType( + schema.voidType); + final JavaFunctionArgument dvSimArg = new JavaFunctionArgument( + "dvSim", types.dvSimType); + ctorType.addArgument(dvSimArg); + final JavaConstructor ctor = new JavaConstructor(ctorType); + ctor.setVisibility(JavaVisibility.PUBLIC); + { + final JavaBlock body = new JavaBlock(schema); + final JavaVariableReference dvSimRef = new JavaVariableReference( + dvSimArg); + + // super(dvSim); + final JavaConstructor baseCtor = types.dvAppType + .getConstructor(new JavaType[] { types.dvSimType }, cls); + final JavaConstructorInvocation baseCtorCall = new JavaConstructorInvocation( + new JavaConstructorReference(baseCtor)); + baseCtorCall.addArgument(dvSimRef); + body.addMember(new JavaExpressionStatement(baseCtorCall)); + + ctor.setBody(body); + } + cls.addMember(ctor); + } + + // override run method + final JavaFunction runMethod = cls.newMethod("run", schema.voidType); + runMethod.setVisibility(JavaVisibility.PUBLIC); + final VeraBlock veraBlock = obj.getBlock(); + final JavaBlock runBody = translateBlock(veraBlock, null, null, + runMethod, null, false); + runMethod.setBody(runBody); + + // add call to Vera.initialize(); this is called in run() instead of + // the constructor for several reasons: + // a) it initializes Vera.systemClock; run() occurs after any Verilog + // initial blocks, and specifically the initial block in the Jove + // shell that registers all the signals + // b) it must be called from a SimulationThread to properly seed the RNG + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.junoType, "initialize"); + runBody.addMemberAt(new JavaExpressionStatement(callExpr), 0); + + // create Verilog shell if necessary + final Set shellMembers = obj + .getShellMembers(); + final IfgenPackage ifPkg = ifSchema.getPackage(pkg.getName() + .getCanonicalName(), true); + if (!shellMembers.isEmpty() || ifPkg.getMembers().size() > 0) + { + final IfgenTestbench ifTestbench = new IfgenTestbench(ifSchema, + new IfgenName("vera_shell", IfgenNameKind.EXPRESSION), + Collections. emptyList()); + ifPkg.addMember(ifTestbench); + + Set memberPkgs = new LinkedHashSet(); + memberPkgs.add(ifPkg); + + for (VeraCompilationUnitMember member : shellMembers) + { + if (member instanceof VeraInterfaceType) + { + VeraInterfaceType intf = (VeraInterfaceType) member; + log("Found shell interface: " + intf.getName()); + translateInterface(intf, pkg); + IfgenInterface ifIntf = (IfgenInterface) xlatObjMap + .getIfgenObject(intf); + assert (ifIntf != null); + memberPkgs.add(ifIntf.getPackage()); + //ifShell.addMember(new IfgenShellMember(ifIntf)); + } + else if (member instanceof VeraHDLFunction) + { + VeraHDLFunction func = (VeraHDLFunction) member; + log("Found shell hdl_task: " + func.getName()); + translateHDLFunction(func, pkg); + IfgenHDLTask ifTask = (IfgenHDLTask) xlatObjMap + .getIfgenObject(func); + assert (ifTask != null); + memberPkgs.add(ifTask.getPackage()); + //ifShell.addMember(new IfgenShellMember(ifTask)); + } + else if (member instanceof VeraGlobalFunction) + { + VeraGlobalFunction func = (VeraGlobalFunction) member; + log("Found shell exported task: " + func.getName()); + translateGlobalFunction(func, pkg); + IfgenHVLTask ifTask = (IfgenHVLTask) xlatObjMap + .getIfgenObject(func); + assert (ifTask != null); + memberPkgs.add(ifTask.getPackage()); + //ifShell.addMember(new IfgenShellMember(ifTask)); + } + else + { + throw new AssertionError("Unexpected shell member type: " + + member.getClass().getName()); + } + } + for (IfgenPackage memberPkg : memberPkgs) + { + log("Adding package to shell: " + memberPkg.getName()); + final IfgenUnresolvedName qname = new IfgenUnresolvedName( + memberPkg.getName()); + ifTestbench.addImportDecl(new IfgenWildname(qname, true)); + } + } + else + { + log("No shell members present"); + } + + logExit(); + } + + public void visit(VeraRangeDefine obj) + { + // lazy-translate Verilog import defines + if (!obj.isVerilogImport()) + { + translateRangeDefine(obj, pkg); + } + } + + public void visit(VeraStatementDefine obj) + { + // TODO: visit VeraStatementDefine + } + + public void visit(VeraTypeDefine obj) + { + // TODO: visit VeraTypeDefine + } + + public void visit(VeraUDFFunction obj) + { + translateGlobalFunction(obj, pkg); + } + + public void visit(VeraUserClass obj) + { + translateClass(obj, pkg, true); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ConcatLHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/ConcatLHSTranslator.java new file mode 100644 index 0000000..56215bf --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ConcatLHSTranslator.java @@ -0,0 +1,265 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.VeraBitSliceAccess; +import com.newisys.langschema.vera.VeraBitVectorType; +import com.newisys.langschema.vera.VeraConcatenation; +import com.newisys.langschema.vera.VeraEnumeration; +import com.newisys.langschema.vera.VeraExpression; +import com.newisys.langschema.vera.VeraRange; +import com.newisys.langschema.vera.VeraType; + +/** + * LHS translator for the LHS concatenation operator. + * + * @author Trevor Robinson + */ +final class ConcatLHSTranslator + extends BaseLHSTranslator +{ + private final LHSTranslator[] fieldXlats; + private final int[] lhsSizes; + private final boolean dynamicSize; + private final JavaType maxResultType; + + public ConcatLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext, + VeraConcatenation obj, + boolean readAccess, + boolean writeAccess) + { + super(exprXlat, exprContext); + + final int operandCount = obj.getOperands().size(); + fieldXlats = new LHSTranslator[operandCount]; + lhsSizes = new int[operandCount]; + boolean foundDynamicSize = false; + int maxLHSSize = 0; + int curIndex = 0; + final Iterator iter = obj.getOperands().iterator(); + while (iter.hasNext()) + { + VeraExpression veraExpr = (VeraExpression) iter.next(); + + // determine bit count of field on LHS + int lhsSize; + VeraType veraType = veraExpr.getResultType(); + if (veraType instanceof VeraEnumeration) + { + // enums are 0-bit on LHS and 32-bit on RHS + lhsSize = 0; + } + else + { + assert (veraType.isStrictIntegral()); + + // bit-slice accesses with non-constant indices yield a + // dynamically-sized bit vector result + if (veraExpr instanceof VeraBitSliceAccess) + { + lhsSize = -1; + VeraBitSliceAccess bitSliceExpr = (VeraBitSliceAccess) veraExpr; + VeraRange range = bitSliceExpr.getRange(); + VeraExpression highExpr = range.getFrom(); + VeraExpression lowExpr = range.getTo(); + if (highExpr.isConstant() && lowExpr.isConstant()) + { + Integer high = VeraExpression.toInteger(highExpr + .evaluateConstant()); + Integer low = VeraExpression.toInteger(lowExpr + .evaluateConstant()); + if (high != null && low != null) + { + lhsSize = Math + .abs(high.intValue() - low.intValue()) + 1; + } + } + } + else + { + lhsSize = veraType.getBitCount(); + } + } + lhsSizes[curIndex] = lhsSize; + foundDynamicSize = (lhsSize < 0); + maxLHSSize += (lhsSize >= 0) ? lhsSize : veraType.getBitCount(); + + LHSTranslator fieldXlat = exprXlat.translateLHS(veraExpr, null, + readAccess || (writeAccess && (lhsSize < 0)), writeAccess); + fieldXlats[curIndex++] = fieldXlat; + } + dynamicSize = foundDynamicSize; + // okay to have LHS (not RHS!) greater than max bit vector size; + // we just want to limit RHS promotion + maxLHSSize = Math.min(maxLHSSize, VeraBitVectorType.MAX_SIZE); + maxResultType = schema.getBitVectorType(maxLHSSize); + } + + public JavaType getResultType() + { + return maxResultType; + } + + public JavaExpression getUpdateEvent() + { + return null; + } + + public JavaExpression getReadExpression() + { + List javaExprs = new LinkedList(); + for (int i = 0; i < fieldXlats.length; ++i) + { + javaExprs.add(fieldXlats[i].getReadExpression()); + } + return exprXlat.buildBitVectorConcat(javaExprs); + } + + public ConvertedExpression getWriteExpression(JavaExpression value) + { + // ExpressionTranslator should have converted RHS to BitVector + assert (schema.isBitVector(value.getResultType())); + + ConvertedExpression result = new ConvertedExpression(exprContext); + + // make sure RHS expression appears to be evaluated only once + value = EvalOnceExprBuilder.evalConstExpr(value, result, "bv", true); + result.setResultExpr(value); + result.setOptionalResult(true); + + // if result is dynamically sized/indexed, + // we need position and width variables + JavaVariableReference posRef = null, widthRef = null; + if (dynamicSize) + { + posRef = result.addTempFor("pos", new JavaIntLiteral(schema, 0), + false); + widthRef = new JavaVariableReference(result.addTempVar("width", + schema.intType)); + } + + // generate field assignment statements + int pos = 0; + for (int i = fieldXlats.length - 1; i >= 0; --i) + { + // build RHS expression + JavaExpression rhsExpr; + boolean updatePos = false; + LHSTranslator fieldXlat = fieldXlats[i]; + int lhsSize = lhsSizes[i]; + if (lhsSize == 0) + { + // enumeration variables become undefined and do not affect + // the RHS position + JavaEnum enumCls = (JavaEnum) fieldXlat.getResultType(); + rhsExpr = exprConv.getEnumUndefined(enumCls); + } + else + { + // build RHS high/low index expressions + JavaExpression rhsHighExpr = null, rhsLowExpr = null; + JavaExpression widthExpr = null; + JavaType getBitsResultType = null; + if (lhsSize > 0) + { + if (dynamicSize) + { + widthExpr = new JavaIntLiteral(schema, lhsSize); + } + else + { + rhsLowExpr = new JavaIntLiteral(schema, pos); + pos += lhsSize; + rhsHighExpr = new JavaIntLiteral(schema, pos - 1); + } + getBitsResultType = schema.getBitVectorType(lhsSize); + } + else + { + assert (dynamicSize); + assert (fieldXlat instanceof BitSliceLHSTranslator); + BitSliceLHSTranslator bitSliceXlat = (BitSliceLHSTranslator) fieldXlat; + JavaExpression lhsRangeExpr = bitSliceXlat + .getRangeExpression(); + if (lhsRangeExpr != null) + { + widthExpr = ExpressionBuilder.memberCall(lhsRangeExpr, + "length"); + } + else + { + JavaExpression lhsHighExpr = exprConv + .toInt(bitSliceXlat.getHighExpression()); + JavaExpression lhsLowExpr = exprConv.toInt(bitSliceXlat + .getLowExpression()); + widthExpr = new JavaAdd(schema, ExpressionBuilder + .staticCall(types.mathType, "abs", + new JavaSubtract(schema, lhsHighExpr, + lhsLowExpr)), new JavaIntLiteral(schema, 1)); + } + } + if (dynamicSize) + { + rhsLowExpr = posRef; + rhsHighExpr = new JavaSubtract(schema, new JavaAdd(schema, + posRef, new JavaAssign(schema, widthRef, widthExpr)), + new JavaIntLiteral(schema, 1)); + updatePos = true; + } + + // build RHS bit slice expression + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.bitVectorOpType, "getBitsChecked", + new JavaExpression[] { value, rhsHighExpr, rhsLowExpr }, + null); + if (getBitsResultType != null) + { + callExpr.setResultType(getBitsResultType); + } + rhsExpr = callExpr; + + // convert RHS if necessary + JavaType lhsType = fieldXlat.getResultType(); + JavaType rhsType = rhsExpr.getResultType(); + if (needRHSConversion(lhsType, rhsType)) + { + rhsExpr = exprConv.toType(lhsType, rhsExpr); + } + } + + // generate statement to write to field + fieldXlat.getWriteExpression(rhsExpr).mergeIntoInit(result); + + // update RHS position (if dynamically indexed) + if (updatePos) + { + result.addInitExpr(new JavaAssignAdd(schema, posRef, widthRef)); + } + } + + return result; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionPrinter.java b/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionPrinter.java new file mode 100644 index 0000000..18374ee --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionPrinter.java @@ -0,0 +1,635 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.langschema.Name; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Namespace; +import com.newisys.langschema.Scope; +import com.newisys.langschema.Variable; +import com.newisys.langschema.constraint.*; +import com.newisys.langschema.java.JavaArrayType; +import com.newisys.langschema.java.JavaInterface; +import com.newisys.langschema.java.JavaMemberVariable; +import com.newisys.langschema.java.JavaPackage; +import com.newisys.langschema.java.JavaRawAbstractClass; +import com.newisys.langschema.java.JavaStructuredType; +import com.newisys.langschema.java.JavaStructuredTypeMember; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.JavaVariableModifier; +import com.newisys.langschema.jove.JoveAssocArrayType; +import com.newisys.langschema.jove.JoveBitVectorType; +import com.newisys.langschema.jove.JoveFixedArrayType; + +/** + * Generates a string representation of random constraint expression. + * + * @author Trevor Robinson + */ +final class ConsExpressionPrinter + implements ConsConstraintExpressionVisitor +{ + private final JavaStructuredType typeContext; + private final int parentPrecedence; + private final StringBuffer buf; + + private ConsExpressionPrinter( + JavaStructuredType typeContext, + int parentPrecedence, + StringBuffer buf) + { + this.typeContext = typeContext; + this.parentPrecedence = parentPrecedence; + this.buf = buf; + } + + public static String print( + ConsExpression expr, + JavaStructuredType typeContext) + { + StringBuffer buf = new StringBuffer(); + ConsExpressionPrinter printer = new ConsExpressionPrinter(typeContext, + 100, buf); + if (expr instanceof ConsConstraintSet) + { + // suppress outer braces for top-level constraint block + printer.printConstraints((ConsConstraintSet) expr); + } + else + { + expr.accept(printer); + } + return buf.toString(); + } + + private void printExpression(ConsExpression expr) + { + printExpression(expr, 100); + } + + private void printExpression(ConsExpression expr, int parentPrecedence) + { + ConsExpressionPrinter printer = new ConsExpressionPrinter(typeContext, + parentPrecedence, buf); + expr.accept(printer); + } + + void printName(Name name) + { + String id = name.getIdentifier(); + Namespace namespace = name.getNamespace(); + JavaPackage pkg = typeContext.getPackage(); + if (namespace != null + && namespace != pkg + && (!namespace.getName().getCanonicalName().equals("java.lang") || pkg + .lookupObjects(id, name.getKind()).hasNext())) + { + // print qualified name if all of the following are true: + // a) name is not in default package + // b) name is not in current package + // c) name is not from java.lang, or is from java.lang but is hidden + printNamespace(namespace); + } + buf.append(id); + } + + private void printNamespace(Namespace namespace) + { + printNameNoImport(namespace.getName()); + buf.append('.'); + } + + private void printNameNoImport(Name name) + { + Namespace namespace = name.getNamespace(); + if (namespace != null) + { + printNamespace(namespace); + } + buf.append(name.getIdentifier()); + } + + void printType(JavaType type) + { + if (type instanceof JavaArrayType) + { + JavaArrayType arrayType = (JavaArrayType) type; + printType(arrayType.getElementType()); + + int[] dims; + int dimCount; + if (type instanceof JoveFixedArrayType) + { + dims = ((JoveFixedArrayType) type).getDimensions(); + dimCount = dims.length; + } + else + { + dims = null; + dimCount = arrayType.getIndexTypes().length; + } + + for (int i = 0; i < dimCount; ++i) + { + buf.append('['); + if (dims != null) + { + buf.append("/*" + dims[i] + "*/"); + } + buf.append(']'); + } + } + else if (type instanceof JoveAssocArrayType) + { + JoveAssocArrayType assocType = (JoveAssocArrayType) type; + printName(assocType.getBaseClass().getName()); + String elemName = assocType.getElementType().toReferenceString(); + buf.append("/*" + elemName + "*/"); + } + else if (type instanceof JoveBitVectorType) + { + JoveBitVectorType bvType = (JoveBitVectorType) type; + printName(bvType.getBaseClass().getName()); + buf.append("/*" + bvType.getSize() + "*/"); + } + else if (type instanceof NamedObject) + { + printName(((NamedObject) type).getName()); + } + else + { + buf.append(type.toReferenceString()); + } + } + + private void printUnary(ConsUnaryOperation op, String token, boolean prefix) + { + final int precedence = 1; + final boolean needParens = precedence > parentPrecedence; + if (needParens) buf.append('('); + + if (prefix) buf.append(token); + + ConsExpression op1 = op.getOperand(0); + printExpression(op1, precedence - (prefix ? 0 : 1)); + + if (!prefix) buf.append(token); + + if (needParens) buf.append(')'); + } + + private void printInfix(ConsBinaryOperation op, String token, int precedence) + { + final boolean needParens = precedence > parentPrecedence; + if (needParens) buf.append('('); + + ConsExpression op1 = op.getOperand(0); + printExpression(op1, precedence); + + buf.append(' '); + buf.append(token); + buf.append(' '); + + ConsExpression op2 = op.getOperand(1); + printExpression(op2, precedence - 1); + + if (needParens) buf.append(')'); + } + + private void checkQualify(JavaStructuredTypeMember member, boolean isStatic) + { + JavaStructuredType memberType = member.getStructuredType(); + if (!memberInScope(member, memberType, typeContext)) + { + printType(memberType); + buf.append('.'); + if (!isStatic) + { + buf.append("this"); + buf.append('.'); + } + } + } + + private boolean memberInScope( + JavaStructuredTypeMember member, + JavaStructuredType memberType, + JavaStructuredType fromType) + { + if (memberType == fromType) + { + // member of same class? + return true; + } + else if (containsNameOf(fromType, (NamedObject) member)) + { + // hidden by member in base/nested type + return false; + } + + if (memberType instanceof JavaInterface) + { + // member of implemented interface? + JavaInterface memberIntf = (JavaInterface) memberType; + if (fromType.implementsInterface(memberIntf)) + { + return true; + } + } + + if (memberType instanceof JavaRawAbstractClass + && fromType instanceof JavaRawAbstractClass) + { + // member of superclass? + JavaRawAbstractClass memberClass = (JavaRawAbstractClass) memberType; + JavaRawAbstractClass classContext = (JavaRawAbstractClass) fromType; + if (memberClass.isSuperclassOf(classContext)) + { + return true; + } + } + + // in scope for containing class? + JavaStructuredType outerType = fromType.getStructuredType(); + if (outerType != null) + { + return memberInScope(member, memberType, outerType); + } + + return false; + } + + private boolean containsNameOf(Scope scope, NamedObject obj) + { + Name name = obj.getName(); + Iterator iter = scope.lookupObjects(name.getIdentifier(), name + .getKind()); + return iter.hasNext(); + } + + public void visit(ConsBitVectorLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsDistSet obj) + { + printSetOp(obj, "dist"); + } + + public void visit(ConsInSet obj) + { + printSetOp(obj, obj instanceof ConsNotInSet ? "!in" : "in"); + } + + private void printSetOp(ConsSetOperation obj, String keyword) + { + final int precedence = 5; + final boolean needParens = precedence > parentPrecedence; + if (needParens) buf.append("("); + + ConsExpression expr = obj.getExpr(); + printExpression(expr, precedence); + + buf.append(' '); + buf.append(keyword); + buf.append(' '); + + buf.append("{ "); + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + ConsSetMember member = (ConsSetMember) iter.next(); + member.accept(this); + if (iter.hasNext()) + { + buf.append(", "); + } + } + buf.append(" }"); + + if (needParens) buf.append(")"); + } + + public void visit(ConsImplication obj) + { + printExpression(obj.getOperand(0)); + buf.append(" => "); + printExpression(obj.getOperand(1)); + } + + public void visit(ConsSetRange obj) + { + printExpression(obj.getLow()); + buf.append(':'); + printExpression(obj.getHigh()); + printWeight(obj); + } + + public void visit(ConsSetValue obj) + { + printExpression(obj.getValue()); + printWeight(obj); + } + + private void printWeight(ConsSetMember obj) + { + ConsExpression weight = obj.getWeight(); + if (weight != null) + { + buf.append(obj.isWeightPerItem() ? " := " : " :/ "); + printExpression(weight); + } + } + + public void visit(ConsAdd obj) + { + printInfix(obj, "+", 3); + } + + public void visit(ConsAnd obj) + { + printInfix(obj, "&", 9); + } + + public void visit(ConsArrayAccess obj) + { + printExpression((ConsExpression) obj.getArray(), 0); + Iterator iter = obj.getIndices().iterator(); + while (iter.hasNext()) + { + buf.append('['); + printExpression((ConsExpression) iter.next()); + buf.append(']'); + } + } + + public void visit(ConsBitwiseNot obj) + { + printUnary(obj, "~", true); + } + + public void visit(ConsBooleanLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsCharLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsConditional obj) + { + final int precedence = 13; + final boolean needParens = precedence > parentPrecedence; + if (needParens) buf.append('('); + + ConsExpression op1 = obj.getOperand(0); + printExpression(op1, precedence - 1); + + buf.append(" ? "); + + ConsExpression op2 = obj.getOperand(1); + printExpression(op2, precedence); + + buf.append(" : "); + + ConsExpression op3 = obj.getOperand(2); + printExpression(op3, precedence); + + if (needParens) buf.append(')'); + } + + public void visit(ConsConditionalAnd obj) + { + printInfix(obj, "&&", 11); + } + + public void visit(ConsConditionalOr obj) + { + printInfix(obj, "||", 12); + } + + public void visit(ConsConstraintSet obj) + { + buf.append("{ "); + printConstraints(obj); + buf.append(" }"); + } + + private void printConstraints(ConsConstraintSet obj) + { + final Iterator iter = obj.getExprs().iterator(); + while (iter.hasNext()) + { + ConsExpression expr = (ConsExpression) iter.next(); + printExpression(expr); + if (!endsWithSet(expr)) + { + buf.append(';'); + } + if (iter.hasNext()) + { + buf.append(' '); + } + } + } + + private boolean endsWithSet(ConsExpression expr) + { + if (expr instanceof ConsConstraintSet) + { + return true; + } + else if (expr instanceof ConsImplication) + { + return endsWithSet(((ConsImplication) expr).getOperand(1)); + } + return false; + } + + public void visit(ConsDivide obj) + { + printInfix(obj, "/", 2); + } + + public void visit(ConsDoubleLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsEqual obj) + { + printInfix(obj, "==", 7); + } + + public void visit(ConsFloatLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsGreater obj) + { + printInfix(obj, ">", 5); + } + + public void visit(ConsGreaterOrEqual obj) + { + printInfix(obj, ">=", 5); + } + + public void visit(ConsIntLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsLeftShift obj) + { + printInfix(obj, "<<", 4); + } + + public void visit(ConsLess obj) + { + printInfix(obj, "<", 5); + } + + public void visit(ConsLessOrEqual obj) + { + printInfix(obj, "<=", 5); + } + + public void visit(ConsLogicalNot obj) + { + printUnary(obj, "!", true); + } + + public void visit(ConsLongLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsMemberAccess obj) + { + printExpression((ConsExpression) obj.getObject(), 0); + buf.append('.'); + NamedObject member = (NamedObject) obj.getMember(); + buf.append(member.getName().getIdentifier()); + } + + public void visit(ConsModulo obj) + { + printInfix(obj, "%", 2); + } + + public void visit(ConsMultiply obj) + { + printInfix(obj, "*", 2); + } + + public void visit(ConsNotEqual obj) + { + printInfix(obj, "!=", 7); + } + + public void visit(ConsNullLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsOr obj) + { + printInfix(obj, "|", 10); + } + + public void visit(ConsSignedRightShift obj) + { + printInfix(obj, ">>", 4); + } + + public void visit(ConsStringLiteral obj) + { + buf.append(obj.toString()); + } + + public void visit(ConsSubtract obj) + { + printInfix(obj, "-", 3); + } + + public void visit(ConsSuperReference obj) + { + JavaType type = (JavaType) obj.getType(); + if (type != typeContext) + { + printType(type); + buf.append('.'); + } + buf.append("super"); + } + + public void visit(ConsThisReference obj) + { + JavaType type = obj.getType(); + if (type != typeContext) + { + printType(type); + buf.append('.'); + } + buf.append("this"); + } + + public void visit(ConsTypeLiteral obj) + { + printType(obj.getType()); + buf.append(".class"); + } + + public void visit(ConsUnaryMinus obj) + { + printUnary(obj, "-", true); + } + + public void visit(ConsUnaryPlus obj) + { + printUnary(obj, "+", true); + } + + public void visit(ConsUnsignedRightShift obj) + { + printInfix(obj, ">>>", 4); + } + + public void visit(ConsVariableReference obj) + { + Variable var = obj.getVariable(); + if (var instanceof JavaMemberVariable) + { + checkQualify((JavaMemberVariable) var, var.getModifiers().contains( + JavaVariableModifier.STATIC)); + } + buf.append(var.getName().getIdentifier()); + } + + public void visit(ConsXor obj) + { + printInfix(obj, "^", 9); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionTranslator.java new file mode 100644 index 0000000..812f888 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ConsExpressionTranslator.java @@ -0,0 +1,664 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.langschema.constraint.*; +import com.newisys.langschema.java.JavaMemberVariable; +import com.newisys.langschema.java.JavaRawAbstractClass; +import com.newisys.langschema.java.JavaStructuredTypeMember; +import com.newisys.langschema.java.JavaVariable; +import com.newisys.langschema.vera.*; +import com.newisys.verilog.util.BitVector; + +/** + * Schema translator for random constraint expressions. + * + * @author Trevor Robinson + */ +final class ConsExpressionTranslator + extends TranslatorModule + implements VeraExpressionVisitor +{ + private final ConsSchema consSchema; + private ConsExpression result; + + public ConsExpressionTranslator(TranslatorModule xlatContext) + { + super(xlatContext); + consSchema = new ConsSchema(); + } + + public ConsExpression getResult() + { + return result; + } + + private ConsExpression translateNestedExpr(VeraExpression obj) + { + obj.accept(this); + return result; + } + + public void visit(VeraAdd obj) + { + result = new ConsAdd(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraAndReduction obj) + { + // DEFERRED: VeraAndReduction + throw new UnsupportedOperationException(); + } + + public void visit(VeraArithmeticNegative obj) + { + result = new ConsUnaryMinus(translateNestedExpr(obj.getOperand(0))); + } + + public void visit(VeraArrayAccess obj) + { + ConsArrayAccess caa = new ConsArrayAccess(translateNestedExpr(obj + .getArray())); + Iterator iter = obj.getIndices().iterator(); + while (iter.hasNext()) + { + VeraExpression expr = (VeraExpression) iter.next(); + caa.addIndex(translateNestedExpr(expr)); + } + result = caa; + } + + public void visit(VeraArrayCreation obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraArrayInitializer obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssign obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignAdd obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignAnd obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignAndNot obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignDivide obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignLeftShift obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignModulo obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignMultiply obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignOr obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignOrNot obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignRightShift obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignSubtract obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignXor obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraAssignXorNot obj) + { + // assignment not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraBitSliceAccess obj) + { + // DEFERRED: VeraBitSliceAccess + throw new UnsupportedOperationException(); + } + + public void visit(VeraBitVectorLiteral obj) + { + BitVector value = obj.getValue(); + // X/Z constants not allowed in constraints + assert (!value.containsXZ()); + result = new ConsBitVectorLiteral(consSchema, value); + } + + public void visit(VeraBitwiseAnd obj) + { + result = new ConsAnd(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraBitwiseAndNot obj) + { + result = new ConsBitwiseNot(new ConsAnd(translateNestedExpr(obj + .getOperand(0)), translateNestedExpr(obj.getOperand(1)))); + } + + public void visit(VeraBitwiseNegative obj) + { + result = new ConsBitwiseNot(translateNestedExpr(obj.getOperand(0))); + } + + public void visit(VeraBitwiseOr obj) + { + result = new ConsOr(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraBitwiseOrNot obj) + { + result = new ConsBitwiseNot(new ConsOr(translateNestedExpr(obj + .getOperand(0)), translateNestedExpr(obj.getOperand(1)))); + } + + public void visit(VeraBitwiseReverse obj) + { + // DEFERRED: VeraBitwiseReverse + throw new UnsupportedOperationException(); + } + + public void visit(VeraBitwiseXor obj) + { + result = new ConsXor(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraBitwiseXorNot obj) + { + result = new ConsBitwiseNot(new ConsXor(translateNestedExpr(obj + .getOperand(0)), translateNestedExpr(obj.getOperand(1)))); + } + + public void visit(VeraConcatenation obj) + { + // DEFERRED: VeraConcatenation + throw new UnsupportedOperationException(); + } + + public void visit(VeraConditional obj) + { + VeraExpression veraOp2 = obj.getOperand(1); + VeraExpression veraOp3 = obj.getOperand(2); + ConsExpression op1 = translateNestedExpr(obj.getOperand(0)); + if (veraOp3 instanceof VeraVoidLiteral) + { + // a ? b : void -> a => b + result = new ConsImplication(op1, translateNestedExpr(veraOp2)); + } + if (veraOp2 instanceof VeraVoidLiteral) + { + // a ? void : b -> !a => b + result = new ConsImplication(new ConsLogicalNot(op1), + translateNestedExpr(veraOp3)); + } + else + { + result = new ConsConditional(op1, translateNestedExpr(veraOp2), + translateNestedExpr(veraOp3)); + } + } + + public void visit(VeraConstraintSet obj) + { + final ConsConstraintSet ccs = new ConsConstraintSet(consSchema); + final Iterator iter = obj.getExprs().iterator(); + while (iter.hasNext()) + { + VeraExpression expr = (VeraExpression) iter.next(); + ccs.addExpr(translateNestedExpr(expr)); + } + result = ccs; + } + + public void visit(VeraCopyCreation obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraDepthAccess obj) + { + // DEFERRED: VeraDepthAccess + throw new UnsupportedOperationException(); + } + + public void visit(VeraDistSet obj) + { + final ConsDistSet cds = new ConsDistSet(translateNestedExpr(obj + .getExpr())); + translateSetMembers(obj, cds); + result = cds; + } + + public void visit(VeraDivide obj) + { + result = new ConsDivide(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraEnumValueReference obj) + { + final VeraEnumerationElement veraElem = obj.getElement(); + final JavaMemberVariable var = translateEnumElement(veraElem); + result = new ConsVariableReference(consSchema, var); + } + + public void visit(VeraEqual obj) + { + result = new ConsEqual(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraExactEqual obj) + { + // 4-state operators not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraExactNotEqual obj) + { + // 4-state operators not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraFunctionInvocation obj) + { + // DEFERRED: VeraFunctionInvocation + throw new UnsupportedOperationException(); + } + + public void visit(VeraFunctionReference obj) + { + // DEFERRED: VeraFunctionReference + throw new UnsupportedOperationException(); + } + + public void visit(VeraGreater obj) + { + result = new ConsGreater(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraGreaterOrEqual obj) + { + result = new ConsGreaterOrEqual(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraIfElseConstraint obj) + { + final ConsExpression ifExpr = translateNestedExpr(obj.getIfExpression()); + final ConsExpression thenExpr = translateNestedExpr(obj + .getThenExpression()); + final VeraExpression veraElseExpr = obj.getElseExpression(); + if (veraElseExpr != null) + { + // "if (a) b; else c;" -> "{ a => b; !a => c; }" + final ConsConstraintSet ccs = new ConsConstraintSet(consSchema); + ccs.addExpr(new ConsImplication(ifExpr, thenExpr)); + ccs.addExpr(new ConsImplication(new ConsLogicalNot(ifExpr), + translateNestedExpr(veraElseExpr))); + result = ccs; + } + else + { + // "if (a) b;" -> "a => b;" + result = new ConsImplication(ifExpr, thenExpr); + } + } + + public void visit(VeraImplicationConstraint obj) + { + result = new ConsImplication(translateNestedExpr(obj.getPredicate()), + translateNestedExpr(obj.getConstraint())); + } + + public void visit(VeraInSet obj) + { + final ConsInSet cis = new ConsInSet(translateNestedExpr(obj.getExpr())); + translateSetMembers(obj, cis); + result = cis; + } + + private void translateSetMembers( + VeraSetOperation veraSetOp, + ConsSetOperation consSetOp) + { + final Iterator iter = veraSetOp.getMembers().iterator(); + while (iter.hasNext()) + { + // translate next member + final VeraSetMember veraMember = (VeraSetMember) iter.next(); + final ConsSetMember member; + if (veraMember instanceof VeraSetValue) + { + VeraSetValue veraValue = (VeraSetValue) veraMember; + member = new ConsSetValue(translateNestedExpr(veraValue + .getValue())); + } + else + { + VeraSetRange veraRange = (VeraSetRange) veraMember; + member = new ConsSetRange(translateNestedExpr(veraRange + .getLow()), translateNestedExpr(veraRange.getHigh())); + } + + // translate weight if present (i.e. dist operator) + final VeraExpression veraWeight = veraMember.getWeight(); + if (veraWeight != null) + { + member.setWeight(translateNestedExpr(veraWeight), veraMember + .isWeightPerItem()); + } + + consSetOp.addMember(member); + } + } + + public void visit(VeraInstanceCreation obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraIntegerLiteral obj) + { + result = new ConsIntLiteral(consSchema, obj.getValue()); + } + + public void visit(VeraInterfaceReference obj) + { + // DEFERRED: VeraInterfaceReference + throw new UnsupportedOperationException(); + } + + public void visit(VeraLeftShift obj) + { + result = new ConsLeftShift(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraLess obj) + { + result = new ConsLess(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraLessOrEqual obj) + { + result = new ConsLessOrEqual(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraLogicalAnd obj) + { + result = new ConsConditionalAnd(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraLogicalNegative obj) + { + result = new ConsLogicalNot(translateNestedExpr(obj.getOperand(0))); + } + + public void visit(VeraLogicalOr obj) + { + result = new ConsConditionalOr(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraMemberAccess obj) + { + // translate object expression + final VeraExpression veraObj = obj.getObject(); + final ConsExpression consObj = translateNestedExpr(veraObj); + + // translate member + final VeraStructuredTypeMember veraMember = obj.getMember(); + final JavaStructuredTypeMember member = translateMember(veraMember); + + result = new ConsMemberAccess(consObj, member); + } + + public void visit(VeraModulo obj) + { + result = new ConsModulo(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraMultiply obj) + { + result = new ConsMultiply(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraNotAndReduction obj) + { + // DEFERRED: VeraNotAndReduction + throw new UnsupportedOperationException(); + } + + public void visit(VeraNotEqual obj) + { + result = new ConsNotEqual(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraNotInSet obj) + { + final ConsNotInSet cnis = new ConsNotInSet(translateNestedExpr(obj + .getExpr())); + translateSetMembers(obj, cnis); + result = cnis; + } + + public void visit(VeraNotOrReduction obj) + { + // DEFERRED: VeraNotOrReduction + throw new UnsupportedOperationException(); + } + + public void visit(VeraNotXorReduction obj) + { + // DEFERRED: VeraNotXorReduction + throw new UnsupportedOperationException(); + } + + public void visit(VeraNullLiteral obj) + { + result = new ConsNullLiteral(consSchema); + } + + public void visit(VeraOrReduction obj) + { + // DEFERRED: VeraOrReduction + throw new UnsupportedOperationException(); + } + + public void visit(VeraPostDecrement obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraPostIncrement obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraPreDecrement obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraPreIncrement obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraReplication obj) + { + // DEFERRED: VeraReplication + throw new UnsupportedOperationException(); + } + + public void visit(VeraRightShift obj) + { + final VeraExpression veraOp1 = obj.getOperand(0); + final ConsExpression op1 = translateNestedExpr(veraOp1); + final ConsExpression op2 = translateNestedExpr(obj.getOperand(1)); + if (veraOp1.getResultType() instanceof VeraIntegerType) + { + result = new ConsSignedRightShift(op1, op2); + } + else + { + result = new ConsUnsignedRightShift(op1, op2); + } + } + + public void visit(VeraSignalReference obj) + { + // DEFERRED: VeraSignalReference + throw new UnsupportedOperationException(); + } + + public void visit(VeraStringLiteral obj) + { + result = new ConsStringLiteral(consSchema, obj.getValue()); + } + + public void visit(VeraSubtract obj) + { + result = new ConsSubtract(translateNestedExpr(obj.getOperand(0)), + translateNestedExpr(obj.getOperand(1))); + } + + public void visit(VeraSuperReference obj) + { + final VeraClass veraType = obj.getType(); + final JavaRawAbstractClass type = (JavaRawAbstractClass) translateType(veraType); + result = new ConsSuperReference(consSchema, type); + } + + public void visit(VeraSystemClockReference obj) + { + // not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraThisReference obj) + { + final VeraClass veraType = obj.getType(); + final JavaRawAbstractClass type = (JavaRawAbstractClass) translateType(veraType); + result = new ConsThisReference(consSchema, type); + } + + public void visit(VeraVariableReference obj) + { + final VeraVariable veraVar = obj.getVariable(); + final JavaVariable var = translateVariable(veraVar); + result = new ConsVariableReference(consSchema, var); + } + + public void visit(VeraVoidLiteral obj) + { + // 'void' only valid in conditional (?:) operator + throw new UnsupportedOperationException(); + } + + public void visit(VeraWildEqual obj) + { + // 4-state operators not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraWildNotEqual obj) + { + // 4-state operators not allowed in constraints + throw new UnsupportedOperationException(); + } + + public void visit(VeraXorReduction obj) + { + // DEFERRED: VeraXorReduction + throw new UnsupportedOperationException(); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ConvertedExpression.java b/java/juno/src/com/newisys/schemabuilder/juno/ConvertedExpression.java new file mode 100644 index 0000000..8b3366f --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ConvertedExpression.java @@ -0,0 +1,450 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.java.*; + +/** + * Represents a complete translation of a Vera expression, which may result in + * multiple Java statements. + * + * @author Trevor Robinson + */ +final class ConvertedExpression +{ + final JavaSchema schema; + private final TempBlockScope tempScope; + + private List initMembers; + private boolean initExprs; + private JavaExpression resultExpr; + private boolean optionalResult; + private List updateMembers; + + public ConvertedExpression(JavaSchema schema, TempBlockScope tempScope) + { + this.schema = schema; + this.tempScope = tempScope; + } + + public ConvertedExpression(ConvertedExpression other) + { + this.schema = other.schema; + this.tempScope = other.tempScope; + } + + public TempBlockScope getScope() + { + return tempScope; + } + + public boolean isSimpleExpr() + { + return !hasInitExprs() && !hasUpdateMembers(); + } + + public boolean hasInitMembers() + { + return initMembers != null && !initMembers.isEmpty(); + } + + public List getInitMembers() + { + return initMembers != null ? initMembers : Collections.EMPTY_LIST; + } + + public void addInitMember(JavaBlockMember member) + { + if (initMembers == null) + { + initMembers = new LinkedList(); + } + initMembers.add(member); + if (member instanceof NamedObject) + { + tempScope.addObject((NamedObject) member); + } + if (!isBlankVar(member)) initExprs = true; + } + + private boolean isBlankVar(JavaBlockMember member) + { + return member instanceof JavaLocalVariable + && ((JavaLocalVariable) member).getInitializer() == null; + } + + public void addInitMembers(List members) + { + for (JavaBlockMember member : members) + { + addInitMember(member); + } + } + + public void addInitExpr(JavaExpression expr) + { + addInitMember(new JavaExpressionStatement(expr)); + } + + public JavaLocalVariable createTempVar(String id, JavaType type) + { + return VarBuilder.createLocalVar(tempScope, id, type); + } + + public JavaLocalVariable addTempVar(String id, JavaType type) + { + JavaLocalVariable var = createTempVar(id, type); + addInitMember(var); + return var; + } + + public JavaLocalVariable createTempFor( + String id, + JavaExpression expr, + boolean makeFinal) + { + JavaType type = expr.getResultType(); + JavaLocalVariable var = createTempVar(id, type); + var.setInitializer(expr); + if (makeFinal) + { + var.addModifier(JavaVariableModifier.FINAL); + } + return var; + } + + public JavaVariableReference addTempFor( + String id, + JavaExpression expr, + boolean makeFinal) + { + JavaLocalVariable var = createTempFor(id, expr, makeFinal); + addInitMember(var); + return new JavaVariableReference(var); + } + + public boolean hasInitExprs() + { + return initExprs; + } + + public JavaExpression getResultExpr() + { + return resultExpr; + } + + public void setResultExpr(JavaExpression expression) + { + this.resultExpr = expression; + } + + public void convertResultExpr(JavaType type, ExpressionConverter exprConv) + { + resultExpr = exprConv.toType(type, resultExpr); + } + + public boolean hasOptionalResult() + { + return optionalResult; + } + + public void setOptionalResult(boolean optionalResult) + { + this.optionalResult = optionalResult; + } + + public boolean hasUpdateMembers() + { + return updateMembers != null && !updateMembers.isEmpty(); + } + + public List getUpdateMembers() + { + return updateMembers != null ? updateMembers : Collections.EMPTY_LIST; + } + + public void addUpdateMember(JavaBlockMember member) + { + if (updateMembers == null) + { + updateMembers = new LinkedList(); + } + updateMembers.add(member); + } + + public void addUpdateMembers(List members) + { + for (JavaBlockMember member : members) + { + addUpdateMember(member); + } + } + + public void addUpdateExpr(JavaExpression expr) + { + addUpdateMember(new JavaExpressionStatement(expr)); + } + + public JavaExpression mergeIntoResult(ConvertedExpression other) + { + if (initMembers != null) + { + other.addInitMembers(initMembers); + } + if (resultExpr != null) + { + other.setResultExpr(resultExpr); + } + if (updateMembers != null) + { + other.addUpdateMembers(updateMembers); + } + return resultExpr; + } + + public void mergeIntoInit(ConvertedExpression other) + { + if (initMembers != null) + { + other.addInitMembers(initMembers); + } + if (resultExpr != null && !optionalResult) + { + other.addInitExpr(resultExpr); + } + if (updateMembers != null) + { + other.addUpdateMembers(updateMembers); + } + } + + public void mergeIntoUpdate(ConvertedExpression other) + { + if (initMembers != null) + { + other.addInitMembers(initMembers); + } + if (resultExpr != null && !optionalResult) + { + other.addUpdateExpr(resultExpr); + } + if (updateMembers != null) + { + other.addUpdateMembers(updateMembers); + } + } + + public JavaExpression flatten(String tempID) + { + flatten(tempID, false, null); + return resultExpr; + } + + public JavaExpression flattenEvalOnce(String tempID) + { + flatten(tempID, !EvalOnceExprBuilder.isSimpleExpression(resultExpr), + null); + return resultExpr; + } + + private JavaBlockMember flatten( + String tempID, + boolean forceTemp, + JavaType varType) + { + JavaBlockMember member = null; + + if (resultExpr != null) + { + JavaType resultType = resultExpr.getResultType(); + if (varType == null) varType = resultType; + if (resultType == schema.voidType || tempID == null) + { + // if the expression is void (or no temporary is requested), + // add the expression to the init members as a statement and + // set the result expression to null + if (!optionalResult && !(varType instanceof JavaNullType)) + { + // if the expression is not a valid statement expression, + // create a dummy variable assignment + if (!JavaExpressionStatement.isValidExpression(resultExpr)) + { + JavaLocalVariable tempVar = VarBuilder.createLocalVar( + tempScope, "dummy", varType); + tempVar.setInitializer(resultExpr); + member = tempVar; + } + else + { + member = new JavaExpressionStatement(resultExpr); + } + addInitMember(member); + } + resultExpr = null; + optionalResult = false; + } + else if (forceTemp || hasUpdateMembers()) + { + // if we have update members, introduce a temporary variable + // for the result expression; the result expression becomes a + // reference to the temporary + JavaLocalVariable tempVar = createTempVar(tempID, varType); + tempVar.setInitializer(resultExpr); + member = tempVar; + addInitMember(member); + resultExpr = new JavaVariableReference(tempVar); + } + } + + // move update members to init members + if (hasUpdateMembers()) + { + addInitMembers(updateMembers); + updateMembers.clear(); + } + + return member; + } + + public JavaVariableReference toVarRef(String tempID, JavaType varType) + { + if (!(resultExpr instanceof JavaVariableReference)) + { + flatten(tempID, true, varType); + } + return (JavaVariableReference) resultExpr; + } + + public JavaExpression toBlockExpr(JavaBlock block, String tempID) + { + // flatten result expression and update members into init members + flatten(tempID, false, null); + + // inject init members into block + injectInitMembers(block); + + return resultExpr; + } + + public JavaExpression toEvalOnceExpr(JavaBlock block, String tempID) + { + // flatten result expression and update members into init members + flatten(tempID, !EvalOnceExprBuilder.isSimpleExpression(resultExpr), + null); + + // inject init members into block + injectInitMembers(block); + + return resultExpr; + } + + public JavaBlockMember toBlockStmt(JavaBlock block) + { + // flatten result expression and update members into init members + JavaBlockMember member = flatten(null, false, null); + assert (resultExpr == null); + + // inject init members into block + if (member == null && hasInitMembers()) + { + member = initMembers.get(0); + } + injectInitMembers(block); + + return member; + } + + public void toLocalVar(JavaBlock block, JavaLocalVariable var) + { + // use result expression as variable initializer + // and add variable to init members + var.setInitializer(resultExpr); + addInitMember(var); + resultExpr = null; + + // move update members to init members + if (hasUpdateMembers()) + { + addInitMembers(updateMembers); + updateMembers.clear(); + } + + // inject init members into block + injectInitMembers(block); + } + + private void injectInitMembers(JavaBlock block) + { + if (initMembers != null) + { + block.addMembers(initMembers); + initMembers.clear(); + } + } + + public JavaExpression toMemberInitExpr( + JavaRawAbstractClass cls, + JavaMemberVariable var) + { + // need to create initializer function if init/update members present + if (hasInitMembers() || hasUpdateMembers()) + { + // create private initializer function + String memberID = var.getName().getIdentifier(); + String initID = buildID("getInit", memberID); + JavaType memberType = var.getType(); + JavaFunctionType funcType = new JavaFunctionType(memberType); + JavaFunction initFunc = new JavaFunction(initID, funcType); + cls.addMember(initFunc); + + // make static if necessary + if (var.hasModifier(JavaVariableModifier.STATIC)) + { + initFunc.addModifier(JavaFunctionModifier.STATIC); + } + + // create body for function + JavaBlock body = new JavaBlock(schema); + initFunc.setBody(body); + + // inject statements from converted expression into body + toBlockExpr(body, "result"); + assert (resultExpr != null); + + // add return statement at end of body + body.addMember(new JavaReturnStatement(schema, resultExpr)); + + // return expression that invokes initializer function + resultExpr = new JavaFunctionInvocation(new JavaFunctionReference( + initFunc)); + } + + return resultExpr; + } + + private static String buildID(String part1, String part2) + { + return part1 + Character.toUpperCase(part2.charAt(0)) + + part2.substring(1); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/DefaultFactoryCallBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/DefaultFactoryCallBuilder.java new file mode 100644 index 0000000..abb5562 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/DefaultFactoryCallBuilder.java @@ -0,0 +1,154 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.java.*; + +/** + * Generic FactoryCallBuilder implementation that generates calls to a static + * method of the given class called "create". If a given instance creation has + * arguments, then the create method is expected to have the following + * arguments: create(Object[], Class[], String). The first argument is an array + * of argument values, the second is an array of argument declared types, and + * the third is the default implementation name (passed to the constructor of + * this class; possibly null). If the instance creation has no arguments, the + * prototype is: create(String), where the argument is the implementation name + * described previously. + * + * @author Trevor Robinson + */ +public class DefaultFactoryCallBuilder + implements FactoryCallBuilder +{ + private final JavaSchema schema; + private final SchemaTypes types; + private final ExpressionConverter exprConv; + private final JavaRawAbstractClass factoryCls; + private final String defaultImplName; + + public DefaultFactoryCallBuilder( + JavaSchema schema, + SchemaTypes types, + ExpressionConverter exprConv, + JavaRawClass factoryCls, + String defaultImplName) + { + this.schema = schema; + this.types = types; + this.exprConv = exprConv; + this.factoryCls = factoryCls; + this.defaultImplName = defaultImplName; + } + + protected List wrapArgs( + List javaArgExprs, + boolean includeTypes) + { + // translate (expr1, expr2...) -> (new Object[] { expr1, expr2... }, + // new Class[] { typeof(expr1).class, typeof(expr2).class... }) + List wrappedArgs = new LinkedList(); + + Iterator iter = javaArgExprs.iterator(); + if (iter.hasNext()) + { + // create Object[] argument which will contain actual arguments + JavaArrayInitializer argsInitExpr = new JavaArrayInitializer( + types.objectArrayType); + JavaArrayCreation argsNewExpr = new JavaArrayCreation( + types.objectArrayType); + argsNewExpr.setInitializer(argsInitExpr); + wrappedArgs.add(argsNewExpr); + + JavaArrayInitializer typesInitExpr = null; + if (includeTypes) + { + // create Class[] argument which will contain argument types + typesInitExpr = new JavaArrayInitializer(types.classArrayType); + JavaArrayCreation typesNewExpr = new JavaArrayCreation( + types.classArrayType); + typesNewExpr.setInitializer(typesInitExpr); + wrappedArgs.add(typesNewExpr); + } + + // translate actual arguments into array initializer(s) + while (iter.hasNext()) + { + JavaExpression argExpr = (JavaExpression) iter.next(); + + // add actual argument to arguments initializer + argExpr = exprConv.toObject(argExpr); + argsInitExpr.addElement(argExpr); + + if (includeTypes) + { + // add argument type to types initializer + JavaType argType = argExpr.getResultType(); + typesInitExpr.addElement(new JavaTypeLiteral(argType)); + } + } + } + + return wrappedArgs; + } + + public JavaExpression callFactory( + JavaRawClass cls, + List args, + JavaStructuredType containingType) + { + // get factory method + final JavaType[] argTypes; + if (args.size() > 0) + { + argTypes = new JavaType[] { types.objectArrayType, + types.classArrayType, types.stringType }; + } + else + { + argTypes = new JavaType[] { types.stringType }; + } + JavaFunction factoryMethod = factoryCls.getMethod("create", argTypes); + + // generate call to factory method + JavaFunctionInvocation callExpr = new JavaFunctionInvocation( + new JavaFunctionReference(factoryMethod)); + List wrappedArgs = wrapArgs(args, true); + for (JavaExpression arg : wrappedArgs) + { + callExpr.addArgument(arg); + } + + // add default implementation argument + JavaExpression defImplArg; + if (defaultImplName != null) + { + defImplArg = new JavaStringLiteral(schema, defaultImplName); + } + else + { + defImplArg = new JavaNullLiteral(schema); + } + callExpr.addArgument(defImplArg); + + return callExpr; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/EqualityOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/EqualityOperationBuilder.java new file mode 100644 index 0000000..d79e416 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/EqualityOperationBuilder.java @@ -0,0 +1,40 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; + +/** + * Interface for building Java equality operation expressions. + * + * @author Trevor Robinson + */ +interface EqualityOperationBuilder +{ + JavaExpression equal(JavaExpression op1, JavaExpression op2); + + JavaExpression notEqual(JavaExpression op1, JavaExpression op2); + + JavaExpression exactEqual(JavaExpression op1, JavaExpression op2); + + JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2); + + JavaExpression wildEqual(JavaExpression op1, JavaExpression op2); + + JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/EqualsEqualityOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/EqualsEqualityOperationBuilder.java new file mode 100644 index 0000000..dd6d989 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/EqualsEqualityOperationBuilder.java @@ -0,0 +1,84 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.Literal; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaLogicalNot; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds equality operation expressions using Object.equals() (or in some + * cases, Vera.equals()). + * + * @author Trevor Robinson + */ +final class EqualsEqualityOperationBuilder + extends TranslatorModule + implements EqualityOperationBuilder +{ + private final boolean checkNull; + + public EqualsEqualityOperationBuilder(TranslatorModule xlatContext) + { + this(xlatContext, false); + } + + public EqualsEqualityOperationBuilder( + TranslatorModule xlatContext, + boolean checkNull) + { + super(xlatContext); + this.checkNull = checkNull; + } + + public JavaExpression equal(JavaExpression op1, JavaExpression op2) + { + if (checkNull && !(op1 instanceof Literal)) + { + return ExpressionBuilder.staticCall(types.junoType, "equals", op1, + op2); + } + return ExpressionBuilder.memberCall(op1, "equals", op2); + } + + public JavaExpression notEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaLogicalNot(schema, equal(op1, op2)); + } + + public JavaExpression exactEqual(JavaExpression op1, JavaExpression op2) + { + return equal(op1, op2); + } + + public JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2) + { + return notEqual(op1, op2); + } + + public JavaExpression wildEqual(JavaExpression op1, JavaExpression op2) + { + return equal(op1, op2); + } + + public JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2) + { + return notEqual(op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/EvalOnceExprBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/EvalOnceExprBuilder.java new file mode 100644 index 0000000..1168cc4 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/EvalOnceExprBuilder.java @@ -0,0 +1,156 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.langschema.Literal; +import com.newisys.langschema.java.JavaArrayAccess; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaMemberAccess; +import com.newisys.langschema.java.JavaStructuredTypeMember; +import com.newisys.langschema.java.JavaSuperReference; +import com.newisys.langschema.java.JavaThisReference; +import com.newisys.langschema.java.JavaVariableReference; + +/** + * Provides utility methods for obtaining a single-evaluation, multiple-use + * expression from an arbitrary expression. For instance, assume that + * arr[++i]++ must be translated with a separate get and put + * for the array. Obtaining a single-evaluation for arr[++i] + * might emit a variable declaration int arr_index = ++i; and + * return the expression arr[arr_index]. The resulting code + * would be: + *
      + *     int arr_index = ++i;
      + *     arr[arr_index] = arr[arr_index] + 1;
      + * 
      + * + * @author Trevor Robinson + */ +final class EvalOnceExprBuilder +{ + private EvalOnceExprBuilder() + { + // do nothing + } + + public static JavaExpression evalConstExpr( + JavaExpression expr, + ConvertedExpression exprContext, + String tempID, + boolean multiRef) + { + if (multiRef && !isSimpleExpression(expr)) + { + // introduce temporary variable initialized to expression and + // return a reference to it + return exprContext.addTempFor(tempID, expr, true); + } + else + { + // temporary is not needed; return original expression + return expr; + } + } + + public static JavaExpression evalLHSExpr( + JavaExpression expr, + ConvertedExpression exprContext, + String tempID, + boolean multiRef) + { + if (multiRef && !isSimpleExpression(expr)) + { + if (expr instanceof JavaMemberAccess) + { + // extract information about member access + JavaMemberAccess ma = (JavaMemberAccess) expr; + JavaExpression objExpr = ma.getObject(); + JavaStructuredTypeMember member = ma.getMember(); + + // introduce temporary variable initialized to member access + // object expression + JavaVariableReference objVarRef = exprContext.addTempFor(tempID + + "_obj", objExpr, true); + + // return member access that references temporary variable + return new JavaMemberAccess(objVarRef, member); + } + else + { + assert (expr instanceof JavaArrayAccess); + JavaArrayAccess aa = (JavaArrayAccess) expr; + + // introduce temporary for array expression, if necessary + JavaExpression arrayExpr = aa.getArray(); + arrayExpr = evalConstExpr(arrayExpr, exprContext, tempID + + "_array", true); + + // create array access expression that references temporary + JavaArrayAccess accessExpr = new JavaArrayAccess(arrayExpr); + + // introduce temporaries for index expressions, if necessary + Iterator iter = aa.getIndices().iterator(); + int indexNo = 0; + while (iter.hasNext()) + { + JavaExpression indexExpr = (JavaExpression) iter.next(); + indexExpr = evalConstExpr(indexExpr, exprContext, tempID + + "_index" + indexNo++, true); + accessExpr.addIndex(indexExpr); + } + + return accessExpr; + } + } + else + { + // if temporary is not needed, return original expression + return expr; + } + } + + public static boolean isSimpleExpression(JavaExpression expr) + { + return expr instanceof Literal || isSimpleRef(expr); + } + + public static boolean isSimpleRef(JavaExpression expr) + { + // check for simple variable reference + if (isSimpleVarRef(expr)) return true; + + // check for member access using simple variable reference + if (expr instanceof JavaMemberAccess) + { + JavaMemberAccess ma = (JavaMemberAccess) expr; + JavaExpression objExpr = ma.getObject(); + if (isSimpleVarRef(objExpr)) return true; + } + + return false; + } + + public static boolean isSimpleVarRef(JavaExpression expr) + { + return expr instanceof JavaVariableReference + || expr instanceof JavaThisReference + || expr instanceof JavaSuperReference; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ExpressionConverter.java b/java/juno/src/com/newisys/schemabuilder/juno/ExpressionConverter.java new file mode 100644 index 0000000..3753bab --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ExpressionConverter.java @@ -0,0 +1,1197 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.Literal; +import com.newisys.langschema.Type; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.verilog.util.Bit; + +/** + * Provides methods for performing type tests and expression type conversion + * for the built-in types. + * + * @author Trevor Robinson + */ +public final class ExpressionConverter +{ + final JoveSchema schema; + final SchemaTypes types; + + public ExpressionConverter(JoveSchema schema, SchemaTypes types) + { + this.schema = schema; + this.types = types; + } + + //////////////////////////////////////////////////////////// + // Type tests + //////////////////////////////////////////////////////////// + + public boolean isAssocArray(Type type) + { + return type instanceof JavaAbstractClass + && types.assocArrayType.isSuperclassOf((JavaAbstractClass) type); + } + + public boolean isEnum(Type type) + { + return type instanceof JavaStructuredType + && ((JavaStructuredType) type) + .implementsInterface(types.junoEnumType); + } + + public JavaExpression getEnumUndefined(JavaEnum enumCls) + { + return new JavaVariableReference(enumCls.getField("UNDEFINED")); + } + + public boolean isSignal(Type type) + { + return type instanceof JavaStructuredType + && ((JavaStructuredType) type) + .implementsInterface(types.signalType); + } + + public boolean isInputSignal(Type type) + { + return type instanceof JavaStructuredType + && ((JavaStructuredType) type) + .implementsInterface(types.inputSignalType); + } + + public boolean isOutputSignal(Type type) + { + return type instanceof JavaStructuredType + && ((JavaStructuredType) type) + .implementsInterface(types.outputSignalType); + } + + public boolean isString(Type type) + { + return type == types.stringType || type == types.junoStringType; + } + + //////////////////////////////////////////////////////////// + // Conversions to Bit + //////////////////////////////////////////////////////////// + + public JavaExpression getBitExpr(Bit b) + { + final String[] names = { "ZERO", "ONE", "Z", "X" }; + final String name = names[b.getID()]; + return new JavaVariableReference(schema.bitType.getField(name)); + } + + public JavaExpression commonToBit(JavaExpression expr) + { + // narrowing conversion: BitOp.toBit((int) expr) + // narrowing conversion: BitOp.toBit((long) expr) + // narrowing conversion: BitOp.toBit((Integer) expr) + // narrowing conversion: BitOp.toBit((Long) expr) + // narrowing conversion: BitOp.toBit((String) expr) + // narrowing conversion: BitOp.toBit((Object) expr) + return ExpressionBuilder.staticCall(types.bitOpType, "toBit", expr); + } + + public JavaExpression bitVectorToBit(JavaExpression expr) + { + // narrowing conversion + // expr.getBit(0) + return ExpressionBuilder.memberCall(expr, "getBit", new JavaIntLiteral( + schema, 0)); + } + + public JavaExpression booleanToBit(JavaExpression expr) + { + // widening conversion + // expr ? Bit.ONE : Bit.ZERO + return new JavaConditional(expr, getBitExpr(Bit.ONE), + getBitExpr(Bit.ZERO)); + } + + public boolean hasBitConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type) || isString(type) + || type == schema.getObjectType(); + } + + public JavaExpression toBit(JavaExpression expr) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isBit(type)) + { + // do nothing + } + else if (schema.isBitVector(type)) + { + expr = bitVectorToBit(expr); + } + else if (schema.isInt(type) || schema.isLong(type)) + { + expr = commonToBit(expr); + } + else if (schema.isBoolean(type)) + { + expr = booleanToBit(expr); + } + else if (isEnum(type)) + { + expr = commonToBit(enumToIntWrapper(expr)); + } + else if (isString(type)) + { + expr = commonToBit(toJavaString(expr, false)); + } + else if (type == schema.getObjectType()) + { + expr = commonToBit(expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to Bit"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to logical Bit + //////////////////////////////////////////////////////////// + + public JavaExpression commonToLogicalBit(JavaExpression expr) + { + // narrowing conversion: BitOp.toLogicalBit((int) expr) + // narrowing conversion: BitOp.toLogicalBit((long) expr) + // narrowing conversion: BitOp.toLogicalBit((Integer) expr) + // narrowing conversion: BitOp.toLogicalBit((Long) expr) + // narrowing conversion: BitOp.toLogicalBit((BitVector) expr) + return ExpressionBuilder.staticCall(types.bitOpType, "toLogicalBit", + expr); + } + + public JavaExpression toLogicalBit(JavaExpression expr) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isBit(type)) + { + // do nothing + } + else if (schema.isInt(type) || schema.isLong(type) + || schema.isBitVector(type)) + { + expr = commonToLogicalBit(expr); + } + else if (schema.isBoolean(type)) + { + expr = booleanToBit(expr); + } + else if (isEnum(type)) + { + expr = commonToLogicalBit(enumToIntWrapper(expr)); + } + else if (isString(type)) + { + expr = commonToBit(toJavaString(expr, false)); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to Bit"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to BitVector + //////////////////////////////////////////////////////////// + + public JavaExpression getBitVectorExpr(Bit b) + { + final String[] names = { "BIT_0", "BIT_1", "BIT_Z", "BIT_X" }; + final String name = names[b.getID()]; + JavaMemberVariable field = types.bitVectorOpType.getField(name); + field.setType(schema.getBitVectorType(1)); + return new JavaVariableReference(field); + } + + public JavaExpression getBitVectorExpr(int len) + { + // new BitVector(len) + return ExpressionBuilder.newInstance(schema.getBitVectorType(len), + new JavaIntLiteral(schema, len)); + } + + public JavaExpression setBitVectorLength(JavaExpression expr, int len) + { + // truncate or zero-extend + // expr.setLength(len, Bit.ZERO) + JavaFunctionInvocation callExpr = ExpressionBuilder.memberCall(expr, + "setLength", new JavaIntLiteral(schema, len), getBitExpr(Bit.ZERO)); + callExpr.setResultType(schema.getBitVectorType(len)); + return callExpr; + } + + public JavaExpression bitToBitVector(JavaExpression expr, int len) + { + // widening conversion + // BitOp.toBitVector(len, (Bit) expr) + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.bitOpType, "toBitVector", new JavaExpression[] { + new JavaIntLiteral(schema, len), expr }, null); + callExpr.setResultType(schema.getBitVectorType(len)); + return callExpr; + } + + public JavaExpression intToBitVector( + JavaExpression expr, + int len, + boolean signExtend) + { + // widening conversion + // new BitVector(len, (int) expr, signExtend) + return ExpressionBuilder.newInstance(schema.getBitVectorType(len), + new JavaExpression[] { new JavaIntLiteral(schema, len), expr, + new JavaBooleanLiteral(schema, signExtend) }, null); + } + + public JavaExpression longToBitVector( + JavaExpression expr, + int len, + boolean signExtend) + { + // widening conversion + // new BitVector(len, (long) expr, signExtend) + return ExpressionBuilder.newInstance(schema.getBitVectorType(len), + new JavaExpression[] { new JavaIntLiteral(schema, len), expr, + new JavaBooleanLiteral(schema, signExtend) }, null); + } + + public JavaExpression intWrapperToBitVector( + JavaExpression expr, + int len, + boolean signExtend) + { + // widening conversion + // IntegerOp.toBitVector((Integer) expr, len, signExtend) + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.integerOpType, "toBitVector", new JavaExpression[] { expr, + new JavaIntLiteral(schema, len), + new JavaBooleanLiteral(schema, signExtend) }, null); + callExpr.setResultType(schema.getBitVectorType(len)); + return callExpr; + } + + public JavaExpression longWrapperToBitVector( + JavaExpression expr, + int len, + boolean signExtend) + { + // widening conversion + // LongOp.toBitVector((Long) expr, len, signExtend) + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.longWrapperOpType, "toBitVector", new JavaExpression[] { + expr, new JavaIntLiteral(schema, len), + new JavaBooleanLiteral(schema, signExtend) }, null); + callExpr.setResultType(schema.getBitVectorType(len)); + return callExpr; + } + + public JavaExpression intWrapperToUnsizedBitVector(JavaExpression expr) + { + // widening conversion + // IntegerOp.toBitVector((Integer) expr) + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.integerOpType, "toBitVector", expr); + callExpr.setResultType(schema.getBitVectorType(32)); + return callExpr; + } + + public JavaExpression longWrapperToUnsizedBitVector(JavaExpression expr) + { + // widening conversion + // LongOp.toBitVector((Long) expr) + JavaFunctionInvocation callExpr = ExpressionBuilder.staticCall( + types.longWrapperOpType, "toBitVector", expr); + callExpr.setResultType(schema.getBitVectorType(32)); + return callExpr; + } + + public JavaExpression stringToBitVector(JavaExpression expr) + { + // new BitVector(expr.getBytes()) + return ExpressionBuilder.newInstance(schema.bitVectorType, + ExpressionBuilder.memberCall(expr, "getBytes")); + } + + public JavaExpression objectToBitVector(JavaExpression expr) + { + // BitVectorOp.toBitVector((Object) expr) + return ExpressionBuilder.staticCall(types.bitVectorOpType, + "toBitVector", expr); + } + + public boolean hasBitVectorConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type) || isString(type) + || type == schema.getObjectType(); + } + + public JavaExpression toBitVector( + JavaExpression expr, + int len, + boolean signExtend) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isBitVector(type)) + { + if (len > 0 && schema.getBitVectorSize(type) != len) + { + expr = setBitVectorLength(expr, len); + } + } + else if (type == schema.integerWrapperType) + { + if (len > 0) + { + expr = intWrapperToBitVector(expr, len, signExtend); + } + else + { + expr = intWrapperToUnsizedBitVector(expr); + } + } + else if (schema.isInt(type)) + { + if (len <= 0) len = 32; + expr = intToBitVector(expr, len, signExtend); + } + else if (type == schema.longWrapperType) + { + if (len > 0) + { + expr = longWrapperToBitVector(expr, len, signExtend); + } + else + { + expr = longWrapperToUnsizedBitVector(expr); + } + } + else if (schema.isLong(type)) + { + if (len <= 0) len = 64; + expr = longToBitVector(expr, len, signExtend); + } + else if (schema.isBoolean(type)) + { + if (len <= 0) len = 1; + expr = bitToBitVector(booleanToBit(expr), len); + } + else if (type == schema.bitType) + { + if (len <= 0) len = 1; + expr = bitToBitVector(expr, len); + } + else if (isEnum(type)) + { + expr = enumToIntWrapper(expr); + if (len > 0) + { + expr = intWrapperToBitVector(expr, len, signExtend); + } + else + { + expr = intWrapperToUnsizedBitVector(expr); + } + } + else if (isString(type)) + { + expr = stringToBitVector(toJavaString(expr, true)); + if (len > 0) + { + expr = setBitVectorLength(expr, len); + } + } + else if (type == schema.getObjectType()) + { + expr = objectToBitVector(expr); + if (len > 0) + { + expr = setBitVectorLength(expr, len); + } + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to BitVector"); + } + return expr; + } + + public JavaExpression toUnsizedBitVector(JavaExpression expr) + throws TypeConversionException + { + return toBitVector(expr, -1, false); + } + + //////////////////////////////////////////////////////////// + // Conversions to Boolean + //////////////////////////////////////////////////////////// + + public JavaExpression bitToBoolean(JavaExpression expr, boolean xzTrue) + { + // narrowing conversion: loses X/Z + if (!xzTrue) + { + // expr == Bit.ONE + return new JavaEqual(schema, expr, new JavaVariableReference( + schema.bitType.getField("ONE"))); + } + else + { + // expr != Bit.ZERO + return new JavaNotEqual(schema, expr, new JavaVariableReference( + schema.bitType.getField("ZERO"))); + } + } + + public JavaExpression bitVectorToBoolean( + JavaExpression expr, + boolean lowBitOnly, + boolean xzTrue) + { + // narrowing conversion + if (lowBitOnly) + { + // !xzTrue: expr.getBit(0) == Bit.ONE + // xzTrue: expr.getBit(0) != Bit.ZERO + return bitToBoolean(ExpressionBuilder.memberCall(expr, "getBit", + new JavaIntLiteral(schema, 0)), xzTrue); + } + else + { + // BooleanOp.toBoolean((BitVector) expr) + // BooleanOp.toBooleanXZTrue((BitVector) expr) + return ExpressionBuilder.staticCall(types.booleanOpType, xzTrue + ? "toBooleanXZTrue" : "toBoolean", expr); + } + } + + public JavaExpression intToBoolean(JavaExpression expr, boolean lowBitOnly) + { + // narrowing conversion + // !lowBitOnly: expr != 0 + // lowBitOnly: (expr & 1) != 0 + if (expr instanceof JavaIntLiteral) + { + int value = ((JavaIntLiteral) expr).getValue(); + return new JavaBooleanLiteral(schema, !lowBitOnly ? value != 0 + : (value & 1) != 0); + } + if (lowBitOnly) + { + expr = new JavaAnd(schema, expr, new JavaIntLiteral(schema, 1)); + } + return new JavaNotEqual(schema, expr, new JavaIntLiteral(schema, 0)); + } + + public JavaExpression intWrapperToBoolean( + JavaExpression expr, + boolean lowBitOnly, + boolean xzTrue) + { + // narrowing conversion + // IntegerOp.toBoolean((Integer) expr) + // IntegerOp.lowBitToBoolean((Integer) expr) + // IntegerOp.toBooleanXZTrue((Integer) expr) + // IntegerOp.lowBitToBooleanXZTrue((Integer) expr) + return ExpressionBuilder.staticCall(types.integerOpType, lowBitOnly + ? (xzTrue ? "lowBitToBooleanXZTrue" : "lowBitToBoolean") : (xzTrue + ? "toBooleanXZTrue" : "toBoolean"), expr); + } + + public JavaExpression longWrapperToBoolean( + JavaExpression expr, + boolean lowBitOnly, + boolean xzTrue) + { + // narrowing conversion + // LongWrapperOp.toBoolean((Long) expr) + // LongWrapperOp.lowBitToBoolean((Integer) expr) + // LongWrapperOp.toBooleanXZTrue((Long) expr) + // LongWrapperOp.lowBitToBooleanXZTrue((Integer) expr) + return ExpressionBuilder.staticCall(types.longWrapperOpType, lowBitOnly + ? (xzTrue ? "lowBitToBooleanXZTrue" : "lowBitToBoolean") : (xzTrue + ? "toBooleanXZTrue" : "toBoolean"), expr); + } + + public JavaExpression objectToBoolean(JavaExpression expr) + { + // narrowing conversion + // BooleanOp.toBoolean((Object) expr) + // BooleanOp.toBoolean((String) expr) + return ExpressionBuilder.staticCall(types.booleanOpType, "toBoolean", + expr); + } + + public boolean hasBooleanConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type) || isString(type) + || type == schema.getObjectType(); + } + + public JavaExpression toBoolean( + JavaExpression expr, + boolean lowBitOnly, + boolean xzTrue) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isBoolean(type)) + { + // do nothing + } + else if (type == schema.integerWrapperType) + { + expr = intWrapperToBoolean(expr, lowBitOnly, xzTrue); + } + else if (type == schema.longWrapperType) + { + expr = longWrapperToBoolean(expr, lowBitOnly, xzTrue); + } + else if (schema.isInt(type) || schema.isLong(type)) + { + expr = intToBoolean(expr, lowBitOnly); + } + else if (schema.isBitVector(type)) + { + expr = bitVectorToBoolean(expr, lowBitOnly, xzTrue); + } + else if (type == schema.bitType) + { + expr = bitToBoolean(expr, xzTrue); + } + else if (isEnum(type)) + { + expr = intWrapperToBoolean(enumToIntWrapper(expr), lowBitOnly, + xzTrue); + } + else if (isString(type)) + { + expr = objectToBoolean(toJavaString(expr, false)); + } + else if (type == schema.getObjectType()) + { + expr = objectToBoolean(expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to boolean"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to int + //////////////////////////////////////////////////////////// + + public JavaExpression bitToInt(JavaExpression expr) + { + // checked conversion: throws IllegalArgumentException if X/Z + // BitOp.toInt((Bit) expr) + return ExpressionBuilder.staticCall(types.bitOpType, "toInt", expr); + } + + public JavaExpression bitVectorToInt(JavaExpression expr) + { + // checked conversion: throws IllegalArgumentException if X/Z + // BitVectorOp.toInt((BitVector) expr) + return ExpressionBuilder.staticCall(types.bitVectorOpType, "toInt", + expr); + } + + public JavaExpression booleanToInt(JavaExpression expr) + { + // widening conversion + // expr ? 1 : 0 + return new JavaConditional(expr, new JavaIntLiteral(schema, 1), + new JavaIntLiteral(schema, 0)); + } + + public JavaExpression enumToInt(JavaExpression expr) + { + // widening conversion + // expr.toInt() + return ExpressionBuilder.memberCall(expr, "toInt"); + } + + public JavaExpression longToInt(JavaExpression expr) + { + // narrowing conversion + // (int) expr + return new JavaCastExpression(schema.intType, expr); + } + + public JavaExpression objectToInt(JavaExpression expr) + { + // narrowing conversion + // IntOp.toInt((Object) expr) + // IntOp.toInt((String) expr) + return ExpressionBuilder.staticCall(types.intOpType, "toInt", expr); + } + + public boolean hasIntConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type) || isString(type) + || type == schema.getObjectType(); + } + + public JavaExpression toInt(JavaExpression expr) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isInt(type)) + { + // do nothing + } + else if (schema.isLong(type)) + { + expr = longToInt(expr); + } + else if (schema.isBoolean(type)) + { + expr = booleanToInt(expr); + } + else if (schema.isBitVector(type)) + { + expr = bitVectorToInt(expr); + } + else if (type == schema.bitType) + { + expr = bitToInt(expr); + } + else if (isEnum(type)) + { + expr = enumToInt(expr); + } + else if (isString(type)) + { + expr = objectToInt(toJavaString(expr, true)); + } + else if (type == schema.getObjectType()) + { + expr = objectToInt(expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to int"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to Integer + //////////////////////////////////////////////////////////// + + public JavaExpression commonToIntWrapper(JavaExpression expr) + { + // narrowing conversion: loses Z: IntegerOp.toInteger((Bit) expr) + // narrowing conversion: loses positional X/Z, truncates to 32 bits: + // IntegerOp.toInteger((BitVector) expr) + // narrowing conversion: IntegerOp.toInteger((String) expr) + // narrowing conversion: IntegerOp.toInteger((Object) expr) + return ExpressionBuilder.staticCall(types.integerOpType, "toInteger", + expr); + } + + public JavaExpression enumToIntWrapper(JavaExpression expr) + { + // widening conversion + // expr.toInteger() + return ExpressionBuilder.memberCall(expr, "toInteger"); + } + + public JavaExpression longToIntWrapper(JavaExpression expr) + { + // narrowing conversion + // new Integer((int) expr) + return ExpressionBuilder.newInstance(schema.integerWrapperType, + new JavaCastExpression(schema.intType, expr)); + } + + public JavaExpression longWrapperToIntWrapper(JavaExpression expr) + { + // narrowing conversion + // IntegerOp.toInteger((Long) expr) + return ExpressionBuilder.staticCall(types.integerOpType, "toInteger", + expr); + } + + public JavaExpression toInteger(JavaExpression expr) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isInt(type)) + { + // do nothing + } + else if (type == schema.longWrapperType) + { + expr = longWrapperToIntWrapper(expr); + } + else if (schema.isLong(type)) + { + expr = longToIntWrapper(expr); + } + else if (schema.isBoolean(type)) + { + expr = booleanToInt(expr); + } + else if (schema.isBitVector(type) || type == schema.bitType) + { + expr = commonToIntWrapper(expr); + } + else if (isEnum(type)) + { + expr = enumToIntWrapper(expr); + } + else if (isString(type)) + { + expr = commonToIntWrapper(toJavaString(expr, true)); + } + else if (type == schema.getObjectType()) + { + expr = commonToIntWrapper(expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to Integer"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to Long + //////////////////////////////////////////////////////////// + + public JavaExpression commonToLongWrapper(JavaExpression expr) + { + // narrowing conversion: loses Z: LongWrapperOp.toLongWrapper((Bit) expr) + // narrowing conversion: loses positional X/Z, truncates to 32 bits: + // LongWrapperOp.toLongWrapper((BitVector) expr) + // narrowing conversion: LongWrapperOp.toLongWrapper((String) expr) + // narrowing conversion: LongWrapperOp.toLongWrapper((Object) expr) + return ExpressionBuilder.staticCall(types.longWrapperOpType, + "toLongWrapper", expr); + } + + public JavaExpression enumToLongWrapper(JavaExpression expr) + { + // widening conversion + // LongWrapperOp.toLongWrapper(expr.toInteger()) + return intWrapperToLongWrapper(enumToIntWrapper(expr)); + } + + public JavaExpression intToLongWrapper(JavaExpression expr) + { + // widening conversion + // new Long((int) expr) + return ExpressionBuilder.newInstance(schema.longWrapperType, expr); + } + + public JavaExpression intWrapperToLongWrapper(JavaExpression expr) + { + // narrowing conversion + // LongWrapperOp.toLongWrapper((Integer) expr) + return ExpressionBuilder.staticCall(types.longWrapperOpType, + "toLongWrapper", expr); + } + + public boolean hasLongWrapperConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type) || isString(type) + || type == schema.getObjectType(); + } + + public JavaExpression toLongWrapper(JavaExpression expr) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isLong(type)) + { + // do nothing + } + else if (type == schema.integerWrapperType) + { + expr = intWrapperToLongWrapper(expr); + } + else if (schema.isInt(type)) + { + expr = intToLongWrapper(expr); + } + else if (schema.isBoolean(type)) + { + expr = intToLongWrapper(booleanToInt(expr)); + } + else if (schema.isBitVector(type) || type == schema.bitType) + { + expr = commonToLongWrapper(expr); + } + else if (isEnum(type)) + { + expr = enumToLongWrapper(expr); + } + else if (isString(type)) + { + expr = commonToLongWrapper(toJavaString(expr, true)); + } + else if (type == schema.getObjectType()) + { + expr = commonToLongWrapper(expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to Long"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to Object + //////////////////////////////////////////////////////////// + + public boolean hasObjectConversion(Type type) + { + return type instanceof JavaPrimitiveType + || type instanceof JavaReferenceType; + } + + public JavaExpression toObject(JavaExpression expr) + { + Type type = expr.getResultType(); + assert (type instanceof JavaPrimitiveType || type instanceof JavaReferenceType); + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to shift count (int) + //////////////////////////////////////////////////////////// + + public JavaExpression bitToShiftCount(JavaExpression expr) + { + // checked conversion: throws IllegalArgumentException if X/Z + // BitOp.toShiftCount((Bit) expr) + return ExpressionBuilder.staticCall(types.bitOpType, "toShiftCount", + expr); + } + + public JavaExpression bitVectorToShiftCount( + JavaExpression expr, + boolean limit) + { + // checked conversion: throws IllegalArgumentException if X/Z + // BitVectorOp.toShiftCount((BitVector) expr [, 31]) + if (limit) + { + return ExpressionBuilder.staticCall(types.bitVectorOpType, + "toShiftCount", expr, new JavaIntLiteral(schema, 31)); + } + return ExpressionBuilder.staticCall(types.bitVectorOpType, + "toShiftCount", expr); + } + + public JavaExpression intToShiftCount(JavaExpression expr, boolean limit) + { + // narrowing conversion + // Math.min(expr, 31) + if (limit) + { + if (expr instanceof JavaIntLiteral) + { + JavaIntLiteral lit = (JavaIntLiteral) expr; + if (lit.getValue() > 31) expr = new JavaIntLiteral(schema, 31); + } + else + { + expr = ExpressionBuilder.staticCall(types.mathType, "min", + expr, new JavaIntLiteral(schema, 31)); + } + } + return expr; + } + + public boolean hasShiftCountConversion(JavaType type) + { + return schema.isDVIntegral(type) || isEnum(type); + } + + public JavaExpression toShiftCount(JavaExpression expr, boolean limit) + throws TypeConversionException + { + JavaType type = expr.getResultType(); + if (schema.isInt(type) || schema.isLong(type)) + { + expr = intToShiftCount(expr, limit); + } + else if (schema.isBoolean(type)) + { + expr = booleanToInt(expr); + } + else if (schema.isBitVector(type)) + { + expr = bitVectorToShiftCount(expr, limit); + } + else if (type == schema.bitType) + { + expr = bitToShiftCount(expr); + } + else if (isEnum(type)) + { + expr = intToShiftCount(enumToInt(expr), limit); + } + else + { + throw new TypeConversionException("Cannot convert " + + type.toDebugString() + " to shift count (int)"); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to String + //////////////////////////////////////////////////////////// + + public JavaExpression toStringOrBlank(JavaExpression expr) + { + return ExpressionBuilder.staticCall(types.stringOpType, + "toStringOrBlank", expr); + } + + public JavaExpression junoStringToJavaString( + JavaExpression expr, + boolean nullAsBlank) + { + // expr.toStringOrBlank() + // expr.toStringOrNull() + return ExpressionBuilder.memberCall(expr, nullAsBlank + ? "toStringOrBlank" : "toStringOrNull"); + } + + public JavaExpression primitiveToJavaString(JavaExpression expr) + { + // String.valueOf(expr) + return ExpressionBuilder.staticCall(schema.getStringType(), "valueOf", + expr); + } + + public JavaExpression objectToJavaString(JavaExpression expr) + { + // expr.toString() + return ExpressionBuilder.memberCall(expr, "toString"); + } + + public boolean hasJavaStringConversion(Type type) + { + return hasObjectConversion(type); + } + + public JavaExpression toJavaString(JavaExpression expr, boolean nullAsBlank) + throws TypeConversionException + { + Type type = expr.getResultType(); + if (types.stringType.isAssignableFrom(type)) + { + if (nullAsBlank && !(expr instanceof Literal)) + { + expr = toStringOrBlank(expr); + } + } + else if (type == types.junoStringType) + { + expr = junoStringToJavaString(expr, nullAsBlank); + } + else if (type instanceof JavaPrimitiveType) + { + expr = primitiveToJavaString(expr); + } + else + { + expr = objectToJavaString(expr); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to JunoString + //////////////////////////////////////////////////////////// + + public JavaExpression getNullJunoString() + { + return new JavaVariableReference(types.junoStringType.getField("NULL")); + } + + public JavaExpression javaStringToJunoString(JavaExpression expr) + { + // new JunoString((String) expr) + return ExpressionBuilder.newInstance(types.junoStringType, expr); + } + + public boolean hasJunoStringConversion(Type type) + { + return hasObjectConversion(type); + } + + public JavaExpression toJunoString(JavaExpression expr) + throws TypeConversionException + { + Type type = expr.getResultType(); + if (type instanceof JavaNullType) + { + expr = getNullJunoString(); + } + else if (types.junoStringType.isAssignableFrom(type)) + { + // do nothing + } + else if (type == types.stringType) + { + expr = javaStringToJunoString(expr); + } + else + { + expr = javaStringToJunoString(toJavaString(expr, false)); + } + return expr; + } + + //////////////////////////////////////////////////////////// + // Conversions to arbitrary type + //////////////////////////////////////////////////////////// + + public boolean hasConversion(JavaType fromType, JavaType toType) + { + if (toType.isAssignableFrom(fromType)) + { + // no conversion necessary + return true; + } + else if (schema.isInt(toType)) + { + return hasIntConversion(fromType); + } + else if (schema.isBoolean(toType)) + { + return hasBooleanConversion(fromType); + } + else if (toType == schema.longWrapperType) + { + return hasLongWrapperConversion(fromType); + } + else if (schema.isBitVector(toType)) + { + return hasBitVectorConversion(fromType); + } + else if (toType == schema.bitType) + { + return hasBitConversion(fromType); + } + else if (toType == types.stringType) + { + return hasJavaStringConversion(fromType); + } + else if (toType == types.junoStringType) + { + return hasJunoStringConversion(fromType); + } + else if (toType == types.objectType) + { + return hasObjectConversion(fromType); + } + return false; + } + + public JavaExpression toType(JavaType type, JavaExpression expr) + throws TypeConversionException + { + Type srcType = expr.getResultType(); + if (schema.isBitVector(type)) + { + expr = toBitVector(expr, schema.getBitVectorSize(type), false); + } + else if (type.isAssignableFrom(srcType)) + { + // do nothing + } + else if (type == schema.integerWrapperType) + { + expr = toInteger(expr); + } + else if (schema.isInt(type)) + { + expr = toInt(expr); + } + else if (schema.isBoolean(type)) + { + expr = toBoolean(expr, true, false); + } + else if (type == schema.longWrapperType) + { + expr = toLongWrapper(expr); + } + else if (type == schema.bitType) + { + expr = toBit(expr); + } + else if (type == types.stringType) + { + expr = toJavaString(expr, false); + } + else if (type == types.junoStringType) + { + expr = toJunoString(expr); + } + else if (type == types.objectType) + { + expr = toObject(expr); + } + else if ((type instanceof JavaAbstractClass + && srcType instanceof JavaAbstractClass && ((JavaAbstractClass) srcType) + .isSuperclassOf((JavaAbstractClass) type)) + || (type instanceof JavaStructuredType + && srcType instanceof JavaInterface && ((JavaStructuredType) type) + .implementsInterface((JavaInterface) srcType))) + { + expr = new JavaCastExpression(type, expr); + } + else + { + throw new TypeConversionException("Cannot convert " + + srcType.toDebugString() + " to " + type.toDebugString()); + } + return expr; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ExpressionTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/ExpressionTranslator.java new file mode 100644 index 0000000..4f9ca7d --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ExpressionTranslator.java @@ -0,0 +1,2995 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.juno.runtime.BooleanOp; +import com.newisys.langschema.Scope; +import com.newisys.langschema.StructuredTypeMember; +import com.newisys.langschema.Type; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.vera.*; +import com.newisys.schemaanalyzer.juno.FunctionAnalysis; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorFormat; + +/** + * Schema translator for (non-constraint) expressions. + * + * @author Trevor Robinson + */ +final class ExpressionTranslator + extends TranslatorModule + implements VeraExpressionVisitor +{ + final JavaStructuredType containingType; + final VarInfoMap varInfoMap; + final JavaLocalVariable returnVar; + final JavaType promoteType; + final JavaType desiredResultType; + final ConvertedExpression result; + + boolean assignSampleAsync = false; + boolean sampleAsync = true; + + public ExpressionTranslator( + TranslatorModule xlatContext, + JavaStructuredType containingType, + VarInfoMap varInfoMap, + JavaLocalVariable returnVar, + JavaType promoteType, + JavaType desiredResultType, + ConvertedExpression result) + { + super(xlatContext); + this.containingType = containingType; + this.varInfoMap = varInfoMap; + this.returnVar = returnVar; + this.promoteType = promoteType; + this.desiredResultType = desiredResultType; + this.result = result; + } + + public void setAssignSampleAsync(boolean assignSampleAsync) + { + this.assignSampleAsync = assignSampleAsync; + } + + ConvertedExpression translateNewExpr( + VeraExpression veraExpr, + JavaType promoteType, + JavaType desiredResultType, + boolean sampleAsync) + { + return translateExpr(veraExpr, result.getScope(), containingType, + varInfoMap, returnVar, promoteType, desiredResultType, sampleAsync); + } + + ConvertedExpression translateNewExpr( + VeraExpression veraExpr, + JavaType desiredResultType, + boolean sampleAsync) + { + return translateNewExpr(veraExpr, promoteType, desiredResultType, + sampleAsync); + } + + ConvertedExpression translateNewExpr( + VeraExpression veraExpr, + JavaType desiredResultType) + { + return translateNewExpr(veraExpr, promoteType, desiredResultType, + sampleAsync); + } + + ConvertedExpression translateNewExpr(VeraExpression veraExpr) + { + return translateNewExpr(veraExpr, promoteType, null, sampleAsync); + } + + JavaExpression translateNestedExpr( + VeraExpression veraExpr, + String tempID, + JavaType promoteType, + JavaType desiredResultType, + boolean sampleAsync) + { + ConvertedExpression nestedResult = translateNewExpr(veraExpr, + promoteType, desiredResultType, sampleAsync); + JavaExpression resultExpr = nestedResult.flatten(tempID); + result.addInitMembers(nestedResult.getInitMembers()); + return resultExpr; + } + + JavaExpression translateNestedExpr( + VeraExpression veraExpr, + String tempID, + JavaType desiredResultType, + boolean sampleAsync) + { + return translateNestedExpr(veraExpr, tempID, promoteType, + desiredResultType, sampleAsync); + } + + JavaExpression translateNestedExpr( + VeraExpression veraExpr, + String tempID, + JavaType desiredResultType) + { + return translateNestedExpr(veraExpr, tempID, promoteType, + desiredResultType, sampleAsync); + } + + JavaExpression translateNestedExpr( + VeraExpression veraExpr, + JavaType desiredResultType) + { + return translateNestedExpr(veraExpr, "temp", promoteType, + desiredResultType, sampleAsync); + } + + JavaExpression translateNestedExpr(VeraExpression veraExpr, String tempID) + { + return translateNestedExpr(veraExpr, tempID, promoteType, null, + sampleAsync); + } + + JavaExpression translateNestedExpr(VeraExpression veraExpr) + { + return translateNestedExpr(veraExpr, "temp", promoteType, null, + sampleAsync); + } + + JavaExpression translateNestedIntExpr(VeraExpression veraExpr, String tempID) + { + return translateNestedExpr(veraExpr, tempID, promoteType, + schema.intType, sampleAsync); + } + + JavaExpression translateNestedIntExpr(VeraExpression veraExpr) + { + return translateNestedExpr(veraExpr, "temp", promoteType, + schema.intType, sampleAsync); + } + + LHSTranslator translateLHS( + VeraExpression veraExpr, + JavaType desiredResultType, + boolean readAccess, + boolean writeAccess) + { + return translateLHS(veraExpr, result, desiredResultType, readAccess, + writeAccess); + } + + LHSTranslator translateLHS( + VeraExpression veraExpr, + ConvertedExpression result, + JavaType desiredResultType, + boolean readAccess, + boolean writeAccess) + { + LHSTranslator xlat; + if (veraExpr instanceof VeraArrayAccess) + { + xlat = new ArrayLHSTranslator(this, result, + (VeraArrayAccess) veraExpr, readAccess, writeAccess); + } + else if (veraExpr instanceof VeraBitSliceAccess) + { + xlat = new BitSliceLHSTranslator(this, result, + (VeraBitSliceAccess) veraExpr, readAccess, writeAccess); + } + else if (veraExpr instanceof VeraConcatenation) + { + xlat = new ConcatLHSTranslator(this, result, + (VeraConcatenation) veraExpr, readAccess, writeAccess); + } + else + { + xlat = new SimpleLHSTranslator(this, result, desiredResultType, + veraExpr, readAccess, writeAccess); + } + return xlat; + } + + static final int OP_NONE = 0; + static final int OP_ADD = 1; + static final int OP_SUBTRACT = 2; + static final int OP_MULTIPLY = 3; + static final int OP_DIVIDE = 4; + static final int OP_MODULO = 5; + static final int OP_NEGATE = 6; + static final int OP_AND = 7; + static final int OP_AND_NOT = 8; + static final int OP_OR = 9; + static final int OP_OR_NOT = 10; + static final int OP_XOR = 11; + static final int OP_XOR_NOT = 12; + static final int OP_NOT = 13; + static final int OP_REVERSE = 14; + static final int OP_REDUCTIVE_AND = 15; + static final int OP_REDUCTIVE_AND_NOT = 16; + static final int OP_REDUCTIVE_OR = 17; + static final int OP_REDUCTIVE_OR_NOT = 18; + static final int OP_REDUCTIVE_XOR = 19; + static final int OP_REDUCTIVE_XOR_NOT = 20; + static final int OP_EQ = 21; + static final int OP_NE = 22; + static final int OP_EXACT_EQ = 23; + static final int OP_EXACT_NE = 24; + static final int OP_WILD_EQ = 25; + static final int OP_WILD_NE = 26; + static final int OP_GT = 27; + static final int OP_GE = 28; + static final int OP_LT = 29; + static final int OP_LE = 30; + static final int OP_SHIFT_LEFT = 31; + static final int OP_SHIFT_RIGHT = 32; + static final int OP_PRE_INC = 33; + static final int OP_PRE_DEC = 34; + static final int OP_POST_INC = 35; + static final int OP_POST_DEC = 36; + + private int getTypeWidthChecked(JavaType type) + { + return (type != null && schema.isDVIntegral(type)) ? schema + .getTypeWidth(type) : -1; + } + + private JavaExpression contextPromote( + JavaExpression expr, + boolean signExtend) + { + JavaType type = expr.getResultType(); + if (schema.isDVIntegral(type)) + { + int len = schema.getTypeWidth(type); + int promoteLen = getTypeWidthChecked(promoteType); + if (len < promoteLen) + { + if (schema.isBitVector(type)) + { + if (len > 0) + { + // original length is known (and is definitely less + // than the promotion length) so we can unconditionally + // call setLength() on the resulting bit vector + expr = exprConv.setBitVectorLength(expr, promoteLen); + } + else + { + // original length is not known (and may already be + // larger than the promotion length) so we must call + // BitVectorOp.promote() which checks the length at + // run time + expr = ExpressionBuilder.staticCall( + types.bitVectorOpType, "promote", expr, + new JavaIntLiteral(schema, promoteLen)); + } + } + else + { + // bit/integer/enum -> bit vector + expr = exprConv.toBitVector(expr, promoteLen, signExtend); + } + } + } + return expr; + } + + private void doUnaryArithmetic(VeraUnaryOperation obj, int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 1); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + JavaExpression op1 = translateNestedExpr(veraOp1); + op1 = contextPromote(op1, false); + final JavaType type1 = op1.getResultType(); + final ArithmeticOperationBuilder builder; + if (type1 instanceof JavaNumericType) + { + // int/long + builder = new IntOperationBuilder(this); + } + else if (type1 instanceof JavaBooleanType) + { + // boolean + builder = new BooleanOperationBuilder(this); + } + else if (type1 == schema.bitType) + { + // Bit + builder = new BitOperationBuilder(this); + } + else if (schema.isBitVector(type1)) + { + // BitVector + builder = new BitVectorOperationBuilder(this); + } + else + { + // Integer or enum + op1 = exprConv.toInteger(op1); + builder = new IntegerOperationBuilder(this); + } + + final JavaExpression resultExpr; + switch (opcode) + { + case OP_NEGATE: + resultExpr = builder.negate(op1); + break; + case OP_NOT: + resultExpr = builder.not(op1); + break; + case OP_REVERSE: + resultExpr = builder.reverse(op1); + break; + case OP_REDUCTIVE_AND: + resultExpr = builder.reductiveAnd(op1); + break; + case OP_REDUCTIVE_AND_NOT: + resultExpr = builder.reductiveAndNot(op1); + break; + case OP_REDUCTIVE_OR: + resultExpr = builder.reductiveOr(op1); + break; + case OP_REDUCTIVE_OR_NOT: + resultExpr = builder.reductiveOrNot(op1); + break; + case OP_REDUCTIVE_XOR: + resultExpr = builder.reductiveXor(op1); + break; + case OP_REDUCTIVE_XOR_NOT: + resultExpr = builder.reductiveXorNot(op1); + break; + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + private void doBinaryArithmetic( + VeraBinaryArithmeticOperation obj, + int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = translateNestedExpr(veraOp1); + final JavaExpression op2 = translateNestedExpr(veraOp2); + final JavaExpression resultExpr = doBinaryArithmetic(op1, op2, opcode); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + JavaExpression doBinaryArithmetic( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + op1 = contextPromote(op1, false); + op2 = contextPromote(op2, opcode == OP_ADD); + final JavaType type1 = op1.getResultType(); + final JavaType type2 = op2.getResultType(); + final ArithmeticOperationBuilder builder; + if (type1 instanceof JavaNumericType + && type2 instanceof JavaNumericType) + { + // int/long / int/long + builder = new IntOperationBuilder(this); + } + else if (type1 instanceof JavaBooleanType + && type2 instanceof JavaBooleanType) + { + // boolean / boolean + builder = new BooleanOperationBuilder(this); + } + else if (type1 == schema.bitType && type2 == schema.bitType) + { + // Bit / Bit + builder = new BitOperationBuilder(this); + } + else if (schema.isBitVector(type1) || schema.isBitVector(type2)) + { + // promote to BitVector + op1 = exprConv.toUnsizedBitVector(op1); + op2 = exprConv.toUnsizedBitVector(op2); + builder = new BitVectorOperationBuilder(this); + } + else + { + // promote to Integer + op1 = exprConv.toInteger(op1); + op2 = exprConv.toInteger(op2); + builder = new IntegerOperationBuilder(this); + } + + switch (opcode) + { + case OP_ADD: + return builder.add(op1, op2); + case OP_SUBTRACT: + return builder.subtract(op1, op2); + case OP_MULTIPLY: + return builder.multiply(op1, op2); + case OP_DIVIDE: + return builder.divide(op1, op2); + case OP_MODULO: + return builder.mod(op1, op2); + case OP_AND: + return builder.and(op1, op2); + case OP_AND_NOT: + return builder.andNot(op1, op2); + case OP_OR: + return builder.or(op1, op2); + case OP_OR_NOT: + return builder.orNot(op1, op2); + case OP_XOR: + return builder.xor(op1, op2); + case OP_XOR_NOT: + return builder.xorNot(op1, op2); + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + } + + private void doShift(VeraShiftOperation obj, int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = translateNestedExpr(veraOp1); + final JavaExpression op2 = translateNestedIntExpr(veraOp2, "count"); + final JavaExpression resultExpr = doShift(op1, op2, opcode); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + private JavaExpression doShift( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + if (opcode == OP_SHIFT_LEFT) + { + op1 = contextPromote(op1, false); + } + final JavaType type1 = op1.getResultType(); + final ShiftOperationBuilder builder; + if (type1 instanceof JavaNumericType) + { + // int/long + op2 = exprConv.toShiftCount(op2, true); + builder = new IntOperationBuilder(this); + } + else if (schema.isBitVector(type1)) + { + // BitVector + op2 = exprConv.toShiftCount(op2, false); + builder = new BitVectorOperationBuilder(this); + } + else + { + // promote to Integer + op1 = exprConv.toInteger(op1); + op2 = exprConv.toInteger(op2); + builder = new IntegerOperationBuilder(this); + } + + switch (opcode) + { + case OP_SHIFT_LEFT: + return builder.shiftLeft(op1, op2); + case OP_SHIFT_RIGHT: + return builder.shiftRight(op1, op2); + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + } + + private void doEquality(VeraBinaryOperation obj, int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = translateNestedExpr(veraOp1); + final JavaExpression op2 = translateNestedExpr(veraOp2); + final JavaExpression resultExpr = buildEquality(op1, op2, opcode); + resultExpr.addAnnotations(obj.getAnnotations()); + } + + JavaExpression buildEquality( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + JavaType type1 = op1.getResultType(); + JavaType type2 = op2.getResultType(); + EqualityOperationBuilder builder = null; + if (!(type1 instanceof JavaPrimitiveType && type2 instanceof JavaPrimitiveType)) + { + if (schema.isBitVector(type1) || schema.isBitVector(type2)) + { + // promote to BitVector + op1 = exprConv.toUnsizedBitVector(op1); + op2 = exprConv.toUnsizedBitVector(op2); + builder = new BitVectorOperationBuilder(this); + } + else if (type1 == schema.integerWrapperType + || type2 == schema.integerWrapperType + || type1 == schema.intType || type2 == schema.intType) + { + // promote to Integer + op1 = exprConv.toInteger(op1); + op2 = exprConv.toInteger(op2); + builder = new IntegerOperationBuilder(this); + } + else if (type1 == schema.bitType || type2 == schema.bitType + || type1 == schema.booleanType || type2 == schema.booleanType) + { + // promote to Bit + op1 = exprConv.toBit(op1); + op2 = exprConv.toBit(op2); + builder = new BitOperationBuilder(this); + } + else if (type1 == types.stringType && type2 == types.stringType) + { + // both String + builder = new EqualsEqualityOperationBuilder(this, true); + } + else if (needsClone(type1)) + { + // use equals() method for cloned objects + builder = new EqualsEqualityOperationBuilder(this); + } + else if (needsClone(type2)) + { + if (type2 == types.junoStringType) + { + // swap operands to use JunoString.equals() + JavaExpression opTmp = op1; + op1 = op2; + op2 = opTmp; + JavaType typeTmp = type1; + type1 = type2; + type2 = typeTmp; + } + // use equals() method for cloned objects + builder = new EqualsEqualityOperationBuilder(this); + } + } + if (builder == null) + { + // use built-in operators for primitives or non-cloned objects + + // the built-in equality operators require boolean == boolean or + // numeric == numeric, so we need to convert boolean to int when + // boolean == numeric; also, if the numeric expression is a + // constant, we can optimize it away + if (type1 instanceof JavaBooleanType + ^ type2 instanceof JavaBooleanType) + { + final JavaExpression boolOp, otherOp; + if (type1 instanceof JavaBooleanType) + { + boolOp = op1; + otherOp = op2; + } + else + { + boolOp = op2; + otherOp = op1; + } + if (otherOp instanceof JavaIntLiteral) + { + final JavaIntLiteral lit = (JavaIntLiteral) otherOp; + final int litValue = lit.getValue(); + final boolean isEq = (opcode == OP_EQ + || opcode == OP_EXACT_EQ || opcode == OP_WILD_EQ); + final JavaExpression resultExpr; + if (litValue < 0 || litValue > 1) + { + // comparing to other than 0/1 is always false + resultExpr = new JavaBooleanLiteral(schema, false); + } + else if (isEq == (litValue == 1)) + { + // == 1, != 0 -> boolOp + resultExpr = boolOp; + } + else + { + // == 0, != 1 -> !boolOp + resultExpr = new JavaLogicalNot(schema, boolOp); + } + result.setResultExpr(resultExpr); + return resultExpr; + } + else if (type1 instanceof JavaBooleanType) + { + op1 = exprConv.toInt(op1); + } + else + { + op2 = exprConv.toInt(op2); + } + } + + builder = new PrimitiveEqualityOperationBuilder(this); + } + + final JavaExpression resultExpr; + switch (opcode) + { + case OP_EQ: + resultExpr = builder.equal(op1, op2); + break; + case OP_NE: + resultExpr = builder.notEqual(op1, op2); + break; + case OP_EXACT_EQ: + resultExpr = builder.exactEqual(op1, op2); + break; + case OP_EXACT_NE: + resultExpr = builder.exactNotEqual(op1, op2); + break; + case OP_WILD_EQ: + resultExpr = builder.wildEqual(op1, op2); + break; + case OP_WILD_NE: + resultExpr = builder.wildNotEqual(op1, op2); + break; + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + result.setResultExpr(resultExpr); + return resultExpr; + } + + private void doRelation(VeraComparisonOperation obj, int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + JavaExpression op1 = translateNestedExpr(veraOp1); + JavaExpression op2 = translateNestedExpr(veraOp2); + final JavaType type1 = op1.getResultType(); + final JavaType type2 = op2.getResultType(); + final RelationalOperationBuilder builder; + if (type1 instanceof JavaNumericType + && type2 instanceof JavaNumericType) + { + // int/long / int/long + builder = new IntOperationBuilder(this); + } + else if (schema.isBitVector(type1) || schema.isBitVector(type2)) + { + // promote to BitVector + op1 = exprConv.toUnsizedBitVector(op1); + op2 = exprConv.toUnsizedBitVector(op2); + builder = new BitVectorOperationBuilder(this); + } + else + { + // promote to Integer + op1 = exprConv.toInteger(op1); + op2 = exprConv.toInteger(op2); + builder = new IntegerOperationBuilder(this); + } + + final JavaExpression resultExpr; + switch (opcode) + { + case OP_GT: + resultExpr = builder.greater(op1, op2); + break; + case OP_GE: + resultExpr = builder.greaterOrEqual(op1, op2); + break; + case OP_LT: + resultExpr = builder.less(op1, op2); + break; + case OP_LE: + resultExpr = builder.lessOrEqual(op1, op2); + break; + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + boolean hasJavaLHS(VeraExpression veraExpr) + { + if (veraExpr.isAssignable()) + { + if (veraExpr instanceof VeraVariableReference + || veraExpr instanceof VeraMemberAccess + || veraExpr instanceof VeraSignalReference) + { + return true; + } + else if (veraExpr instanceof VeraArrayAccess) + { + // associative array access is not a Java LHS + Type type = veraExpr.getResultType(); + return type instanceof VeraFixedArrayType + || type instanceof VeraDynamicArrayType; + } + else + { + assert (veraExpr instanceof VeraBitSliceAccess || veraExpr instanceof VeraConcatenation); + } + } + return false; + } + + private void doAssignOp(VeraAssignment obj, int opcode) + { + List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraLHS = (VeraExpression) operands.get(0); + final VeraExpression veraRHS = (VeraExpression) operands.get(1); + buildAssignOp(veraLHS, veraRHS, opcode); + result.getResultExpr().addAnnotations(obj.getAnnotations()); + } + + void buildAssignOp(VeraExpression veraLHS, VeraExpression veraRHS) + { + buildAssignOp(veraLHS, veraRHS, OP_NONE); + } + + void buildAssignOp( + VeraExpression veraLHS, + VeraExpression veraRHS, + int opcode) + { + JavaExpression rhs = null; + JavaType rhsType = null; + + // attempt to use built-in operator if LHS translates to a Java LHS + if (hasJavaLHS(veraLHS)) + { + // translate LHS + JavaExpression lhs = translateNestedExpr(veraLHS, + types.outputSignalType); + JavaType lhsType = lhs.getResultType(); + if (exprConv.isOutputSignal(lhsType)) + { + // Vera does not allow compound assignment on signals + assert (opcode == OP_NONE); + + // translate RHS using signal width for signalType type + final JavaType signalType = translateType(veraLHS + .getResultType()); + rhs = translateNestedExpr(veraRHS, "rhs", signalType, + signalType, assignSampleAsync); + rhs = exprConv.toObject(rhs); + + // translate drive + result.setResultExpr(ExpressionBuilder.memberCall(lhs, "drive", + rhs)); + return; + } + else + { + // translate RHS using LHS type for promotion type + rhs = translateNestedExpr(veraRHS, "rhs", lhsType, lhsType, + assignSampleAsync); + rhsType = rhs.getResultType(); + + if (opcode == OP_NONE) + { + // return Java assignment expression + LHSTranslator lhsXlat = new SimpleLHSTranslator(this, + result, lhs, false, true); + if (rhs instanceof JavaArrayInitializer) + { + // initializers for Vera global variables are changed to + // assignments by the Vera schema builder (see + // VeraSchemaBuilder.visit(ProgramDecl)); for array + // initializers, we need to wrap them in an array + // creation expression to produce valid Java + JavaArrayInitializer initExpr = (JavaArrayInitializer) rhs; + JavaArrayType arrayType = initExpr.getResultType(); + JavaArrayCreation newArrayExpr = new JavaArrayCreation( + arrayType); + newArrayExpr.setInitializer(initExpr); + rhs = newArrayExpr; + } + else + { + rhs = convertRHS(rhs, rhsType, lhsType, false); + } + lhsXlat.getWriteExpression(rhs).mergeIntoResult(result); + return; + } + else if (lhsType instanceof JavaNumericType + && rhsType instanceof JavaNumericType) + { + // check for wait_var update event + JavaExpression updateEvent = getWaitVarEventRef(lhs); + if (updateEvent != null) + { + // LHS must be evaluated twice if update event is + // present + lhs = EvalOnceExprBuilder.evalLHSExpr(lhs, result, + "lhs", true); + } + + // attempt to use Java compound assignment operator + JavaExpression resultExpr = getJavaCompoundAssign(lhs, rhs, + opcode); + if (resultExpr != null) + { + result.setResultExpr(resultExpr); + + // generate wait_var notification + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor( + "old_value", lhs, true); + checkUpdate(result, oldValue, lhs, true, + updateEvent); + } + + return; + } + } + } + } + + // translate LHS + final LHSTranslator lhsXlat = translateLHS(veraLHS, + types.outputSignalType, opcode != OP_NONE, true); + final JavaType lhsType = lhsXlat.getResultType(); + + // translate RHS using LHS type for promotion type (if not done already) + if (rhs == null) + { + rhs = translateNestedExpr(veraRHS, "rhs", lhsType, lhsType, + assignSampleAsync); + rhsType = rhs.getResultType(); + } + + // perform compound assignment operation if specified + if (opcode != OP_NONE) + { + rhs = expandAssignOp(lhsXlat.getReadExpression(), rhs, opcode); + } + + // assign result to LHS + if (!exprConv.isOutputSignal(lhsType)) + { + rhs = convertRHS(rhs, rhsType, lhsType, false); + } + lhsXlat.getWriteExpression(rhs).mergeIntoResult(result); + } + + private JavaExpression getJavaCompoundAssign( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + switch (opcode) + { + case OP_ADD: + return new JavaAssignAdd(schema, op1, op2); + case OP_SUBTRACT: + return new JavaAssignSubtract(schema, op1, op2); + case OP_MULTIPLY: + return new JavaAssignMultiply(schema, op1, op2); + case OP_DIVIDE: + return new JavaAssignDivide(schema, op1, op2); + case OP_MODULO: + return new JavaAssignModulo(schema, op1, op2); + case OP_AND: + return new JavaAssignAnd(schema, op1, op2); + case OP_OR: + return new JavaAssignOr(schema, op1, op2); + case OP_XOR: + return new JavaAssignXor(schema, op1, op2); + case OP_SHIFT_LEFT: + return new JavaAssignLeftShift(schema, op1, op2); + case OP_SHIFT_RIGHT: + return new JavaAssignSignedRightShift(schema, op1, op2); + default: + // simply return null if no operator is available + return null; + } + } + + private JavaExpression expandAssignOp( + JavaExpression op1, + JavaExpression op2, + int opcode) + { + switch (opcode) + { + case OP_ADD: + case OP_SUBTRACT: + Type type1 = op1.getResultType(); + if (exprConv.isEnum(type1)) + { + JavaEnum cls = (JavaEnum) type1; + String methodID = opcode == OP_ADD ? "next" : "previous"; + JavaFunction method = cls.getMethod(methodID, + new JavaType[] { schema.intType }); + JavaFunctionInvocation callExpr = new JavaFunctionInvocation( + new JavaMemberAccess(op1, method)); + callExpr.addArgument(exprConv.toInt(op2)); + return callExpr; + } + case OP_MULTIPLY: + case OP_DIVIDE: + case OP_MODULO: + case OP_AND: + case OP_AND_NOT: + case OP_OR: + case OP_OR_NOT: + case OP_XOR: + case OP_XOR_NOT: + return doBinaryArithmetic(op1, op2, opcode); + case OP_SHIFT_LEFT: + case OP_SHIFT_RIGHT: + return doShift(op1, op2, opcode); + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + } + + private void doIncDec(VeraIncDecOperation obj, int opcode) + { + // get Vera expression + List operands = obj.getOperands(); + assert (operands.size() == 1); + final VeraExpression veraExpr = (VeraExpression) operands.get(0); + + // attempt to use built-in operator if expr translates to a Java LHS + if (hasJavaLHS(veraExpr)) + { + JavaExpression lhs = translateNestedExpr(veraExpr); + final JavaType lhsType = lhs.getResultType(); + if (lhsType instanceof JavaNumericType) + { + // check for wait_var update event + JavaExpression updateEvent = getWaitVarEventRef(lhs); + if (updateEvent != null) + { + // LHS must be evaluated twice if update event is present + lhs = EvalOnceExprBuilder.evalLHSExpr(lhs, result, "lhs", + true); + } + + // build result expression + final JavaExpression resultExpr; + switch (opcode) + { + case OP_PRE_INC: + resultExpr = new JavaPreIncrement(schema, lhs); + break; + case OP_PRE_DEC: + resultExpr = new JavaPreDecrement(schema, lhs); + break; + case OP_POST_INC: + resultExpr = new JavaPostIncrement(schema, lhs); + break; + case OP_POST_DEC: + resultExpr = new JavaPostDecrement(schema, lhs); + break; + default: + throw new RuntimeException("Unknown opcode: " + opcode); + } + result.setResultExpr(resultExpr); + + // generate wait_var notification + if (updateEvent != null) + { + JavaExpression oldValue = result.addTempFor("old_value", + lhs, true); + checkUpdate(result, oldValue, lhs, true, updateEvent); + } + + return; + } + } + + // decode operator + // optimization: force use of pre-inc/dec in void context + final boolean isPreOp = (opcode == OP_PRE_INC || opcode == OP_PRE_DEC) + || desiredResultType == schema.voidType; + final boolean isIncOp = (opcode == OP_PRE_INC || opcode == OP_POST_INC); + + // translate LHS + final LHSTranslator lhsXlat = translateLHS(veraExpr, desiredResultType, + true, true); + final JavaType lhsType = lhsXlat.getResultType(); + + // get read expression + JavaExpression readExpr = lhsXlat.getReadExpression(); + if (!isPreOp) + { + // post-inc/dec evaluates read twice + readExpr = result.addTempFor("temp", readExpr, true); + } + + // perform inc/dec operation + JavaExpression opExpr = expandIncDecOp(readExpr, isIncOp); + + // convert operation result type if necessary + JavaType opResultType = opExpr.getResultType(); + if (needRHSConversion(lhsType, opResultType)) + { + opExpr = exprConv.toType(lhsType, opExpr); + } + + // assign result back + final ConvertedExpression writeExpr = lhsXlat + .getWriteExpression(opExpr); + + if (isPreOp) + { + // for pre-inc/dec, the result comes from the write + writeExpr.mergeIntoResult(result); + } + else + { + // for post-inc/dec, return the read and add statement for write + result.setResultExpr(readExpr); + writeExpr.mergeIntoUpdate(result); + } + } + + private JavaExpression expandIncDecOp(JavaExpression expr, boolean isIncOp) + { + final Type resultType = expr.getResultType(); + if (exprConv.isEnum(resultType)) + { + final JavaRawAbstractClass cls = (JavaRawAbstractClass) resultType; + final String methodID = isIncOp ? "next" : "previous"; + return new JavaFunctionInvocation(new JavaMemberAccess(expr, cls + .getMethod(methodID))); + } + else + { + final int addSubOpcode = isIncOp ? OP_ADD : OP_SUBTRACT; + return expandAssignOp(expr, new JavaIntLiteral(schema, 1), + addSubOpcode); + } + } + + public void visit(VeraAdd obj) + { + doBinaryArithmetic(obj, OP_ADD); + } + + public void visit(VeraAndReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_AND); + } + + public void visit(VeraArithmeticNegative obj) + { + doUnaryArithmetic(obj, OP_NEGATE); + } + + public void visit(VeraArrayAccess obj) + { + final LHSTranslator xlat = new ArrayLHSTranslator(this, result, obj, + true, false); + // default access is read; + // write contexts explicitly check for array access + JavaExpression readExpr = xlat.getReadExpression(); + readExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(readExpr); + } + + public void visit(VeraArrayCreation obj) + { + // translate array tyoe + final VeraDynamicArrayType veraArrayType = obj.getType(); + final JavaArrayType arrayType = (JavaArrayType) translateType(veraArrayType); + + // translate size expression + final JavaExpression sizeExpr = exprConv.toInt(translateNestedIntExpr( + obj.getSizeExpr(), "size")); + + // create Java array creation schema object + final JavaArrayCreation newExpr = new JavaArrayCreation(arrayType); + newExpr.addAnnotations(obj.getAnnotations()); + newExpr.addDimension(sizeExpr); + + // determine whether array elements need initialization + JavaType elemType = arrayType.getElementType(); + JavaExpression elemInitExpr = getInitValue(elemType, false, true); + + // check for source array to copy from + final JavaExpression resultExpr; + final VeraExpression veraSrcExpr = obj.getSourceExpr(); + if (veraSrcExpr != null) + { + // translate source array expression + final JavaExpression srcExpr = translateNestedExpr(veraSrcExpr, + "src"); + assert (srcExpr.getResultType() instanceof JavaArrayType); + + // generate call to Vera.copyArray() + if (elemInitExpr == null) + { + elemInitExpr = new JavaCastExpression(types.objectType, + new JavaNullLiteral(schema)); + } + final JavaExpression[] args = { newExpr, srcExpr, elemInitExpr }; + resultExpr = ExpressionBuilder + .checkDowncast(ExpressionBuilder.staticCall(types.junoType, + "copyArray", args, null), arrayType); + } + else if (elemInitExpr != null) + { + // no source array, but elements need initialization + // generate call to Vera.initArray() + final JavaExpression[] args = { newExpr, elemInitExpr, + new JavaIntLiteral(schema, 0) }; + resultExpr = ExpressionBuilder + .checkDowncast(ExpressionBuilder.staticCall(types.junoType, + "initArray", args, null), arrayType); + } + else + { + // no initialization necessary + resultExpr = newExpr; + } + result.setResultExpr(resultExpr); + } + + public void visit(VeraArrayInitializer obj) + { + // translate array tyoe + final VeraArrayType veraArrayType = (VeraArrayType) obj.getResultType(); + final JavaArrayType arrayType = (JavaArrayType) translateType(veraArrayType); + final JavaType elemType = arrayType.getAccessType(1); + + // create Java array initializer schema object + final JavaArrayInitializer initExpr = new JavaArrayInitializer( + arrayType); + initExpr.addAnnotations(obj.getAnnotations()); + + // translate initializer elements + final Iterator iter = obj.getElements().iterator(); + while (iter.hasNext()) + { + final VeraExpression veraElemExpr = (VeraExpression) iter.next(); + final JavaExpression elemExpr = translateNestedExpr(veraElemExpr, + "elem", elemType); + initExpr.addElement(exprConv.toType(elemType, elemExpr)); + } + result.setResultExpr(initExpr); + } + + public void visit(VeraAssign obj) + { + doAssignOp(obj, OP_NONE); + } + + public void visit(VeraAssignAdd obj) + { + doAssignOp(obj, OP_ADD); + } + + public void visit(VeraAssignAnd obj) + { + doAssignOp(obj, OP_AND); + } + + public void visit(VeraAssignAndNot obj) + { + doAssignOp(obj, OP_AND_NOT); + } + + public void visit(VeraAssignDivide obj) + { + doAssignOp(obj, OP_DIVIDE); + } + + public void visit(VeraAssignLeftShift obj) + { + doAssignOp(obj, OP_SHIFT_LEFT); + } + + public void visit(VeraAssignModulo obj) + { + doAssignOp(obj, OP_MODULO); + } + + public void visit(VeraAssignMultiply obj) + { + doAssignOp(obj, OP_MULTIPLY); + } + + public void visit(VeraAssignOr obj) + { + doAssignOp(obj, OP_OR); + } + + public void visit(VeraAssignOrNot obj) + { + doAssignOp(obj, OP_OR_NOT); + } + + public void visit(VeraAssignRightShift obj) + { + doAssignOp(obj, OP_SHIFT_RIGHT); + } + + public void visit(VeraAssignSubtract obj) + { + doAssignOp(obj, OP_SUBTRACT); + } + + public void visit(VeraAssignXor obj) + { + doAssignOp(obj, OP_XOR); + } + + public void visit(VeraAssignXorNot obj) + { + doAssignOp(obj, OP_XOR_NOT); + } + + public void visit(VeraBitSliceAccess obj) + { + final LHSTranslator xlat = new BitSliceLHSTranslator(this, result, obj, + true, false); + // default access is read; + // write contexts explicitly check for bit slice access + JavaExpression readExpr = xlat.getReadExpression(); + readExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(readExpr); + } + + public void visit(VeraBitVectorLiteral obj) + { + final JavaExpression resultExpr; + final BitVector bv = obj.getValue(); + int len = bv.length(); + final boolean xz = bv.containsXZ(); + final int radix = obj.getRadix(); + final int promoteLen = getTypeWidthChecked(desiredResultType); + if (len == 1 && !xz && desiredResultType instanceof JavaBooleanType) + { + // boolean result: 1'b0,1 -> false, true + resultExpr = new JavaBooleanLiteral(schema, BooleanOp.toBoolean(bv)); + } + else if (len == 1 && promoteLen <= 1) + { + if (schema.isBitVector(desiredResultType)) + { + // BitVector result: 1'b0,1,x,z -> BitVectorOp.BIT_0, BIT_1, ... + resultExpr = exprConv.getBitVectorExpr(bv.getBit(0)); + } + else + { + // Bit result: 1'b0,1,x,z -> Bit.ZERO, ONE, X, Z + resultExpr = exprConv.getBitExpr(bv.getBit(0)); + } + } + else + { + // BitVector result + // extend length if necessary for context + int resultLen = (promoteLen > len) ? promoteLen : len; + + // get bit vector type of give length + JavaClass bitVectorType = schema.getBitVectorType(resultLen); + + if (!xz && (len < 32 || (len == 32 && bv.getBit(31) == Bit.ZERO))) + { + // int result + JavaIntLiteral intLiteral = new JavaIntLiteral(schema, bv + .intValue()); + intLiteral.setRadix(getJavaIntRadix(radix)); + resultExpr = ExpressionBuilder.newInstance(bitVectorType, + new JavaIntLiteral(schema, resultLen), intLiteral); + } + else if (!xz + && (len < 64 || (len == 64 && bv.getBit(63) == Bit.ZERO))) + { + // long result + JavaLongLiteral longLiteral = new JavaLongLiteral(schema, bv + .longValue()); + longLiteral.setRadix(getJavaIntRadix(radix)); + resultExpr = ExpressionBuilder.newInstance(bitVectorType, + new JavaIntLiteral(schema, resultLen), longLiteral); + } + else if (xz ? bv.getBitCount(Bit.X) == len + || bv.getBitCount(Bit.Z) == len + : bv.getBitCount(Bit.ZERO) == len + || bv.getBitCount(Bit.ONE) == len) + { + // 256'bx -> new BitVector(256, Bit.X) + resultExpr = ExpressionBuilder.newInstance(bitVectorType, + new JavaIntLiteral(schema, resultLen), exprConv + .getBitExpr(bv.getBit(0))); + } + else + { + // 128'hXF -> new BitVector("128'hXF") + BitVectorFormat bvFormat = new BitVectorFormat(); + if (radix < 8) bvFormat.setFormatWidth(0); + String bvStr = bvFormat.format(bv.setLength(resultLen), radix); + resultExpr = ExpressionBuilder.newInstance(bitVectorType, + new JavaStringLiteral(schema, bvStr)); + } + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + private int getJavaIntRadix(int bvRadix) + { + final int intRadix; + switch (bvRadix) + { + case 16: + case 8: + // 16'hFFFF -> 0xFFFF + // 8'o377 -> 0377 + intRadix = bvRadix; + break; + case 2: + // 16'b1111 -> 0xF + intRadix = 16; + break; + default: + // 16'd100 -> 100 + intRadix = 10; + } + return intRadix; + } + + public void visit(VeraBitwiseAnd obj) + { + doBinaryArithmetic(obj, OP_AND); + } + + public void visit(VeraBitwiseAndNot obj) + { + doBinaryArithmetic(obj, OP_AND_NOT); + } + + public void visit(VeraBitwiseNegative obj) + { + doUnaryArithmetic(obj, OP_NOT); + } + + public void visit(VeraBitwiseOr obj) + { + doBinaryArithmetic(obj, OP_OR); + } + + public void visit(VeraBitwiseOrNot obj) + { + doBinaryArithmetic(obj, OP_OR_NOT); + } + + public void visit(VeraBitwiseReverse obj) + { + doUnaryArithmetic(obj, OP_REVERSE); + } + + public void visit(VeraBitwiseXor obj) + { + doBinaryArithmetic(obj, OP_XOR); + } + + public void visit(VeraBitwiseXorNot obj) + { + doBinaryArithmetic(obj, OP_XOR_NOT); + } + + public void visit(VeraConcatenation obj) + { + final JavaExpression resultExpr; + final List operands = obj.getOperands(); + final List javaExprs = new LinkedList(); + if (obj.getResultType() instanceof VeraStringType) + { + // string concatenation + for (final VeraExpression veraExpr : operands) + { + JavaExpression javaExpr = translateNestedExpr(veraExpr, "str"); + javaExpr = exprConv.toJavaString(javaExpr, false); + javaExprs.add(javaExpr); + } + resultExpr = buildStringConcat(javaExprs); + } + else + { + // bit concatenation + for (final VeraExpression veraExpr : operands) + { + int veraBits = veraExpr.getResultType().getBitCount(); + JavaType desiredResultType = schema.getBitVectorType(veraBits); + JavaExpression javaExpr = translateNestedExpr(veraExpr, "bv", + null, desiredResultType, sampleAsync); + javaExpr = exprConv.toBitVector(javaExpr, veraBits, false); + javaExprs.add(javaExpr); + } + resultExpr = buildBitVectorConcat(javaExprs); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + JavaExpression buildStringConcat(List javaExprs) + { + final JavaArrayType stringArrType = schema.getArrayType(schema + .getStringType(), 1); + final JavaFunction concatMethod = types.stringOpType.getMethod( + "concat", new JavaType[] { stringArrType }); + final JavaFunctionInvocation concatCall = new JavaFunctionInvocation( + new JavaFunctionReference(concatMethod)); + for (final JavaExpression expr : javaExprs) + { + concatCall.addArgument(expr); + } + return concatCall; + } + + JavaExpression buildBitVectorConcat(List javaExprs) + { + final JavaArrayType bvArrType = schema.getArrayType( + schema.bitVectorType, 1); + final JavaFunction concatMethod = types.bitVectorOpType.getMethod( + "concat", new JavaType[] { bvArrType }); + final JavaFunctionInvocation concatCall = new JavaFunctionInvocation( + new JavaFunctionReference(concatMethod)); + for (final JavaExpression expr : javaExprs) + { + concatCall.addArgument(exprConv.toUnsizedBitVector(expr)); + } + return concatCall; + } + + public void visit(VeraConditional obj) + { + // translate operands + final List operands = obj.getOperands(); + assert (operands.size() == 3); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final VeraExpression veraOp3 = (VeraExpression) operands.get(2); + final JavaExpression op1 = exprConv.toBoolean(translateNestedExpr( + veraOp1, "cond", schema.booleanType), false, false); + final ConvertedExpression op2Info = translateNewExpr(veraOp2); + final ConvertedExpression op3Info = translateNewExpr(veraOp3); + + // convert types of conditional choices + JavaExpression op2 = op2Info.getResultExpr(); + JavaExpression op3 = op3Info.getResultExpr(); + final JavaType type2 = op2.getResultType(); + final JavaType type3 = op3.getResultType(); + final JavaType resultType; + if (type2.equals(type3)) + { + // simple case: types match exactly + resultType = type2; + } + else + { + if (schema.isBitVector(type2) || schema.isBitVector(type3)) + { + // promote to BitVector + op2 = exprConv.toUnsizedBitVector(op2); + op3 = exprConv.toUnsizedBitVector(op3); + JavaType newType2 = op2.getResultType(); + JavaType newType3 = op3.getResultType(); + int size2 = schema.getBitVectorSize(newType2); + int size3 = schema.getBitVectorSize(newType3); + resultType = size3 > size2 ? newType3 : newType2; + } + else if ((type2 == types.stringType || type2 instanceof JavaNullType) + && (type3 == types.stringType || type3 instanceof JavaNullType)) + { + // both String or null + resultType = schema.getStringType(); + } + else if ((exprConv.isString(type2) || type2 instanceof JavaNullType) + && (exprConv.isString(type3) || type3 instanceof JavaNullType)) + { + // convert to JunoString + op2 = exprConv.toJunoString(op2); + op3 = exprConv.toJunoString(op3); + resultType = types.junoStringType; + } + else if (type2 instanceof JavaPrimitiveType + && type3 instanceof JavaPrimitiveType) + { + if (desiredResultType instanceof JavaBooleanType + && (type2 instanceof JavaBooleanType || type3 instanceof JavaBooleanType)) + { + // convert to boolean + op2 = exprConv.toBoolean(op2, false, false); + op3 = exprConv.toBoolean(op3, false, false); + resultType = schema.booleanType; + } + else + { + // promote to common primitive type + resultType = schema.promote(type2, type3); + op2 = exprConv.toType(resultType, op2); + op3 = exprConv.toType(resultType, op3); + } + } + else if (exprConv.hasIntConversion(type2) + && exprConv.hasIntConversion(type3)) + { + // convert to Integer + op2 = exprConv.toInteger(op2); + op3 = exprConv.toInteger(op3); + resultType = schema.integerWrapperType; + } + else if (type2 instanceof JavaNullType + && type3 instanceof JavaStructuredType) + { + // second operand is null; use type of third + resultType = type3; + } + else if (type3 instanceof JavaNullType + && type2 instanceof JavaStructuredType) + { + // third operand is null; use type of second + resultType = type3; + } + else + { + throw new TypeConversionException( + "Incompatible types in conditional: " + + type2.toDebugString() + ", " + type3.toDebugString()); + } + } + + // create Java conditional operation + final JavaExpression resultExpr; + if (op2Info.hasInitExprs() || op2Info.hasUpdateMembers() + || op3Info.hasInitExprs() || op3Info.hasUpdateMembers()) + { + JavaLocalVariable resultVar = result.addTempVar("result", + resultType); + JavaVariableReference resultVarRef = new JavaVariableReference( + resultVar); + JavaBlock thenBlock = assignCondResult(resultType, resultVarRef, + op2, op2Info); + JavaBlock elseBlock = assignCondResult(resultType, resultVarRef, + op3, op3Info); + JavaIfStatement ifStmt = new JavaIfStatement(op1, thenBlock, + elseBlock); + result.addInitMember(ifStmt); + resultExpr = resultVarRef; + } + else + { + resultExpr = new JavaConditional(op1, op2, op3); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + private JavaBlock assignCondResult( + JavaType resultType, + JavaVariableReference resultVarRef, + JavaExpression resultExpr, + ConvertedExpression exprInfo) + { + JavaBlock block = new JavaBlock(schema); + block.addMembers(exprInfo.getInitMembers()); + if (needsClone(resultType)) + { + resultExpr = getCloneExpr(resultExpr); + } + JavaAssign assignExpr = new JavaAssign(schema, resultVarRef, resultExpr); + block.addMember(new JavaExpressionStatement(assignExpr)); + block.addMembers(exprInfo.getUpdateMembers()); + return block; + } + + public void visit(VeraConstraintSet obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraCopyCreation obj) + { + // translate class type + final VeraClass veraType = (VeraClass) obj.getType(); + final JavaRawAbstractClass type = (JavaRawAbstractClass) translateType(veraType); + + // translate source object expression + final VeraExpression veraSrcExpr = obj.getSource(); + final JavaExpression srcExpr = translateNestedExpr(veraSrcExpr, "src"); + final JavaRawAbstractClass srcCls = (JavaRawAbstractClass) srcExpr + .getResultType(); + assert (types.junoObjectType.isSuperclassOf(srcCls)); + + // Vera: Foo x = new y; + // Java: Foo x = (Foo) y.clone(); + final JavaExpression resultExpr = ExpressionBuilder.checkDowncast( + ExpressionBuilder.memberCall(srcExpr, "clone"), type); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraDepthAccess obj) + { + final JavaExpression signalExpr = translateNestedExpr(obj.getSignal(), + types.inputSignalType); + final JavaExpression resultExpr = checkSample(signalExpr, obj + .getDepth()); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraDistSet obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraDivide obj) + { + doBinaryArithmetic(obj, OP_DIVIDE); + } + + public void visit(VeraEnumValueReference obj) + { + final VeraEnumerationElement veraElem = obj.getElement(); + final JavaMemberVariable var = translateEnumElement(veraElem); + final JavaExpression resultExpr = new JavaVariableReference(var); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraEqual obj) + { + doEquality(obj, OP_EQ); + } + + public void visit(VeraExactEqual obj) + { + doEquality(obj, OP_EXACT_EQ); + } + + public void visit(VeraExactNotEqual obj) + { + doEquality(obj, OP_EXACT_NE); + } + + public void visit(VeraFunctionInvocation obj) + { + if (!obj.getConstraints().isEmpty()) + { + throw new UnsupportedOperationException( + "with-constraints are not currently supported"); + } + + // determine Vera function and Java object expression (if any) + final VeraExpression funcExpr = obj.getFunction(); + final VeraFunction veraFunc; + final JavaExpression objExpr; + if (funcExpr instanceof VeraFunctionReference) + { + final VeraFunctionReference funcRef = (VeraFunctionReference) funcExpr; + veraFunc = funcRef.getFunction(); + objExpr = null; + } + else + { + assert (funcExpr instanceof VeraMemberAccess); + final VeraMemberAccess memberExpr = (VeraMemberAccess) funcExpr; + final StructuredTypeMember member = memberExpr.getMember(); + assert (member instanceof VeraMemberFunction); + veraFunc = (VeraMemberFunction) member; + final VeraExpression veraObjExpr = memberExpr.getObject(); + objExpr = translateNestedExpr(veraObjExpr, "obj"); + } + + if (builtinFuncMap.isBuiltinFunction(veraFunc)) + { + BuiltinFunctionTranslator xlat = builtinFuncMap + .getTranslator(veraFunc); + if (xlat == null) + { + throw new UnsupportedOperationException(veraFunc.toString()); + } + xlat.translate(this, veraFunc, objExpr, obj.getArguments()); + } + else + { + final JavaFunctor functor = translateFunction(veraFunc); + final JavaRawAbstractClass cls = (JavaRawAbstractClass) functor + .getStructuredType(); + if (functor instanceof JavaFunction) + { + final JavaFunction func = (JavaFunction) functor; + final String methodID = func.getName().getIdentifier(); + translateCall(veraFunc, cls, methodID, objExpr, obj + .getArguments()); + } + else + { + assert (objExpr instanceof JavaSuperReference); + translateCtorCall(veraFunc, cls, obj.getArguments()); + } + } + + JavaExpression resultExpr = result.getResultExpr(); + if (resultExpr != null) + { + resultExpr.addAnnotations(obj.getAnnotations()); + } + } + + void translateCall( + VeraFunction veraFunc, + JavaRawAbstractClass cls, + String methodID, + JavaExpression obj, + List veraArgExprs) + { + VeraFunctionType veraFuncType = veraFunc.getType(); + + // look for unique match on method ID and argument count first, + // partly as an optimization, partly to handle built-in functions + // that take a signal reference instead of sampling the signal + JavaFunction method = null; + if (!veraFuncType.isVarArgs()) + { + int veraArgCount = veraArgExprs.size(); + method = findUniqueMethod(cls, methodID, veraArgCount); + } + if (method == null) + { + // determine Java argument types + List javaArgTypes = new LinkedList(); + getArgTypes(veraFunc, veraArgExprs, javaArgTypes); + + // search for best Java method + method = findMethod(cls, methodID, javaArgTypes); + } + + // translate Vera argument expressions to Java expressions + JavaFunctionType javaFuncType = method.getType(); + List javaArgExprs = new LinkedList(); + translateArgs(veraFuncType, veraArgExprs, javaFuncType, javaArgExprs); + + // generate Java function invocation expression + JavaExpression funcExpr; + if (obj != null) + { + funcExpr = new JavaMemberAccess(obj, method); + } + else + { + funcExpr = new JavaFunctionReference(method); + } + JavaFunctionInvocation callExpr = new JavaFunctionInvocation(funcExpr); + for (JavaExpression argExpr : javaArgExprs) + { + callExpr.addArgument(argExpr); + } + result.setResultExpr(callExpr); + } + + void translateCallAsStatic( + VeraFunction veraFunc, + JavaRawAbstractClass cls, + String methodID, + JavaExpression obj, + List veraArgExprs) + { + // determine Java argument types + List javaArgTypes = new LinkedList(); + javaArgTypes.add(obj.getResultType()); + getArgTypes(veraFunc, veraArgExprs, javaArgTypes); + + // search for best Java method + JavaFunction method = findMethod(cls, methodID, javaArgTypes); + + // translate Vera argument expressions to Java expressions + VeraFunctionType veraFuncType = veraFunc.getType(); + JavaFunctionType javaFuncType = method.getType(); + List javaArgExprs = new LinkedList(); + javaArgExprs.add(obj); + translateArgs(veraFuncType, veraArgExprs, javaFuncType, javaArgExprs); + + // generate Java function invocation expression + JavaExpression funcExpr = new JavaFunctionReference(method); + JavaFunctionInvocation callExpr = new JavaFunctionInvocation(funcExpr); + for (JavaExpression argExpr : javaArgExprs) + { + callExpr.addArgument(argExpr); + } + result.setResultExpr(callExpr); + } + + private JavaFunction findUniqueMethod( + JavaRawAbstractClass cls, + String id, + int argCount) + { + // search given class and base classes for a unique method + // with the given ID and argument count + JavaFunction result = null; + JavaAbstractClass curClass = cls; + while (curClass != null) + { + // search the current class for methods with the given ID + Iterator iter = curClass.lookupObjects(id, JavaNameKind.METHOD); + while (iter.hasNext()) + { + JavaFunction method = (JavaFunction) iter.next(); + if (method.getType().getArguments().size() == argCount) + { + // if we find multiple methods, return null + if (result != null) return null; + + result = method; + } + } + + // next iteration searches base class + curClass = curClass.getBaseClass(); + } + return result; + } + + void translateCtorCall( + VeraFunction veraFunc, + JavaRawAbstractClass cls, + List veraArgExprs) + { + // determine Java argument types + VeraFunctionType veraFuncType = veraFunc.getType(); + List javaArgTypes = new LinkedList(); + getArgTypes(veraFunc, veraArgExprs, javaArgTypes); + + // search for best Java constructor + JavaConstructor ctor = findCtor(cls, javaArgTypes); + + // translate Vera argument expressions to Java expressions + JavaFunctionType javaFuncType = ctor.getType(); + List javaArgExprs = new LinkedList(); + translateArgs(veraFuncType, veraArgExprs, javaFuncType, javaArgExprs); + + // constructor call must be first statement in block + assert (!result.hasInitMembers()); + + // generate Java constructor invocation expression + JavaConstructorReference ctorRef = new JavaConstructorReference(ctor); + JavaConstructorInvocation callExpr = new JavaConstructorInvocation( + ctorRef); + for (JavaExpression argExpr : javaArgExprs) + { + callExpr.addArgument(argExpr); + } + result.setResultExpr(callExpr); + } + + private void getArgTypes( + VeraFunction veraFunc, + List veraArgExprs, + List javaArgTypes) + { + final VeraFunctionType veraFuncType = veraFunc.getType(); + final Iterator veraExprIter = veraArgExprs.iterator(); + + // translate types of non-varargs + { + final FunctionAnalysis baseFuncAnalysis = analyzer + .getBaseFunctionAnalysis(veraFunc); + final List veraArgs = veraFuncType + .getArguments(); + final Iterator veraArgIter = veraArgs + .iterator(); + int index = 0; + while (veraArgIter.hasNext() && veraExprIter.hasNext()) + { + VeraFunctionArgument veraArg = veraArgIter.next(); + VeraExpression veraExpr = veraExprIter.next(); + + // get Java type from translated result type of Vera expression + // NOTE: the type of the formal argument is not used, since the + // expression type could yield a more optimal translation in the + // case of an overloaded Java method + VeraType veraExprType = veraExpr.getResultType(); + JavaType javaArgType = translateType(veraExprType, + isArgumentXZ(veraFunc, index, baseFuncAnalysis), + isArgumentStatefulString(veraFunc, index, baseFuncAnalysis)); + + // wrap by-reference arguments in a reference pseudo-type object, + // except for Vera arrays and strings, which are always passed by + // reference in Java + if (veraArg.isByRef() && !needsClone(javaArgType) + && veraExpr.isAssignable()) + { + javaArgType = new JavaRefType(javaArgType); + } + + javaArgTypes.add(javaArgType); + ++index; + } + } + + if (veraFuncType.isVarArgsByRef()) + { + // by-ref var-args always translate specifically to final arguments + // of Object[], Class[] + javaArgTypes.add(types.objectArrayType); + javaArgTypes.add(types.classArrayType); + } + else if (veraExprIter.hasNext()) + { + assert (veraFuncType.isVarArgs()); + + // translate types of varargs + while (veraExprIter.hasNext()) + { + VeraExpression veraExpr = veraExprIter.next(); + VeraType veraExprType = veraExpr.getResultType(); + JavaType javaArgType = translateType(veraExprType, true, false); + javaArgTypes.add(javaArgType); + } + } + } + + private JavaFunction findMethod( + JavaRawAbstractClass cls, + String id, + List javaArgTypes) + { + // search given class and base classes for the best method + JavaFunction bestMethod = null; + int lowScore = Integer.MAX_VALUE; + LinkedList rejected = new LinkedList(); + JavaAbstractClass curClass = cls; + while (curClass != schema.getObjectType()) + { + // search the current class for methods with the given ID + Iterator iter = curClass.lookupObjects(id, JavaNameKind.METHOD); + while (iter.hasNext()) + { + JavaFunction method = (JavaFunction) iter.next(); + + // ignore methods from java.lang.Object + if (method.getStructuredType() == schema.getObjectType()) + continue; + + int score = getArgMatchScore(method.getType(), javaArgTypes); + if (score < 0) + { + rejected.add(method); + } + else if (score < lowScore) + { + bestMethod = method; + lowScore = score; + } + } + + // next iteration searches base class + curClass = curClass.getBaseClass(); + } + + if (bestMethod == null) + { + // no matching method found + JavaType[] argTypes = new JavaType[javaArgTypes.size()]; + javaArgTypes.toArray(argTypes); + JavaFunction[] considered = new JavaFunction[rejected.size()]; + rejected.toArray(considered); + throw new MethodNotFoundException(cls, id, argTypes, considered); + } + + return bestMethod; + } + + private JavaConstructor findCtor( + JavaRawAbstractClass cls, + List javaArgTypes) + { + // search given class for the best constructor + JavaConstructor bestCtor = null; + int lowScore = Integer.MAX_VALUE; + LinkedList rejected = new LinkedList(); + Iterator iter = cls.getMembers().iterator(); + while (iter.hasNext()) + { + Object member = iter.next(); + if (member instanceof JavaConstructor) + { + JavaConstructor ctor = (JavaConstructor) member; + int score = getArgMatchScore(ctor.getType(), javaArgTypes); + if (score < 0) + { + rejected.add(ctor); + } + else if (score < lowScore) + { + bestCtor = ctor; + lowScore = score; + } + } + } + + if (bestCtor == null) + { + // no matching constructor found + JavaType[] argTypes = new JavaType[javaArgTypes.size()]; + javaArgTypes.toArray(argTypes); + JavaConstructor[] considered = new JavaConstructor[rejected.size()]; + rejected.toArray(considered); + throw new ConstructorNotFoundException(cls, argTypes, considered); + } + + return bestCtor; + } + + private int getArgMatchScore( + JavaFunctionType funcType, + List actualArgTypes) + { + final int argTypeCount = actualArgTypes.size(); + final List formalArgs = funcType.getArguments(); + final int formalArgCount = formalArgs.size(); + + // check for compatible argument count + final boolean varArgs = funcType.isVarArgs(); + if (varArgs ? argTypeCount < formalArgCount - 1 + : argTypeCount != formalArgCount) return -1; + + // attempt to convert each actual argument to the type of + // the formal argument + int convCount = 0; + Iterator formalArgIter = formalArgs.iterator(); + JavaType formalArgType = null; + Iterator actualArgTypeIter = actualArgTypes.iterator(); + int argIndex = 0; + while (actualArgTypeIter.hasNext()) + { + JavaType actualArgType = actualArgTypeIter.next(); + if (formalArgIter.hasNext()) + { + JavaFunctionArgument formalArg = formalArgIter.next(); + formalArgType = formalArg.getType(); + if (varArgs + && argIndex == formalArgCount - 1 + && (argTypeCount > formalArgCount || getDimensions(actualArgType) == getDimensions(formalArgType) - 1)) + { + formalArgType = ((JavaArrayType) formalArgType) + .getAccessType(1); + } + } + + // handle by-reference arguments + JavaType formalTargetType = formalArgType; + JavaType actualTargetType = actualArgType; + boolean byRef = false; + if (actualArgType instanceof JavaRefType) + { + if (!(formalArgType instanceof JavaArrayType)) return -1; + JavaArrayType formalArrayType = (JavaArrayType) formalArgType; + if (formalArrayType.getIndexTypes().length != 1) return -1; + formalTargetType = formalArrayType.getElementType(); + actualTargetType = ((JavaRefType) actualArgType).targetType; + byRef = true; + } + + if (!formalTargetType.isAssignableFrom(actualTargetType)) + { + if (exprConv.hasConversion(actualTargetType, formalTargetType) + && (!byRef || exprConv.hasConversion(formalTargetType, + actualTargetType))) + { + ++convCount; + } + else + { + // no conversion available, give up + return -1; + } + } + else if (formalTargetType instanceof JavaArrayType != actualTargetType instanceof JavaArrayType) + { + // do not allow array types to be passed in non-array arguments + return -1; + } + ++argIndex; + } + return convCount; + } + + private int getDimensions(JavaType type) + { + if (type instanceof JavaArrayType) + { + return ((JavaArrayType) type).getIndexTypes().length; + } + return 0; + } + + private void translateArgs( + VeraFunctionType veraFuncType, + List veraArgExprs, + JavaFunctionType javaFuncType, + List javaArgExprs) + { + // translate declared arguments + List veraArgs = veraFuncType.getArguments(); + Iterator veraArgIter = veraArgs.iterator(); + Iterator veraExprIter = veraArgExprs.iterator(); + List javaArgs = javaFuncType.getArguments(); + Iterator javaArgIter = javaArgs + .listIterator(javaArgExprs.size()); + while (veraArgIter.hasNext() && veraExprIter.hasNext()) + { + VeraFunctionArgument veraArg = veraArgIter.next(); + VeraExpression veraExpr = veraExprIter.next(); + JavaFunctionArgument javaArg = javaArgIter.next(); + JavaType javaArgType = javaArg.getType(); + + JavaExpression javaExpr = null; + if (veraArg.isByRef()) + { + if (needsClone(javaArgType)) + { + // translate expression normally + javaExpr = translateNestedExpr(veraExpr, "arg", javaArgType); + } + else if (javaArgType instanceof JavaArrayType) + { + // use reference holder to pass by-reference + javaExpr = getRefHolderExprs(javaArg, javaArgType, veraExpr); + } + else + { + // Vera argument is by-reference but chosen Java method does + // not use a reference holder; this case is used by built-in + // functions like assoc_index that have optional by-ref + // arguments; because translated methods are not overloaded, + // and overloaded built-in methods do not explicitly take + // array arguments, the check for a Java array argument is + // not ambiguous + } + } + if (javaExpr == null) + { + // translate expression normally + javaExpr = translateNestedExpr(veraExpr, "arg", javaArgType, + javaArgType, sampleAsync); + JavaType javaExprType = javaExpr.getResultType(); + + // convert/clone result if necessary + javaExpr = convertRHS(javaExpr, javaExprType, javaArgType, true); + } + javaArgExprs.add(javaExpr); + } + + // translate variable arguments + if (veraFuncType.isVarArgsByRef()) + { + // check that Java method expects additional Object[] argument + assert (javaArgIter.hasNext()); + JavaFunctionArgument javaArg = javaArgIter.next(); + assert (javaArg.getType() == types.objectArrayType); + + // check that Java method expects additional Class[] argument + assert (javaArgIter.hasNext()); + javaArg = javaArgIter.next(); + assert (javaArg.getType() == types.classArrayType); + + assert (!javaArgIter.hasNext()); + + // create Object[] argument which will contain actual arguments + JavaArrayInitializer argsInitExpr = new JavaArrayInitializer( + types.objectArrayType); + JavaLocalVariable argsVar = result.createTempFor("args", + argsInitExpr, true); + JavaVariableReference argsRef = new JavaVariableReference(argsVar); + javaArgExprs.add(argsRef); + + // create Class[] argument which will contain argument types + JavaArrayInitializer typesInitExpr = new JavaArrayInitializer( + types.classArrayType); + JavaLocalVariable typesVar = result.createTempFor("types", + typesInitExpr, true); + javaArgExprs.add(new JavaVariableReference(typesVar)); + + // translate remaining actual arguments into array initializer + int argIndex = 0; + while (veraExprIter.hasNext()) + { + VeraExpression veraExpr = veraExprIter.next(); + + // add argument read expression to arguments initializer + ConvertedExpression argContext = new ConvertedExpression(result); + LHSTranslator argXlat = translateLHS(veraExpr, argContext, + null, true, true); + JavaExpression argExpr = argXlat.getReadExpression(); + argsInitExpr.addElement(argExpr); + + // add argument type to types initializer + JavaType argType = argExpr.getResultType(); + typesInitExpr.addElement(new JavaTypeLiteral(argType)); + + // add write-back expression to list + JavaArrayAccess argsAccess = new JavaArrayAccess(argsRef); + argsAccess.addIndex(new JavaIntLiteral(schema, argIndex++)); + JavaExpression argValue = ExpressionBuilder.checkDowncast( + argsAccess, argType); + argValue = exprConv.toType(argType, argValue); + argXlat.getWriteExpression(argValue) + .mergeIntoResult(argContext); + argContext.mergeIntoUpdate(result); + } + + // add var-args variables as last init members + result.addInitMember(argsVar); + result.addInitMember(typesVar); + } + else if (veraExprIter.hasNext()) + { + assert (veraFuncType.isVarArgs()); + + if (javaFuncType.isVarArgs()) + { + // translate remaining actual arguments into result array + while (veraExprIter.hasNext()) + { + VeraExpression veraExpr = veraExprIter.next(); + // add argument expression to arguments initializer + JavaExpression argExpr = translateNestedExpr(veraExpr, + "arg"); + javaArgExprs.add(argExpr); + } + } + else + { + // Java method should expect one additional array argument + assert (javaArgIter.hasNext()); + JavaFunctionArgument javaArg = javaArgIter.next(); + JavaArrayType argArrayType = (JavaArrayType) javaArg.getType(); + JavaType argElemType = argArrayType.getElementType(); + + assert (!javaArgIter.hasNext()); + + // create array argument which will contain actual arguments + JavaArrayInitializer argsInitExpr = new JavaArrayInitializer( + argArrayType); + JavaArrayCreation newArrayExpr = new JavaArrayCreation( + argArrayType); + newArrayExpr.setInitializer(argsInitExpr); + javaArgExprs.add(newArrayExpr); + + // translate remaining actual arguments into array initializer + while (veraExprIter.hasNext()) + { + VeraExpression veraExpr = veraExprIter.next(); + // add argument expression to arguments initializer + JavaExpression argExpr = translateNestedExpr(veraExpr, + "arg"); + argsInitExpr.addElement(exprConv.toType(argElemType, + argExpr)); + } + } + } + } + + private JavaExpression getRefHolderExprs( + JavaFunctionArgument javaArg, + JavaType javaArgType, + VeraExpression veraExpr) + { + // get type of argument array and its element type + assert (javaArgType instanceof JavaArrayType); + JavaArrayType argArrayType = (JavaArrayType) javaArgType; + + JavaExpression holderRef = null; + + // check whether actual argument is a variable reference that was + // already translated to a holder variable assignable to Java argument + if (veraExpr instanceof VeraVariableReference && varInfoMap != null) + { + final VeraVariableReference veraVarRef = (VeraVariableReference) veraExpr; + final VeraVariable veraVar = veraVarRef.getVariable(); + final VarInfo info = varInfoMap.getInfo(veraVar); + if (info != null && info.isHolderVar()) + { + JavaVariable targetVar = info.getTargetVar(); + if (argArrayType.isAssignableFrom(targetVar.getType())) + { + holderRef = info.getHolderReference(); + } + } + } + + if (holderRef == null) + { + // translate the actual argument + JavaType argElemType = argArrayType.getAccessType(1); + LHSTranslator lhsXlat = translateLHS(veraExpr, argElemType, true, + true); + JavaType refType = lhsXlat.getResultType(); + JavaExpression readExpr = lhsXlat.getReadExpression(); + + // determine type of holder array to create + JavaArrayType refArrayType = schema.getArrayType(refType, 1); + JavaArrayType holderType; + if (argArrayType.isAssignableFrom(refArrayType)) + { + // array of actual argument type is assignable to formal + // argument + // type: use actual argument type + // example: actual is Integer[], formal is Object[] + holderType = refArrayType; + } + else + { + // array of actual argument type is not assignable to formal + // argument: use formal argument type and convert expression + // example: actual is int[], formal is Object[] + readExpr = exprConv.toType(argElemType, readExpr); + JavaType convRefType = readExpr.getResultType(); + holderType = schema.getArrayType(convRefType, 1); + } + + // create expression to initialize reference holder + JavaArrayInitializer initExpr = new JavaArrayInitializer(holderType); + initExpr.addElement(readExpr); + + // create reference holder variable + String argName = javaArg.getName().getIdentifier(); + holderRef = result.addTempFor(argName + "_holder", initExpr, true); + + // create expression to write back value in holder + JavaArrayAccess holderAccess = new JavaArrayAccess(holderRef); + holderAccess.addIndex(new JavaIntLiteral(schema, 0)); + JavaExpression valueExpr = exprConv.toType(refType, holderAccess); + lhsXlat.getWriteExpression(valueExpr).mergeIntoUpdate(result); + } + + return holderRef; + } + + public void visit(VeraFunctionReference obj) + { + // must be converted in the context of an invocation + assert false; + } + + public void visit(VeraGreater obj) + { + doRelation(obj, OP_GT); + } + + public void visit(VeraGreaterOrEqual obj) + { + doRelation(obj, OP_GE); + } + + public void visit(VeraIfElseConstraint obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraImplicationConstraint obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraInSet obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraInstanceCreation obj) + { + // translate type + final VeraComplexType veraType = obj.getType(); + final JavaRawClass cls = (JavaRawClass) translateType(veraType); + + JavaExpression resultExpr = null; + final List veraArgExprs = obj.getArguments(); + + if (veraType instanceof VeraClass) + { + // find the Vera new() task + final VeraClass veraCls = (VeraClass) veraType; + Iterator iter = veraCls.lookupObjects("new", VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + VeraMemberFunction veraFunc = (VeraMemberFunction) iter.next(); + assert (!iter.hasNext()); + + // make sure constructor has been translated + JavaConstructor ctor = translateConstructor(veraFunc, cls); + + // determine Java argument types + final VeraFunctionType veraFuncType = veraFunc.getType(); + final List javaArgTypes = new LinkedList(); + getArgTypes(veraFunc, veraArgExprs, javaArgTypes); + + // determine whether instantiation should be translated to + // static factory method call + final FactoryCallBuilder fcb = factoryXlatMap + .getFactory(veraType.getName().getCanonicalName()); + if (fcb != null) + { + // translate Vera argument expressions to Java expressions + final JavaFunctionType javaFuncType = ctor.getType(); + final List javaArgExprs = new LinkedList(); + translateArgs(veraFuncType, veraArgExprs, javaFuncType, + javaArgExprs); + + // generate call to Java factory method + resultExpr = fcb.callFactory(cls, javaArgExprs, + containingType); + } + else + { + // search for best Java constructor + ctor = findCtor(cls, javaArgTypes); + + // translate Vera argument expressions to Java expressions + final JavaFunctionType javaFuncType = ctor.getType(); + final List javaArgExprs = new LinkedList(); + translateArgs(veraFuncType, veraArgExprs, javaFuncType, + javaArgExprs); + + // create Java instance creation schema object + JavaInstanceCreation newExpr = new JavaInstanceCreation( + cls, ctor); + for (JavaExpression argExpr : javaArgExprs) + { + newExpr.addArgument(argExpr); + } + resultExpr = newExpr; + } + } + } + else + { + assert (veraType instanceof VeraPortType); + } + + if (resultExpr == null) + { + // default constructor; no arguments + assert (veraArgExprs.isEmpty()); + resultExpr = new JavaInstanceCreation(cls, null); + } + + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraIntegerLiteral obj) + { + JavaExpression resultExpr; + final int i = obj.getValue(); + if (desiredResultType instanceof JavaBooleanType) + { + resultExpr = new JavaBooleanLiteral(schema, i != 0); + } + else if (desiredResultType == schema.bitType) + { + resultExpr = exprConv.getBitExpr((i & 1) != 0 ? Bit.ONE : Bit.ZERO); + } + else + { + resultExpr = new JavaIntLiteral(schema, i); + int promoteLen = getTypeWidthChecked(desiredResultType); + if (promoteLen > 32) + { + resultExpr = exprConv.intToBitVector(resultExpr, promoteLen, + false); + } + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraInterfaceReference obj) + { + // VeraInterfaceReference should only be used internally by the + // VeraSchemaBuilder, to produce a VeraSignalReference + assert false; + } + + public void visit(VeraLeftShift obj) + { + doShift(obj, OP_SHIFT_LEFT); + } + + public void visit(VeraLess obj) + { + doRelation(obj, OP_LT); + } + + public void visit(VeraLessOrEqual obj) + { + doRelation(obj, OP_LE); + } + + public void visit(VeraLogicalAnd obj) + { + // translate operands + final List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = exprConv.toBoolean(translateNestedExpr( + veraOp1, "test", schema.booleanType), false, false); + result.setResultExpr(op1); + final ConvertedExpression op2Info = translateNewExpr(veraOp2, + schema.booleanType); + final JavaExpression op2 = exprConv.toBoolean(op2Info.getResultExpr(), + false, false); + + // create Java conditional-and operation + final JavaExpression resultExpr; + if (op2Info.hasInitExprs()) + { + JavaVariableReference resultVarRef = result.toVarRef("test", + schema.booleanType); + JavaBlock thenBlock = assignCondResult(schema.booleanType, + resultVarRef, op2, op2Info); + JavaIfStatement ifStmt = new JavaIfStatement(resultVarRef, + thenBlock, null); + result.addInitMember(ifStmt); + resultExpr = resultVarRef; + } + else + { + resultExpr = new JavaConditionalAnd(schema, op1, op2); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraLogicalNegative obj) + { + final List operands = obj.getOperands(); + assert (operands.size() == 1); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final JavaExpression op1 = translateNestedExpr(veraOp1, + schema.booleanType); + final JavaExpression resultExpr; + if (op1.getResultType() instanceof JavaPrimitiveType) + { + JavaExpression booleanOp1 = exprConv.toBoolean(op1, false, false); + resultExpr = getNotExpr(booleanOp1); + + } + else + { + resultExpr = ExpressionBuilder.memberCall(exprConv + .toLogicalBit(op1), "not"); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraLogicalOr obj) + { + // translate operands + final List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = exprConv.toBoolean(translateNestedExpr( + veraOp1, "test", schema.booleanType), false, false); + result.setResultExpr(op1); + final ConvertedExpression op2Info = translateNewExpr(veraOp2, + schema.booleanType); + final JavaExpression op2 = exprConv.toBoolean(op2Info.getResultExpr(), + false, false); + + // create Java conditional-or operation + final JavaExpression resultExpr; + if (op2Info.hasInitExprs()) + { + JavaVariableReference resultVarRef = result.toVarRef("test", + schema.booleanType); + JavaBlock thenBlock = assignCondResult(schema.booleanType, + resultVarRef, op2, op2Info); + JavaIfStatement ifStmt = new JavaIfStatement( + getNotExpr(resultVarRef), thenBlock, null); + result.addInitMember(ifStmt); + resultExpr = resultVarRef; + } + else + { + resultExpr = new JavaConditionalOr(schema, op1, op2); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraMemberAccess obj) + { + // translate object + final VeraExpression veraObj = obj.getObject(); + final JavaExpression javaObj = translateNestedExpr(veraObj, "obj"); + + // translate member + final VeraStructuredTypeMember veraMember = obj.getMember(); + final JavaStructuredTypeMember member = translateMember(veraMember); + + // translate member access to static variable or function to a direct + // variable or function reference to avoid compiler warnings + JavaExpression resultExpr = null; + if (member instanceof JavaMemberVariable) + { + JavaMemberVariable memberVar = (JavaMemberVariable) member; + if (memberVar.hasModifier(JavaVariableModifier.STATIC)) + { + resultExpr = new JavaVariableReference(memberVar); + } + } + else if (member instanceof JavaFunction) + { + JavaFunction memberFunc = (JavaFunction) member; + if (memberFunc.hasModifier(JavaFunctionModifier.STATIC)) + { + resultExpr = new JavaFunctionReference(memberFunc); + } + } + + // create Java member access schema object + if (resultExpr == null) + { + // check for special handling of protected access + if (member.getVisibility() == JavaVisibility.PROTECTED) + { + // check for valid Vera protected access + JavaRawAbstractClass thisCls = (JavaRawAbstractClass) containingType; + while (thisCls.getStructuredType() != null) + { + thisCls = (JavaRawAbstractClass) thisCls + .getStructuredType(); + } + JavaRawAbstractClass memberCls = (JavaRawAbstractClass) member + .getStructuredType(); + assert (memberCls.isSuperclassOf(thisCls)); + + // Vera allows protected access to members of classes not + // involved in the implementation of this class; Java requires + // the other class to be this class or a subclass of this class + JavaRawAbstractClass objCls = (JavaRawAbstractClass) javaObj + .getResultType(); + if (!thisCls.isSuperclassOf(objCls)) + { + // change member visibility to public to allow access + if (member instanceof JavaMemberVariable) + { + ((JavaMemberVariable) member) + .setVisibility(JavaVisibility.PUBLIC); + } + else if (member instanceof JavaFunction) + { + ((JavaFunction) member) + .setVisibility(JavaVisibility.PUBLIC); + } + } + } + resultExpr = new JavaMemberAccess(javaObj, member); + } + + // translate signal references as sample call + // unless signal result is desired + if (!exprConv.isSignal(desiredResultType)) + { + resultExpr = checkSample(resultExpr, -1); + } + + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + private JavaExpression checkSample(JavaExpression expr, int depth) + { + // does expression refer to input signal? + Type resultType = expr.getResultType(); + if (exprConv.isInputSignal(resultType)) + { + // call appropriate sample method + if (depth >= 0) + { + expr = ExpressionBuilder.memberCall(expr, sampleAsync + ? "sampleDepthAsync" : "sampleDepth", new JavaIntLiteral( + schema, depth)); + } + else + { + expr = ExpressionBuilder.memberCall(expr, sampleAsync + ? "sampleAsync" : "sample"); + } + } + return expr; + } + + public void visit(VeraModulo obj) + { + doBinaryArithmetic(obj, OP_MODULO); + } + + public void visit(VeraMultiply obj) + { + doBinaryArithmetic(obj, OP_MULTIPLY); + } + + public void visit(VeraNotAndReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_AND_NOT); + } + + public void visit(VeraNotEqual obj) + { + doEquality(obj, OP_NE); + } + + public void visit(VeraNotInSet obj) + { + // constraints are not handled by this class + assert false; + } + + public void visit(VeraNotOrReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_OR_NOT); + } + + public void visit(VeraNotXorReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_XOR_NOT); + } + + public void visit(VeraNullLiteral obj) + { + final JavaExpression resultExpr = new JavaNullLiteral(schema); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraOrReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_OR); + } + + public void visit(VeraPostDecrement obj) + { + doIncDec(obj, OP_POST_DEC); + } + + public void visit(VeraPostIncrement obj) + { + doIncDec(obj, OP_POST_INC); + } + + public void visit(VeraPreDecrement obj) + { + doIncDec(obj, OP_PRE_DEC); + } + + public void visit(VeraPreIncrement obj) + { + doIncDec(obj, OP_PRE_INC); + } + + public void visit(VeraReplication obj) + { + final List operands = obj.getOperands(); + assert (operands.size() == 2); + final VeraExpression veraOp1 = (VeraExpression) operands.get(0); + final VeraExpression veraOp2 = (VeraExpression) operands.get(1); + final JavaExpression op1 = exprConv.toInt(translateNestedIntExpr( + veraOp1, "count")); + final int veraBits = veraOp2.getResultType().getBitCount(); + final JavaType desiredResultType = schema.getBitVectorType(veraBits); + final JavaExpression op2 = translateNestedExpr(veraOp2, "temp", null, + desiredResultType, sampleAsync); + final JavaExpression resultExpr; + if (obj.getResultType() instanceof VeraStringType) + { + resultExpr = ExpressionBuilder.staticCall(types.stringOpType, + "replicate", op1, exprConv.toJavaString(op2, true)); + } + else + { + resultExpr = ExpressionBuilder.staticCall(types.bitVectorOpType, + "replicate", op1, exprConv.toBitVector(op2, veraBits, false)); + } + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraRightShift obj) + { + doShift(obj, OP_SHIFT_RIGHT); + } + + public void visit(VeraSignalReference obj) + { + // translate signal + final VeraInterfaceSignal signal = obj.getSignal(); + final JavaMemberVariable signalVar = translateInterfaceSignal(signal); + + // create Java variable reference schema object + JavaExpression resultExpr = new JavaVariableReference(signalVar); + + // translate signal references as sample call + // unless signal result is desired + if (!exprConv.isSignal(desiredResultType)) + { + resultExpr = checkSample(resultExpr, -1); + } + + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraStringLiteral obj) + { + final JavaExpression resultExpr = new JavaStringLiteral(schema, obj + .getValue()); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraSubtract obj) + { + doBinaryArithmetic(obj, OP_SUBTRACT); + } + + public void visit(VeraSuperReference obj) + { + // translate class type + final VeraClass veraType = obj.getType(); + final JavaRawAbstractClass type = (JavaRawAbstractClass) translateType(veraType); + + // create Java 'super' reference schema object + final JavaExpression resultExpr = new JavaSuperReference(type); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraSystemClockReference obj) + { + final JavaExpression resultExpr = new JavaVariableReference( + types.junoType.getField("systemClock")); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraThisReference obj) + { + // translate class type + final VeraClass veraType = obj.getType(); + final JavaRawAbstractClass type = (JavaRawAbstractClass) translateType(veraType); + + // create Java 'this' reference schema object + final JavaExpression resultExpr = new JavaThisReference(type); + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + public void visit(VeraVariableReference obj) + { + // translate variable + final VeraVariable veraVar = obj.getVariable(); + final JavaVariable var = translateVariable(veraVar); + + // build Java variable reference + JavaExpression resultExpr = translateVarRef(veraVar, var, schema, + varInfoMap, result.getScope()); + + resultExpr.addAnnotations(obj.getAnnotations()); + result.setResultExpr(resultExpr); + } + + static JavaExpression translateVarRef( + final VeraVariable veraVar, + final JavaVariable var, + final JavaSchema schema, + final VarInfoMap varInfoMap, + final Scope localScope) + { + JavaExpression resultExpr = null; + + // handle remapped variable references (by-ref holder, fork vars) + if (varInfoMap != null) + { + VarInfo info = varInfoMap.getInfo(veraVar); + if (info != null) + { + resultExpr = info.getReference(); + } + } + + if (resultExpr == null) + { + // check whether field reference is shadowed by local variable + if (localScope != null + && var instanceof JavaMemberVariable + && VarBuilder.containsID(localScope, var.getName() + .getIdentifier(), JavaNameKind.EXPRESSION)) + { + // create 'this.var' member access + JavaMemberVariable memberVar = (JavaMemberVariable) var; + JavaStructuredType memberType = memberVar.getStructuredType(); + resultExpr = new JavaMemberAccess(new JavaThisReference( + memberType), memberVar); + } + else + { + // create Java variable reference schema object + resultExpr = new JavaVariableReference(var); + } + } + + return resultExpr; + } + + public void visit(VeraVoidLiteral obj) + { + // 'void' can only appear as the RHS of a drive, and should be + // checked for explicitly in those contexts + throw new RuntimeException("Illegal use of 'void'"); + } + + public void visit(VeraWildEqual obj) + { + doEquality(obj, OP_WILD_EQ); + } + + public void visit(VeraWildNotEqual obj) + { + doEquality(obj, OP_WILD_NE); + } + + public void visit(VeraXorReduction obj) + { + doUnaryArithmetic(obj, OP_REDUCTIVE_XOR); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/FactoryCallBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/FactoryCallBuilder.java new file mode 100644 index 0000000..d0be54d --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/FactoryCallBuilder.java @@ -0,0 +1,49 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.List; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaStructuredType; + +/** + * Interface used to generate calls to factory methods when translating a Vera + * instance creation expression. + * + * @author Trevor Robinson + */ +public interface FactoryCallBuilder +{ + /** + * Returns an expression that constructs a new instance of a class derived + * from the given class using the given argument expressions. + * + * @param cls translated Java class for the original instance creation + * @param args List of JavaExpression constructor arguments + * @param containingType Java class/interface containing the instance + * creation expression + * @return an expression returning a new instance of a class derived from + * the given Java class + */ + JavaExpression callFactory( + JavaRawClass cls, + List args, + JavaStructuredType containingType); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/FactoryTranslationMap.java b/java/juno/src/com/newisys/schemabuilder/juno/FactoryTranslationMap.java new file mode 100644 index 0000000..e5b8b16 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/FactoryTranslationMap.java @@ -0,0 +1,46 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +/** + * Mapping of Vera class names to Java factory call builders used to translate + * instance creation expressions for those classes. + * + * @author Trevor Robinson + */ +final class FactoryTranslationMap + implements Serializable +{ + private static final long serialVersionUID = 3257849883108389939L; + + private final Map xlatMap = new HashMap(); + + public void addFactory(String veraCls, FactoryCallBuilder fcb) + { + xlatMap.put(veraCls, fcb); + } + + public FactoryCallBuilder getFactory(String veraCls) + { + return xlatMap.get(veraCls); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/IntOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/IntOperationBuilder.java new file mode 100644 index 0000000..4491c3c --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/IntOperationBuilder.java @@ -0,0 +1,172 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds various operation expressions for int/long-type operands. + * + * @author Trevor Robinson + */ +final class IntOperationBuilder + extends TranslatorModule + implements ArithmeticOperationBuilder, ShiftOperationBuilder, + RelationalOperationBuilder +{ + public IntOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + private JavaExpression doIntOpCall(String methodID, JavaExpression op1) + { + return ExpressionBuilder.staticCall(types.intOpType, methodID, op1); + } + + public JavaExpression add(JavaExpression op1, JavaExpression op2) + { + return new JavaAdd(schema, op1, op2); + } + + public JavaExpression subtract(JavaExpression op1, JavaExpression op2) + { + return new JavaSubtract(schema, op1, op2); + } + + public JavaExpression multiply(JavaExpression op1, JavaExpression op2) + { + return new JavaMultiply(schema, op1, op2); + } + + public JavaExpression divide(JavaExpression op1, JavaExpression op2) + { + return new JavaDivide(schema, op1, op2); + } + + public JavaExpression mod(JavaExpression op1, JavaExpression op2) + { + return new JavaModulo(schema, op1, op2); + } + + public JavaExpression negate(JavaExpression op1) + { + return new JavaUnaryMinus(schema, op1); + } + + public JavaExpression and(JavaExpression op1, JavaExpression op2) + { + return new JavaAnd(schema, op1, op2); + } + + public JavaExpression andNot(JavaExpression op1, JavaExpression op2) + { + return new JavaBitwiseNot(schema, new JavaAnd(schema, op1, op2)); + } + + public JavaExpression or(JavaExpression op1, JavaExpression op2) + { + return new JavaOr(schema, op1, op2); + } + + public JavaExpression orNot(JavaExpression op1, JavaExpression op2) + { + return new JavaBitwiseNot(schema, new JavaOr(schema, op1, op2)); + } + + public JavaExpression xor(JavaExpression op1, JavaExpression op2) + { + return new JavaXor(schema, op1, op2); + } + + public JavaExpression xorNot(JavaExpression op1, JavaExpression op2) + { + return new JavaBitwiseNot(schema, new JavaXor(schema, op1, op2)); + } + + public JavaExpression not(JavaExpression op1) + { + return new JavaBitwiseNot(schema, op1); + } + + public JavaExpression reverse(JavaExpression op1) + { + return doIntOpCall("bitwiseReverse", op1); + } + + public JavaExpression reductiveAnd(JavaExpression op1) + { + return doIntOpCall("reductiveAnd", op1); + } + + public JavaExpression reductiveAndNot(JavaExpression op1) + { + return doIntOpCall("reductiveAndNot", op1); + } + + public JavaExpression reductiveOr(JavaExpression op1) + { + return doIntOpCall("reductiveOr", op1); + } + + public JavaExpression reductiveOrNot(JavaExpression op1) + { + return doIntOpCall("reductiveOrNot", op1); + } + + public JavaExpression reductiveXor(JavaExpression op1) + { + return doIntOpCall("reductiveXor", op1); + } + + public JavaExpression reductiveXorNot(JavaExpression op1) + { + return doIntOpCall("reductiveXorNot", op1); + } + + public JavaExpression shiftLeft(JavaExpression op1, JavaExpression op2) + { + return new JavaLeftShift(schema, op1, op2); + } + + public JavaExpression shiftRight(JavaExpression op1, JavaExpression op2) + { + return new JavaSignedRightShift(schema, op1, op2); + } + + public JavaExpression greater(JavaExpression op1, JavaExpression op2) + { + return new JavaGreater(schema, op1, op2); + } + + public JavaExpression greaterOrEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaGreaterOrEqual(schema, op1, op2); + } + + public JavaExpression less(JavaExpression op1, JavaExpression op2) + { + return new JavaLess(schema, op1, op2); + } + + public JavaExpression lessOrEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaLessOrEqual(schema, op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/IntegerOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/IntegerOperationBuilder.java new file mode 100644 index 0000000..acf3180 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/IntegerOperationBuilder.java @@ -0,0 +1,211 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.util.ExpressionBuilder; + +/** + * Builds various operation expressions for Integer-type operands. + * + * @author Trevor Robinson + */ +final class IntegerOperationBuilder + extends TranslatorModule + implements ArithmeticOperationBuilder, ShiftOperationBuilder, + EqualityOperationBuilder, RelationalOperationBuilder +{ + public IntegerOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + private JavaExpression doIntegerOpCall(String methodID, JavaExpression op1) + { + return ExpressionBuilder.staticCall(types.integerOpType, methodID, op1); + } + + private JavaExpression doIntegerOpCall( + String methodID, + JavaExpression op1, + JavaExpression op2) + { + return ExpressionBuilder.staticCall(types.integerOpType, methodID, op1, + op2); + } + + public JavaExpression add(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("add", op1, op2); + } + + public JavaExpression subtract(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("subtract", op1, op2); + } + + public JavaExpression multiply(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("multiply", op1, op2); + } + + public JavaExpression divide(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("divide", op1, op2); + } + + public JavaExpression mod(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("mod", op1, op2); + } + + public JavaExpression negate(JavaExpression op1) + { + return doIntegerOpCall("negate", op1); + } + + public JavaExpression and(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseAnd", op1, op2); + } + + public JavaExpression andNot(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseAndNot", op1, op2); + } + + public JavaExpression or(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseOr", op1, op2); + } + + public JavaExpression orNot(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseOrNot", op1, op2); + } + + public JavaExpression xor(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseXor", op1, op2); + } + + public JavaExpression xorNot(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("bitwiseXorNot", op1, op2); + } + + public JavaExpression not(JavaExpression op1) + { + return doIntegerOpCall("bitwiseNot", op1); + } + + public JavaExpression reverse(JavaExpression op1) + { + return doIntegerOpCall("bitwiseReverse", op1); + } + + public JavaExpression reductiveAnd(JavaExpression op1) + { + return doIntegerOpCall("reductiveAnd", op1); + } + + public JavaExpression reductiveAndNot(JavaExpression op1) + { + return doIntegerOpCall("reductiveAndNot", op1); + } + + public JavaExpression reductiveOr(JavaExpression op1) + { + return doIntegerOpCall("reductiveOr", op1); + } + + public JavaExpression reductiveOrNot(JavaExpression op1) + { + return doIntegerOpCall("reductiveOrNot", op1); + } + + public JavaExpression reductiveXor(JavaExpression op1) + { + return doIntegerOpCall("reductiveXor", op1); + } + + public JavaExpression reductiveXorNot(JavaExpression op1) + { + return doIntegerOpCall("reductiveXorNot", op1); + } + + public JavaExpression shiftLeft(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("shiftLeft", op1, op2); + } + + public JavaExpression shiftRight(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("shiftRight", op1, op2); + } + + public JavaExpression equal(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("equal", op1, op2); + } + + public JavaExpression notEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("notEqual", op1, op2); + } + + public JavaExpression exactEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("exactEqual", op1, op2); + } + + public JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("exactNotEqual", op1, op2); + } + + public JavaExpression wildEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("wildEqual", op1, op2); + } + + public JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("wildNotEqual", op1, op2); + } + + public JavaExpression greater(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("greater", op1, op2); + } + + public JavaExpression greaterOrEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("greaterOrEqual", op1, op2); + } + + public JavaExpression less(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("less", op1, op2); + } + + public JavaExpression lessOrEqual(JavaExpression op1, JavaExpression op2) + { + return doIntegerOpCall("lessOrEqual", op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/JavaKeywords.java b/java/juno/src/com/newisys/schemabuilder/juno/JavaKeywords.java new file mode 100644 index 0000000..0b199dc --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/JavaKeywords.java @@ -0,0 +1,97 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.HashSet; +import java.util.Set; + +/** + * Lookup table of Java keywords. Used to avoid translated identifier + * collisions. + * + * @author Trevor Robinson + */ +final class JavaKeywords +{ + private static final Set keywords = new HashSet(); + + static + { + keywords.add("abstract"); + keywords.add("boolean"); + keywords.add("break"); + keywords.add("byte"); + keywords.add("case"); + keywords.add("catch"); + keywords.add("char"); + keywords.add("class"); + keywords.add("const"); + keywords.add("continue"); + keywords.add("default"); + keywords.add("do"); + keywords.add("double"); + keywords.add("else"); + keywords.add("extends"); + keywords.add("false"); + keywords.add("final"); + keywords.add("finally"); + keywords.add("float"); + keywords.add("for"); + keywords.add("goto"); + keywords.add("if"); + keywords.add("implements"); + keywords.add("import"); + keywords.add("instanceof"); + keywords.add("int"); + keywords.add("interface"); + keywords.add("long"); + keywords.add("native"); + keywords.add("new"); + keywords.add("null"); + keywords.add("package"); + keywords.add("private"); + keywords.add("protected"); + keywords.add("public"); + keywords.add("return"); + keywords.add("short"); + keywords.add("static"); + keywords.add("strictfp"); + keywords.add("super"); + keywords.add("switch"); + keywords.add("synchronized"); + keywords.add("this"); + keywords.add("throw"); + keywords.add("throws"); + keywords.add("transient"); + keywords.add("true"); + keywords.add("try"); + keywords.add("void"); + keywords.add("volatile"); + keywords.add("while"); + } + + private JavaKeywords() + { + // prevent instantiation + } + + public static boolean isKeyword(String id) + { + return keywords.contains(id); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/JavaRefType.java b/java/juno/src/com/newisys/schemabuilder/juno/JavaRefType.java new file mode 100644 index 0000000..7774353 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/JavaRefType.java @@ -0,0 +1,67 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.java.JavaTypeImpl; +import com.newisys.langschema.java.JavaTypeVisitor; + +/** + * Used internally to simulate a Java reference type. Used in the translation + * of by-reference function arguments. + * + * @author Trevor Robinson + */ +class JavaRefType + extends JavaTypeImpl +{ + private static final long serialVersionUID = 1L; + + final JavaType targetType; + + public JavaRefType(JavaType targetType) + { + super(targetType.getSchema()); + this.targetType = targetType; + } + + public JavaType toRealType() + { + return schema.getArrayType(targetType, 1); + } + + public boolean isSubtype(JavaType type) + { + return targetType.isSubtype(type); + } + + public String toInternalName() + { + throw new UnsupportedOperationException(); + } + + public String toReferenceString() + { + return targetType.toReferenceString() + "&"; + } + + public void accept(JavaTypeVisitor visitor) + { + // do nothing + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/JunoSchemaBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/JunoSchemaBuilder.java new file mode 100644 index 0000000..db7a0af --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/JunoSchemaBuilder.java @@ -0,0 +1,133 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.dv.ifgen.schema.IfgenSchema; +import com.newisys.langschema.java.JavaFunction; +import com.newisys.langschema.java.JavaRawAbstractClass; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaSchemaObject; +import com.newisys.langschema.java.JavaVariable; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.langschema.vera.VeraSchema; +import com.newisys.langschema.vera.VeraSchemaMember; +import com.newisys.langschema.vera.VeraSchemaObject; +import com.newisys.schemaanalyzer.juno.VeraSchemaAnalyzer; +import com.newisys.util.logging.IndentLogger; + +/** + * Primary facade for using the Juno translator. + * + * @author Trevor Robinson + */ +public final class JunoSchemaBuilder +{ + private final VeraSchema veraSchema; + private final JoveSchema javaSchema; + private final IfgenSchema ifSchema; + private final VeraSchemaAnalyzer analyzer; + private final PackageNamer packageNamer; + private final IndentLogger log; + private final SchemaTypes types; + private final ExpressionConverter exprConv; + private final ManualTranslationMap manXlatMap; + private final FactoryTranslationMap factoryXlatMap; + private TranslatedObjectMap xlatObjMap; + + public JunoSchemaBuilder( + VeraSchema veraSchema, + JoveSchema javaSchema, + IfgenSchema ifSchema, + VeraSchemaAnalyzer analyzer, + PackageNamer packageNamer, + IndentLogger log) + { + this.veraSchema = veraSchema; + this.javaSchema = javaSchema; + this.ifSchema = ifSchema; + this.analyzer = analyzer; + this.packageNamer = packageNamer; + this.log = log; + this.types = new SchemaTypes(javaSchema); + this.exprConv = new ExpressionConverter(javaSchema, types); + this.manXlatMap = new ManualTranslationMap(); + this.factoryXlatMap = new FactoryTranslationMap(); + } + + public SchemaTypes getTypes() + { + return types; + } + + public ExpressionConverter getExprConv() + { + return exprConv; + } + + public void addTranslatedClass(String name, JavaRawAbstractClass cls) + { + manXlatMap.addClass(name, cls); + } + + public void addTranslatedFunction(String name, JavaFunction func) + { + manXlatMap.addFunction(name, func); + } + + public void addTranslatedVariable(String name, JavaVariable var) + { + manXlatMap.addVariable(name, var); + } + + public void addFactory(String veraCls, FactoryCallBuilder fcb) + { + factoryXlatMap.addFactory(veraCls, fcb); + } + + public void addFactory( + String veraCls, + JavaRawClass factoryCls, + String defaultImplName) + { + addFactory(veraCls, new DefaultFactoryCallBuilder(javaSchema, types, + exprConv, factoryCls, defaultImplName)); + } + + public JoveSchema build() + { + SchemaMemberTranslator xlat = new SchemaMemberTranslator(javaSchema, + ifSchema, analyzer, packageNamer, log, types, exprConv, manXlatMap, + factoryXlatMap); + Iterator iter = veraSchema.getMembers().iterator(); + while (iter.hasNext()) + { + VeraSchemaMember obj = (VeraSchemaMember) iter.next(); + obj.accept(xlat); + } + + xlatObjMap = xlat.xlatObjMap; + return javaSchema; + } + + public JavaSchemaObject getTranslatedObject(VeraSchemaObject veraObject) + { + return xlatObjMap.getJavaObject(veraObject); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/LHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/LHSTranslator.java new file mode 100644 index 0000000..c66ff59 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/LHSTranslator.java @@ -0,0 +1,38 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaType; + +/** + * Interface for performing different types of translations of a left-hand-side + * (aka lvalue) expression. + * + * @author Trevor Robinson + */ +interface LHSTranslator +{ + JavaType getResultType(); + + JavaExpression getUpdateEvent(); + + JavaExpression getReadExpression(); + + ConvertedExpression getWriteExpression(JavaExpression value); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ManualTranslationMap.java b/java/juno/src/com/newisys/schemabuilder/juno/ManualTranslationMap.java new file mode 100644 index 0000000..8b1c1cf --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ManualTranslationMap.java @@ -0,0 +1,76 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.HashMap; +import java.util.Map; + +import com.newisys.langschema.java.JavaFunction; +import com.newisys.langschema.java.JavaRawAbstractClass; +import com.newisys.langschema.java.JavaSchemaObject; +import com.newisys.langschema.java.JavaVariable; + +/** + * Mapping of Vera construct names to manually translated Java schema objects. + * + * @author Trevor Robinson + */ +final class ManualTranslationMap +{ + private final Map xlatMap = new HashMap(); + + private void addObject(String uri, JavaSchemaObject javaObject) + { + xlatMap.put(uri, javaObject); + } + + public void addClass(String name, JavaRawAbstractClass cls) + { + addObject("class:" + name, cls); + } + + public void addFunction(String name, JavaFunction func) + { + addObject("func:" + name, func); + } + + public void addVariable(String name, JavaVariable var) + { + addObject("var:" + name, var); + } + + private Object getObject(String uri) + { + return xlatMap.get(uri); + } + + public JavaRawAbstractClass getClass(String name) + { + return (JavaRawAbstractClass) getObject("class:" + name); + } + + public JavaFunction getFunction(String name) + { + return (JavaFunction) getObject("func:" + name); + } + + public JavaVariable getVariable(String name) + { + return (JavaVariable) getObject("var:" + name); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/PackageNamer.java b/java/juno/src/com/newisys/schemabuilder/juno/PackageNamer.java new file mode 100644 index 0000000..93cdc46 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/PackageNamer.java @@ -0,0 +1,143 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.io.File; + +/** + * Generates valid Java package names from relative Vera component paths. + * + * @author Trevor Robinson + */ +public final class PackageNamer +{ + private String basePath; + private String basePackage = "juno"; + private String externalPackage = "juno.external"; + + public PackageNamer(String basePath) + { + this.basePath = basePath; + } + + public String getBasePath() + { + return basePath; + } + + public void setBasePath(String basePath) + { + this.basePath = basePath; + } + + public String getBasePackage() + { + return basePackage; + } + + public void setBasePackage(String basePackage) + { + this.basePackage = basePackage; + } + + public String getExternalPackage() + { + return externalPackage; + } + + public void setExternalPackage(String externalPackage) + { + this.externalPackage = externalPackage; + } + + public String getPackageName(String path) + { + if (path.startsWith(basePath)) + { + // get relative path from base path + int relStart = basePath.length(); + if (relStart < path.length()) + { + char c = path.charAt(relStart); + if (c == File.separatorChar || c == '/') ++relStart; + } + String relPath = path.substring(relStart); + + // get directory part of relative path + File relFile = new File(relPath); + String dir = relFile.getParent(); + + // if file has no directory part, return the base package + if (dir == null) return basePackage; + + // build package name by replacing path separator with '.', + // replacing invalid characters with '_', and lowercasing + int len = dir.length(); + StringBuffer buf = new StringBuffer(basePackage.length() + 1 + len); + buf.append(basePackage); + buf.append('.'); + boolean isStart = true; + for (int i = 0; i < len; ++i) + { + char c = dir.charAt(i); + if (c == File.separatorChar) + { + c = '.'; + isStart = true; + } + else if (isStart) + { + if (!Character.isJavaIdentifierStart(c)) + { + if (!Character.isJavaIdentifierPart(c)) + { + // replace invalid ID char + c = '_'; + } + else + { + // insert underscore before invalid start char + buf.append('_'); + } + } + c = Character.toLowerCase(c); + isStart = false; + } + else + { + if (!Character.isJavaIdentifierPart(c)) + { + // replace invalid ID char + c = '_'; + } + else + { + c = Character.toLowerCase(c); + } + } + buf.append(c); + } + return buf.toString(); + } + else + { + // path is outside of designated tree; place in external package + return externalPackage; + } + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/PrimitiveEqualityOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/PrimitiveEqualityOperationBuilder.java new file mode 100644 index 0000000..12ee2fa --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/PrimitiveEqualityOperationBuilder.java @@ -0,0 +1,67 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaEqual; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaNotEqual; + +/** + * Builds equality operation expressions using the Java operators (== and !=). + * + * @author Trevor Robinson + */ +final class PrimitiveEqualityOperationBuilder + extends TranslatorModule + implements EqualityOperationBuilder +{ + public PrimitiveEqualityOperationBuilder(TranslatorModule xlatContext) + { + super(xlatContext); + } + + public JavaExpression equal(JavaExpression op1, JavaExpression op2) + { + return new JavaEqual(schema, op1, op2); + } + + public JavaExpression notEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaNotEqual(schema, op1, op2); + } + + public JavaExpression exactEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaEqual(schema, op1, op2); + } + + public JavaExpression exactNotEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaNotEqual(schema, op1, op2); + } + + public JavaExpression wildEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaEqual(schema, op1, op2); + } + + public JavaExpression wildNotEqual(JavaExpression op1, JavaExpression op2) + { + return new JavaNotEqual(schema, op1, op2); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/RelationalOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/RelationalOperationBuilder.java new file mode 100644 index 0000000..809a822 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/RelationalOperationBuilder.java @@ -0,0 +1,36 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; + +/** + * Interface for building Java relational operation expressions. + * + * @author Trevor Robinson + */ +interface RelationalOperationBuilder +{ + JavaExpression greater(JavaExpression op1, JavaExpression op2); + + JavaExpression greaterOrEqual(JavaExpression op1, JavaExpression op2); + + JavaExpression less(JavaExpression op1, JavaExpression op2); + + JavaExpression lessOrEqual(JavaExpression op1, JavaExpression op2); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/SchemaMemberTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/SchemaMemberTranslator.java new file mode 100644 index 0000000..a79e29a --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/SchemaMemberTranslator.java @@ -0,0 +1,62 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.dv.ifgen.schema.IfgenSchema; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraGlobalFunction; +import com.newisys.langschema.vera.VeraSchemaMemberVisitor; +import com.newisys.schemaanalyzer.juno.VeraSchemaAnalyzer; +import com.newisys.util.logging.IndentLogger; + +/** + * Schema translator for top-level schema members (which includes only + * compilation units). + * + * @author Trevor Robinson + */ +final class SchemaMemberTranslator + extends TranslatorModule + implements VeraSchemaMemberVisitor +{ + public SchemaMemberTranslator( + JoveSchema schema, + IfgenSchema ifSchema, + VeraSchemaAnalyzer analyzer, + PackageNamer packageNamer, + IndentLogger log, + SchemaTypes types, + ExpressionConverter exprConv, + ManualTranslationMap manXlatMap, + FactoryTranslationMap factoryXlatMap) + { + super(schema, ifSchema, analyzer, packageNamer, log, types, exprConv, + manXlatMap, factoryXlatMap); + } + + public void visit(VeraCompilationUnit obj) + { + translateCompUnit(obj); + } + + public void visit(VeraGlobalFunction obj) + { + // ignore built-in functions + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/SchemaTypes.java b/java/juno/src/com/newisys/schemabuilder/juno/SchemaTypes.java new file mode 100644 index 0000000..c8cc04f --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/SchemaTypes.java @@ -0,0 +1,206 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.dv.ClockSignal; +import com.newisys.dv.DV; +import com.newisys.dv.DVApplication; +import com.newisys.dv.DVSimulation; +import com.newisys.dv.InOutSignal; +import com.newisys.dv.InputSignal; +import com.newisys.dv.OutputSignal; +import com.newisys.dv.PortSignalWrapper; +import com.newisys.dv.Signal; +import com.newisys.dv.vlogdef.Defines; +import com.newisys.eventsim.Event; +import com.newisys.juno.runtime.*; +import com.newisys.langschema.java.JavaAnnotationType; +import com.newisys.langschema.java.JavaArrayType; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaRawInterface; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.randsolver.annotation.Constraint; +import com.newisys.randsolver.annotation.Rand; +import com.newisys.randsolver.annotation.RandExclude; +import com.newisys.randsolver.annotation.Randc; +import com.newisys.randsolver.annotation.Randomizable; +import com.newisys.verilog.EdgeSet; +import com.newisys.verilog.util.BitRange; +import com.newisys.verilog.util.Length; + +/** + * Cache of the Java schema types used by the translator. + * + * @author Trevor Robinson + */ +public final class SchemaTypes +{ + final JoveSchema schema; + + final JavaRawClass absCallErrorType; + final JavaRawClass assocArrayType; + final JavaRawClass bitAssocArrayType; + final JavaRawClass bitObjectAssocArrayType; + final JavaRawClass bitOpType; + final JavaRawClass bitRangeType; + final JavaRawClass bitVectorOpType; + final JavaRawClass booleanOpType; + final JavaRawClass classType; + final JavaArrayType classArrayType; + final JavaRawInterface clockSignalType; + final JavaAnnotationType constraintType; + final JavaRawClass definesType; + final JavaRawClass dvAppType; + final JavaRawClass dvSimType; + final JavaRawClass dvType; + final JavaRawClass edgeSetType; + final JavaRawClass eventType; + final JavaArrayType eventArrayType; + final JavaRawInterface inOutSignalType; + final JavaArrayType inOutSignalArrayType; + final JavaRawInterface inputSignalType; + final JavaRawClass intOpType; + final JavaRawClass integerOpType; + final JavaAnnotationType lengthType; + final JavaRawClass longWrapperOpType; + final JavaRawClass mathType; + final JavaRawClass objectType; + final JavaArrayType objectArrayType; + final JavaRawInterface outputSignalType; + final JavaRawClass portSignalWrapperType; + final JavaAnnotationType randType; + final JavaAnnotationType randcType; + final JavaAnnotationType randExcludeType; + final JavaAnnotationType randomizableType; + final JavaRawInterface runnableType; + final JavaRawInterface signalType; + final JavaRawClass stringType; + final JavaRawClass stringAssocArrayType; + final JavaRawClass stringObjectAssocArrayType; + final JavaRawClass stringOpType; + final JavaRawClass unsuppOpType; + final JavaRawClass junoType; + final JavaRawInterface junoEnumType; + final JavaRawClass junoEnumUtilType; + final JavaRawClass junoEventType; + final JavaRawClass junoEventValueFactoryType; + final JavaRawClass junoObjectType; + final JavaRawClass junoStringType; + final JavaRawClass junoStringValueFactoryType; + + public SchemaTypes(JoveSchema schema) + { + this.schema = schema; + + absCallErrorType = (JavaRawClass) schema + .getTypeForSystemClass(AbstractMethodCallError.class.getName()); + assocArrayType = (JavaRawClass) schema + .getTypeForSystemClass(AssocArray.class.getName()); + bitAssocArrayType = (JavaRawClass) schema + .getTypeForSystemClass(BitAssocArray.class.getName()); + bitObjectAssocArrayType = (JavaRawClass) schema + .getTypeForSystemClass(BitObjectAssocArray.class.getName()); + bitOpType = (JavaRawClass) schema.getTypeForSystemClass(BitOp.class + .getName()); + bitRangeType = (JavaRawClass) schema + .getTypeForSystemClass(BitRange.class.getName()); + bitVectorOpType = (JavaRawClass) schema + .getTypeForSystemClass(BitVectorOp.class.getName()); + booleanOpType = (JavaRawClass) schema + .getTypeForSystemClass(BooleanOp.class.getName()); + classType = (JavaRawClass) schema.getTypeForSystemClass(Class.class + .getName()); + classArrayType = schema.getArrayType(classType, 1); + clockSignalType = (JavaRawInterface) schema + .getTypeForSystemClass(ClockSignal.class.getName()); + constraintType = (JavaAnnotationType) schema + .getTypeForSystemClass(Constraint.class.getName()); + definesType = (JavaRawClass) schema.getTypeForSystemClass(Defines.class + .getName()); + dvAppType = (JavaRawClass) schema + .getTypeForSystemClass(DVApplication.class.getName()); + dvSimType = (JavaRawClass) schema + .getTypeForSystemClass(DVSimulation.class.getName()); + dvType = (JavaRawClass) schema + .getTypeForSystemClass(DV.class.getName()); + edgeSetType = (JavaRawClass) schema.getTypeForSystemClass(EdgeSet.class + .getName()); + eventType = (JavaRawClass) schema.getTypeForSystemClass(Event.class + .getName()); + eventArrayType = schema.getArrayType(eventType, 1); + inOutSignalType = (JavaRawInterface) schema + .getTypeForSystemClass(InOutSignal.class.getName()); + inOutSignalArrayType = schema.getArrayType(inOutSignalType, 1); + inputSignalType = (JavaRawInterface) schema + .getTypeForSystemClass(InputSignal.class.getName()); + intOpType = (JavaRawClass) schema.getTypeForSystemClass(IntOp.class + .getName()); + integerOpType = (JavaRawClass) schema + .getTypeForSystemClass(IntegerOp.class.getName()); + lengthType = (JavaAnnotationType) schema + .getTypeForSystemClass(Length.class.getName()); + longWrapperOpType = (JavaRawClass) schema + .getTypeForSystemClass(LongWrapperOp.class.getName()); + mathType = (JavaRawClass) schema.getTypeForSystemClass(Math.class + .getName()); + objectType = schema.getObjectType(); + objectArrayType = schema.getArrayType(objectType, 1); + outputSignalType = (JavaRawInterface) schema + .getTypeForSystemClass(OutputSignal.class.getName()); + portSignalWrapperType = (JavaRawClass) schema + .getTypeForSystemClass(PortSignalWrapper.class.getName()); + randType = (JavaAnnotationType) schema.getTypeForSystemClass(Rand.class + .getName()); + randcType = (JavaAnnotationType) schema + .getTypeForSystemClass(Randc.class.getName()); + randExcludeType = (JavaAnnotationType) schema + .getTypeForSystemClass(RandExclude.class.getName()); + randomizableType = (JavaAnnotationType) schema + .getTypeForSystemClass(Randomizable.class.getName()); + runnableType = (JavaRawInterface) schema + .getTypeForSystemClass(Runnable.class.getName()); + signalType = (JavaRawInterface) schema + .getTypeForSystemClass(Signal.class.getName()); + stringType = schema.getStringType(); + stringAssocArrayType = (JavaRawClass) schema + .getTypeForSystemClass(StringAssocArray.class.getName()); + stringObjectAssocArrayType = (JavaRawClass) schema + .getTypeForSystemClass(StringObjectAssocArray.class.getName()); + stringOpType = (JavaRawClass) schema + .getTypeForSystemClass(StringOp.class.getName()); + unsuppOpType = (JavaRawClass) schema + .getTypeForSystemClass(UnsupportedOperationException.class + .getName()); + junoType = (JavaRawClass) schema.getTypeForSystemClass(Juno.class + .getName()); + junoEnumType = (JavaRawInterface) schema + .getTypeForSystemClass(JunoEnum.class.getName()); + junoEnumUtilType = (JavaRawClass) schema + .getTypeForSystemClass(JunoEnumUtil.class.getName()); + junoEventType = (JavaRawClass) schema + .getTypeForSystemClass(JunoEvent.class.getName()); + junoEventValueFactoryType = (JavaRawClass) schema + .getTypeForSystemClass(JunoEventValueFactory.class.getName()); + junoObjectType = (JavaRawClass) schema + .getTypeForSystemClass(JunoObject.class.getName()); + junoStringType = (JavaRawClass) schema + .getTypeForSystemClass(JunoString.class.getName()); + junoStringValueFactoryType = (JavaRawClass) schema + .getTypeForSystemClass(JunoStringValueFactory.class.getName()); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/ShiftOperationBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/ShiftOperationBuilder.java new file mode 100644 index 0000000..66cc8e4 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/ShiftOperationBuilder.java @@ -0,0 +1,32 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; + +/** + * Interface for building Java bitwise shift operation expressions. + * + * @author Trevor Robinson + */ +interface ShiftOperationBuilder +{ + JavaExpression shiftLeft(JavaExpression op1, JavaExpression op2); + + JavaExpression shiftRight(JavaExpression op1, JavaExpression op2); +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/SimpleLHSTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/SimpleLHSTranslator.java new file mode 100644 index 0000000..cb38809 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/SimpleLHSTranslator.java @@ -0,0 +1,105 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.vera.VeraExpression; + +/** + * LHS translator for scalar variable accesses. + * + * @author Trevor Robinson + */ +final class SimpleLHSTranslator + extends BaseLHSTranslator +{ + private final JavaType resultType; + private final JavaExpression updateEvent; + private final JavaExpression lhsOnceExpr; + + public SimpleLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext, + JavaType desiredResultType, + VeraExpression obj, + boolean readAccess, + boolean writeAccess) + { + super(exprXlat, exprContext); + + // translate Vera expression + assert (obj.isAssignable()); + JavaExpression lhsExpr = translateExpr(obj, "lhs", desiredResultType); + resultType = lhsExpr.getResultType(); + + // check for wait_var update event + updateEvent = getWaitVarEventRef(lhsExpr); + + // introduce temporary variables as necessary + boolean multiAccess = (readAccess && writeAccess) + || (updateEvent != null); + lhsOnceExpr = EvalOnceExprBuilder.evalLHSExpr(lhsExpr, exprContext, + "lhs", multiAccess); + } + + public SimpleLHSTranslator( + ExpressionTranslator exprXlat, + ConvertedExpression exprContext, + JavaExpression lhsExpr, + boolean readAccess, + boolean writeAccess) + { + super(exprXlat, exprContext); + + // store the expression result type + resultType = lhsExpr.getResultType(); + + // check for wait_var update event + updateEvent = getWaitVarEventRef(lhsExpr); + + // introduce temporary variables as necessary + boolean multiAccess = (readAccess && writeAccess) + || (updateEvent != null); + lhsOnceExpr = EvalOnceExprBuilder.evalLHSExpr(lhsExpr, exprContext, + "lhs", multiAccess); + } + + public JavaType getResultType() + { + return resultType; + } + + public JavaExpression getUpdateEvent() + { + return updateEvent; + } + + public JavaExpression getReadExpression() + { + return lhsOnceExpr; + } + + public ConvertedExpression getWriteExpression(JavaExpression value) + { + ConvertedExpression result = new ConvertedExpression(exprContext); + getAssignWriteExpression(result, resultType, lhsOnceExpr, value, + updateEvent); + return result; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TempBlockScope.java b/java/juno/src/com/newisys/schemabuilder/juno/TempBlockScope.java new file mode 100644 index 0000000..d3a6b7b --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TempBlockScope.java @@ -0,0 +1,72 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Scope; +import com.newisys.langschema.util.NameTable; + +/** + * Scope implementation that maintains a name table and also delegates lookups + * to a base scope (if any). Used to maintain temporary block scopes during + * translation, so that temporary variables can be assigned unique names. + * + * @author Trevor Robinson + */ +class TempBlockScope + implements Scope +{ + private final Scope baseScope; + private final NameTable nameTable = new NameTable(); + + public TempBlockScope() + { + this.baseScope = null; + } + + public TempBlockScope(Scope baseScope) + { + this.baseScope = baseScope; + } + + public void addObject(NamedObject obj) + { + nameTable.addObject(obj); + } + + public void removeObject(NamedObject obj) + { + nameTable.removeObject(obj); + } + + public Iterator< ? extends NamedObject> lookupObjects( + String identifier, + NameKind kind) + { + Iterator< ? extends NamedObject> iter = nameTable.lookupObjects( + identifier, kind); + if (!iter.hasNext() && baseScope != null) + { + iter = baseScope.lookupObjects(identifier, kind); + } + return iter; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TranslatedClass.java b/java/juno/src/com/newisys/schemabuilder/juno/TranslatedClass.java new file mode 100644 index 0000000..0f24933 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TranslatedClass.java @@ -0,0 +1,53 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaMemberVariable; +import com.newisys.langschema.java.JavaPackage; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaSchema; + +/** + * Represents a Java class translated from Vera. Used to identify and maintain + * translation state for translated classes. + * + * @author Trevor Robinson + */ +class TranslatedClass + extends JavaRawClass +{ + private static final long serialVersionUID = 3763097483382960689L; + + boolean membersTranslated; + JavaMemberVariable randInfoVar; + + public TranslatedClass(JavaSchema schema, String id, JavaPackage pkg) + { + super(schema, id, pkg); + } + + public TranslatedClass(JavaSchema schema, String id, JavaRawClass outerClass) + { + super(schema, id, outerClass.getPackage(), outerClass); + } + + public TranslatedClass(JavaRawClass outerClass) + { + super(outerClass); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TranslatedObjectMap.java b/java/juno/src/com/newisys/schemabuilder/juno/TranslatedObjectMap.java new file mode 100644 index 0000000..b2a6f92 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TranslatedObjectMap.java @@ -0,0 +1,74 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.HashMap; +import java.util.Map; + +import com.newisys.dv.ifgen.schema.IfgenSchemaObject; +import com.newisys.langschema.java.JavaSchemaObject; +import com.newisys.langschema.java.JavaVariable; +import com.newisys.langschema.vera.VeraSchemaObject; + +/** + * Maintains a mapping of Vera schema object to translated Java and Ifgen + * schema objects. Also maintains wait_var event variables corresponding to + * Java variables. + * + * @author Trevor Robinson + */ +final class TranslatedObjectMap +{ + private final Map javaObjects = new HashMap(); + private final Map ifgenObjects = new HashMap(); + private final Map waitVarEvents = new HashMap(); + + public void addJavaObject( + VeraSchemaObject veraObject, + JavaSchemaObject javaObject) + { + javaObjects.put(veraObject, javaObject); + } + + public JavaSchemaObject getJavaObject(VeraSchemaObject veraObject) + { + return javaObjects.get(veraObject); + } + + public void addIfgenObject( + VeraSchemaObject veraObject, + IfgenSchemaObject ifgenObject) + { + ifgenObjects.put(veraObject, ifgenObject); + } + + public IfgenSchemaObject getIfgenObject(VeraSchemaObject veraObject) + { + return ifgenObjects.get(veraObject); + } + + public void addWaitVarEvent(JavaVariable var, JavaVariable eventVar) + { + waitVarEvents.put(var, eventVar); + } + + public JavaVariable getWaitVarEvent(JavaVariable var) + { + return waitVarEvents.get(var); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TranslatorModule.java b/java/juno/src/com/newisys/schemabuilder/juno/TranslatorModule.java new file mode 100644 index 0000000..bc9f8df --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TranslatorModule.java @@ -0,0 +1,3517 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import com.newisys.dv.ifgen.IfgenJavaTranslator; +import com.newisys.dv.ifgen.IfgenTranslatorException; +import com.newisys.dv.ifgen.schema.*; +import com.newisys.langschema.CompilationUnit; +import com.newisys.langschema.Container; +import com.newisys.langschema.Name; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.StructuredType; +import com.newisys.langschema.StructuredTypeMember; +import com.newisys.langschema.Visibility; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.jove.JoveAssocArrayType; +import com.newisys.langschema.jove.JoveBitVectorType; +import com.newisys.langschema.jove.JoveFixedArrayType; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.langschema.vera.*; +import com.newisys.schemaanalyzer.juno.BlockAnalysis; +import com.newisys.schemaanalyzer.juno.ClassAnalysis; +import com.newisys.schemaanalyzer.juno.FunctionAnalysis; +import com.newisys.schemaanalyzer.juno.VariableAnalysis; +import com.newisys.schemaanalyzer.juno.VeraSchemaAnalyzer; +import com.newisys.util.MathUtils; +import com.newisys.util.logging.IndentLogger; +import com.newisys.verilog.EdgeSet; +import com.newisys.verilog.util.Bit; + +/** + * Base class for the various modules of the translator. Used to share common + * methods and references to objects providing common services. + * + * @author Trevor Robinson + */ +class TranslatorModule +{ + protected final JoveSchema schema; + protected final IfgenSchema ifSchema; + protected final VeraSchemaAnalyzer analyzer; + protected final PackageNamer packageNamer; + protected final IndentLogger log; + protected final ManualTranslationMap manXlatMap; + protected final FactoryTranslationMap factoryXlatMap; + protected final SchemaTypes types; + protected final ExpressionConverter exprConv; + protected final BuiltinFunctionTranslatorMap builtinFuncMap; + protected final TranslatedObjectMap xlatObjMap; + protected final IfgenJavaTranslator ifgenXlat; + protected final VerilogImporter vlogImporter; + + private final Map globalClasses; + + public TranslatorModule( + JoveSchema schema, + IfgenSchema ifSchema, + VeraSchemaAnalyzer analyzer, + PackageNamer packageNamer, + IndentLogger log, + SchemaTypes types, + ExpressionConverter exprConv, + ManualTranslationMap manXlatMap, + FactoryTranslationMap factoryXlatMap) + { + this.schema = schema; + this.ifSchema = ifSchema; + this.analyzer = analyzer; + this.packageNamer = packageNamer; + this.log = log; + this.manXlatMap = manXlatMap; + this.factoryXlatMap = factoryXlatMap; + this.types = types; + this.exprConv = exprConv; + this.builtinFuncMap = new BuiltinFunctionTranslatorMap(types); + this.xlatObjMap = new TranslatedObjectMap(); + this.ifgenXlat = new IfgenJavaTranslator(schema); + this.vlogImporter = new VerilogImporter(schema, packageNamer, types); + + this.globalClasses = new HashMap(); + } + + public TranslatorModule(TranslatorModule other) + { + this.schema = other.schema; + this.ifSchema = other.ifSchema; + this.analyzer = other.analyzer; + this.packageNamer = other.packageNamer; + this.log = other.log; + this.manXlatMap = other.manXlatMap; + this.factoryXlatMap = other.factoryXlatMap; + this.types = other.types; + this.exprConv = other.exprConv; + this.builtinFuncMap = other.builtinFuncMap; + this.xlatObjMap = other.xlatObjMap; + this.ifgenXlat = other.ifgenXlat; + this.vlogImporter = other.vlogImporter; + + this.globalClasses = other.globalClasses; + } + + protected void logEnter(String msg) + { + log.println(msg); + log.incIndent(); + } + + protected void log(String msg) + { + log.println(msg); + } + + protected void logExit() + { + log.decIndent(); + } + + protected static String fixID(String id) + { + return JavaKeywords.isKeyword(id) ? "_" + id : id; + } + + private JavaPackage getPackage(CompilationUnit compUnit) + { + final String path = compUnit.getSourcePath(); + final String pkgName = packageNamer.getPackageName(path); + final JavaPackage pkg = schema.getPackage(pkgName, true); + return pkg; + } + + protected JavaPackage translateCompUnit(VeraCompilationUnit obj) + { + // check whether compilation unit has already been translated + JavaPackage pkg = (JavaPackage) xlatObjMap.getJavaObject(obj); + if (pkg != null) return pkg; + + final String path = obj.getSourcePath(); + logEnter("Translating compilation unit: " + path); + + // get the containing package + pkg = getPackage(obj); + xlatObjMap.addJavaObject(obj, pkg); + + // translate the compilation unit members + final CompUnitMemberTranslator xlat = new CompUnitMemberTranslator( + this, pkg); + final Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraCompilationUnitMember member = (VeraCompilationUnitMember) iter + .next(); + member.accept(xlat); + } + + logExit(); + return pkg; + } + + protected JavaPackage translateCompUnitOf(VeraCompilationUnitMember obj) + { + return translateCompUnit(obj.getCompilationUnit()); + } + + protected JavaRawClass translateClass( + VeraUserClass obj, + JavaPackage pkg, + boolean translateMembers) + { + // check whether class has already been translated + JavaRawClass lookupCls = (JavaRawClass) xlatObjMap.getJavaObject(obj); + if (lookupCls != null) + { + if (translateMembers && lookupCls instanceof TranslatedClass) + { + translateClassMembers(obj, pkg, (TranslatedClass) lookupCls); + } + return lookupCls; + } + + final String id = obj.getName().getIdentifier(); + logEnter("Translating class: " + id); + + try + { + // check whether class has been manually translated + lookupCls = (JavaRawClass) manXlatMap.getClass(id); + if (lookupCls != null) + { + log("Using manually translated class: " + lookupCls.getName()); + xlatObjMap.addJavaObject(obj, lookupCls); + return lookupCls; + } + + // make sure class is actually defined + if (obj.isTypedefOnly()) + { + throw new RuntimeException( + "Cannot translate typedef-only class: " + id); + } + if (!obj.isDefined()) + { + if (id.equals("_Synopsys_Vera_List_")) + { + // _Synopsys_Vera_List_ is magically defined + obj.setDefined(true); + } + else if (id.equals("OVAAssert") || id.equals("OVAEngine") + || id.equals("OVAEvent")) + { + logExit(); + return (JavaRawClass) schema + .getTypeForSystemClass("com.newisys.juno.runtime." + id); + } + else + { + log("Warning: Converting extern-only class: " + id); + } + } + + // create the Java class + TranslatedClass cls = new TranslatedClass(schema, fixID(id), pkg); + cls.addAnnotations(obj.getAnnotations()); + pkg.addMember(cls); + xlatObjMap.addJavaObject(obj, cls); + + // set the visibility (local classes remain package-protected) + if (obj.getVisibility() != VeraVisibility.LOCAL) + { + cls.setVisibility(JavaVisibility.PUBLIC); + } + + // mark virtual classes as abstract + if (obj.isVirtual()) + { + cls.addModifier(JavaTypeModifier.ABSTRACT); + } + + // set the base class + final VeraClass veraBase = obj.getBaseClass(); + final JavaRawClass baseClass; + if (veraBase instanceof VeraUserClass) + { + baseClass = translateClass((VeraUserClass) veraBase, + translateMembers); + assert (baseClass != null); + } + else + { + assert (veraBase == obj.getVeraSchema().rootClass); + baseClass = types.junoObjectType; + } + cls.setBaseClass(baseClass); + + if (translateMembers) + { + translateClassMembers(obj, pkg, cls); + } + + return cls; + } + finally + { + logExit(); + } + } + + private void translateClassMembers( + VeraUserClass obj, + JavaPackage pkg, + TranslatedClass cls) + { + // avoid multiple member translations + if (cls.membersTranslated) return; + cls.membersTranslated = true; + + // translate the class members + final ClassMemberTranslator xlat = new ClassMemberTranslator(this, pkg, + cls); + final Iterator memberIter = obj.getMembers().iterator(); + while (memberIter.hasNext()) + { + VeraClassMember member = (VeraClassMember) memberIter.next(); + member.accept(xlat); + } + + // Java non-abstract classes must implement all inherited abstract + // methods; older versions of Vera did not require this + if (!cls.getModifiers().contains(JavaTypeModifier.ABSTRACT)) + { + implementAbstractMethods(cls); + } + } + + private void implementAbstractMethods(JavaRawAbstractClass cls) + { + final Collection methods = cls.getNonOverriddenMethods(); + final Iterator methodIter = methods.iterator(); + while (methodIter.hasNext()) + { + final JavaFunction method = (JavaFunction) methodIter.next(); + if (method.getModifiers().contains(JavaFunctionModifier.ABSTRACT)) + { + String id = method.getName().getIdentifier(); + JavaFunctionType origType = method.getType(); + + log("Warning: Class '" + cls.toReferenceString() + + "' must implement method '" + id + "'; generating stub"); + + JavaFunctionType funcType = new JavaFunctionType(origType); + JavaFunction func = new JavaFunction(id, funcType); + func.setVisibility(method.getVisibility()); + + JavaBlock body = new JavaBlock(schema); + body.addMember(new JavaThrowStatement(ExpressionBuilder + .newInstance(types.absCallErrorType))); + func.setBody(body); + + cls.addMember(func); + } + } + } + + protected JavaRawClass translateClass( + VeraUserClass obj, + boolean translateMembers) + { + return translateClass(obj, translateCompUnitOf(obj), translateMembers); + } + + protected JavaRawClass translateClassOf(VeraClassMember obj) + { + VeraClass veraClass = (VeraClass) obj.getStructuredType(); + return veraClass != null ? (JavaRawClass) translateType(veraClass) + : null; + } + + private JavaRawClass getClassForGlobal( + Container container, + String id, + JavaPackage pkg) + { + // check whether class has already been created for this container + JavaRawClass cls = globalClasses.get(container); + if (cls != null) return cls; + + // in case two Vera containers have the same Java class name (e.g. + // foo.vr and foo.vri -> FooGlobals), search for class by name + Iterator iter = pkg.lookupObjects(id, JavaNameKind.TYPE); + if (iter.hasNext()) + { + cls = (JavaRawClass) iter.next(); + return cls; + } + + // create public final class + cls = new JavaRawClass(schema, id, pkg); + cls.setBaseClass(types.objectType); + cls.setVisibility(JavaVisibility.PUBLIC); + cls.addModifier(JavaTypeModifier.FINAL); + pkg.addMember(cls); + globalClasses.put(container, cls); + + // create empty private ctor to prevent instantiation + JavaConstructor ctor = cls.newConstructor(); + ctor.setVisibility(JavaVisibility.PRIVATE); + ctor.setBody(new JavaBlock(schema)); + + return cls; + } + + private JavaRawClass getClassForGlobal( + VeraCompilationUnitMember obj, + JavaPackage pkg) + { + final CompilationUnit compUnit = obj.getCompilationUnit(); + final String id = getIDForCompUnit(compUnit, true) + "Globals"; + return getClassForGlobal(compUnit, id, pkg); + } + + protected static String getIDForCompUnit( + CompilationUnit compUnit, + boolean uppercase) + { + File srcFile = new File(compUnit.getSourcePath()); + String srcName = srcFile.getName(); + int dotPos = srcName.lastIndexOf('.'); + if (dotPos >= 0) srcName = srcName.substring(0, dotPos); + return makeJavaIdentifier(srcName, uppercase); + } + + protected static String makeJavaIdentifier(String str, boolean uppercase) + { + StringBuffer buf = null; + int len = str.length(); + for (int i = 0; i < len; ++i) + { + char c = str.charAt(i); + boolean valid = (i == 0) ? Character.isJavaIdentifierStart(c) + : Character.isJavaIdentifierPart(c); + + char newc = c; + if (!valid) + { + newc = '_'; + } + else if (i == 0 && uppercase) + { + newc = Character.toUpperCase(c); + } + + if (newc != c) + { + if (buf == null) + { + buf = new StringBuffer(len); + buf.append(str.substring(0, i)); + } + buf.append(newc); + } + else if (buf != null) + { + buf.append(newc); + } + } + return buf != null ? buf.toString() : str; + } + + protected JavaFunction translateGlobalFunction( + VeraGlobalFunction obj, + JavaPackage pkg) + { + // check whether function has already been translated + JavaFunction func = (JavaFunction) xlatObjMap.getJavaObject(obj); + if (func != null) return func; + + String id = obj.getName().getIdentifier(); + logEnter("Translating global function: " + id); + + // translate function type + final VeraFunctionType veraFuncType = obj.getType(); + final JavaFunctionType funcType = translateFunctionType(veraFuncType, + obj, true); + + // translate visibility + final JavaVisibility vis = obj.getVisibility() == VeraVisibility.LOCAL + ? JavaVisibility.DEFAULT : JavaVisibility.PUBLIC; + + // get containing class for function + final JavaRawClass cls = getClassForGlobal(obj, pkg); + + // ensure identifier is not a Java keyword + id = fixID(id); + + // create Java static function + func = new JavaFunction(id, funcType); + func.addAnnotations(obj.getAnnotations()); + func.setVisibility(vis); + func.addModifier(JavaFunctionModifier.STATIC); + cls.addMember(func); + xlatObjMap.addJavaObject(obj, func); + + // translate function body + final VeraBlock veraBody = obj.getBody(); + final JavaBlock body = translateBlock(veraBody, obj, veraFuncType, + func, funcType, false); + func.setBody(body); + + logExit(); + return func; + } + + protected JavaFunction translateGlobalFunction(VeraGlobalFunction obj) + { + return translateGlobalFunction(obj, translateCompUnitOf(obj)); + } + + protected JavaFunction translateHDLFunction( + VeraHDLFunction obj, + JavaPackage pkg) + { + // check whether function has already been translated + JavaFunction func = (JavaFunction) xlatObjMap.getJavaObject(obj); + if (func != null) return func; + + final String veraID = obj.getName().getIdentifier(); + logEnter("Translating HDL function: " + veraID); + + // ensure identifier is not a Java keyword + final String id = fixID(veraID); + // translate Vera hdl_task to Ifgen hdl_task + final IfgenPackage ifPkg = ifSchema.getPackage(pkg.getName() + .getCanonicalName(), true); + final IfgenName ifName = new IfgenName(id, IfgenNameKind.METHOD, ifPkg); + final IfgenHDLTask ifTask = new IfgenHDLTask(ifSchema, ifName); + ifTask.setInstancePath(new IfgenModuleDef(ifSchema, IfgenUnresolvedName.parse(obj.getInstPath()), false)); + ifTask.addAnnotations(obj.getAnnotations()); + ifPkg.addMember(ifTask); + xlatObjMap.addIfgenObject(obj, ifTask); + + // translate arguments + final VeraFunctionType veraFuncType = obj.getType(); + for (final VeraFunctionArgument arg : veraFuncType.getArguments()) + { + final String argID = arg.getName().getIdentifier(); + final IfgenName ifArgName = new IfgenName(fixID(argID), + IfgenNameKind.EXPRESSION); + final IfgenDirection ifArgDir = arg.isByRef() + ? IfgenDirection.INOUT : IfgenDirection.INPUT; + final VeraType argType = arg.getType(); + final IfgenType ifArgType; + final int argSize; + if (argType instanceof VeraBitVectorType) + { + VeraBitVectorType bvType = (VeraBitVectorType) argType; + ifArgType = ifSchema.BIT_TYPE; + argSize = bvType.getSize(); + } + else if (argType instanceof VeraBitType) + { + ifArgType = ifSchema.BIT_TYPE; + argSize = 1; + } + else if (argType instanceof VeraIntegerType) + { + ifArgType = ifSchema.INTEGER_TYPE; + argSize = 1; + } + else + { + throw new RuntimeException("Unexpected argument type '" + + argType + "' for hdl_task '" + veraID + "'"); + } + final IfgenTaskArg ifArg = new IfgenTaskArg(ifSchema, ifArgName, + ifArgDir, ifArgType, argSize); + ifArg.addAnnotations(arg.getAnnotations()); + ifTask.addArgument(ifArg); + xlatObjMap.addIfgenObject(arg, ifArg); + } + + // translate function type + final JavaFunctionType funcType = translateFunctionType(veraFuncType, + obj, true); + + // get containing class for function + final JavaRawClass cls = getClassForGlobal(obj, pkg); + + // create Java static function + func = new JavaFunction(id, funcType); + func.addAnnotations(obj.getAnnotations()); + func.setVisibility(JavaVisibility.PUBLIC); + func.addModifier(JavaFunctionModifier.STATIC); + cls.addMember(func); + xlatObjMap.addJavaObject(obj, func); + + // generate function body: + // DV.simulation.callVerilogTask("taskname", new Object[] { args }); + final JavaVariableReference simRef = new JavaVariableReference( + types.dvType.getField("simulation")); + final JavaArrayInitializer argsInitExpr = new JavaArrayInitializer( + types.objectArrayType); + final Iterator argIter = funcType.getArguments().iterator(); + while (argIter.hasNext()) + { + JavaFunctionArgument arg = (JavaFunctionArgument) argIter.next(); + argsInitExpr.addElement(exprConv + .toObject(new JavaVariableReference(arg))); + } + final JavaArrayCreation argsNewExpr = new JavaArrayCreation( + types.objectArrayType); + argsNewExpr.setInitializer(argsInitExpr); + final JavaFunctionInvocation callExpr = ExpressionBuilder.memberCall( + simRef, "callVerilogTask", new JavaStringLiteral(schema, veraID), + argsNewExpr); + final JavaBlock body = new JavaBlock(schema); + body.addMember(new JavaExpressionStatement(callExpr)); + func.setBody(body); + + logExit(); + return func; + } + + protected JavaFunctor translateMemberFunctionOrCtor( + VeraMemberFunction obj, + JavaRawAbstractClass cls) + { + if (obj.isConstructor()) + { + return translateConstructor(obj, cls); + } + else + { + return translateMemberFunction(obj, cls); + } + } + + protected JavaConstructor translateConstructor( + VeraMemberFunction obj, + JavaRawAbstractClass cls) + { + // check whether constructor has already been translated + JavaConstructor ctor = (JavaConstructor) xlatObjMap.getJavaObject(obj); + if (ctor != null) return ctor; + + final String clsID = cls.getName().getIdentifier(); + final String id = obj.getName().getIdentifier(); + logEnter("Translating constructor: " + clsID + "." + id); + + try + { + // if this is a hand-translated class, just look up a constructor + // (it doesn't matter if there are overloaded versions; the + // expression translator will find the right one itself) + if (!(cls instanceof TranslatedClass)) + { + final Set ctors = cls.getConstructors(cls); + if (ctors.isEmpty()) + { + throw new RuntimeException( + "Manually translated constructor not found for " + obj + + " in " + cls); + } + ctor = (JavaConstructor) ctors.iterator().next(); + xlatObjMap.addJavaObject(obj, ctor); + return ctor; + } + + // translate function type + final VeraFunctionType veraFuncType = obj.getType(); + final JavaFunctionType funcType = translateFunctionType( + veraFuncType, obj, true); + + // translate visibility + final JavaVisibility vis = translateMemberVisibility(obj + .getVisibility()); + + // create Java constructor + ctor = new JavaConstructor(funcType); + ctor.addAnnotations(obj.getAnnotations()); + ctor.setVisibility(vis); + cls.addMember(ctor); + xlatObjMap.addJavaObject(obj, ctor); + + if (!obj.isImplicit()) + { + // get the analysis for this class + final VeraUserClass veraCls = (VeraUserClass) obj + .getStructuredType(); + final ClassAnalysis clsAnalysis = analyzer + .getClassAnalysis(veraCls); + final boolean makeDefCtor = clsAnalysis.needDefaultCtor() + && !clsAnalysis.hasDefaultCtor(); + final boolean transformSuperCall = makeDefCtor + || clsAnalysis.transformSuperCall(); + + // translate constructor body + final VeraBlock veraBody = obj.getBody(); + JavaBlock body = translateBlock(veraBody, null, veraFuncType, + ctor, funcType, transformSuperCall); + + // check whether default constructor must be introduced + if (makeDefCtor) + { + // add an empty, protected default constructor + final JavaConstructor defCtor = new JavaConstructor(schema); + defCtor.setVisibility(JavaVisibility.PROTECTED); + defCtor.setBody(new JavaBlock(schema)); + cls.addMember(defCtor); + + // create init() method using translated constructor body + final JavaFunctionType initType = new JavaFunctionType( + funcType); + final JavaFunction initFunc = new JavaFunction("init", + initType); + initFunc.setVisibility(JavaVisibility.PROTECTED); + initFunc.setBody(body); + cls.addMember(initFunc); + + // generate init() call for body of translated constructor + final JavaFunctionInvocation initCall = new JavaFunctionInvocation( + new JavaFunctionReference(initFunc)); + final Iterator argIter = funcType.getArguments().iterator(); + while (argIter.hasNext()) + { + final JavaFunctionArgument arg = (JavaFunctionArgument) argIter + .next(); + initCall.addArgument(new JavaVariableReference(arg)); + } + body = new JavaBlock(schema); + body.addMember(new JavaExpressionStatement(initCall)); + } + + ctor.setBody(body); + } + else + { + // generate empty body for implicit constructor + // TODO: generate super() call using base ctor args if present + // TODO: add implicit modifier to Java constructor? + ctor.setBody(new JavaBlock(schema)); + } + + // generate additional constructor without optional arguments + if (hasOptionalArgs(veraFuncType)) + { + final JavaFunctionType optFuncType = translateFunctionType( + veraFuncType, obj, false); + final JavaConstructor optCtor = new JavaConstructor(optFuncType); + optCtor.setVisibility(vis); + cls.addMember(optCtor); + final JavaBlock optBody = new JavaBlock(schema); + final JavaConstructorInvocation optCtorCall = new JavaConstructorInvocation( + new JavaConstructorReference(ctor)); + final Iterator veraArgIter = veraFuncType.getArguments() + .iterator(); + final Iterator javaArgIter = funcType.getArguments().iterator(); + final Iterator optArgIter = optFuncType.getArguments() + .iterator(); + while (veraArgIter.hasNext()) + { + VeraFunctionArgument veraArg = (VeraFunctionArgument) veraArgIter + .next(); + JavaFunctionArgument javaArg = (JavaFunctionArgument) javaArgIter + .next(); + JavaExpression optArgExpr; + if (veraArg.isOptional()) + { + VeraExpression veraArgExpr = veraArg.getInitializer(); + assert (veraArgExpr != null); + JavaType javaArgType = javaArg.getType(); + ConvertedExpression convExpr = translateExpr( + veraArgExpr, null, cls, null, null, javaArgType, + javaArgType); + optArgExpr = convExpr.toBlockExpr(optBody, "arg"); + JavaType optExprType = optArgExpr.getResultType(); + optArgExpr = convertRHS(optArgExpr, optExprType, + javaArgType, true); + } + else + { + JavaFunctionArgument optArg = (JavaFunctionArgument) optArgIter + .next(); + optArgExpr = new JavaVariableReference(optArg); + } + optCtorCall.addArgument(optArgExpr); + } + optBody.addMember(new JavaExpressionStatement(optCtorCall)); + optCtor.setBody(optBody); + } + + return ctor; + } + finally + { + logExit(); + } + } + + private JavaFunction translateMemberFunction( + VeraMemberFunction obj, + JavaRawAbstractClass cls) + { + // check whether function has already been translated + JavaFunction func = (JavaFunction) xlatObjMap.getJavaObject(obj); + if (func != null) return func; + + String clsID = cls.getName().getIdentifier(); + String id = obj.getName().getIdentifier(); + logEnter("Translating member function: " + clsID + "." + id); + + try + { + // if this is a hand-translated class, just look up the method by name + // (it doesn't matter if there are overloaded versions; the expression + // translator will find the right one itself) + if (!(cls instanceof TranslatedClass)) + { + final Set methods = cls.getMethods(id, cls); + if (methods.isEmpty()) + { + throw new RuntimeException( + "Manually translated method not found for " + obj + + " in " + cls); + } + func = (JavaFunction) methods.iterator().next(); + xlatObjMap.addJavaObject(obj, func); + return func; + } + + // get global analysis for function + FunctionAnalysis funcAnalysis = analyzer.getFunctionAnalysis(obj); + if (funcAnalysis != null && funcAnalysis.isNonVirtualOverride()) + { + // if function is involved in non-virtual overriding, + // prefix its identifier with the class identifier + id = clsID + "_" + id; + } + + // translate function type + final VeraFunctionType veraFuncType = obj.getType(); + final JavaFunctionType funcType = translateFunctionType( + veraFuncType, obj, true); + + // translate visibility + final JavaVisibility vis = translateMemberVisibility(obj + .getVisibility()); + + // ensure identifier is not a Java keyword + id = fixID(id); + + // check for illegal method override + boolean anyIllegal = false; + final String newID = buildID("juno", id); + final JavaType[] argTypes = getArgTypes(funcType); + final Set methods = cls.getMethods(id, argTypes, + true, true, cls); + final Iterator methodIter = methods.iterator(); + while (methodIter.hasNext()) + { + final JavaFunction method = methodIter.next(); + final StructuredType methodType = method.getStructuredType(); + + // any methods found should be in a base class/interface + assert (methodType != cls); + + boolean thisIllegal = false; + if (method.getModifiers().contains(JavaFunctionModifier.FINAL)) + { + log("Warning: Member function '" + cls.toReferenceString() + + "." + id + "' conflicts with final method in " + + methodType.getName() + "; renaming to " + newID); + thisIllegal = true; + } + if (vis.isLessVisible(method.getVisibility())) + { + log("Warning: Member function '" + cls.toReferenceString() + + "." + id + "' conflicts with method in " + + methodType.getName() + + " with greater visibility; renaming to " + newID); + thisIllegal = true; + } + JavaType newReturnType = funcType.getReturnType(); + JavaType baseReturnType = method.getType().getReturnType(); + if (!newReturnType.equals(baseReturnType)) + { + log("Warning: Member function '" + cls.toReferenceString() + + "." + id + "' (returning " + + newReturnType.toReferenceString() + + ") conflicts with method in " + methodType.getName() + + " (returning " + baseReturnType.toReferenceString() + + ") due to different return types; renaming to " + + newID); + thisIllegal = true; + } + + if (thisIllegal) + { + // any illegal override should be from a non-translated class, + // such as java.lang.Object + assert (!(methodType instanceof TranslatedClass)); + anyIllegal = true; + } + } + if (anyIllegal) id = newID; + + // create Java function + func = new JavaFunction(id, funcType); + func.addAnnotations(obj.getAnnotations()); + func.setVisibility(vis); + cls.addMember(func); + xlatObjMap.addJavaObject(obj, func); + + // translate non-virtual functions as final + if (!obj.isVirtual()) + { + func.addModifier(JavaFunctionModifier.FINAL); + } + + // translate function body + if (obj.isPureVirtual()) + { + assert (obj.isVirtual()); + func.addModifier(JavaFunctionModifier.ABSTRACT); + } + else + { + final VeraBlock veraBody = obj.getBody(); + if (veraBody == null) + { + log("Warning: Member function '" + cls.toReferenceString() + + "." + id + "' was not translated; generating stub"); + } + + final JavaBlock body = translateBlock(veraBody, obj, + veraFuncType, func, funcType, false); + func.setBody(body); + } + + return func; + } + finally + { + logExit(); + } + } + + protected static JavaType[] getArgTypes(JavaFunctionType funcType) + { + final List args = funcType.getArguments(); + final JavaType[] argTypes = new JavaType[args.size()]; + final Iterator argIter = args.iterator(); + int argIndex = 0; + while (argIter.hasNext()) + { + JavaFunctionArgument arg = argIter.next(); + argTypes[argIndex++] = arg.getType(); + } + return argTypes; + } + + protected static JavaExpression[] getArgArray(List args) + { + final JavaExpression[] argArray = new JavaExpression[args.size()]; + args.toArray(argArray); + return argArray; + } + + protected static String buildID(String part1, String part2) + { + return part1 + Character.toUpperCase(part2.charAt(0)) + + part2.substring(1); + } + + protected boolean isReturnXZ( + VeraFunction func, + FunctionAnalysis baseFuncAnalysis) + { + boolean xz; + if (baseFuncAnalysis != null) + { + xz = baseFuncAnalysis.isReturnXZInOverride(); + } + else + { + VeraFunctionType funcType = func.getType(); + VeraLocalVariable returnVar = func.getReturnVar(); + xz = funcType.isReturnsXZ(); + if (!xz && returnVar != null) + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(returnVar); + xz = varAnalysis == null || !varAnalysis.isNotAssignedXZ(); + } + } + return xz; + } + + protected boolean isArgumentXZ( + VeraFunction func, + int index, + FunctionAnalysis baseFuncAnalysis) + { + boolean xz; + if (baseFuncAnalysis != null) + { + xz = baseFuncAnalysis.isArgumentXZInOverride(index); + } + else + { + VeraFunctionType funcType = func.getType(); + VeraFunctionArgument arg = funcType.getArguments().get(index); + xz = arg.isReturnsXZ(); + if (!xz) + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(arg); + xz = varAnalysis == null || !varAnalysis.isNotAssignedXZ(); + } + } + return xz; + } + + protected boolean isArgumentStatefulString( + VeraFunction func, + int index, + FunctionAnalysis baseFuncAnalysis) + { + boolean stateful; + if (baseFuncAnalysis != null) + { + stateful = baseFuncAnalysis + .isArgumentStatefulStringInOverride(index); + } + else + { + VeraFunctionType funcType = func.getType(); + VeraFunctionArgument arg = funcType.getArguments().get(index); + VariableAnalysis varAnalysis = analyzer.getVariableAnalysis(arg); + stateful = varAnalysis == null + || varAnalysis.isNeedStatefulString(); + } + return stateful; + } + + private boolean hasOptionalArgs(VeraFunctionType veraFuncType) + { + Iterator iter = veraFuncType.getArguments().iterator(); + while (iter.hasNext()) + { + VeraFunctionArgument veraArg = (VeraFunctionArgument) iter.next(); + if (veraArg.isOptional()) return true; + } + return false; + } + + private JavaFunctionType translateFunctionType( + VeraFunctionType veraFuncType, + VeraFunction func, + boolean includeOptional) + { + // get function analysis of base function + FunctionAnalysis baseFuncAnalysis = analyzer + .getBaseFunctionAnalysis(func); + + // translate return type + final VeraType veraReturnType = veraFuncType.getReturnType(); + final JavaType returnType; + if (veraReturnType != null) + { + returnType = translateType(veraReturnType, isReturnXZ(func, + baseFuncAnalysis), false); + } + else + { + returnType = schema.voidType; + } + + // create Java function type + final JavaFunctionType funcType = new JavaFunctionType(returnType); + + // translate arguments + Iterator iter = veraFuncType.getArguments().iterator(); + for (int index = 0; iter.hasNext(); ++index) + { + VeraFunctionArgument veraArg = (VeraFunctionArgument) iter.next(); + if (!includeOptional && veraArg.isOptional()) continue; + String argID = veraArg.getName().getIdentifier(); + final VeraType veraArgType = veraArg.getType(); + final boolean byRef = veraArg.isByRef(); + JavaType argType = translateType(veraArgType, isArgumentXZ(func, + index, baseFuncAnalysis), byRef + && isArgumentStatefulString(func, index, baseFuncAnalysis)); + final boolean needsClone = needsClone(argType); + boolean argFinal = needsClone; + + if (!needsClone) + { + if (byRef) + { + argID += "_ref"; + argType = getRefHolderType(argType); + argFinal = true; + } + else + { + final VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(veraArg); + if (varAnalysis != null && !varAnalysis.isWriteAssigned()) + { + log("Note: Marking argument '" + argID + "' in " + + func.getName() + " as final"); + argFinal = true; + } + } + } + + JavaFunctionArgument arg = new JavaFunctionArgument(fixID(argID), + argType); + if (argFinal) arg.addModifier(JavaVariableModifier.FINAL); + //addLengthAnnotation(arg, argType); + funcType.addArgument(arg); + xlatObjMap.addJavaObject(veraArg, arg); + } + return funcType; + } + + protected boolean needsClone(JavaType type) + { + // true for types that have value/copy semantics in Vera, + // but have mutable reference semantics in Java + return type instanceof JoveFixedArrayType + || exprConv.isAssocArray(type) || type == types.junoStringType; + } + + protected boolean needHolderVar( + JavaType javaType, + VeraVariable veraVar, + VariableAnalysis varAnalysis) + { + if (!needsClone(javaType) && varAnalysis != null) + { + if (varAnalysis.isPassedByRefNVA()) + { + // variables passed by-ref need holder (optimization) + return true; + } + if ((varAnalysis.isForkRead() || varAnalysis.isForkWrite()) + && !veraVar.hasModifier(VeraVariableModifier.SHADOW)) + { + // non-shadow variables read or written in fork need holder + return true; + } + } + return false; + } + + protected JavaType getRefHolderType(JavaType argType) + { + return schema.getArrayType(argType, 1); + } + + protected JavaBlock translateBlock( + VeraBlock veraBlock, + VeraFunction veraFunc, + VeraFunctionType veraFuncType, + JavaClassMember member, + JavaFunctionType funcType, + boolean transformSuperNewCall) + { + JavaBlock block = new JavaBlock(schema); + final TempBlockScope tempScope = new TempBlockScope(funcType); + + // get the analysis for this block + final BlockAnalysis analysis = analyzer.getBlockAnalysis(veraBlock); + + // add variable reference mappers for by-ref arguments if present + VarInfoMap varInfoMap = new VarInfoMap(); + if (veraFuncType != null) + { + for (VeraFunctionArgument veraArg : veraFuncType.getArguments()) + { + JavaVariable javaArg = translateVariable(veraArg); + JavaType javaArgType = javaArg.getType(); + + VarInfo info = null; + if (veraArg.isByRef()) + { + if (!needsClone(javaArgType)) + { + // argument has been translated as by-ref holder + info = new VarInfo(schema, veraArg, javaArg, true); + } + } + else + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(veraArg); + + // need to introduce JunoString for by-value argument? + if (varAnalysis != null + && varAnalysis.isNeedStatefulString()) + { + // create local variable (JunoString) + String id = javaArg.getName().getIdentifier(); + JavaRawClass junoStringType = types.junoStringType; + JavaLocalVariable localVar = VarBuilder.createLocalVar( + tempScope, id + "_JunoString", junoStringType); + tempScope.addObject(localVar); + localVar.addModifier(JavaVariableModifier.FINAL); + localVar + .setInitializer(ExpressionBuilder.newInstance( + junoStringType, new JavaVariableReference( + javaArg))); + block.addMember(localVar); + + // translate variable references to JunoString + info = new VarInfo(schema, veraArg, localVar, false); + } + // need to introduce holder for by-value argument? + else if (needHolderVar(javaArgType, veraArg, varAnalysis)) + { + // create local variable (holder) + String id = javaArg.getName().getIdentifier(); + JavaArrayType holderType = schema.getArrayType( + javaArgType, 1); + JavaLocalVariable localVar = VarBuilder.createLocalVar( + tempScope, id + "_holder", holderType); + tempScope.addObject(localVar); + localVar.addModifier(JavaVariableModifier.FINAL); + JavaArrayInitializer arrayInit = new JavaArrayInitializer( + holderType); + arrayInit + .addElement(new JavaVariableReference(javaArg)); + localVar.setInitializer(arrayInit); + block.addMember(localVar); + + // translate variable references to holder + info = new VarInfo(schema, veraArg, localVar, true); + } + } + + if (info != null) + { + varInfoMap.addInfo(info); + } + } + } + + final JavaRawAbstractClass cls = (JavaRawAbstractClass) member + .getStructuredType(); + + // add return variable to block if present + JavaLocalVariable returnVar = null; + if (veraFunc != null) + { + returnVar = translateReturnVar(veraFunc, funcType, cls, member, + block, tempScope, varInfoMap); + } + + if (veraBlock != null) + { + // translate the block members + final BlockMemberTranslator xlat = new BlockMemberTranslator(this, + block, tempScope, varInfoMap, returnVar, cls, member); + xlat.setTransformSuperNewCall(transformSuperNewCall); + xlat.translateBlockMembers(veraBlock); + block.addAnnotations(veraBlock.getAnnotations()); + } + else + { + // generate stub for missing body of UDF or untranslated function + block.addMember(new JavaThrowStatement(ExpressionBuilder + .newInstance(types.unsuppOpType))); + } + + // make sure last statement returns result variable + if (returnVar != null) + { + List members = block.getMembers(); + Object lastMember = members.get(members.size() - 1); + if (!(lastMember instanceof JavaReturnStatement)) + { + addReturnStatement(block, returnVar, funcType.getReturnType(), + varInfoMap); + } + } + + // create thread context if necessary + block = checkThreadContext(block, analysis); + + return block; + } + + protected JavaReturnStatement addReturnStatement( + JavaBlock block, + JavaLocalVariable returnVar, + JavaType returnType, + VarInfoMap varInfoMap) + { + JavaExpression returnExpr = null; + if (returnVar != null) + { + VarInfo info = varInfoMap.getInfo(returnVar); + if (info != null) + { + returnExpr = info.getReference(); + } + else + { + returnExpr = new JavaVariableReference(returnVar); + } + returnExpr = exprConv.toType(returnType, returnExpr); + } + JavaReturnStatement stmt = new JavaReturnStatement(schema, returnExpr); + block.addMember(stmt); + return stmt; + } + + protected JavaBlock checkThreadContext( + JavaBlock block, + BlockAnalysis analysis) + { + // block -> + // enter_context(); + // try { } + // finally { leave_context(); } + if (analysis != null && analysis.isNeedThreadContext()) + { + JavaBlock ctxBlock = new JavaBlock(schema); + + ctxBlock.addMember(new JavaExpressionStatement(ExpressionBuilder + .staticCall(types.junoType, "enter_context"))); + + JavaTryStatement tryStmt = new JavaTryStatement(block); + ctxBlock.addMember(tryStmt); + + JavaBlock finallyBlock = new JavaBlock(schema); + finallyBlock.addMember(new JavaExpressionStatement( + ExpressionBuilder.staticCall(types.junoType, "leave_context"))); + tryStmt.setFinallyBlock(finallyBlock); + + block = ctxBlock; + } + return block; + } + + // cls and assocMember are only required for static variables + protected JavaVariable translateLocalVariable( + VeraLocalVariable obj, + boolean isReturnVar, + JavaRawAbstractClass cls, + JavaClassMember assocMember, + JavaBlock block, + TempBlockScope tempScope, + JavaLocalVariable returnVar, + VarInfoMap varInfoMap) + { + String id = obj.getName().getIdentifier(); + + // get the analysis for this variable + final VariableAnalysis varAnalysis = analyzer.getVariableAnalysis(obj); + if (!isReturnVar && varAnalysis != null && !varAnalysis.isReadAccess()) + { + // suppress translation of unreferenced variables + // NOTE: unread (but assigned) variables could technically be + // suppressed as well, but that would involve translating their + // assignment expressions into statements + if (!varAnalysis.isWriteAccess()) + { + log("Warning: Suppressing translation of unreferenced local '" + + id + "' in " + describeClassMember(assocMember)); + return null; + } + else + { + String msg = "Warning: Local variable '" + id + "' in " + + describeClassMember(assocMember) + " is never read"; + if (varAnalysis.isWriteSideEffects()) + { + msg += ", but assignment has side effects"; + } + log(msg); + } + } + + // create variable + JavaVariable var; + id = fixID(id); + VeraType veraType = obj.getType(); + JavaType type = translateType(veraType, varAnalysis == null + || !varAnalysis.isNotAssignedXZ(), varAnalysis == null + || varAnalysis.isNeedStatefulString()); + VeraExpression veraInitExpr = obj.getInitializer(); + if (obj.hasModifier(VeraVariableModifier.STATIC)) + { + // Vera static local variable becomes Java static member variable + JavaMemberVariable memberVar = VarBuilder.createMemberVar(cls, id, + type); + memberVar.setVisibility(JavaVisibility.PRIVATE); + memberVar.addModifier(JavaVariableModifier.STATIC); + cls.addMemberBefore(memberVar, assocMember); + var = memberVar; + + // cloned variables are final + if (needsClone(type)) + { + memberVar.addModifier(JavaVariableModifier.FINAL); + } + + // translate initializer expression + JavaExpression initExpr; + if (veraInitExpr != null) + { + ConvertedExpression convExpr = translateExpr(veraInitExpr, + tempScope, cls, varInfoMap, returnVar, type, type); + convertInitializer(convExpr, type); + initExpr = convExpr.toMemberInitExpr(cls, memberVar); + } + else + { + initExpr = getInitValue(type, false, false); + } + var.setInitializer(initExpr); + + // create wait_var event if necessary + checkWaitVarMember(obj, memberVar, varAnalysis, cls, assocMember); + } + else + { + JavaLocalVariable localVar; + if (needHolderVar(type, obj, varAnalysis)) + { + // create local variable (holder) + JavaArrayType holderType = schema.getArrayType(type, 1); + localVar = VarBuilder.createLocalVar(tempScope, id + "_holder", + holderType); + tempScope.addObject(localVar); + var = localVar; + + // holder variables are always final + localVar.addModifier(JavaVariableModifier.FINAL); + + // translate initializer expression + JavaArrayInitializer arrayInit = new JavaArrayInitializer( + holderType); + if (veraInitExpr != null) + { + ConvertedExpression convExpr = translateExpr(veraInitExpr, + tempScope, cls, varInfoMap, returnVar, type, type); + convertInitializer(convExpr, type); + arrayInit.addElement(convExpr.getResultExpr()); + convExpr.setResultExpr(arrayInit); + convExpr.toLocalVar(block, localVar); + } + else + { + arrayInit.addElement(getInitValue(type, true, false)); + localVar.setInitializer(arrayInit); + block.addMember(localVar); + } + + // record that variable was translated as holder + varInfoMap.addInfo(new VarInfo(schema, obj, localVar, true)); + } + else + { + // create local variable + localVar = VarBuilder.createLocalVar(tempScope, id, type); + tempScope.addObject(localVar); + var = localVar; + + boolean needInit = true; + if (needsClone(type)) + { + // cloned variables are always final and initialized + var.addModifier(JavaVariableModifier.FINAL); + } + else if (varAnalysis != null && !varAnalysis.isReadUnassigned()) + { + // local variables not read when unassigned and not written + // when assigned can be marked as final + if (varAnalysis.isWaitVar()) + { + // the wait_var checking code does not support final + // fields since they are uninitialized before the + // assignment (i.e. they have no old value that can be + // read); such code is nonsensical and should be fixed + // in Vera + log("Warning: Local variable '" + obj.getName() + + "' in " + describeClassMember(assocMember) + + " is never changed and should be marked final, " + + "but is a wait_var target"); + } + else if (!varAnalysis.isWriteAssigned()) + { + log("Note: Marking local variable '" + obj.getName() + + "' in " + describeClassMember(assocMember) + + " as final"); + var.addModifier(JavaVariableModifier.FINAL); + needInit = false; + } + else + { + // variable is not final, but does not need to be + // initialized, since it is not read when unassigned + // TODO: this case does not handle initialization of + // forked shadow variables; need separate DA/DU analysis + // of shadow variables to optimize away unnecessary init + needInit = varAnalysis.isForkRead(); + } + } + + // translate initializer expression + if (veraInitExpr != null) + { + ConvertedExpression convExpr = translateExpr(veraInitExpr, + tempScope, cls, varInfoMap, returnVar, type, type); + convertInitializer(convExpr, type); + convExpr.toLocalVar(block, localVar); + } + else + { + if (needInit) + { + localVar + .setInitializer(getInitValue(type, true, false)); + } + block.addMember(localVar); + } + } + + // create wait_var event if necessary + checkWaitVarLocal(obj, localVar, varAnalysis, block, tempScope); + } + var.addAnnotations(obj.getAnnotations()); + //addLengthAnnotation(var, type); + xlatObjMap.addJavaObject(obj, var); + return var; + } + + protected String describeClassMember(JavaClassMember member) + { + if (member instanceof NamedObject) + { + return ((NamedObject) member).getName().getCanonicalName(); + } + else + { + StructuredType cls = member.getStructuredType(); + Name clsName = cls.getName(); + if (member instanceof JavaConstructor) + { + return clsName.getCanonicalName() + "." + + clsName.getIdentifier(); + } + else + { + assert (member instanceof JavaInitializerBlock); + return "initializer in " + clsName; + } + } + } + + private JavaLocalVariable translateReturnVar( + VeraFunction veraFunc, + JavaFunctionType funcType, + JavaRawAbstractClass cls, + JavaClassMember assocMember, + JavaBlock block, + TempBlockScope tempScope, + VarInfoMap varInfoMap) + { + JavaLocalVariable returnVar = null; + + // create return variable if function result is non-void + JavaType returnType = funcType.getReturnType(); + if (!(returnType instanceof JavaVoidType)) + { + VeraLocalVariable veraReturnVar = veraFunc.getReturnVar(); + if (veraReturnVar != null) + { + // translate return variable + returnVar = (JavaLocalVariable) translateLocalVariable( + veraReturnVar, true, cls, assocMember, block, tempScope, + null, varInfoMap); + } + else + { + // UDF functions do not have a return variable + } + } + + return returnVar; + } + + protected void checkWaitVarLocal( + VeraVariable veraVar, + JavaLocalVariable javaVar, + VariableAnalysis varAnalysis, + JavaBlock block, + TempBlockScope tempScope) + { + if (varAnalysis != null && varAnalysis.isWaitVar()) + { + final VeraType veraType = veraVar.getType(); + final JavaType eventType = getWaitVarEventType(veraType); + final JavaLocalVariable eventVar = VarBuilder.createLocalVar( + tempScope, getEventVarID(veraVar), eventType); + tempScope.addObject(eventVar); + eventVar.addModifier(JavaVariableModifier.FINAL); + eventVar.setInitializer(getInitValue(eventType, true, false)); + block.addMember(eventVar); + xlatObjMap.addWaitVarEvent(javaVar, eventVar); + } + } + + private String getEventVarID(VeraVariable veraVar) + { + return fixID(veraVar.getName().getIdentifier()) + "_changed"; + } + + protected JavaMemberVariable translateGlobalVariable( + VeraGlobalVariable obj, + JavaPackage pkg) + { + // check whether variable has already been translated + JavaMemberVariable var = (JavaMemberVariable) xlatObjMap + .getJavaObject(obj); + if (var != null) return var; + + String id = obj.getName().getIdentifier(); + logEnter("Translating global variable: " + id); + + // get the analysis for this variable + final VariableAnalysis varAnalysis = analyzer.getVariableAnalysis(obj); + + // translate variable type + final JavaType type = translateType(obj.getType(), varAnalysis == null + || !varAnalysis.isNotAssignedXZ(), varAnalysis == null + || varAnalysis.isNeedStatefulString()); + + // get containing class for variable + final JavaRawClass cls = getClassForGlobal(obj, pkg); + + // ensure identifier is not a Java keyword + id = fixID(id); + + // create the Java variable + var = new JavaMemberVariable(id, type); + var.addAnnotations(obj.getAnnotations()); + var.setVisibility(JavaVisibility.PUBLIC); + var.addModifier(JavaVariableModifier.STATIC); + if (needsClone(type)) + { + var.addModifier(JavaVariableModifier.FINAL); + } + //addLengthAnnotation(var, type); + cls.addMember(var); + xlatObjMap.addJavaObject(obj, var); + + // set initializer expression if necessary + var.setInitializer(getInitValue(type, false, false)); + + // create wait_var event if necessary + checkWaitVarMember(obj, var, varAnalysis, cls, null); + + logExit(); + return var; + } + + protected JavaMemberVariable translateGlobalVariable(VeraGlobalVariable obj) + { + return translateGlobalVariable(obj, translateCompUnitOf(obj)); + } + + protected JavaMemberVariable translateMemberVariable( + VeraMemberVariable obj, + JavaRawClass cls) + { + // check whether variable has already been translated + JavaMemberVariable var = (JavaMemberVariable) xlatObjMap + .getJavaObject(obj); + if (var != null) return var; + + final String clsID = cls.getName().getIdentifier(); + String id = obj.getName().getIdentifier(); + logEnter("Translating member variable: " + clsID + "." + id); + + try + { + // if this is a hand-translated class, just look up the field by name + if (!(cls instanceof TranslatedClass)) + { + try + { + var = cls.getField(id, cls); + } + catch (FieldNotFoundException e) + { + throw new RuntimeException( + "Manually translated field not found for '" + + obj.getName() + "' in '" + cls.getName() + "'"); + } + xlatObjMap.addJavaObject(obj, var); + return var; + } + + // get the analysis for this variable + final VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(obj); + + if (varAnalysis != null && !varAnalysis.isReadAccess()) + { + // suppress translation of unreferenced variables + // NOTE: unread (but assigned) variables could technically be + // suppressed as well, but that would involve translating their + // assignment expressions into statements + if (!varAnalysis.isWriteAccess()) + { + log("Warning: Suppressing translation of unreferenced field: " + + obj.getName()); + return null; + } + else + { + String msg = "Warning: Field '" + obj.getName() + + "' is never read"; + if (varAnalysis.isWriteSideEffects()) + { + msg += ", but assignment has side effects"; + } + log(msg); + } + } + + // determine Java variable visibility + JavaVisibility vis = translateMemberVisibility(obj.getVisibility()); + if (varAnalysis != null) + { + // determine strictest visibility based on usage analysis + // NOTE: private fields accessed from forks (which are translated + // to inner classes) are given default access to avoid synthetic + // accessor + final JavaVisibility genVis; + if (!varAnalysis.isFieldAccessOutsideClass() + && !varAnalysis.isForkRead() && !varAnalysis.isForkWrite()) + { + genVis = JavaVisibility.PRIVATE; + } + else if (!varAnalysis.isFieldAccessOutsideDirectory()) + { + genVis = JavaVisibility.DEFAULT; + } + else if (!varAnalysis.isFieldAccessOutsideSubClass()) + { + genVis = JavaVisibility.PROTECTED; + } + else + { + genVis = JavaVisibility.PUBLIC; + } + + if (genVis != vis) + { + log("Note: Changing visibility of field '" + obj.getName() + + "' from " + vis + " to " + genVis); + vis = genVis; + } + } + + // create the Java variable + id = fixID(id); + final VeraType veraType = obj.getType(); + final JavaType type = translateType(veraType, varAnalysis == null + || !varAnalysis.isNotAssignedXZ(), varAnalysis == null + || varAnalysis.isNeedStatefulString()); + var = new JavaMemberVariable(id, type); + var.addAnnotations(obj.getAnnotations()); + var.setVisibility(vis); + final Set veraModifiers = obj.getModifiers(); + final boolean isStatic = veraModifiers + .contains(VeraVariableModifier.STATIC); + if (isStatic) + { + var.addModifier(JavaVariableModifier.STATIC); + } + boolean needInit = true; + if (needsClone(type)) + { + // cloned variables are always final and initialized + var.addModifier(JavaVariableModifier.FINAL); + } + else if (!isStatic && varAnalysis != null + && !varAnalysis.isFieldUnassignedInCtor() + && !varAnalysis.isReadUnassigned() + && !classHasTransformedCtor(obj)) + { + if (varAnalysis.isWaitVar()) + { + // the wait_var checking code does not support final fields + // since they are uninitialized before the assignment (i.e. + // they have no old value that can be read); such code is + // nonsensical and should be fixed in Vera + log("Warning: Field '" + + obj.getName() + + "' is never changed" + + " and should be marked final, but is a wait_var target"); + } + else if (!varAnalysis.isFieldWriteOutsideCtor() + && !varAnalysis.isWriteAssigned()) + { + // instance variables assigned exactly once in ctor and not + // elsewhere, and not read when unassigned, can be marked as final + log("Note: Marking field '" + obj.getName() + "' as final"); + var.addModifier(JavaVariableModifier.FINAL); + needInit = false; + } + else + { + // variable is not final, but does not need to be + // initialized, since it is not read when unassigned and is + // assigned in the ctor + needInit = false; + } + } + if (obj.hasModifier(VeraVariableModifier.RANDC)) + { + // add Randc annotation + var.addAnnotation(new JavaAnnotation(types.randcType)); + addLengthAnnotation(var, type); + } + else if (obj.hasModifier(VeraVariableModifier.RAND)) + { + // add Rand annotation + var.addAnnotation(new JavaAnnotation(types.randType)); + addLengthAnnotation(var, type); + } + // TODO: packing modifiers + cls.addMember(var); + xlatObjMap.addJavaObject(obj, var); + + // translate initializer expression + VeraExpression veraInitExpr = obj.getInitializer(); + if (veraInitExpr != null) + { + ConvertedExpression convExpr = translateExpr(veraInitExpr, + null, cls, null, null, type, type); + convertInitializer(convExpr, type); + JavaExpression initExpr = convExpr.toMemberInitExpr(cls, var); + var.setInitializer(initExpr); + } + else if (needInit) + { + JavaExpression initExpr = getInitValue(type, false, false); + var.setInitializer(initExpr); + } + + // TODO: random size + assert (obj.getRandomSize() == null); + + // create wait_var event if necessary + checkWaitVarMember(obj, var, varAnalysis, cls, null); + + return var; + } + finally + { + logExit(); + } + } + + private void addLengthAnnotation(JavaVariable var, JavaType type) + { + if (type instanceof JoveBitVectorType) + { + // add Length annotation + final JavaAnnotation ann = new JavaAnnotation(types.lengthType); + final int len = ((JoveBitVectorType) type).getSize(); + ann.setElementValue("value", new JavaIntLiteral(schema, len)); + var.addAnnotation(ann); + } + } + + private boolean classHasTransformedCtor(VeraClassMember member) + { + VeraUserClass cls = (VeraUserClass) member.getStructuredType(); + ClassAnalysis analysis = analyzer.getClassAnalysis(cls); + return (analysis.needDefaultCtor() && !analysis.hasDefaultCtor()) + || analysis.transformSuperCall(); + } + + protected void checkWaitVarMember( + VeraVariable veraVar, + JavaMemberVariable javaVar, + VariableAnalysis varAnalysis, + JavaRawAbstractClass cls, + JavaClassMember assocMember) + { + if (varAnalysis != null && varAnalysis.isWaitVar()) + { + final VeraType veraType = veraVar.getType(); + final JavaType eventType = getWaitVarEventType(veraType); + final JavaMemberVariable eventVar = VarBuilder.createMemberVar(cls, + getEventVarID(veraVar), eventType); + JavaVisibility vis = javaVar.getVisibility(); + eventVar.setVisibility(vis); + if (javaVar.hasModifier(JavaVariableModifier.STATIC)) + { + eventVar.addModifier(JavaVariableModifier.STATIC); + } + eventVar.addModifier(JavaVariableModifier.FINAL); + eventVar.setInitializer(getInitValue(eventType, true, false)); + if (assocMember != null) + { + cls.addMemberBefore(eventVar, assocMember); + } + else + { + cls.addMember(eventVar); + } + xlatObjMap.addWaitVarEvent(javaVar, eventVar); + } + } + + private static JavaVisibility translateMemberVisibility(Visibility veraVis) + { + JavaVisibility vis; + if (veraVis == VeraVisibility.PUBLIC) + { + vis = JavaVisibility.PUBLIC; + } + else if (veraVis == VeraVisibility.PROTECTED) + { + vis = JavaVisibility.PROTECTED; + } + else + { + assert (veraVis == VeraVisibility.LOCAL); + vis = JavaVisibility.PRIVATE; + } + return vis; + } + + protected final JavaType getWaitVarEventType(VeraType veraType) + { + JavaType eventType = types.junoEventType; + if (veraType instanceof VeraArrayType) + { + eventType = TypeTranslator.translateArrayType(this, + (VeraArrayType) veraType, eventType); + } + return eventType; + } + + protected final JavaExpression getWaitVarEventRef(JavaExpression varRefExpr) + { + JavaExpression result = null; + if (hasMemberWaitVarEvent(varRefExpr)) + { + result = getMemberWaitVarEvent(varRefExpr); + } + else if (varRefExpr instanceof JavaVariableReference) + { + JavaVariableReference varRef = (JavaVariableReference) varRefExpr; + JavaVariable var = varRef.getVariable(); + JavaVariable eventVar = xlatObjMap.getWaitVarEvent(var); + if (eventVar != null) + { + result = new JavaVariableReference(eventVar); + } + } + else if (varRefExpr instanceof JavaMemberAccess) + { + JavaMemberAccess ma = (JavaMemberAccess) varRefExpr; + StructuredTypeMember member = ma.getMember(); + assert (member instanceof JavaMemberVariable); + JavaMemberVariable var = (JavaMemberVariable) member; + JavaVariable eventVar = xlatObjMap.getWaitVarEvent(var); + if (eventVar != null) + { + assert (eventVar instanceof JavaMemberVariable); + JavaExpression object = ma.getObject(); + result = new JavaMemberAccess(object, + (JavaMemberVariable) eventVar); + } + } + else if (varRefExpr instanceof JavaArrayAccess) + { + JavaArrayAccess aa = (JavaArrayAccess) varRefExpr; + JavaExpression arrayExpr = aa.getArray(); + JavaExpression arrayEventVar = getWaitVarEventRef(arrayExpr); + if (arrayEventVar != null) + { + if (arrayEventVar.getResultType() instanceof JavaArrayType) + { + // map wait_var on array elem to event array elem + JavaArrayAccess eventVarAccess = new JavaArrayAccess( + arrayEventVar); + Iterator iter = aa.getIndices().iterator(); + while (iter.hasNext()) + { + eventVarAccess.addIndex((JavaExpression) iter.next()); + } + result = eventVarAccess; + } + else + { + // map wait_var on ref holder to event var ref + result = arrayEventVar; + } + } + } + return result; + } + + protected final boolean hasMemberWaitVarEvent(JavaExpression varRefExpr) + { + return varRefExpr.getResultType() == types.junoStringType; + } + + protected final JavaExpression getMemberWaitVarEvent( + JavaExpression varRefExpr) + { + return ExpressionBuilder.memberCall(varRefExpr, "getChangeEvent"); + } + + protected JavaEnum translateEnum( + VeraEnumeration obj, + JavaPackage pkg, + JavaRawAbstractClass outerClass) + { + // check whether enumeration has already been translated + JavaEnum cls = (JavaEnum) xlatObjMap.getJavaObject(obj); + if (cls != null) return cls; + + final String id = obj.getName().getIdentifier(); + if (outerClass == null) + { + logEnter("Translating enumeration: " + id); + } + else + { + logEnter("Translating member enumeration: " + id); + } + + // create the Java class + cls = new JavaEnum(schema, fixID(id), pkg); + cls.addAnnotations(obj.getAnnotations()); + cls.setVisibility(JavaVisibility.PUBLIC); + cls.addBaseInterface(types.junoEnumType.parameterize(cls)); + xlatObjMap.addJavaObject(obj, cls); + + // handle class-scope enumeration + if (outerClass != null) + { + outerClass.addMember(cls); + } + else + { + pkg.addMember(cls); + } + + // define value field + final JavaMemberVariable valueVar = cls.newField("value", + schema.integerWrapperType); + valueVar.setVisibility(JavaVisibility.PRIVATE); + valueVar.addModifier(JavaVariableModifier.FINAL); + final JavaVariableReference valueVarRef = new JavaVariableReference( + valueVar); + + // define value ctor + { + final JavaConstructor ctor = cls.newConstructor(); + final JavaFunctionType ctorType = ctor.getType(); + final JavaFunctionArgument valueArg = new JavaFunctionArgument( + "value", schema.integerWrapperType); + ctorType.addArgument(valueArg); + final JavaBlock ctorBody = new JavaBlock(schema); + final JavaMemberAccess thisValueAccess = new JavaMemberAccess( + new JavaThisReference(cls), valueVar); + ctorBody.addMember(new JavaExpressionStatement(new JavaAssign( + schema, thisValueAccess, new JavaVariableReference(valueArg)))); + ctor.setBody(ctorBody); + } + + // create the UNDEFINED enumeration constant + final JavaMemberVariable undefinedVar = cls.newValue("UNDEFINED", + false, new JavaNullLiteral(schema)); + undefinedVar.addAnnotation(new JavaAnnotation(types.randExcludeType)); + + // translate the enumeration elements + final List elements = obj.getMembers(); + final int elemCount = elements.size(); + assert (elemCount > 0); + int largestValue = 1; + boolean negValue = false; + for (final VeraEnumerationElement elem : elements) + { + // create enumeration constant + final String elemID = elem.getName().getIdentifier(); + int intValue = elem.getValue(); + final JavaMemberVariable var = cls.newValue(fixID(elemID), false, + new JavaIntLiteral(schema, intValue)); + var.addAnnotations(elem.getAnnotations()); + xlatObjMap.addJavaObject(elem, var); + + // remember largest value and whether any values are negative + if (intValue < 0) + { + negValue = true; + intValue = -intValue; + } + if (intValue > largestValue) + { + largestValue = intValue; + } + } + + // implement next()/previous() methods + JavaFunction advanceFunc = types.junoEnumUtilType.getMethod("advance", + cls, schema.intType); + JavaFunctionReference advanceRef = new JavaFunctionReference( + advanceFunc); + + // implement next() + { + JavaFunction func = cls.newMethod("next", cls); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + JavaFunctionInvocation advanceCall = new JavaFunctionInvocation( + advanceRef); + advanceCall.addArgument(new JavaThisReference(cls)); + advanceCall.addArgument(new JavaIntLiteral(schema, 1)); + body.addMember(new JavaReturnStatement(schema, advanceCall)); + } + + // implement next(int) + { + JavaFunction func = cls.newMethod("next", cls); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaFunctionType funcType = func.getType(); + JavaFunctionArgument arg = funcType.newArgument("count", + schema.intType); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + JavaFunctionInvocation advanceCall = new JavaFunctionInvocation( + advanceRef); + advanceCall.addArgument(new JavaThisReference(cls)); + advanceCall.addArgument(new JavaVariableReference(arg)); + body.addMember(new JavaReturnStatement(schema, advanceCall)); + } + + // implement previous() + { + JavaFunction func = cls.newMethod("previous", cls); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + JavaFunctionInvocation advanceCall = new JavaFunctionInvocation( + advanceRef); + advanceCall.addArgument(new JavaThisReference(cls)); + advanceCall.addArgument(new JavaIntLiteral(schema, -1)); + body.addMember(new JavaReturnStatement(schema, advanceCall)); + } + + // implement previous(int) + { + JavaFunction func = cls.newMethod("previous", cls); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaFunctionType funcType = func.getType(); + JavaFunctionArgument arg = funcType.newArgument("count", + schema.intType); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + JavaFunctionInvocation advanceCall = new JavaFunctionInvocation( + advanceRef); + advanceCall.addArgument(new JavaThisReference(cls)); + advanceCall.addArgument(new JavaUnaryMinus(schema, + new JavaVariableReference(arg))); + body.addMember(new JavaReturnStatement(schema, advanceCall)); + } + + // implement forValue()/getForValue() + for (int i = 0; i < 2; ++i) + { + String funcID = i == 0 ? "forValue" : "getForValue"; + JavaFunction func = cls.newMethod(funcID, cls); + func.setVisibility(JavaVisibility.PUBLIC); + if (i == 0) func.addModifier(JavaFunctionModifier.STATIC); + + JavaFunctionType funcType = func.getType(); + JavaFunctionArgument valueArg = funcType.newArgument("value", + schema.integerWrapperType); + JavaFunctionArgument checkedArg = funcType.newArgument("checked", + schema.booleanType); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + JavaFunction forValueFunc = types.junoEnumUtilType.getMethod( + "forValue", schema.getClassType(), schema.integerWrapperType, + schema.booleanType); + JavaFunctionReference forValueRef = new JavaFunctionReference( + forValueFunc); + JavaFunctionInvocation forValueCall = new JavaFunctionInvocation( + forValueRef); + forValueCall.addArgument(new JavaTypeLiteral(cls)); + forValueCall.addArgument(new JavaVariableReference(valueArg)); + forValueCall.addArgument(new JavaVariableReference(checkedArg)); + body.addMember(new JavaReturnStatement(schema, forValueCall)); + } + + // implement getPackedSize() + { + JavaFunction func = cls.newMethod("getPackedSize", schema.intType); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + int packedSize = MathUtils.log2(largestValue) + 1; + if (negValue) ++packedSize; + body.addMember(new JavaReturnStatement(schema, new JavaIntLiteral( + schema, packedSize))); + } + + // implement isSigned() + { + JavaFunction func = cls.newMethod("isSigned", schema.booleanType); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + body.addMember(new JavaReturnStatement(schema, + new JavaBooleanLiteral(schema, negValue))); + } + + // implement isDefined() + { + JavaFunction func = cls.newMethod("isDefined", schema.booleanType); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + body.addMember(new JavaReturnStatement(schema, new JavaNotEqual( + schema, valueVarRef, new JavaNullLiteral(schema)))); + } + + // implement toInt() + { + JavaFunction func = cls.newMethod("toInt", schema.intType); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + body.addMember(new JavaReturnStatement(schema, valueVarRef)); + } + + // implement toInteger() + { + JavaFunction func = cls.newMethod("toInteger", + schema.integerWrapperType); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + body.addMember(new JavaReturnStatement(schema, valueVarRef)); + } + + // implement toString() + { + JavaFunction func = cls.newMethod("toString", schema + .getStringType()); + func.setVisibility(JavaVisibility.PUBLIC); + + JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + body.addMember(new JavaReturnStatement(schema, ExpressionBuilder + .staticCall(types.junoEnumUtilType, "toString", + new JavaThisReference(cls)))); + } + + logExit(); + return cls; + } + + protected JavaEnum translateEnum(VeraEnumeration obj) + { + return translateEnum(obj, translateCompUnitOf(obj), + translateClassOf(obj)); + } + + protected JavaMemberVariable translateEnumElement(VeraEnumerationElement obj) + { + JavaMemberVariable var = (JavaMemberVariable) xlatObjMap + .getJavaObject(obj); + if (var == null) + { + final VeraEnumeration veraEnum = obj.getEnumeration(); + final JavaEnum enumClass = translateEnum(veraEnum); + final String elemID = obj.getName().getIdentifier(); + var = enumClass.getField(elemID); + } + return var; + } + + protected JavaRawClass translatePort(VeraPortType obj, JavaPackage pkg) + { + // check whether port has already been translated + JavaRawClass cls = (JavaRawClass) xlatObjMap.getJavaObject(obj); + if (cls != null) return cls; + + String id = obj.getName().getIdentifier(); + logEnter("Translating port: " + id); + + // translate Vera port to Ifgen port + id = elaborateID(id, "Port"); + final IfgenPackage ifPkg = ifSchema.getPackage(pkg.getName() + .getCanonicalName(), true); + final IfgenName ifName = new IfgenName(id, IfgenNameKind.TYPE, ifPkg); + final IfgenPort ifPort = new IfgenPort(ifSchema, ifName); + ifPort.addAnnotations(obj.getAnnotations()); + ifPkg.addMember(ifPort); + xlatObjMap.addIfgenObject(obj, ifPort); + + // translate port signals + for (final VeraPortSignal signal : obj.getMembers()) + { + final String signalID = signal.getName().getIdentifier(); + final IfgenPortSignal ifSignal = new IfgenPortSignal(ifPort, + fixID(signalID), IfgenDirection.INOUT, false); + ifSignal.addAnnotations(signal.getAnnotations()); + ifPort.addMember(ifSignal); + xlatObjMap.addIfgenObject(signal, ifSignal); + } + + // translate Ifgen port to Java class + cls = ifgenXlat.translatePort(ifPort); + xlatObjMap.addJavaObject(obj, cls); + + // put translated signals in xlatObjMap + for (final VeraPortSignal signal : obj.getMembers()) + { + final IfgenPortSignal ifSignal = (IfgenPortSignal) xlatObjMap + .getIfgenObject(signal); + final JavaMemberVariable var = ifgenXlat + .translatePortSignal(ifSignal); + xlatObjMap.addJavaObject(signal, var); + } + + logExit(); + return cls; + } + + protected JavaRawClass translatePort(VeraPortType obj) + { + return translatePort(obj, translateCompUnitOf(obj)); + } + + protected JavaRawClass translateInterface( + VeraInterfaceType obj, + JavaPackage pkg) + { + // check whether interface has already been translated + JavaRawClass cls = (JavaRawClass) xlatObjMap.getJavaObject(obj); + if (cls != null) return cls; + + String id = obj.getName().getIdentifier(); + logEnter("Translating interface: " + id); + // translate Vera interface to Ifgen interface + id = elaborateID(id, "Interface", "intf"); + final IfgenPackage ifPkg = ifSchema.getPackage(pkg.getName() + .getCanonicalName(), true); + final IfgenName ifName = new IfgenName(id, IfgenNameKind.TYPE, ifPkg); + final IfgenInterface ifIntf = new IfgenInterface(ifSchema, ifName); + ifIntf.addAnnotations(obj.getAnnotations()); + ifPkg.addMember(ifIntf); + xlatObjMap.addIfgenObject(obj, ifIntf); + + // translate interface signals + // TODO: extrapolate default module prefix + HashMap sampleUsage = new HashMap(); + HashMap driveUsage = new HashMap(); + for (final VeraInterfaceSignal signal : obj.getMembers()) + { + final String signalID = signal.getName().getIdentifier(); + final VeraSignalKind kind = signal.getKind(); + final IfgenSignalType ifType; + if (kind == VeraSignalKind.CLOCK) + { + ifType = IfgenSignalType.CLOCK; + } + else + { + assert (kind == VeraSignalKind.NORMAL); + final VeraSignalDirection dir = signal.getDirection(); + switch (dir) + { + case INPUT: + ifType = IfgenSignalType.INPUT; + break; + case OUTPUT: + ifType = IfgenSignalType.OUTPUT; + break; + case INOUT: + ifType = IfgenSignalType.INOUT; + break; + default: + throw new AssertionError("Unknown direction: " + dir); + } + } + final int width = signal.getWidth(); + final IfgenInterfaceSignal ifSignal = new IfgenInterfaceSignal( + ifIntf, fixID(signalID), ifType, width); + ifSignal.addAnnotations(signal.getAnnotations()); + if (ifType.isInput() && ifType != IfgenSignalType.CLOCK) + { + final IfgenEdge edge = getIfgenEdge(signal.getSampleEdges()); + final int skew = signal.getSampleSkew(); + final IfgenSampleDef sampleDef = new IfgenSampleDef(ifSchema, + edge, skew); + ifSignal.setSample(sampleDef); + incUsage(sampleUsage, sampleDef); + ifSignal.setSampleDepth(signal.getSampleDepth() + 1); + } + if (ifType.isOutput()) + { + final IfgenEdge edge = getIfgenEdge(signal.getDriveEdges()); + final int skew = signal.getDriveSkew(); + final IfgenDriveDef driveDef = new IfgenDriveDef(ifSchema, + edge, skew); + ifSignal.setDrive(driveDef); + incUsage(driveUsage, driveDef); + } + final String node = signal.getHDLNode(); + if (node != null) + { + ifSignal.setHDLNode(new IfgenHDLSignalRef( + new IfgenStringLiteral(ifSchema, node))); + } + ifIntf.addMember(ifSignal); + xlatObjMap.addIfgenObject(signal, ifSignal); + } + + // insert default sample/drive specification + final IfgenSampleDef topSample = getTopUsage(sampleUsage); + if (topSample != null) + { + ifIntf.addMember(0, topSample); + } + final IfgenDriveDef topDrive = getTopUsage(driveUsage); + if (topDrive != null) + { + ifIntf.addMember(0, topDrive); + } + + // translate Ifgen interface to Java class + cls = ifgenXlat.translateInterface(ifIntf); + xlatObjMap.addJavaObject(obj, cls); + + // put translated signals in xlatObjMap + for (final VeraInterfaceSignal signal : obj.getMembers()) + { + final IfgenInterfaceSignal ifSignal = (IfgenInterfaceSignal) xlatObjMap + .getIfgenObject(signal); + final JavaMemberVariable var = ifgenXlat + .translateInterfaceSignal(ifSignal); + xlatObjMap.addJavaObject(signal, var); + } + + logExit(); + return cls; + } + + private IfgenEdge getIfgenEdge(EdgeSet edges) + { + final IfgenEdge edge; + if (edges.contains(EdgeSet.ANYEDGE)) + { + edge = IfgenEdge.ANYEDGE; + } + else if (edges.contains(EdgeSet.POSEDGE)) + { + edge = IfgenEdge.POSEDGE; + } + else if (edges.contains(EdgeSet.NEGEDGE)) + { + edge = IfgenEdge.NEGEDGE; + } + else + { + throw new AssertionError("Unexpected edge set: " + edges); + } + return edge; + } + + protected JavaRawClass translateInterface(VeraInterfaceType obj) + { + return translateInterface(obj, translateCompUnitOf(obj)); + } + + protected JavaMemberVariable translateInterfaceSignal( + VeraInterfaceSignal obj) + { + translateInterface(obj.getStructuredType()); + final JavaMemberVariable var = (JavaMemberVariable) xlatObjMap + .getJavaObject(obj); + assert (var != null); + return var; + } + + private IfgenInterfaceSignal getIfgenInterfaceSignal(VeraInterfaceSignal obj) + { + translateInterface(obj.getStructuredType()); + final IfgenInterfaceSignal signal = (IfgenInterfaceSignal) xlatObjMap + .getIfgenObject(obj); + assert (signal != null); + return signal; + } + + protected JavaMemberVariable translateBind( + VeraBindVariable obj, + JavaPackage pkg) + { + // check whether bind has already been translated + JavaMemberVariable var = (JavaMemberVariable) xlatObjMap + .getJavaObject(obj); + if (var != null) return var; + + String id = obj.getName().getIdentifier(); + logEnter("Translating bind: " + id); + + // get Ifgen port + final VeraPortType port = obj.getPort(); + translatePort(port); + final IfgenPort ifPort = (IfgenPort) xlatObjMap.getIfgenObject(port); + + // translate Vera bind to Ifgen bind + id = elaborateID(id, "Bind"); + final IfgenPackage ifPkg = ifSchema.getPackage(pkg.getName() + .getCanonicalName(), true); + final IfgenName ifName = new IfgenName(id, IfgenNameKind.EXPRESSION, + ifPkg); + final IfgenBind ifBind = new IfgenBind(ifSchema, ifName, ifPort); + ifBind.addAnnotations(obj.getAnnotations()); + ifPkg.addMember(ifBind); + xlatObjMap.addIfgenObject(obj, ifBind); + + // translate bind members + HashMap intfUsage = new HashMap(); + for (final VeraBindMember member : obj.getMembers()) + { + final VeraPortSignal portSignal = member.getPortSignal(); + final IfgenPortSignal ifPortSignal = (IfgenPortSignal) xlatObjMap + .getIfgenObject(portSignal); + final IfgenSignalRef ifSignalRef; + final VeraExpression veraExpr = member.getInterfaceExpr(); + if (veraExpr instanceof VeraVoidLiteral) + { + continue; + } + else if (veraExpr instanceof VeraConcatenation) + { + final VeraConcatenation veraConcat = (VeraConcatenation) veraExpr; + final IfgenConcatSignalRef ifConcat = new IfgenConcatSignalRef(); + for (final VeraExpression veraElem : veraConcat.getOperands()) + { + IfgenSignalRef elemRef = translateSignalRef(veraElem); + IfgenInterface intf = getSignalRefIntf(elemRef); + incUsage(intfUsage, intf); + ifConcat.addMember(elemRef); + } + ifSignalRef = ifConcat; + } + else + { + ifSignalRef = translateSignalRef(veraExpr); + IfgenInterface intf = getSignalRefIntf(ifSignalRef); + incUsage(intfUsage, intf); + } + final IfgenBindSignal ifBindSignal = new IfgenBindSignal(ifBind, + ifPortSignal, ifSignalRef); + ifBindSignal.addAnnotations(member.getAnnotations()); + ifBind.addMember(ifBindSignal); + } + + // insert default interface specification + final IfgenInterface topIntf = getTopUsage(intfUsage); + if (topIntf != null) + { + ifBind.addMember(0, new IfgenInterfaceDef(topIntf)); + } + + // translate Ifgen bind to Java member variable + try + { + var = ifgenXlat.translateBind(ifBind); + } + catch (IfgenTranslatorException e) + { + throw new RuntimeException(e); + } + xlatObjMap.addJavaObject(obj, var); + + logExit(); + return var; + } + + private static String elaborateID( + String id, + String suffix, + String... altPatterns) + { + final String lcID = id.toLowerCase(); + final String lcSuffix = suffix.toLowerCase(); + if (!lcID.contains(lcSuffix) && !containsAny(lcID, altPatterns)) + { + if (id.indexOf('_') < 0 + && Pattern.compile("[A-Z]").matcher(id).find()) + { + id = id + suffix; + } + else + { + id = id + "_" + lcSuffix; + } + } + else + { + id = fixID(id); + } + return id; + } + + private static boolean containsAny(String s, String[] subs) + { + for (String sub : subs) + { + if (s.contains(sub)) return true; + } + return false; + } + + private void incUsage(final Map usageMap, K key) + { + Integer oldCount = usageMap.get(key); + int newCount = (oldCount != null) ? oldCount + 1 : 1; + usageMap.put(key, newCount); + } + + private K getTopUsage(final Map usageMap) + { + int highCount = 0; + K highKey = null; + for (Map.Entry e : usageMap.entrySet()) + { + int count = e.getValue(); + if (count > highCount) + { + highCount = count; + highKey = e.getKey(); + } + } + return highKey; + } + + private IfgenSignalRef translateSignalRef(VeraExpression expr) + { + // extract signal reference and possibly bit range from expression + final VeraSignalReference veraSignalRef; + final VeraExpression veraHighBit, veraLowBit; + if (expr instanceof VeraBitSliceAccess) + { + VeraBitSliceAccess bsa = (VeraBitSliceAccess) expr; + veraSignalRef = (VeraSignalReference) bsa.getArray(); + VeraRange range = bsa.getRange(); + veraHighBit = range.getFrom(); + veraLowBit = range.getTo(); + } + else if (expr instanceof VeraArrayAccess) + { + VeraArrayAccess aa = (VeraArrayAccess) expr; + veraSignalRef = (VeraSignalReference) aa.getArray(); + List indices = aa.getIndices(); + assert (indices.size() == 1); + veraHighBit = (VeraExpression) indices.get(0); + veraLowBit = null; + } + else if (expr instanceof VeraSignalReference) + { + veraSignalRef = (VeraSignalReference) expr; + veraHighBit = null; + veraLowBit = null; + } + else + { + throw new RuntimeException("Unexpected expression type in bind: " + + expr); + } + + // translate the signal reference + VeraInterfaceSignal veraSignal = veraSignalRef.getSignal(); + IfgenInterfaceSignal ifSignal = getIfgenInterfaceSignal(veraSignal); + IfgenSignalRef signalRef = new IfgenInterfaceSignalRef(ifSignal); + + // check for partial signal reference + if (veraHighBit != null) + { + int highBit = evalIntExpr(veraHighBit); + int lowBit = (veraLowBit != null) ? evalIntExpr(veraLowBit) + : highBit; + signalRef = new IfgenSliceSignalRef(signalRef, highBit, lowBit); + } + + return signalRef; + } + + private IfgenInterface getSignalRefIntf(IfgenSignalRef ref) + { + if (ref instanceof IfgenSliceSignalRef) + { + IfgenSliceSignalRef sliceRef = (IfgenSliceSignalRef) ref; + ref = sliceRef.getSignal(); + } + if (ref instanceof IfgenInterfaceSignalRef) + { + IfgenInterfaceSignalRef intfRef = (IfgenInterfaceSignalRef) ref; + return intfRef.getSignal().getInterface(); + } + throw new AssertionError("Unexpected signal reference type: " + + ref.getClass()); + } + + private int evalIntExpr(VeraExpression expr) + { + final Integer result = VeraExpression + .toInteger(expr.evaluateConstant()); + if (result == null) + { + throw new RuntimeException("Integer expression expected: " + expr); + } + return result.intValue(); + } + + protected JavaMemberVariable translateBind(VeraBindVariable obj) + { + return translateBind(obj, translateCompUnitOf(obj)); + } + + protected JavaType translateType( + VeraType obj, + boolean allowXZ, + boolean statefulString) + { + TypeTranslator xlat = new TypeTranslator(this, allowXZ, statefulString); + obj.accept(xlat); + return xlat.getType(); + } + + protected JavaType translateType(VeraType obj) + { + return translateType(obj, true, true); + } + + protected JavaExpression getInitValue( + JavaType type, + boolean required, + boolean needFactory) + { + JavaExpression expr = null; + if (type instanceof JavaStructuredType) + { + if (type == schema.bitType) + { + expr = exprConv.getBitExpr(Bit.X); + } + else if (type instanceof JoveBitVectorType) + { + int size = ((JoveBitVectorType) type).getSize(); + expr = exprConv.getBitVectorExpr(size); + } + else if (type == types.junoStringType) + { + if (needFactory) + { + expr = new JavaVariableReference( + types.junoStringValueFactoryType.getField("INSTANCE")); + } + else + { + expr = ExpressionBuilder.newInstance(types.junoStringType); + } + } + else if (type == types.junoEventType) + { + if (needFactory) + { + expr = new JavaVariableReference( + types.junoEventValueFactoryType.getField("INSTANCE")); + } + else + { + expr = ExpressionBuilder.newInstance(types.junoEventType); + } + } + else if (exprConv.isEnum(type)) + { + JavaAbstractClass enumCls = (JavaAbstractClass) type; + expr = new JavaVariableReference(enumCls.getField("UNDEFINED")); + } + else if (type instanceof JoveAssocArrayType) + { + JoveAssocArrayType assocType = (JoveAssocArrayType) type; + JavaExpression initExpr = getInitValue(assocType + .getElementType(), true, true); + if (initExpr.getResultType() instanceof JavaNullType) + { + // avoid ambiguous method invocation + initExpr = new JavaCastExpression(types.objectType, + initExpr); + } + expr = ExpressionBuilder.newInstance(assocType, initExpr); + } + else if (type instanceof JoveFixedArrayType) + { + final JoveFixedArrayType arrayType = (JoveFixedArrayType) type; + final JavaArrayCreation newExpr = new JavaArrayCreation( + arrayType); + final int[] dimensions = arrayType.getDimensions(); + for (int i = 0; i < dimensions.length; ++i) + { + JavaIntLiteral dimExpr = new JavaIntLiteral(schema, + dimensions[i]); + newExpr.addDimension(dimExpr); + } + + final JavaType elemType = arrayType.getElementType(); + JavaExpression elemInitExpr = getInitValue(elemType, false, + true); + if (elemInitExpr != null) + { + if (elemInitExpr.getResultType() instanceof JavaNullType) + { + // avoid ambiguous method invocation + elemInitExpr = new JavaCastExpression(types.objectType, + elemInitExpr); + } + final JavaExpression[] args = { newExpr, elemInitExpr, + new JavaIntLiteral(schema, 0) }; + expr = ExpressionBuilder.checkDowncast(ExpressionBuilder + .staticCall(types.junoType, "initArray", args, null), + arrayType); + } + else + { + expr = newExpr; + } + } + else if (required) + { + expr = new JavaNullLiteral(schema); + } + } + else if (required) + { + if (type instanceof JavaDoubleType) + { + expr = new JavaDoubleLiteral(schema, 0); + } + else if (type instanceof JavaFPType) + { + expr = new JavaFloatLiteral(schema, 0); + } + else if (type instanceof JavaLongType) + { + expr = new JavaLongLiteral(schema, 0); + } + else if (type instanceof JavaIntegralType) + { + expr = new JavaIntLiteral(schema, 0); + } + else if (type instanceof JavaBooleanType) + { + expr = new JavaBooleanLiteral(schema, false); + } + else + { + expr = new JavaNullLiteral(schema); + } + } + return expr; + } + + protected JavaFunctor translateFunction(VeraFunction obj) + { + // check whether function has already been translated + JavaFunctor func = (JavaFunctor) xlatObjMap.getJavaObject(obj); + if (func != null) return func; + + // delegate translation based on function kind + if (obj instanceof VeraGlobalFunction) + { + func = translateGlobalFunction((VeraGlobalFunction) obj); + } + else + { + assert (obj instanceof VeraMemberFunction); + VeraMemberFunction memberFunc = (VeraMemberFunction) obj; + func = translateMemberFunctionOrCtor(memberFunc, + translateClassOf(memberFunc)); + } + return func; + } + + protected JavaVariable translateVariable(VeraVariable obj) + { + // check whether variable has already been translated + // (function arguments and local variables are found here) + JavaVariable var = (JavaVariable) xlatObjMap.getJavaObject(obj); + if (var != null) return var; + + // delegate translation based on variable kind + if (obj instanceof VeraGlobalVariable) + { + var = translateGlobalVariable((VeraGlobalVariable) obj); + } + else if (obj instanceof VeraMemberVariable) + { + VeraMemberVariable memberVar = (VeraMemberVariable) obj; + var = translateMemberVariable(memberVar, + translateClassOf(memberVar)); + } + else if (obj instanceof VeraBindVariable) + { + var = translateBind((VeraBindVariable) obj); + } + return var; + } + + protected JavaStructuredTypeMember translateMember( + VeraStructuredTypeMember obj) + { + // check whether member has already been translated + JavaStructuredTypeMember member = (JavaStructuredTypeMember) xlatObjMap + .getJavaObject(obj); + if (member != null) return member; + + // delegate translation based on member kind + if (obj instanceof VeraMemberFunction) + { + VeraMemberFunction memberFunc = (VeraMemberFunction) obj; + member = translateMemberFunction(memberFunc, + translateClassOf(memberFunc)); + } + else if (obj instanceof VeraMemberVariable) + { + VeraMemberVariable memberVar = (VeraMemberVariable) obj; + member = translateMemberVariable(memberVar, + translateClassOf(memberVar)); + } + else + { + assert (obj instanceof VeraPortSignal); + VeraPortSignal portSignal = (VeraPortSignal) obj; + VeraPortType port = portSignal.getStructuredType(); + translatePort(port); + member = (JavaMemberVariable) xlatObjMap.getJavaObject(obj); + assert (member != null); + } + return member; + } + + protected final ConvertedExpression translateExpr( + VeraExpression veraExpr, + TempBlockScope tempScope, + JavaStructuredType containingType, + VarInfoMap varInfoMap, + JavaLocalVariable returnVar, + JavaType promoteType, + JavaType desiredResultType, + boolean sampleAsync) + { + if (tempScope == null) tempScope = new TempBlockScope(); + ConvertedExpression result = new ConvertedExpression(schema, tempScope); + final VeraDefineReference defineRef = veraExpr + .getDefineRef(); + if (defineRef != null) + { + final VeraExpressionDefine define = defineRef.getDefine(); + final List veraArgExprs = defineRef.getArguments(); + List convExprs = null; + List javaArgExprs = null; + if (!veraArgExprs.isEmpty()) + { + convExprs = new ArrayList(veraArgExprs + .size()); + javaArgExprs = new ArrayList(veraArgExprs + .size()); + for (final VeraExpression veraArgExpr : veraArgExprs) + { + // TODO: handle define argument with side effects + final ConvertedExpression convExpr = translateExpr( + veraArgExpr, tempScope, containingType, varInfoMap, + returnVar, promoteType, desiredResultType, true); + convExprs.add(convExpr); + javaArgExprs.add(convExpr.getResultExpr()); + } + } + final JavaClassMember member = translateExpressionDefine(define, + javaArgExprs); + if (member != null) + { + final JavaExpression resultExpr; + if (member instanceof JavaMemberVariable) + { + resultExpr = new JavaVariableReference( + (JavaMemberVariable) member); + } + else + { + final JavaFunctionInvocation callExpr = new JavaFunctionInvocation( + new JavaFunctionReference((JavaFunction) member)); + if (convExprs != null) + { + for (final ConvertedExpression convExpr : convExprs) + { + callExpr.addArgument(convExpr + .mergeIntoResult(result)); + } + } + resultExpr = callExpr; + } + result.setResultExpr(resultExpr); + } + } + if (result.getResultExpr() == null) + { + ExpressionTranslator xlat = new ExpressionTranslator(this, + containingType, varInfoMap, returnVar, promoteType, + desiredResultType, result); + xlat.sampleAsync = sampleAsync; + veraExpr.accept(xlat); + } + return result; + } + + protected final ConvertedExpression translateExpr( + VeraExpression veraExpr, + TempBlockScope tempScope, + JavaStructuredType containingType, + VarInfoMap varInfoMap, + JavaLocalVariable returnVar, + JavaType promoteType, + JavaType desiredResultType) + { + return translateExpr(veraExpr, tempScope, containingType, varInfoMap, + returnVar, promoteType, desiredResultType, true); + } + + protected void convertInitializer( + ConvertedExpression convExpr, + JavaType type) + { + JavaExpression rhs = convExpr.getResultExpr(); + JavaType rhsType = rhs.getResultType(); + rhs = convertRHS(rhs, rhsType, type, true); + convExpr.setResultExpr(rhs); + } + + protected JavaExpression convertRHS( + JavaExpression rhs, + JavaType lhsType, + boolean initializing) + { + JavaType rhsType = rhs.getResultType(); + return convertRHS(rhs, rhsType, lhsType, initializing); + } + + protected boolean needRHSConversion(JavaType lhsType, JavaType rhsType) + { + return (!lhsType.equals(rhsType) && !lhsType.isAssignableFrom(rhsType)) + || schema.getBitVectorSize(lhsType) != schema + .getBitVectorSize(rhsType); + } + + protected JavaExpression convertRHS( + JavaExpression rhs, + JavaType rhsType, + JavaType lhsType, + boolean initializing) + { + // attempt type conversion if necessary + if (needRHSConversion(lhsType, rhsType)) + { + rhs = exprConv.toType(lhsType, rhs); + } + // otherwise clone object if necessary + else if (initializing) + { + if (needsClone(rhsType) + && (rhs instanceof JavaVariableReference || rhs instanceof JavaMemberAccess)) + { + rhs = getCloneExpr(rhs); + } + else if (rhsType instanceof JavaNullType && needsClone(lhsType)) + { + rhs = ExpressionBuilder.newInstance((JavaRawClass) lhsType); + } + } + return rhs; + } + + protected JavaExpression getCloneExpr(JavaExpression expr) + { + JavaType type = expr.getResultType(); + if (type instanceof JavaArrayType) + { + // (Foo[]) foo.clone() + return new JavaCastExpression(type, ExpressionBuilder.memberCall( + expr, "clone")); + } + else + { + // new Foo(foo) + return ExpressionBuilder.newInstance((JavaClass) type, expr); + } + } + + protected JavaExpression getNotExpr(JavaExpression expr) + { + assert (expr.getResultType() == schema.booleanType); + if (expr instanceof JavaLogicalNot) + { + return ((JavaLogicalNot) expr).getOperand(0); + } + else + { + return new JavaLogicalNot(schema, expr); + } + } + + public JavaExpression getEdgeExpr(EdgeSet e) + { + final String name; + final byte mask = e.getMask(); + switch (mask) + { + case EdgeSet.POSEDGE_MASK: + name = "POSEDGE"; + break; + case EdgeSet.NEGEDGE_MASK: + name = "NEGEDGE"; + break; + case EdgeSet.ANYEDGE_MASK: + name = "ANYEDGE"; + break; + case EdgeSet.MASK_01: + name = "EDGE_01"; + break; + case EdgeSet.MASK_0X: + name = "EDGE_0X"; + break; + case EdgeSet.MASK_10: + name = "EDGE_10"; + break; + case EdgeSet.MASK_1X: + name = "EDGE_1X"; + break; + case EdgeSet.MASK_X0: + name = "EDGE_X0"; + break; + case EdgeSet.MASK_X1: + name = "EDGE_X1"; + break; + case 0: + name = "NO_EDGE"; + break; + default: + name = null; + } + + JavaExpression edgeExpr; + if (name != null) + { + edgeExpr = new JavaVariableReference(types.edgeSetType + .getField(name)); + } + else + { + edgeExpr = ExpressionBuilder.newInstance(types.edgeSetType, + new JavaIntLiteral(schema, mask)); + } + return edgeExpr; + } + + protected void checkUpdate( + ConvertedExpression result, + JavaExpression oldValue, + JavaExpression newValue, + boolean primitive, + JavaExpression updateEvent) + { + JavaExpression changedExpr; + if (primitive) + { + changedExpr = new JavaNotEqual(schema, newValue, oldValue); + } + else + { + changedExpr = new JavaLogicalNot(schema, ExpressionBuilder + .staticCall(types.junoType, "equals", newValue, oldValue)); + } + + JavaExpression triggerCall = getTriggerCall(updateEvent); + JavaBlock triggerBlock = new JavaBlock(schema); + triggerBlock.addMember(new JavaExpressionStatement(triggerCall)); + + JavaIfStatement checkStmt = new JavaIfStatement(changedExpr, + triggerBlock); + result.addUpdateMember(checkStmt); + } + + private JavaExpression getTriggerCall(JavaExpression eventExpr) + { + JavaArrayType veraEventArrayType = schema.getArrayType( + types.junoEventType, 1); + JavaArrayInitializer eventsInitExpr = new JavaArrayInitializer( + veraEventArrayType); + eventsInitExpr.addElement(eventExpr); + JavaArrayCreation eventsExpr = new JavaArrayCreation(veraEventArrayType); + eventsExpr.setInitializer(eventsInitExpr); + JavaExpression triggerCall = ExpressionBuilder.staticCall( + types.junoType, "trigger", eventsExpr); + return triggerCall; + } + + protected JavaClassMember translateExpressionDefine( + VeraExpressionDefine obj, + List javaArgExprs, + JavaPackage pkg) + { + if (!obj.hasArguments()) + { + // check whether no-arg define has already been translated + JavaClassMember member = (JavaClassMember) xlatObjMap + .getJavaObject(obj); + if (member != null) return member; + + // check whether define value is imported from Verilog + if (obj.isVerilogImport()) + { + member = vlogImporter.translateDefine(obj); + if (member != null) xlatObjMap.addJavaObject(obj, member); + return member; + } + } + else + { + // cannot translate function macro without argument types + if (javaArgExprs == null) return null; + } + + // get containing class for translated define + final JavaRawClass cls = getClassForGlobal(obj, pkg); + + // get identifier of define + String id = obj.getName().getIdentifier(); + + // ensure identifier is not a Java keyword + id = fixID(id); + + // attempt to look up method for function define + VarInfoMap varInfoMap = null; + List argVarList = null; + if (obj.hasArguments()) + { + final JavaType[] argTypes = new JavaType[javaArgExprs.size()]; + int index = 0; + for (JavaExpression argExpr : javaArgExprs) + { + JavaType argType = argExpr.getResultType(); + // generalize argument type + if (argType instanceof JoveBitVectorType) + { + argType = schema.bitVectorType; + } + argTypes[index++] = argType; + } + + try + { + final JavaFunction method = cls.getMethod(id, argTypes, cls); + return method; + } + catch (MethodNotFoundException e) + { + // ignored + } + catch (AmbiguousMethodException e) + { + // ignored + } + + varInfoMap = new VarInfoMap(); + argVarList = new LinkedList(); + final List defArgs = obj.getArguments(); + index = 0; + for (VeraDefineArgument argDefn : defArgs) + { + VariableAnalysis varAnalysis = analyzer + .getVariableAnalysis(argDefn); + if (varAnalysis != null && varAnalysis.isWriteAccess()) + { + // cannot translate define with assignment to argument + return null; + } + String argID = argDefn.getName().getIdentifier(); + JavaType argType = argTypes[index]; + JavaFunctionArgument arg = new JavaFunctionArgument(argID, + argType); + varInfoMap.addInfo(new VarInfo(schema, argDefn, arg, false)); + argVarList.add(arg); + ++index; + } + } + + // translate expression + final VeraExpression veraExpr = obj.getExpression(); + final ConvertedExpression convExpr = translateExpr(veraExpr, null, cls, + varInfoMap, null, null, null); + JavaType type = convExpr.getResultExpr().getResultType(); + + // cannot translate defines for null expressions + if (type instanceof JavaNullType) return null; + + logEnter("Translating expression define: " + id); + + // translate visibility + final JavaVisibility vis = obj.getVisibility() == VeraVisibility.LOCAL + ? JavaVisibility.DEFAULT : JavaVisibility.PUBLIC; + + // generalize return type + if (type instanceof JoveBitVectorType) + { + type = schema.bitVectorType; + } + + // translate constant expression as variable, non-constant as function + JavaClassMember member; + if (!obj.hasArguments() && veraExpr.isConstant()) + { + // create Java static final member variable + final JavaMemberVariable var = new JavaMemberVariable(id, type); + var.addAnnotations(obj.getAnnotations()); + var.setVisibility(vis); + var.addModifier(JavaVariableModifier.STATIC); + var.addModifier(JavaVariableModifier.FINAL); + member = var; + + // set initializer + final JavaExpression initExpr = convExpr.toMemberInitExpr(cls, var); + var.setInitializer(initExpr); + } + else + { + // create Java static function + final JavaFunctionType funcType = new JavaFunctionType(type, + argVarList); + final JavaFunction func = new JavaFunction(id, funcType); + func.addAnnotations(obj.getAnnotations()); + func.setVisibility(vis); + func.addModifier(JavaFunctionModifier.STATIC); + member = func; + + // create function body + final JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + // inject statements from converted expression into body + final JavaExpression resultExpr = convExpr.toBlockExpr(body, + "result"); + assert (resultExpr != null); + + // add return statement at end of body + body.addMember(new JavaReturnStatement(schema, resultExpr)); + } + cls.addMember(member); + if (!obj.hasArguments()) xlatObjMap.addJavaObject(obj, member); + + logExit(); + return member; + } + + protected JavaClassMember translateExpressionDefine( + VeraExpressionDefine obj, + List javaArgExprs) + { + return translateExpressionDefine(obj, javaArgExprs, + translateCompUnitOf(obj)); + } + + protected JavaClassMember translateRangeDefine( + VeraRangeDefine obj, + JavaPackage pkg) + { + // range macros with arguments are not supported + if (obj.hasArguments()) return null; + + // check whether define has already been translated + JavaClassMember member = (JavaClassMember) xlatObjMap + .getJavaObject(obj); + if (member != null) return member; + + // check whether define value is imported from Verilog + if (obj.isVerilogImport()) + { + member = vlogImporter.translateDefine(obj); + if (member != null) xlatObjMap.addJavaObject(obj, member); + return member; + } + + // get containing class for translated define + final JavaRawClass cls = getClassForGlobal(obj, pkg); + + // get identifier of define + String id = obj.getName().getIdentifier(); + + // ensure identifier is not a Java keyword + id = fixID(id); + + // attempt to look up method for function define + VarInfoMap varInfoMap = null; + List argVarList = null; + + // translate expression + final VeraRange range = obj.getRange(); + final VeraExpression veraFromExpr = range.getFrom(); + final VeraExpression veraToExpr = range.getTo(); + final ConvertedExpression fromConvExpr = translateExpr(veraFromExpr, + null, cls, varInfoMap, null, null, schema.intType); + final ConvertedExpression toConvExpr = translateExpr(veraToExpr, null, + cls, varInfoMap, null, null, schema.intType); + + // check that range expressions are integral + final JavaType fromType = fromConvExpr.getResultExpr().getResultType(); + final JavaType toType = toConvExpr.getResultExpr().getResultType(); + if (!fromType.isIntegralConvertible() + || !toType.isIntegralConvertible()) return null; + + fromConvExpr.convertResultExpr(schema.intType, exprConv); + toConvExpr.convertResultExpr(schema.intType, exprConv); + + logEnter("Translating range define: " + id); + + // translate visibility + final JavaVisibility vis = obj.getVisibility() == VeraVisibility.LOCAL + ? JavaVisibility.DEFAULT : JavaVisibility.PUBLIC; + + // translate constant expression as variable, non-constant as function + if (veraFromExpr.isConstant() && veraToExpr.isConstant() + && fromConvExpr.isSimpleExpr() && toConvExpr.isSimpleExpr()) + { + // create Java static final member variable + final JavaMemberVariable var = new JavaMemberVariable(id, + types.bitRangeType); + var.addAnnotations(obj.getAnnotations()); + var.setVisibility(vis); + var.addModifier(JavaVariableModifier.STATIC); + var.addModifier(JavaVariableModifier.FINAL); + member = var; + + // set initializer + final JavaInstanceCreation rangeExpr = ExpressionBuilder + .newInstance(types.bitRangeType, fromConvExpr.getResultExpr(), + toConvExpr.getResultExpr()); + var.setInitializer(rangeExpr); + } + else + { + // create Java static function + final JavaFunctionType funcType = new JavaFunctionType( + types.bitRangeType, argVarList); + final JavaFunction func = new JavaFunction(id, funcType); + func.addAnnotations(obj.getAnnotations()); + func.setVisibility(vis); + func.addModifier(JavaFunctionModifier.STATIC); + member = func; + + // create function body + final JavaBlock body = new JavaBlock(schema); + func.setBody(body); + + // inject statements from converted expressions into body + final JavaExpression fromExpr = fromConvExpr.toBlockExpr(body, + "high"); + final JavaExpression toExpr = toConvExpr.toBlockExpr(body, "low"); + assert (fromExpr != null && toExpr != null); + + // add return statement at end of body + final JavaInstanceCreation rangeExpr = ExpressionBuilder + .newInstance(types.bitRangeType, fromExpr, toExpr); + body.addMember(new JavaReturnStatement(schema, rangeExpr)); + } + cls.addMember(member); + if (!obj.hasArguments()) xlatObjMap.addJavaObject(obj, member); + + logExit(); + return member; + } + + protected JavaClassMember translateRangeDefine(VeraRangeDefine obj) + { + return translateRangeDefine(obj, translateCompUnitOf(obj)); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TypeConversionException.java b/java/juno/src/com/newisys/schemabuilder/juno/TypeConversionException.java new file mode 100644 index 0000000..6648e50 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TypeConversionException.java @@ -0,0 +1,49 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +/** + * Internal exception thrown when there is no conversion to the desired type. + * + * @author Trevor Robinson + */ +class TypeConversionException + extends RuntimeException +{ + private static final long serialVersionUID = 3257005436652498994L; + + public TypeConversionException() + { + super(); + } + + public TypeConversionException(String message) + { + super(message); + } + + public TypeConversionException(Throwable cause) + { + super(cause); + } + + public TypeConversionException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/TypeTranslator.java b/java/juno/src/com/newisys/schemabuilder/juno/TypeTranslator.java new file mode 100644 index 0000000..7c6c396 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/TypeTranslator.java @@ -0,0 +1,231 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.Type; +import com.newisys.langschema.java.JavaRawClass; +import com.newisys.langschema.java.JavaType; +import com.newisys.langschema.jove.JoveAssocArrayType; +import com.newisys.langschema.jove.JoveFixedArrayType; +import com.newisys.langschema.vera.*; + +/** + * Schema translator for types. + * + * @author Trevor Robinson + */ +final class TypeTranslator + extends TranslatorModule + implements VeraTypeVisitor +{ + private final boolean allowXZ; + private final boolean statefulString; + private JavaType type; + + public TypeTranslator( + TranslatorModule xlatContext, + boolean allowXZ, + boolean statefulString) + { + super(xlatContext); + this.allowXZ = allowXZ; + this.statefulString = statefulString; + } + + public JavaType getType() + { + assert (type != null); + return type; + } + + static JavaType translateArrayType( + TranslatorModule module, + VeraArrayType arrayType, + JavaType elemType) + { + if (arrayType instanceof VeraAssocArrayType) + { + return TypeTranslator.translateAssocArrayType(module, + (VeraAssocArrayType) arrayType, elemType); + } + else if (arrayType instanceof VeraDynamicArrayType) + { + return TypeTranslator.translateDynamicArrayType(module, + (VeraDynamicArrayType) arrayType, elemType); + } + else + { + assert (arrayType instanceof VeraFixedArrayType); + return TypeTranslator.translateFixedArrayType( + (VeraFixedArrayType) arrayType, elemType); + } + } + + public void visit(VeraAssocArrayType obj) + { + JavaType elemType = translateType(obj.getElementType()); + type = translateAssocArrayType(this, obj, elemType); + } + + static JavaType translateAssocArrayType( + TranslatorModule module, + VeraAssocArrayType arrayType, + JavaType elemType) + { + Type[] indexTypes = arrayType.getIndexTypes(); + assert (indexTypes.length == 1); + JavaRawClass baseClass; + if (indexTypes[0] instanceof VeraStringType) + { + baseClass = module.types.stringObjectAssocArrayType; + } + else + { + assert (indexTypes[0] instanceof VeraBitVectorType); + baseClass = module.types.bitObjectAssocArrayType; + } + return new JoveAssocArrayType(baseClass, elemType); + } + + public void visit(VeraBitType obj) + { + if (allowXZ) + { + type = schema.bitType; + } + else + { + type = schema.booleanType; + } + } + + public void visit(VeraDynamicArrayType obj) + { + JavaType elemType = translateType(obj.getElementType()); + type = translateDynamicArrayType(this, obj, elemType); + } + + static JavaType translateDynamicArrayType( + TranslatorModule module, + VeraDynamicArrayType arrayType, + JavaType elemType) + { + Type[] indexTypes = arrayType.getIndexTypes(); + assert (indexTypes.length == 1); + return module.schema.getArrayType(elemType, 1); + } + + public void visit(VeraEnumeration obj) + { + type = translateEnum(obj); + } + + public void visit(VeraEventType obj) + { + type = types.junoEventType; + } + + public void visit(VeraFixedArrayType obj) + { + JavaType elemType = translateType(obj.getElementType()); + type = translateFixedArrayType(obj, elemType); + } + + static JavaType translateFixedArrayType( + VeraFixedArrayType arrayType, + JavaType elemType) + { + int[] dimensions = arrayType.getDimensions(); + return new JoveFixedArrayType(elemType, dimensions); + } + + public void visit(VeraFixedBitVectorType obj) + { + VeraDefineReference defineRef = obj.getDefineRef(); + String typeDefID = null; + if (defineRef != null) + { + typeDefID = defineRef.getDefine().getName().getIdentifier(); + } + type = schema.getBitVectorType(obj.getSize(), typeDefID); + } + + public void visit(VeraFunctionType obj) + { + // function types are not directly translated + assert false; + } + + public void visit(VeraIntegerType obj) + { + if (allowXZ) + { + type = schema.integerWrapperType; + } + else + { + type = schema.intType; + } + } + + public void visit(VeraInterfaceType obj) + { + type = translateInterface(obj); + } + + public void visit(VeraMagicType obj) + { + type = schema.getObjectType(); + } + + public void visit(VeraNullType obj) + { + type = schema.nullType; + } + + public void visit(VeraPortType obj) + { + type = translatePort(obj); + } + + public void visit(VeraStringType obj) + { + type = statefulString ? types.junoStringType : schema.getStringType(); + } + + public void visit(VeraSystemClass obj) + { + assert (obj == obj.getVeraSchema().rootClass); + type = types.junoObjectType; + } + + public void visit(VeraUnsizedBitVectorType obj) + { + type = schema.bitVectorType; + } + + public void visit(VeraUserClass obj) + { + type = translateClass(obj, false); + } + + public void visit(VeraVoidType obj) + { + type = schema.voidType; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/VarBuilder.java b/java/juno/src/com/newisys/schemabuilder/juno/VarBuilder.java new file mode 100644 index 0000000..c86961b --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/VarBuilder.java @@ -0,0 +1,79 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.Iterator; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.Scope; +import com.newisys.langschema.java.JavaLocalVariable; +import com.newisys.langschema.java.JavaMemberVariable; +import com.newisys.langschema.java.JavaNameKind; +import com.newisys.langschema.java.JavaRawAbstractClass; +import com.newisys.langschema.java.JavaType; + +/** + * Provides utility methods for creating new Java variable declarations. + * + * @author Trevor Robinson + */ +final class VarBuilder +{ + public static JavaLocalVariable createLocalVar( + Scope localScope, + String id, + JavaType type) + { + id = uniquifyID(localScope, id, JavaNameKind.EXPRESSION); + JavaLocalVariable var = new JavaLocalVariable(id, type); + return var; + } + + public static JavaMemberVariable createMemberVar( + JavaRawAbstractClass cls, + String id, + JavaType type) + { + id = uniquifyID(cls, id, JavaNameKind.EXPRESSION); + JavaMemberVariable var = new JavaMemberVariable(id, type); + return var; + } + + public static String uniquifyID(Scope scope, String id, NameKind kind) + { + String curID = id; + if (containsID(scope, curID, kind)) + { + boolean endsWithDigit = Character.isDigit(id + .charAt(id.length() - 1)); + int nextCount = 2; + do + { + curID = id + (endsWithDigit ? "_" : "") + nextCount++; + } + while (containsID(scope, curID, kind)); + } + return curID; + } + + public static boolean containsID(Scope scope, String id, NameKind kind) + { + Iterator iter = scope.lookupObjects(id, kind); + return iter.hasNext(); + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/VarInfo.java b/java/juno/src/com/newisys/schemabuilder/juno/VarInfo.java new file mode 100644 index 0000000..82d9200 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/VarInfo.java @@ -0,0 +1,85 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import com.newisys.langschema.java.JavaArrayAccess; +import com.newisys.langschema.java.JavaExpression; +import com.newisys.langschema.java.JavaIntLiteral; +import com.newisys.langschema.java.JavaSchema; +import com.newisys.langschema.java.JavaVariable; +import com.newisys.langschema.java.JavaVariableReference; +import com.newisys.langschema.vera.VeraVariable; + +/** + * Represents translation information for a particular Vera variable. + * Used for dealing with holder variables when translating by-reference + * arguments. + * + * @author Trevor Robinson + */ +final class VarInfo +{ + final JavaSchema schema; + final VeraVariable veraVar; + final JavaVariable targetVar; + final boolean holderVar; + + public VarInfo( + JavaSchema schema, + VeraVariable veraVar, + JavaVariable targetVar, + boolean holderVar) + { + this.schema = schema; + this.veraVar = veraVar; + this.targetVar = targetVar; + this.holderVar = holderVar; + } + + public JavaVariable getTargetVar() + { + return targetVar; + } + + public boolean isHolderVar() + { + return holderVar; + } + + public JavaExpression getReference() + { + JavaVariableReference varRef = new JavaVariableReference(targetVar); + if (holderVar) + { + JavaArrayAccess varAccess = new JavaArrayAccess(varRef); + varAccess.addIndex(new JavaIntLiteral(schema, 0)); + return varAccess; + } + else + { + return varRef; + } + } + + public JavaExpression getHolderReference() + { + assert (holderVar); + JavaVariableReference varRef = new JavaVariableReference(targetVar); + return varRef; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/VarInfoMap.java b/java/juno/src/com/newisys/schemabuilder/juno/VarInfoMap.java new file mode 100644 index 0000000..056f617 --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/VarInfoMap.java @@ -0,0 +1,77 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.util.HashMap; +import java.util.Map; + +import com.newisys.langschema.java.JavaVariable; +import com.newisys.langschema.vera.VeraVariable; + +/** + * Provides a chainable mapping of Vera and Java variables to VarInfo objects + * describing the translation of by-reference holder variables. + * + * @author Trevor Robinson + */ +final class VarInfoMap +{ + private final Map veraMap = new HashMap(); + private final Map targetMap = new HashMap(); + private final VarInfoMap parent; + + public VarInfoMap() + { + this.parent = null; + } + + public VarInfoMap(VarInfoMap parentMap) + { + this.parent = parentMap; + } + + public void addInfo(VarInfo info) + { + veraMap.put(info.veraVar, info); + targetMap.put(info.targetVar, info); + } + + public VarInfo getInfo(VeraVariable var) + { + VarInfoMap cur = this; + while (cur != null) + { + VarInfo info = cur.veraMap.get(var); + if (info != null) return info; + cur = cur.parent; + } + return null; + } + + public VarInfo getInfo(JavaVariable var) + { + VarInfoMap cur = this; + while (cur != null) + { + VarInfo info = cur.targetMap.get(var); + if (info != null) return info; + cur = cur.parent; + } + return null; + } +} diff --git a/java/juno/src/com/newisys/schemabuilder/juno/VerilogImporter.java b/java/juno/src/com/newisys/schemabuilder/juno/VerilogImporter.java new file mode 100644 index 0000000..6d1192f --- /dev/null +++ b/java/juno/src/com/newisys/schemabuilder/juno/VerilogImporter.java @@ -0,0 +1,185 @@ +/* + * Juno - OpenVera (TM) to Jove Translator + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.juno; + +import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.newisys.langschema.BlankLine; +import com.newisys.langschema.BlockComment; +import com.newisys.langschema.java.*; +import com.newisys.langschema.java.util.ExpressionBuilder; +import com.newisys.langschema.jove.JoveSchema; +import com.newisys.langschema.vera.VeraBitVectorType; +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraExpression; +import com.newisys.langschema.vera.VeraExpressionDefine; +import com.newisys.langschema.vera.VeraIntegerType; +import com.newisys.langschema.vera.VeraRangeDefine; +import com.newisys.langschema.vera.VeraType; + +/** + * Used to provide dynamic access to #defines included from Verilog files. + * + * @author Trevor Robinson + */ +final class VerilogImporter +{ + private final JoveSchema schema; + private final PackageNamer packageNamer; + private final SchemaTypes types; + + private final Map files = new LinkedHashMap(); + private JavaRawClass importCls; + private JavaVariableReference definesVarRef; + + public VerilogImporter( + JoveSchema schema, + PackageNamer packageNamer, + SchemaTypes types) + { + this.schema = schema; + this.packageNamer = packageNamer; + this.types = types; + } + + private void createImportClass() + { + if (importCls != null) return; + + // create public final class + final String pkgName = packageNamer.getExternalPackage(); + final JavaPackage pkg = schema.getPackage(pkgName, true); + final JavaRawClass cls = new JavaRawClass(schema, "VerilogImports", pkg); + cls.setBaseClass(types.objectType); + cls.setVisibility(JavaVisibility.PUBLIC); + cls.addModifier(JavaTypeModifier.FINAL); + pkg.addMember(cls); + importCls = cls; + + // create empty private ctor to prevent instantiation + final JavaConstructor ctor = cls.newConstructor(); + ctor.setVisibility(JavaVisibility.PRIVATE); + ctor.setBody(new JavaBlock(schema)); + + // add defines field (and leave default access) + final JavaMemberVariable definesVar = cls.newField("defines", + types.definesType); + definesVar.addModifier(JavaVariableModifier.STATIC); + definesVar.addModifier(JavaVariableModifier.FINAL); + definesVar.setInitializer(ExpressionBuilder + .newInstance(types.definesType)); + definesVarRef = new JavaVariableReference(definesVar); + } + + private JavaMemberVariable createVar( + String srcPath, + String id, + JavaType type) + { + createImportClass(); + + final File srcFile = new File(srcPath); + final String srcName = srcFile.getName(); + final JavaMemberVariable prevVar = files.get(srcName); + if (prevVar == null) + { + // add static initializer block for reading defines file + JavaInitializerBlock initBlock = new JavaInitializerBlock(schema, + true); + initBlock + .addAnnotation(new BlockComment(" Imports from " + srcName)); + initBlock.addAnnotation(BlankLine.LEADING); + initBlock.addMember(new JavaExpressionStatement(ExpressionBuilder + .memberCall(definesVarRef, "readFile", new JavaStringLiteral( + schema, srcName)))); + importCls.addMember(initBlock); + } + + // create field for define + final JavaMemberVariable var = new JavaMemberVariable(TranslatorModule + .fixID(id), type); + var.setVisibility(JavaVisibility.PUBLIC); + var.addModifier(JavaVariableModifier.STATIC); + var.addModifier(JavaVariableModifier.FINAL); + final String methodID; + if (type instanceof JavaIntType) + methodID = "getInt"; + else if (type instanceof JavaLongType) + methodID = "getLong"; + else if (schema.isBitVector(type)) + methodID = "getBitVector"; + else if (type == types.bitRangeType) + methodID = "getBitRange"; + else + throw new AssertionError("Unexpected Verilog define type: " + type); + var.setInitializer(ExpressionBuilder.memberCall(definesVarRef, + methodID, new JavaStringLiteral(schema, id))); + + // add field to class after previous field from same file + if (prevVar == null) + { + importCls.addMember(var); + } + else + { + importCls.addMemberAfter(var, prevVar); + } + files.put(srcName, var); + + return var; + } + + public JavaMemberVariable translateDefine(VeraExpressionDefine define) + { + assert (define.isVerilogImport() && !define.hasArguments()); + final VeraCompilationUnit compUnit = define.getCompilationUnit(); + final String srcPath = compUnit.getSourcePath(); + final String id = define.getName().getIdentifier(); + final VeraExpression expr = define.getExpression(); + final VeraType veraType = expr.getResultType(); + final JavaType type; + if (veraType instanceof VeraIntegerType) + { + type = schema.intType; + } + else if (veraType instanceof VeraBitVectorType) + { + type = schema.bitVectorType; + } + else + { + throw new AssertionError("Unexpected Verilog define type: " + + veraType); + } + final JavaMemberVariable var = createVar(srcPath, id, type); + return var; + } + + public JavaMemberVariable translateDefine(VeraRangeDefine define) + { + assert (define.isVerilogImport() && !define.hasArguments()); + final VeraCompilationUnit compUnit = define.getCompilationUnit(); + final String srcPath = compUnit.getSourcePath(); + final String id = define.getName().getIdentifier(); + final JavaMemberVariable var = createVar(srcPath, id, + types.bitRangeType); + return var; + } +} diff --git a/java/juno/test/test.vr b/java/juno/test/test.vr new file mode 100644 index 0000000..ff6f9c7 --- /dev/null +++ b/java/juno/test/test.vr @@ -0,0 +1,119 @@ +#define macro96 82 +#define macro9 9 +#define macrofunc(a,b) a/**/b + +#define macro1 42 +#define macro2 macro1 +#define macro3 macro1 + mac/**/ro2 +#undef macro1 +#define macro1 52 + +class a +{ + integer x = 6; + integer y; + + task new(integer i) { y = i; } +} + +extern class x extends a +{ + integer x = 666; + rand integer z[] assoc_size 666; +} + +class x extends a(7) +{ + integer x = super.x; + rand integer z[] assoc_size 8; + + task foo() + { + printf("%0d\n", y); + } +} + +extern class j +{ + static integer j; +} + +#include + +enum Bar = red=10,blue; // Enums have global scope + +class j +{ + static integer j = 3; + + x x = new; + + task new() + { + printf("%0d\n", j); + } + + task foo(integer foo = 5) + { + printf("%0d\n", foo); + if (foo == 4) this.foo(*); + else bar(); + } + + task bar(); +} + +task j::bar() +{ + integer i, j; + x x = new; + a a = new x; + string s = "bar"; + void = x.randomize(); + printf("%0d\n", x.x); + printf("%0d\n", this.j); + printf("%0d\n", assoc_index(CHECK, x.z)); + printf("%0d\n", s.len()); + fork + repeat (this.j) printf("%s\n", s); + { + integer count = 2; + while (--count > 0) + for (i = 0, j = i; i < 4 && j < 8; ++i, j += 2) { + printf("%0d%0d", i, j); + } + } + join all + printf("\n"); + randcase { + 0: { printf("impossible\n"); } + this.j: printf("possible\n"); + } +} + +function bit[1+2+3:0] ugh() +{ + ugh = 4'b01zx; +} + +program main +{ + { + integer j = 2; + j foo; + { + integer j = 1; + { + integer j = 0; + printf("%0d\n", j); + } + printf("%0d\n", j); + } + printf("%0d\n", j); + foo = new; + foo.foo(4); + } + printf("%0d\n", macrofunc(macro9,6)); + printf("%0d\n", macro1); + printf("%0d\n", macro3); +} diff --git a/java/juno/test/testpp.vr b/java/juno/test/testpp.vr new file mode 100644 index 0000000..cd73aeb --- /dev/null +++ b/java/juno/test/testpp.vr @@ -0,0 +1,148 @@ +/* +VeraParser.jj - JavaCC parser definition for the Vera language +Copyright (C) 2003 Trevor A. Robinson + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +// #include + +#include "testpp2.vr" + +// #include using object macro + +#define TESTPP2 "testpp2.vr" +#include TESTPP2 + +// #include using function macro + +#define TESTPP2_EXT(ext) "testpp2.ext" +#include TESTPP2_EXT(vr) + +// #ifdef / #else / #endif + +#define TRUE +// 0/0 +show1 +#ifdef TRUE // 1/0 +show2 + #ifdef TRUE // 2/0 +show3 + #ifdef FALSE // 3/1 +#include "testpp2.vr" +hide0 + #ifdef TRUE // 4/2 +hide1 + #else // 4/2 +hide2 + #endif // 3/1 +hide3 + #else // 3/0 +show4 + #endif // 2/0 +show5 + #else // 2/1 +hide4 + #endif // 1/0 +show6 +#endif // 0/0 +show7 + +#define mo 0 +#define mo1 1 +#define mo2 2 +#define mo1mo2 3 + +// argument references separated by comment achieves token pasting + +#define mf(a,b) a/**/b b +mf(mo1,mo2) // -> 3 2 (gcc -> 1 2 2) +#undef mf + +#define mf(a,b) a/*foo*/b b +mf(mo1,mo2) // -> 3 2 (gcc -> 1 2 2) +#undef mf + +#define mf(a,b) a/* +*/b b +mf(mo1,mo2) // -> 3 2 (gcc -> 1 2 2) +#undef mf + +// no token pasting if whitespace around comment + +#define mf(a,b) a /**/ b b +mf(mo1,mo2) // -> 1 2 2 (gcc -> 1 2 2) +#undef mf + +#define mf(a,b) a/**/ b b +mf(mo1,mo2) // -> 1 2 2 (gcc -> 1 2 2) +#undef mf + +#define mf(a,b) a /**/b b +mf(mo1,mo2) // -> 1 2 2 (gcc -> 1 2 2) +#undef mf + +// no argument prescan; can construct function macro expansion in macro + +#define mf(a,b) a/**/b b +#define mf2(a,b) a b +mf2(mf,(mo1,mo2)) // -> 3 2 (gcc -> 1 2 2) +#undef mf +#undef mf2 + +// recursive expansion supported by expanding function before arguments + +#define mf(x) x x +mf(mf(1)) // -> 1 1 1 1 (gcc -> 1 1 1 1) +#undef mf + +#define mf(x) "x x" +mf(mf(1)) // -> "mf(1) mf(1)" (gcc -> "x x") +#undef mf + +// token pasting works in object macros as well + +#define mo1mo1 mo/**/1 +mo1mo1 // -> 1 (gcc -> 0 1) + +// function macro expansion has precedence over tokenization + +#define mo1mf() ugh +#define mf() mo1 +mf()mf() // -> ugh (gcc -> 1 1) +#undef mf +#undef mo1mf + +// stringification; no argument prescan/recursive expansion + +#define mf(a) "a" +mf(mo1) // -> "mo1" +#undef mf + +// stringification and token pasting + +#define mf(a,b) "a/**/b" +mf(mo1,mo2) // -> "mo1/**/mo2" +#undef mf + +#define mf(a,b) "a"/**/"b" +mf(mo1,mo2) // -> "mo1""mo2" +#undef mf + +// stringification occurs only for macro arguments + +#define mf(a) "a/**/mo2" +mf(mo1) // -> "mo1/**/mo2" +#undef mf diff --git a/java/juno/test/testpp2.vr b/java/juno/test/testpp2.vr new file mode 100644 index 0000000..ab035aa --- /dev/null +++ b/java/juno/test/testpp2.vr @@ -0,0 +1 @@ +testpp2 diff --git a/java/langschema-vera/build.xml b/java/langschema-vera/build.xml new file mode 100644 index 0000000..d0e9636 --- /dev/null +++ b/java/langschema-vera/build.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/langschema-vera/manifest.mf b/java/langschema-vera/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/langschema-vera/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAdd.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAdd.java new file mode 100644 index 0000000..620dbc1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAdd.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera addition operation. + * + * @author Trevor Robinson + */ +public final class VeraAdd + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3618414921537173047L; + + public VeraAdd(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.add((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.add(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.xor(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAddSubAssignment.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAddSubAssignment.java new file mode 100644 index 0000000..42faa3a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAddSubAssignment.java @@ -0,0 +1,43 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera addition/subtraction assignment operations. + * + * @author Trevor Robinson + */ +public abstract class VeraAddSubAssignment + extends VeraAssignment +{ + public VeraAddSubAssignment(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.isIntegralConvertible() && type2.isIntegralConvertible(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAndReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAndReduction.java new file mode 100644 index 0000000..8dc4945 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAndReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-and operation. + * + * @author Trevor Robinson + */ +public final class VeraAndReduction + extends VeraReduction +{ + private static final long serialVersionUID = 3258133570026353974L; + + public VeraAndReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveAnd((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveAnd(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).ztox(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticAssignment.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticAssignment.java new file mode 100644 index 0000000..7bf0669 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticAssignment.java @@ -0,0 +1,43 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera arithmetic assignment operations. + * + * @author Trevor Robinson + */ +public abstract class VeraArithmeticAssignment + extends VeraAssignment +{ + public VeraArithmeticAssignment(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.isStrictIntegral() && type2.isIntegralConvertible(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticNegative.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticNegative.java new file mode 100644 index 0000000..1678e98 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArithmeticNegative.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera arithmetic negation operation. + * + * @author Trevor Robinson + */ +public final class VeraArithmeticNegative + extends VeraUnaryArithmeticOperation +{ + private static final long serialVersionUID = 3257288041289824306L; + + public VeraArithmeticNegative(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.negate((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).negate(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).ztox(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayAccess.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayAccess.java new file mode 100644 index 0000000..5492085 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayAccess.java @@ -0,0 +1,85 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.ArrayAccess; + +/** + * Represents a Vera array access expression. + * + * @author Trevor Robinson + */ +public final class VeraArrayAccess + extends VeraExpression + implements ArrayAccess +{ + private static final long serialVersionUID = 3545518417425020721L; + + private final VeraExpression arrayExpr; + private final List indices = new LinkedList(); + + public VeraArrayAccess(VeraExpression array) + { + super(array.schema); + VeraType resultType = array.getResultType(); + if (resultType instanceof VeraArrayType) + { + VeraArrayType arrayType = (VeraArrayType) resultType; + setResultType(arrayType.getElementType()); + } + else + { + assert (resultType instanceof VeraBitVectorType); + setResultType(schema.bitType); + } + this.arrayExpr = array; + } + + public VeraExpression getArray() + { + return arrayExpr; + } + + public List getIndices() + { + return indices; + } + + public void addIndex(VeraExpression expr) + { + indices.add(expr); + } + + public boolean isAssignable() + { + return true; + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayCreation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayCreation.java new file mode 100644 index 0000000..ec756dc --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayCreation.java @@ -0,0 +1,82 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.List; + +import com.newisys.langschema.ArrayCreation; + +/** + * Represents a Vera array creation expression. + * + * @author Trevor Robinson + */ +public final class VeraArrayCreation + extends VeraExpression + implements ArrayCreation +{ + private static final long serialVersionUID = 3258407331174889523L; + + private final VeraDynamicArrayType type; + private final VeraExpression sizeExpr; + private VeraExpression sourceExpr; + + public VeraArrayCreation(VeraDynamicArrayType type, VeraExpression sizeExpr) + { + super(type.schema); + setResultType(type); + this.type = type; + this.sizeExpr = sizeExpr; + } + + public VeraDynamicArrayType getType() + { + return type; + } + + public List getDimensions() + { + return Collections.singletonList(sizeExpr); + } + + public VeraExpression getSizeExpr() + { + return sizeExpr; + } + + public VeraExpression getSourceExpr() + { + return sourceExpr; + } + + public void setSourceExpr(VeraExpression sourceExpr) + { + this.sourceExpr = sourceExpr; + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayInitializer.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayInitializer.java new file mode 100644 index 0000000..df15d9e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayInitializer.java @@ -0,0 +1,63 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.ArrayInitializer; + +/** + * Represents a Vera array initializer expression. + * + * @author Trevor Robinson + */ +public final class VeraArrayInitializer + extends VeraExpression + implements ArrayInitializer +{ + private static final long serialVersionUID = 4048796745229939504L; + + private final List elements = new LinkedList(); + + public VeraArrayInitializer(VeraArrayType type) + { + super(type.schema); + setResultType(type); + } + + public List getElements() + { + return elements; + } + + public void addElement(VeraExpression elem) + { + elements.add(elem); + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayType.java new file mode 100644 index 0000000..b153006 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraArrayType.java @@ -0,0 +1,90 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ArrayType; +import com.newisys.langschema.Type; + +/** + * Base class for Vera array types. + * + * @author Trevor Robinson + */ +public abstract class VeraArrayType + extends VeraType + implements ArrayType +{ + protected final VeraType elementType; + protected final VeraType[] indexTypes; + + public VeraArrayType(VeraType elementType, VeraType[] indexTypes) + { + super(elementType.schema); + this.elementType = elementType; + this.indexTypes = indexTypes; + } + + public VeraType getElementType() + { + return elementType; + } + + public VeraType[] getIndexTypes() + { + return indexTypes; + } + + public boolean equals(Object obj) + { + if (this.getClass() == obj.getClass()) + { + VeraArrayType other = (VeraArrayType) obj; + if (elementType.equals(other.elementType)) + { + if (indexTypes.length == other.indexTypes.length) + { + for (int i = 0; i < indexTypes.length; ++i) + { + if (!indexTypes[i].equals(other.indexTypes[i])) + { + return false; + } + } + return true; + } + } + } + return false; + } + + public int hashCode() + { + int h = getClass().hashCode() ^ elementType.hashCode(); + for (int i = 0; i < indexTypes.length; ++i) + { + h = (h * 37) ^ indexTypes[i].hashCode(); + } + return h; + } + + public boolean isAssignableFrom(Type other) + { + // array types must be identical + return equals(other); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssign.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssign.java new file mode 100644 index 0000000..ce4b2e6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssign.java @@ -0,0 +1,45 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssign + extends VeraAssignment +{ + private static final long serialVersionUID = 3689628094956844342L; + + public VeraAssign(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAdd.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAdd.java new file mode 100644 index 0000000..92effe2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAdd.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera addition-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignAdd + extends VeraAddSubAssignment +{ + private static final long serialVersionUID = 3256436989158308147L; + + public VeraAssignAdd(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAnd.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAnd.java new file mode 100644 index 0000000..98c70e7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAnd.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera and-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignAnd + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3258133548450920501L; + + public VeraAssignAnd(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAndNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAndNot.java new file mode 100644 index 0000000..33062a9 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignAndNot.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera and-not-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignAndNot + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3258128050926269745L; + + public VeraAssignAndNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignDivide.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignDivide.java new file mode 100644 index 0000000..56efa53 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignDivide.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera division-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignDivide + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3904961971156824627L; + + public VeraAssignDivide(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignLeftShift.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignLeftShift.java new file mode 100644 index 0000000..185b89d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignLeftShift.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera left-shift-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignLeftShift + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 4120846659782521137L; + + public VeraAssignLeftShift(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignModulo.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignModulo.java new file mode 100644 index 0000000..fb52050 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignModulo.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera modulo-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignModulo + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 4121136939509624888L; + + public VeraAssignModulo(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignMultiply.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignMultiply.java new file mode 100644 index 0000000..7082c17 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignMultiply.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera multiplication-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignMultiply + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3617008672002552629L; + + public VeraAssignMultiply(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOr.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOr.java new file mode 100644 index 0000000..05b3070 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOr.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera or-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignOr + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3617578201811859509L; + + public VeraAssignOr(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOrNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOrNot.java new file mode 100644 index 0000000..347df7a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignOrNot.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera or-not-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignOrNot + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 4049361919892599346L; + + public VeraAssignOrNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignRightShift.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignRightShift.java new file mode 100644 index 0000000..626251f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignRightShift.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera right-shift-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignRightShift + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3256439192476332597L; + + public VeraAssignRightShift(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignSubtract.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignSubtract.java new file mode 100644 index 0000000..9be2385 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignSubtract.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera subtraction-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignSubtract + extends VeraAddSubAssignment +{ + private static final long serialVersionUID = 4051041947873194032L; + + public VeraAssignSubtract(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXor.java new file mode 100644 index 0000000..95fc95e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXor.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera xor-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignXor + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3761127128481215799L; + + public VeraAssignXor(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXorNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXorNot.java new file mode 100644 index 0000000..c8b8193 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignXorNot.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera xor-not-assignment operation. + * + * @author Trevor Robinson + */ +public final class VeraAssignXorNot + extends VeraArithmeticAssignment +{ + private static final long serialVersionUID = 3257003237663323697L; + + public VeraAssignXorNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignment.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignment.java new file mode 100644 index 0000000..16148a6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssignment.java @@ -0,0 +1,52 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera assignment operations. + * + * @author Trevor Robinson + */ +public abstract class VeraAssignment + extends VeraBinaryOperation +{ + private static final long serialVersionUID = -8161227644812184570L; + + public VeraAssignment(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!op1.isAssignable()) + { + throw new SemanticException( + "Left-hand expression is not assignable"); + } + setResultType(schema.voidType); + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.isAssignableFrom(type2); + } + + public boolean isConstant() + { + return false; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssocArrayType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssocArrayType.java new file mode 100644 index 0000000..ba3b6c7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraAssocArrayType.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera associative array type. + * + * @author Trevor Robinson + */ +public final class VeraAssocArrayType + extends VeraArrayType +{ + private static final long serialVersionUID = 3256727290326103353L; + + public VeraAssocArrayType(VeraType elementType, VeraType indexType) + { + super(elementType, new VeraType[] { indexType }); + } + + public String toReferenceString() + { + return elementType + "[" + indexTypes[0] + "]"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryArithmeticOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryArithmeticOperation.java new file mode 100644 index 0000000..c42ab5d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryArithmeticOperation.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera binary arithmetic operations. + * + * @author Trevor Robinson + */ +public abstract class VeraBinaryArithmeticOperation + extends VeraBinaryOperation +{ + public VeraBinaryArithmeticOperation(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(getCommonIntegralType(op1, op2)); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryLogicalOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryLogicalOperation.java new file mode 100644 index 0000000..8a49c9f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryLogicalOperation.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera binary logical operations. + * + * @author Trevor Robinson + */ +public abstract class VeraBinaryLogicalOperation + extends VeraBinaryOperation +{ + public VeraBinaryLogicalOperation(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(schema.integerType); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryOperation.java new file mode 100644 index 0000000..053f5a3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBinaryOperation.java @@ -0,0 +1,49 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera binary operations. + * + * @author Trevor Robinson + */ +public abstract class VeraBinaryOperation + extends VeraOperation +{ + protected final VeraExpression op1; + protected final VeraExpression op2; + + public VeraBinaryOperation(VeraExpression op1, VeraExpression op2) + { + super(op1.schema); + this.op1 = op1; + operands.add(op1); + this.op2 = op2; + operands.add(op2); + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.isIntegralConvertible() && type2.isIntegralConvertible(); + } + + public boolean isConstant() + { + return op1.isConstant() && op2.isConstant(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindMember.java new file mode 100644 index 0000000..b18b9be --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindMember.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera signal bind member. + * + * @author Trevor Robinson + */ +public final class VeraBindMember + extends VeraSchemaObjectImpl +{ + private static final long serialVersionUID = 4050197535929152305L; + + private final VeraPortSignal portSignal; + private final VeraExpression interfaceExpr; + + public VeraBindMember( + VeraPortSignal portSignal, + VeraExpression interfaceExpr) + { + super(portSignal.schema); + this.portSignal = portSignal; + this.interfaceExpr = interfaceExpr; + } + + public VeraPortSignal getPortSignal() + { + return portSignal; + } + + public VeraExpression getInterfaceExpr() + { + return interfaceExpr; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "bind of " + portSignal.getName(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindVariable.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindVariable.java new file mode 100644 index 0000000..5cd46a6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBindVariable.java @@ -0,0 +1,85 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a Vera signal bind variable. This is simply the normal Vera bind + * construct. It is equivalent to a pre-initialized, unassignable, global + * variable of the given port type. + * + * @author Trevor Robinson + */ +public final class VeraBindVariable + extends VeraVariable + implements VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3258131370952898102L; + + private final VeraPortType port; + private final List members = new LinkedList(); + private VeraCompilationUnit compUnit; + + public VeraBindVariable(VeraName name, VeraPortType port) + { + super(name, port); + this.port = port; + } + + public VeraPortType getPort() + { + return port; + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraBindMember member) + { + members.add(member); + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitSliceAccess.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitSliceAccess.java new file mode 100644 index 0000000..1e238f1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitSliceAccess.java @@ -0,0 +1,68 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ArraySlice; + +/** + * Represents a Vera bit slice access expression. + * + * @author Trevor Robinson + */ +public final class VeraBitSliceAccess + extends VeraExpression + implements ArraySlice +{ + private static final long serialVersionUID = 3690198762949851445L; + + private final VeraExpression bitExpr; + private final VeraRange range; + + public VeraBitSliceAccess(VeraExpression bitExpr, VeraRange range) + { + super(bitExpr.schema); + setResultType(schema.bitVectorType); + this.bitExpr = bitExpr; + this.range = range; + } + + public VeraExpression getArray() + { + return bitExpr; + } + + public VeraRange getRange() + { + return range; + } + + public boolean isAssignable() + { + return true; + } + + public boolean isConstant() + { + return bitExpr.isConstant() && range.isConstant(); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitType.java new file mode 100644 index 0000000..df305c9 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitType.java @@ -0,0 +1,65 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents the Vera bit type. + * + * @author Trevor Robinson + */ +public final class VeraBitType + extends VeraPrimitiveType +{ + private static final long serialVersionUID = 3618136766570314036L; + + VeraBitType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + return other instanceof VeraBitType + || other instanceof VeraBitVectorType + || other instanceof VeraIntegerType + || other instanceof VeraEnumeration + || other instanceof VeraStringType; + } + + public boolean isStrictIntegral() + { + return true; + } + + public int getBitCount() + { + return 1; + } + + public String toReferenceString() + { + return "bit"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorLiteral.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorLiteral.java new file mode 100644 index 0000000..be75fff --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorLiteral.java @@ -0,0 +1,73 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Literal; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bit vector literal expression. + * + * @author Trevor Robinson + */ +public final class VeraBitVectorLiteral + extends VeraExpression + implements Literal +{ + private static final long serialVersionUID = 3618138961298731319L; + + private final BitVector value; + private int radix; + + public VeraBitVectorLiteral(VeraSchema schema, BitVector value) + { + super(schema); + setResultType(new VeraFixedBitVectorType(schema, value.length())); + this.value = value; + } + + public BitVector getValue() + { + return value; + } + + public int getRadix() + { + return radix; + } + + public void setRadix(int radix) + { + this.radix = radix; + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return value; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorType.java new file mode 100644 index 0000000..3a511e1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitVectorType.java @@ -0,0 +1,65 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Base class for Vera bit vector types. + * + * @author Trevor Robinson + */ +public abstract class VeraBitVectorType + extends VeraPrimitiveType +{ + // Vera 6.2 allows 65535 bits (not 65536!) + public static final int MAX_SIZE = 65535; + + public VeraBitVectorType(VeraSchema schema) + { + super(schema); + } + + public int getSize() + { + return -1; + } + + public boolean isAssignableFrom(Type other) + { + return other instanceof VeraBitVectorType + || other instanceof VeraBitType || other instanceof VeraIntegerType + || other instanceof VeraEnumeration + || other instanceof VeraStringType; + } + + public boolean isStrictIntegral() + { + return true; + } + + public int getBitCount() + { + return getSize(); + } + + public String toReferenceString() + { + return "bit[?:0]"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAnd.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAnd.java new file mode 100644 index 0000000..265ae14 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAnd.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-and operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseAnd + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3691039850740593465L; + + public VeraBitwiseAnd(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseAnd((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.and(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.and(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAndNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAndNot.java new file mode 100644 index 0000000..6ef62e0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseAndNot.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-and-not operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseAndNot + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3617851963027829296L; + + public VeraBitwiseAndNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseAndNot((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.and(bv2).not(); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.and(b2).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseNegative.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseNegative.java new file mode 100644 index 0000000..b43301e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseNegative.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-not operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseNegative + extends VeraUnaryArithmeticOperation +{ + private static final long serialVersionUID = 3258132436020835379L; + + public VeraBitwiseNegative(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.bitwiseNot((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).not(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOr.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOr.java new file mode 100644 index 0000000..99a999c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOr.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-or operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseOr + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 4051050765424472118L; + + public VeraBitwiseOr(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseOr((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.or(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.or(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOrNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOrNot.java new file mode 100644 index 0000000..bcc3fd0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseOrNot.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-or-not operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseOrNot + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3761685706174576183L; + + public VeraBitwiseOrNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseOrNot((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.or(bv2).not(); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.or(b2).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseReverse.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseReverse.java new file mode 100644 index 0000000..b269928 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseReverse.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-reversal operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseReverse + extends VeraUnaryArithmeticOperation +{ + private static final long serialVersionUID = 3258134643735081270L; + + public VeraBitwiseReverse(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.bitwiseReverse((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reverse(); + } + else + { + assert (o instanceof Bit); + return o; + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXor.java new file mode 100644 index 0000000..4e29021 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXor.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-xor operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseXor + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3905522705007980600L; + + public VeraBitwiseXor(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseXor((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.xor(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.xor(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXorNot.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXorNot.java new file mode 100644 index 0000000..5a9c781 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBitwiseXorNot.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera bitwise-xor-not operation. + * + * @author Trevor Robinson + */ +public final class VeraBitwiseXorNot + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3256439209639292977L; + + public VeraBitwiseXorNot(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.bitwiseXorNot((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.xor(bv2).not(); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.xor(b2).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlock.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlock.java new file mode 100644 index 0000000..9f51542 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlock.java @@ -0,0 +1,77 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.Block; +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.util.NameTable; + +/** + * Represents a Vera statement block. + * + * @author Trevor Robinson + */ +public final class VeraBlock + extends VeraStatementImpl + implements Block +{ + private static final long serialVersionUID = 3256439188113862705L; + + private final List members = new LinkedList(); + private final NameTable nameTable = new NameTable(); + + public VeraBlock(VeraSchema schema) + { + super(schema); + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraBlockMember member) + { + member.setContainingStatement(this); + members.add(member); + if (member instanceof NamedObject) + { + nameTable.addObject((NamedObject) member); + } + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "block (" + members.size() + " members)"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMember.java new file mode 100644 index 0000000..147c173 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMember.java @@ -0,0 +1,33 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.BlockMember; + +/** + * Interface implemented by Vera constructs that may be members of a block. + * + * @author Trevor Robinson + */ +public interface VeraBlockMember + extends BlockMember, VeraSchemaObject +{ + void setContainingStatement(VeraStatement stmt); + + void accept(VeraBlockMemberVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMemberVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMemberVisitor.java new file mode 100644 index 0000000..d6d0a8a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBlockMemberVisitor.java @@ -0,0 +1,29 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera block members. + * + * @author Trevor Robinson + */ +public interface VeraBlockMemberVisitor + extends VeraStatementVisitor +{ + void visit(VeraLocalVariable obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakStatement.java new file mode 100644 index 0000000..f4228af --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakStatement.java @@ -0,0 +1,54 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.BreakStatement; +import com.newisys.langschema.LabeledStatement; + +/** + * Represents a Vera break statement. + * + * @author Trevor Robinson + */ +public final class VeraBreakStatement + extends VeraStatementImpl + implements BreakStatement +{ + private static final long serialVersionUID = 3256722866426165303L; + + public VeraBreakStatement(VeraSchema schema) + { + super(schema); + } + + public LabeledStatement getTarget() + { + // Vera does not support labeled breaks + return null; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "break statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakpointStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakpointStatement.java new file mode 100644 index 0000000..edf2d7a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraBreakpointStatement.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera breakpoint statement. + * + * @author Trevor Robinson + */ +public final class VeraBreakpointStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3832902173951604791L; + + public VeraBreakpointStatement(VeraSchema schema) + { + super(schema); + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "breakpoint statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraCaseKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCaseKind.java new file mode 100644 index 0000000..47704ea --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCaseKind.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera case statement kinds. + * + * @author Trevor Robinson + */ +public enum VeraCaseKind +{ + NORMAL, X, Z; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraClass.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClass.java new file mode 100644 index 0000000..5a3d5a7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClass.java @@ -0,0 +1,117 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.Class; +import com.newisys.langschema.Interface; +import com.newisys.langschema.Type; + +/** + * Base class for Vera class types. + * + * @author Trevor Robinson + */ +public abstract class VeraClass + extends VeraStructuredType + implements Class +{ + private static final long serialVersionUID = 3570944955271123003L; + + protected boolean virtual; + protected VeraClass baseClass; + protected final List baseCtorArgs = new LinkedList(); + + public VeraClass(VeraSchema schema, VeraName name, VeraClass baseClass) + { + super(schema, name); + this.baseClass = baseClass; + } + + public Set getModifiers() + { + if (virtual) return Collections.singleton(VeraClassModifier.VIRTUAL); + return Collections.emptySet(); + } + + public boolean isVirtual() + { + return virtual; + } + + public List getBaseClasses() + { + return Collections.singletonList(baseClass); + } + + public VeraClass getBaseClass() + { + return baseClass; + } + + public List< ? extends Interface> getBaseInterfaces() + { + return Collections.emptyList(); + } + + public List getBaseCtorArgs() + { + return baseCtorArgs; + } + + public void addMember(VeraClassMember member) + { + assert (member.getStructuredType() == null); + member.setClass(this); + super.addMember(member); + } + + public boolean isAssignableFrom(Type other) + { + // quick check for identical or null type + if (other == this || other instanceof VeraNullType) + { + return true; + } + else if (other instanceof VeraClass) + { + // check whether this class is a superclass of the given class + return isSuperclassOf((VeraClass) other); + } + return false; + } + + public boolean isSuperclassOf(VeraClass other) + { + while (other != null) + { + if (other == this) return true; + other = other.getBaseClass(); + } + return false; + } + + public String toDebugString() + { + return "class " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassConstraint.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassConstraint.java new file mode 100644 index 0000000..39b7343 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassConstraint.java @@ -0,0 +1,77 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.NamedObject; + +/** + * Represents a Vera class random contraint set. + * + * @author Trevor Robinson + */ +public final class VeraClassConstraint + extends VeraConstraintSet + implements NamedObject, VeraClassMember +{ + private static final long serialVersionUID = 3257007674313880116L; + + private final VeraName name; + private VeraClass cls; + private boolean defined; + + public VeraClassConstraint(VeraSchema schema, VeraName name) + { + super(schema); + this.name = name; + } + + public VeraName getName() + { + return name; + } + + public VeraClass getStructuredType() + { + return cls; + } + + public void setClass(VeraClass cls) + { + this.cls = cls; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public boolean isDefined() + { + return defined; + } + + public void setDefined(boolean defined) + { + this.defined = defined; + } + + public void accept(VeraClassMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMember.java new file mode 100644 index 0000000..3e225b4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMember.java @@ -0,0 +1,33 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ClassMember; + +/** + * Interface implemented by Vera constructs that may be members of a class. + * + * @author Trevor Robinson + */ +public interface VeraClassMember + extends VeraStructuredTypeMember, ClassMember +{ + void setClass(VeraClass cls); + + void accept(VeraClassMemberVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMemberVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMemberVisitor.java new file mode 100644 index 0000000..f01f0a1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassMemberVisitor.java @@ -0,0 +1,36 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera class members. + * + * @author Trevor Robinson + */ +public interface VeraClassMemberVisitor +{ + void visit(VeraClassConstraint obj); + + void visit(VeraEnumeration obj); + + void visit(VeraEnumerationElement obj); + + void visit(VeraMemberFunction obj); + + void visit(VeraMemberVariable obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassModifier.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassModifier.java new file mode 100644 index 0000000..67fc655 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraClassModifier.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.TypeModifier; + +/** + * Enumeration of Vera class modifiers. + * + * @author Trevor Robinson + */ +public enum VeraClassModifier implements TypeModifier +{ + VIRTUAL; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraComparisonOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraComparisonOperation.java new file mode 100644 index 0000000..83d0911 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraComparisonOperation.java @@ -0,0 +1,72 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.BitVector; + +/** + * Base class for Vera comparison operations. + * + * @author Trevor Robinson + */ +public abstract class VeraComparisonOperation + extends VeraBinaryOperation +{ + public VeraComparisonOperation(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(schema.bitType); + } + + protected boolean isWildEqual() + { + boolean result; + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + if (type1.isStrictIntegral() || type2.isStrictIntegral()) + { + VeraType commonType = getCommonIntegralType(type1, type2); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraBitVectorType) + { + result = ((BitVector) io1).equalsWild((BitVector) io2); + } + else if (io1 == null || io2 == null) + { + result = true; + } + else + { + result = io1.equals(io2); + } + } + else + { + result = nullEquals(o1, o2); + } + return result; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnit.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnit.java new file mode 100644 index 0000000..889dc7d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnit.java @@ -0,0 +1,119 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.CompilationUnit; +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.util.NameTable; + +/** + * Represents a Vera compilation unit. + * + * @author Trevor Robinson + */ +public final class VeraCompilationUnit + extends VeraSchemaObjectImpl + implements CompilationUnit, VeraSchemaMember +{ + private static final long serialVersionUID = 3257572819045922614L; + + private final String sourcePath; + private final VeraName name; + private final List members = new LinkedList(); + private final NameTable nameTable = new NameTable(); + private boolean complete; + + public VeraCompilationUnit(VeraSchema schema, String sourcePath) + { + super(schema); + this.sourcePath = sourcePath; + this.name = new VeraName(sourcePath, VeraNameKind.COMP_UNIT, null); + } + + public VeraName getName() + { + return name; + } + + public String getSourcePath() + { + return sourcePath; + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraCompilationUnitMember member) + { + assert (member.getCompilationUnit() == null); + member.setCompilationUnit(this); + members.add(member); + if (member instanceof NamedObject) + { + nameTable.addObject((NamedObject) member); + } + } + + public void removeMember(VeraCompilationUnitMember member) + { + assert (member.getCompilationUnit() == this); + member.setCompilationUnit(null); + members.remove(member); + if (member instanceof NamedObject) + { + nameTable.removeObject((NamedObject) member); + } + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } + + public boolean isComplete() + { + return complete; + } + + public void setComplete(boolean complete) + { + this.complete = complete; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraSchemaMemberVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "compilation unit " + sourcePath; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMember.java new file mode 100644 index 0000000..4213816 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMember.java @@ -0,0 +1,38 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.CompilationUnitMember; + +/** + * Interface implemented by Vera constructs that may be members of a + * compilation unit. + * + * @author Trevor Robinson + */ +public interface VeraCompilationUnitMember + extends CompilationUnitMember +{ + VeraCompilationUnit getCompilationUnit(); + + void setCompilationUnit(VeraCompilationUnit compUnit); + + VeraVisibility getVisibility(); + + void accept(VeraCompilationUnitMemberVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMemberVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMemberVisitor.java new file mode 100644 index 0000000..0dfc82e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCompilationUnitMemberVisitor.java @@ -0,0 +1,56 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera compilation unit members. + * + * @author Trevor Robinson + */ +public interface VeraCompilationUnitMemberVisitor +{ + void visit(VeraBindVariable obj); + + void visit(VeraEnumeration obj); + + void visit(VeraEnumerationElement obj); + + void visit(VeraExpressionDefine obj); + + void visit(VeraGlobalFunction obj); + + void visit(VeraGlobalVariable obj); + + void visit(VeraHDLFunction obj); + + void visit(VeraInterfaceType obj); + + void visit(VeraPortType obj); + + void visit(VeraProgram obj); + + void visit(VeraRangeDefine obj); + + void visit(VeraStatementDefine obj); + + void visit(VeraTypeDefine obj); + + void visit(VeraUDFFunction obj); + + void visit(VeraUserClass obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraComplexType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraComplexType.java new file mode 100644 index 0000000..95d4221 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraComplexType.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ComplexType; + +/** + * Base class for Vera named, complex data/object types, such as classes or + * enumerations. + * + * @author Trevor Robinson + */ +public abstract class VeraComplexType + extends VeraType + implements ComplexType +{ + protected final VeraName name; + private VeraVisibility visibility; + + public VeraComplexType(VeraSchema schema, VeraName name) + { + super(schema); + this.name = name; + visibility = VeraVisibility.PUBLIC; + } + + public VeraName getName() + { + return name; + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public String toReferenceString() + { + return name.getCanonicalName(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraConcatenation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConcatenation.java new file mode 100644 index 0000000..0d7f236 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConcatenation.java @@ -0,0 +1,154 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Iterator; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorBuffer; + +/** + * Represents a Vera concatenation operation. + * + * @author Trevor Robinson + */ +public final class VeraConcatenation + extends VeraNaryOperation +{ + private static final long serialVersionUID = 3256722862113829425L; + + private boolean assignable; + + public VeraConcatenation(VeraSchema schema) + { + super(schema); + } + + public void addOperand(VeraExpression expr) + { + setResultType(null); + super.addOperand(expr); + } + + public VeraType getResultType() + { + VeraType resultType = super.getResultType(); + if (resultType == null) + { + boolean first = true; + int totalBitCount = 0; + assignable = true; + Iterator iter = operands.iterator(); + while (iter.hasNext()) + { + VeraExpression expr = (VeraExpression) iter.next(); + assignable &= expr.isAssignable(); + VeraType type = expr.getResultType(); + if (first) + { + if (type instanceof VeraStringType) + { + resultType = type; + } + else + { + totalBitCount = type.getBitCount(); + } + first = false; + } + else + { + if ((type instanceof VeraStringType) != (totalBitCount == 0)) + { + throw new SemanticException( + "Concatenation of string and non-string"); + } + + if (totalBitCount > 0) + { + int curBitCount = type.getBitCount(); + if (curBitCount > 0) + { + totalBitCount += curBitCount; + if (totalBitCount > VeraBitVectorType.MAX_SIZE) + { + totalBitCount = VeraBitVectorType.MAX_SIZE; + } + } + else + { + totalBitCount = -1; + } + } + } + } + if (totalBitCount > 0) + { + resultType = new VeraFixedBitVectorType(schema, totalBitCount); + } + else if (totalBitCount < 0) + { + resultType = schema.bitVectorType; + } + setResultType(resultType); + } + return resultType; + } + + public boolean isAssignable() + { + getResultType(); + return assignable; + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + if (resultType instanceof VeraStringType) + { + StringBuffer buf = new StringBuffer(); + for (VeraExpression expr : operands) + { + Object o = expr.evaluateConstant(); + buf.append(o); + } + return buf.toString(); + } + else + { + int size = ((VeraBitVectorType) resultType).getSize(); + int lowBit = size; + BitVectorBuffer buf = new BitVectorBuffer(size); + for (VeraExpression expr : operands) + { + BitVector bv = toBitVector(expr.evaluateConstant()); + int highBit = lowBit - 1; + lowBit -= bv.length(); + assert (lowBit >= 0); + buf.setBits(highBit, lowBit, bv); + } + return buf.toBitVector(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraConditional.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConditional.java new file mode 100644 index 0000000..2d80770 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConditional.java @@ -0,0 +1,82 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera conditional (?:) operation. + * + * @author Trevor Robinson + */ +public final class VeraConditional + extends VeraTernaryOperation +{ + private static final long serialVersionUID = 3760843484630037299L; + + public VeraConditional( + VeraExpression op1, + VeraExpression op2, + VeraExpression op3) + { + super(op1, op2, op3); + VeraType type2 = op2.getResultType(); + VeraType type3 = op3.getResultType(); + setResultType(getConditionalType(type2, type3)); + } + + private static VeraType getConditionalType(VeraType type1, VeraType type2) + { + VeraType result; + if (type1.isStrictIntegral() && type2.isStrictIntegral()) + { + result = getCommonIntegralType(type1, type2); + } + else if (isRefOrEnumType(type1) + && (type2.equals(type1) || type2 instanceof VeraNullType)) + { + result = type1; + } + else if (type1 instanceof VeraNullType && isRefOrEnumType(type2)) + { + result = type2; + } + else + { + throw new SemanticException("Incompatible types in conditional"); + } + return result; + } + + public Object evaluateConstant() + { + boolean b1 = toBoolean(op1.evaluateConstant()); + Object result = b1 ? op2.evaluateConstant() : op3.evaluateConstant(); + VeraType resultType = getResultType(); + if (resultType.isStrictIntegral()) + { + result = toCommonIntegralType(result, resultType); + } + return result; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraConstraintSet.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConstraintSet.java new file mode 100644 index 0000000..aefb327 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraConstraintSet.java @@ -0,0 +1,72 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a Vera random contraint set. + * + * @author Trevor Robinson + */ +public class VeraConstraintSet + extends VeraExpression +{ + private static final long serialVersionUID = 3256728368346380336L; + + private final List exprs = new LinkedList(); + private boolean constant = true; + + public VeraConstraintSet(VeraSchema schema) + { + super(schema); + setResultType(schema.bitType); + } + + public final List getExprs() + { + return exprs; + } + + public final void addExpr(VeraExpression expr) + { + assert (expr.getResultType().isIntegralConvertible()); + exprs.add(expr); + if (!expr.isConstant()) constant = false; + } + + public boolean isConstant() + { + return constant; + } + + public Object evaluateConstant() + { + for (VeraExpression expr : exprs) + { + if (!toBoolean(expr.evaluateConstant())) return Boolean.FALSE; + } + return Boolean.TRUE; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraContinueStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraContinueStatement.java new file mode 100644 index 0000000..c9e72ec --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraContinueStatement.java @@ -0,0 +1,54 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ContinueStatement; +import com.newisys.langschema.LabeledStatement; + +/** + * Represents a Vera continue statement. + * + * @author Trevor Robinson + */ +public final class VeraContinueStatement + extends VeraStatementImpl + implements ContinueStatement +{ + private static final long serialVersionUID = 3257564027247932723L; + + public VeraContinueStatement(VeraSchema schema) + { + super(schema); + } + + public LabeledStatement getTarget() + { + // Vera does not support labeled continues + return null; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "continue statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraCopyCreation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCopyCreation.java new file mode 100644 index 0000000..0221dc0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraCopyCreation.java @@ -0,0 +1,64 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.CopyCreation; + +/** + * Represents a Vera copy-creation expression. + * + * @author Trevor Robinson + */ +public final class VeraCopyCreation + extends VeraExpression + implements CopyCreation +{ + private static final long serialVersionUID = 3976739159731681333L; + + private final VeraComplexType type; + private final VeraExpression source; + + public VeraCopyCreation(VeraComplexType type, VeraExpression source) + { + super(type.schema); + assert (type instanceof VeraClass || type instanceof VeraPortType); + setResultType(type); + this.type = type; + this.source = source; + } + + public boolean isConstant() + { + return false; + } + + public VeraComplexType getType() + { + return type; + } + + public VeraExpression getSource() + { + return source; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefine.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefine.java new file mode 100644 index 0000000..c8945e1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefine.java @@ -0,0 +1,111 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.NamedObject; + +/** + * Base class for Vera preprocessor #defines. + * + * @author Trevor Robinson + */ +public abstract class VeraDefine + extends VeraSchemaObjectImpl + implements NamedObject, VeraCompilationUnitMember +{ + private final VeraName name; + private VeraVisibility visibility; + private VeraCompilationUnit compUnit; + private final List arguments = new LinkedList(); + private boolean verilogImport; + + public VeraDefine(VeraSchema schema, VeraName name) + { + super(schema); + this.name = name; + visibility = VeraVisibility.PUBLIC; + } + + public VeraName getName() + { + return name; + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public boolean hasArguments() + { + return !arguments.isEmpty(); + } + + public List getArguments() + { + return arguments; + } + + public void addArgument(VeraDefineArgument arg) + { + arguments.add(arg); + } + + public void addArguments(List args) + { + arguments.addAll(args); + } + + public boolean isVerilogImport() + { + return verilogImport; + } + + public void setVerilogImport(boolean verilogImport) + { + this.verilogImport = verilogImport; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + accept((VeraCompilationUnitMemberVisitor) visitor); + } + + public String toDebugString() + { + return "define " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineArgument.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineArgument.java new file mode 100644 index 0000000..269ee3c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineArgument.java @@ -0,0 +1,45 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera preprocessor #define argument. + * + * @author Trevor Robinson + */ +public final class VeraDefineArgument + extends VeraVariable +{ + private static final long serialVersionUID = 3689069551740400944L; + + public VeraDefineArgument(VeraSchema schema, VeraName name) + { + super(name, schema.magicType); + this.name = name; + } + + public String toDebugString() + { + return "define variable " + name; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReference.java new file mode 100644 index 0000000..3c834c8 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReference.java @@ -0,0 +1,69 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a reference to a Vera preprocessor #define of the given kind. + * + * @author Trevor Robinson + */ +public final class VeraDefineReference + extends VeraSchemaObjectImpl +{ + private static final long serialVersionUID = 3978422507789367604L; + + private final T define; + private List arguments; + + public VeraDefineReference(T define) + { + super(define.schema); + this.define = define; + } + + public T getDefine() + { + return define; + } + + public List getArguments() + { + if (arguments == null) return Collections.emptyList(); + return arguments; + } + + public void addArgument(VeraExpression arg) + { + if (arguments == null) arguments = new LinkedList(); + arguments.add(arg); + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return define.getName() + " define ref"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReferrer.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReferrer.java new file mode 100644 index 0000000..a2067fb --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDefineReferrer.java @@ -0,0 +1,31 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Interface implemented by Vera constructs that may be directly expanded from + * a preprocessor #define. + * + * @author Trevor Robinson + */ +public interface VeraDefineReferrer +{ + VeraDefineReference getDefineRef(); + + void setDefineRef(VeraDefineReference defineRef); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDepthAccess.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDepthAccess.java new file mode 100644 index 0000000..d93cdba --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDepthAccess.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera signal back-reference expression. + * + * @author Trevor Robinson + */ +public final class VeraDepthAccess + extends VeraExpression +{ + private static final long serialVersionUID = 4051048553600137012L; + + private final VeraExpression signal; + private final int depth; + + public VeraDepthAccess(VeraExpression signal, int depth) + { + super(signal.schema); + assert ((signal instanceof VeraMemberAccess && ((VeraMemberAccess) signal) + .getMember() instanceof VeraPortSignal) || signal instanceof VeraSignalReference); + setResultType(signal.getResultType()); + this.signal = signal; + this.depth = depth; + } + + public boolean isAssignable() + { + return false; + } + + public boolean isConstant() + { + return false; + } + + public VeraExpression getSignal() + { + return signal; + } + + public int getDepth() + { + return depth; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDistSet.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDistSet.java new file mode 100644 index 0000000..8ef30a0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDistSet.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera dist operation in a random constraint. + * + * @author Trevor Robinson + */ +public final class VeraDistSet + extends VeraSetOperation +{ + private static final long serialVersionUID = 3258130258472743473L; + + public VeraDistSet(VeraExpression expr) + { + super(expr); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDivide.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDivide.java new file mode 100644 index 0000000..7e88dcd --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDivide.java @@ -0,0 +1,71 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera division operation. + * + * @author Trevor Robinson + */ +public final class VeraDivide + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3257285837837056312L; + + public VeraDivide(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.divide((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.divide(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b2 == Bit.ZERO) + { + throw new ArithmeticException("Bit divide by zero"); + } + return b1.and(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDriveSampleStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDriveSampleStatement.java new file mode 100644 index 0000000..9aec6a3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDriveSampleStatement.java @@ -0,0 +1,105 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera drive or sample statement. + * + * @author Trevor Robinson + */ +public final class VeraDriveSampleStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3257565092449957424L; + + private final VeraExpression destination; + private final VeraExpression source; + private VeraExpression delay; + private boolean nonBlocking; + private boolean soft; + private boolean async; + + public VeraDriveSampleStatement( + VeraExpression destination, + VeraExpression source) + { + super(destination.schema); + this.destination = destination; + this.source = source; + } + + public VeraExpression getDestination() + { + return destination; + } + + public VeraExpression getSource() + { + return source; + } + + public VeraExpression getDelay() + { + return delay; + } + + public void setDelay(VeraExpression delay) + { + this.delay = delay; + } + + public boolean isNonBlocking() + { + return nonBlocking; + } + + public void setNonBlocking(boolean nonBlocking) + { + this.nonBlocking = nonBlocking; + } + + public boolean isSoft() + { + return soft; + } + + public void setSoft(boolean soft) + { + this.soft = soft; + } + + public boolean isAsync() + { + return async; + } + + public void setAsync(boolean async) + { + this.async = async; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "drive/sample statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraDynamicArrayType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDynamicArrayType.java new file mode 100644 index 0000000..e834403 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraDynamicArrayType.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera dynamic array type. + * + * @author Trevor Robinson + */ +public final class VeraDynamicArrayType + extends VeraArrayType +{ + private static final long serialVersionUID = 3256442499567597105L; + + public VeraDynamicArrayType(VeraType elementType) + { + super(elementType, new VeraType[] { elementType.schema.integerType }); + } + + public String toReferenceString() + { + return elementType + "[*]"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumValueReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumValueReference.java new file mode 100644 index 0000000..d06558e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumValueReference.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.EnumerationElementReference; + +/** + * Represents a Vera enumeration value reference expression. + * + * @author Trevor Robinson + */ +public final class VeraEnumValueReference + extends VeraExpression + implements EnumerationElementReference +{ + private static final long serialVersionUID = 3258126977268725296L; + + private final VeraEnumerationElement element; + + public VeraEnumValueReference(VeraEnumerationElement element) + { + super(element.schema); + setResultType(element.getEnumeration()); + this.element = element; + } + + public VeraEnumerationElement getElement() + { + return element; + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return element; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumeration.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumeration.java new file mode 100644 index 0000000..a79d9c4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumeration.java @@ -0,0 +1,131 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.newisys.langschema.Enumeration; +import com.newisys.langschema.EnumerationElement; +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Type; +import com.newisys.langschema.util.NameTable; + +/** + * Represents a Vera enumeration type. + * + * @author Trevor Robinson + */ +public final class VeraEnumeration + extends VeraComplexType + implements Enumeration, VeraClassMember, VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3256438110228134201L; + + private final List members = new LinkedList(); + private final Map values = new HashMap(); + private final NameTable nameTable = new NameTable(); + private VeraClass cls; + private VeraCompilationUnit compUnit; + + public VeraEnumeration(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraEnumerationElement element) + { + members.add(element); + values.put(new Integer(element.getValue()), element); + nameTable.addObject(element); + } + + public EnumerationElement lookupValue(int value) + { + return values.get(value); + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } + + public VeraClass getStructuredType() + { + return cls; + } + + public void setClass(VeraClass cls) + { + this.cls = cls; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public boolean isAssignableFrom(Type other) + { + return other == this; + } + + public boolean isIntegralConvertible() + { + return true; + } + + public int getBitCount() + { + return 32; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraClassMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "enum " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumerationElement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumerationElement.java new file mode 100644 index 0000000..a6ee171 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEnumerationElement.java @@ -0,0 +1,109 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.EnumerationElement; + +/** + * Represents a Vera enumeration element. + * + * @author Trevor Robinson + */ +public final class VeraEnumerationElement + extends VeraSchemaObjectImpl + implements EnumerationElement, VeraCompilationUnitMember, VeraClassMember +{ + private static final long serialVersionUID = 3257289149307237936L; + + private final VeraEnumeration enumeration; + private final VeraName name; + private final int value; + private VeraCompilationUnit compUnit; + private VeraClass cls; + + public VeraEnumerationElement( + VeraEnumeration enumeration, + VeraName name, + int value) + { + super(enumeration.schema); + this.enumeration = enumeration; + this.name = name; + this.value = value; + } + + public VeraName getName() + { + return name; + } + + public int getValue() + { + return value; + } + + public VeraEnumeration getEnumeration() + { + return enumeration; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public VeraClass getStructuredType() + { + return cls; + } + + public void setClass(VeraClass cls) + { + this.cls = cls; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraClassMemberVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "enum element " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqual.java new file mode 100644 index 0000000..823e4a9 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqual.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera equality expression. + * + * @author Trevor Robinson + */ +public final class VeraEqual + extends VeraEqualOperation +{ + private static final long serialVersionUID = 3257282535041151032L; + + public VeraEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return isEqual(); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqualOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqualOperation.java new file mode 100644 index 0000000..ada67d5 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEqualOperation.java @@ -0,0 +1,118 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Base class for Vera equality operations. + * + * @author Trevor Robinson + */ +public abstract class VeraEqualOperation + extends VeraBinaryOperation +{ + public VeraEqualOperation(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(schema.bitType); + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.equals(type2) + || (type1.isStrictIntegral() && type2.isIntegralConvertible()) + || (type1.isIntegralConvertible() && type2.isStrictIntegral()) + || (isRefType(type1) && type2 instanceof VeraNullType) + || (type1 instanceof VeraNullType && isRefType(type2)); + } + + protected Bit isEqual() + { + Bit result; + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + if (type1.isStrictIntegral() || type2.isStrictIntegral()) + { + VeraType commonType = getCommonIntegralType(type1, type2); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraBitVectorType) + { + if (((BitVector) io1).containsXZ() + || ((BitVector) io2).containsXZ()) + { + result = Bit.X; + } + else + { + result = io1.equals(io2) ? Bit.ONE : Bit.ZERO; + } + } + else if (io1 == null || io2 == null) + { + result = Bit.X; + } + else + { + result = io1.equals(io2) ? Bit.ONE : Bit.ZERO; + } + } + else + { + result = nullEquals(o1, o2) ? Bit.ONE : Bit.ZERO; + } + return result; + } + + protected boolean isExactEqual() + { + boolean result; + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + if (type1.isStrictIntegral() || type2.isStrictIntegral()) + { + VeraType commonType = getCommonIntegralType(type1, type2); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraBitVectorType) + { + result = ((BitVector) io1).equalsExact((BitVector) io2); + } + else + { + result = nullEquals(io1, io2); + } + } + else + { + result = nullEquals(o1, o2); + } + return result; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraEventType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEventType.java new file mode 100644 index 0000000..76e0874 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraEventType.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents the Vera event type. + * + * @author Trevor Robinson + */ +public final class VeraEventType + extends VeraPrimitiveType +{ + private static final long serialVersionUID = 3979265867601293878L; + + VeraEventType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + return other instanceof VeraEventType || other instanceof VeraNullType; + } + + public String toReferenceString() + { + return "event"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactEqual.java new file mode 100644 index 0000000..bbf1c23 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactEqual.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; + +/** + * Represents a Vera exact equality (===) expression. + * + * @author Trevor Robinson + */ +public final class VeraExactEqual + extends VeraEqualOperation +{ + private static final long serialVersionUID = 3258409521658279474L; + + public VeraExactEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return isExactEqual() ? Bit.ONE : Bit.ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactNotEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactNotEqual.java new file mode 100644 index 0000000..78d8b83 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExactNotEqual.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; + +/** + * Represents a Vera exact inequality (!==) expression. + * + * @author Trevor Robinson + */ +public final class VeraExactNotEqual + extends VeraEqualOperation +{ + private static final long serialVersionUID = 3257288049896208181L; + + public VeraExactNotEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return !isExactEqual() ? Bit.ONE : Bit.ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectKind.java new file mode 100644 index 0000000..0d055b7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectKind.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera expect statement kinds. + * + * @author Trevor Robinson + */ +public enum VeraExpectKind +{ + SIMPLE, FULL, RESTRICTED; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectStatement.java new file mode 100644 index 0000000..a6a94a2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectStatement.java @@ -0,0 +1,121 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a Vera expect statement. + * + * @author Trevor Robinson + */ +public final class VeraExpectStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 4121981347192714548L; + + private final VeraExpectKind expectKind; + private final List expectTerms = new LinkedList(); + private boolean expectAll; + private VeraExpression delay; + private VeraExpression window; + private boolean soft; + private boolean async; + + public VeraExpectStatement(VeraSchema schema, VeraExpectKind expectKind) + { + super(schema); + this.expectKind = expectKind; + } + + public VeraExpectKind getExpectKind() + { + return expectKind; + } + + public List getExpectTerms() + { + return expectTerms; + } + + public void addExpectTerm(VeraExpectTerm term) + { + expectTerms.add(term); + } + + public boolean isExpectAll() + { + return expectAll; + } + + public void setExpectAll(boolean expectAll) + { + this.expectAll = expectAll; + } + + public VeraExpression getDelay() + { + return delay; + } + + public void setDelay(VeraExpression delay) + { + this.delay = delay; + } + + public VeraExpression getWindow() + { + return window; + } + + public void setWindow(VeraExpression window) + { + this.window = window; + } + + public boolean isSoft() + { + return soft; + } + + public void setSoft(boolean soft) + { + this.soft = soft; + } + + public boolean isAsync() + { + return async; + } + + public void setAsync(boolean async) + { + this.async = async; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "expect statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectTerm.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectTerm.java new file mode 100644 index 0000000..19387a0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpectTerm.java @@ -0,0 +1,60 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.io.Serializable; + +/** + * Represents a term of Vera expect statement. + * + * @author Trevor Robinson + */ +public final class VeraExpectTerm + implements Serializable +{ + private static final long serialVersionUID = 3257853194527846708L; + + private final VeraExpression signal; + private final VeraExpression value; + private final boolean equal; + + public VeraExpectTerm( + VeraExpression signal, + VeraExpression value, + boolean equal) + { + this.signal = signal; + this.value = value; + this.equal = equal; + } + + public VeraExpression getSignal() + { + return signal; + } + + public VeraExpression getValue() + { + return value; + } + + public boolean isEqual() + { + return equal; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpression.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpression.java new file mode 100644 index 0000000..6230dc0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpression.java @@ -0,0 +1,308 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Expression; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Base class for Vera expressions. + * + * @author Trevor Robinson + */ +public abstract class VeraExpression + extends VeraSchemaObjectImpl + implements Expression, VeraDefineReferrer +{ + final static long serialVersionUID = -1004295860595142204L; + + protected final static Integer INTEGER_ZERO = new Integer(0); + protected final static Integer INTEGER_ONE = new Integer(1); + + private VeraType resultType; + private VeraDefineReference defineRef; + + public VeraExpression(VeraSchema schema) + { + super(schema); + } + + public VeraType getResultType() + { + return resultType; + } + + protected final void setResultType(VeraType resultType) + { + this.resultType = resultType; + } + + public VeraDefineReference getDefineRef() + { + return defineRef; + } + + public void setDefineRef(VeraDefineReference defineRef) + { + this.defineRef = defineRef; + } + + public boolean isAssignable() + { + return false; + } + + public Object evaluateConstant() + { + throw new RuntimeException("Cannot evaluate non-constant expression"); + } + + protected static boolean isRefType(VeraType type) + { + return type instanceof VeraClass || type instanceof VeraPortType + || type instanceof VeraEventType || type instanceof VeraNullType; + } + + protected static boolean isRefOrEnumType(VeraType type) + { + return isRefType(type) || type instanceof VeraEnumeration; + } + + protected static VeraType getIntegralType(VeraType type) + { + if (type instanceof VeraEnumeration) + { + return type.schema.integerType; + } + else if (type instanceof VeraMagicType + || type instanceof VeraIntegerType + || type instanceof VeraBitVectorType || type instanceof VeraBitType) + { + return type; + } + else + { + throw new RuntimeException("Integral type expected"); + } + } + + protected static Object toIntegral(Object o) + { + if (o instanceof Integer || o instanceof BitVector || o instanceof Bit + || o == null) + { + return o; + } + else if (o instanceof VeraEnumerationElement) + { + return new Integer(((VeraEnumerationElement) o).getValue()); + } + else + { + throw new RuntimeException("Cannot convert " + + o.getClass().getName() + " to integral type"); + } + } + + public static Integer toInteger(Object o) + { + Object io = toIntegral(o); + if (io instanceof Integer) + { + return (Integer) io; + } + else if (io instanceof BitVector) + { + BitVector bv = (BitVector) io; + if (!bv.containsXZ()) + { + return new Integer(bv.intValue()); + } + } + else if (io instanceof Bit) + { + if (io == Bit.ZERO) + { + return INTEGER_ZERO; + } + if (io == Bit.ONE) + { + return INTEGER_ONE; + } + } + return null; + } + + public static boolean toBoolean(Object o) + { + if (o instanceof Integer) + { + return ((Integer) o).intValue() != 0; + } + else if (o instanceof BitVector) + { + BitVector bv = ((BitVector) o); + return !bv.containsXZ() && bv.isNotZero(); + } + else if (o instanceof Bit) + { + return o == Bit.ONE; + } + else if (o == null) + { + return false; + } + else if (o instanceof VeraEnumerationElement) + { + return ((VeraEnumerationElement) o).getValue() != 0; + } + else + { + throw new RuntimeException("Cannot convert " + + o.getClass().getName() + " to boolean type"); + } + } + + protected static VeraType getCommonIntegralType( + VeraExpression op1, + VeraExpression op2) + { + VeraType type1 = op1.resultType; + VeraType type2 = op2.resultType; + return getCommonIntegralType(type1, type2); + } + + protected static VeraType getCommonIntegralType( + VeraType type1, + VeraType type2) + { + if (type1 instanceof VeraMagicType || type2 instanceof VeraMagicType) + { + return type1; + } + else if ((type1 instanceof VeraIntegerType || type1 instanceof VeraEnumeration) + && (type2 instanceof VeraIntegerType || type2 instanceof VeraEnumeration)) + { + return type1.schema.integerType; + } + else if (type1 instanceof VeraBitType && type2 instanceof VeraBitType) + { + return type1.schema.bitType; + } + else + { + int typeBits = Math.max(type1.getBitCount(), type2.getBitCount()); + return new VeraFixedBitVectorType(type1.schema, typeBits); + } + } + + protected static Object toCommonIntegralType(Object o, VeraType type) + { + if (type instanceof VeraIntegerType) + { + if (o instanceof Integer || o == null) + { + return o; + } + else if (o instanceof VeraEnumerationElement) + { + VeraEnumerationElement ee = (VeraEnumerationElement) o; + return new Integer(ee.getValue()); + } + } + else if (type instanceof VeraBitVectorType) + { + int size = ((VeraBitVectorType) type).getSize(); + if (o instanceof Integer) + { + return new BitVector(size, ((Integer) o).intValue()); + } + else if (o instanceof BitVector) + { + BitVector bv = (BitVector) o; + return bv.length() == size ? bv : bv.setLength(size, Bit.ZERO); + } + else if (o instanceof Bit) + { + return new BitVector(size, (Bit) o); + } + else if (o instanceof VeraEnumerationElement) + { + VeraEnumerationElement ee = (VeraEnumerationElement) o; + return new BitVector(size, ee.getValue()); + } + else if (o == null) + { + return new BitVector(size, Bit.X); + } + } + else if (type instanceof VeraBitType) + { + assert (o instanceof Bit); + return o; + } + throw new RuntimeException("Cannot convert " + + (o != null ? o.getClass().getName() : "null") + " to " + type); + } + + public static BitVector toBitVector(Object o) + { + if (o instanceof BitVector) + { + return (BitVector) o; + } + else if (o instanceof Integer) + { + return new BitVector(32, ((Integer) o).intValue()); + } + else if (o instanceof Bit) + { + return new BitVector(1, (Bit) o); + } + else if (o instanceof VeraEnumerationElement) + { + VeraEnumerationElement ee = (VeraEnumerationElement) o; + return new BitVector(32, ee.getValue()); + } + else if (o == null) + { + return new BitVector(32, Bit.X); + } + throw new RuntimeException("Cannot convert " + o.getClass().getName() + + " to BitVector"); + } + + protected static boolean nullEquals(Object o1, Object o2) + { + return o1 != null ? o1.equals(o2) : o2 == null; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + accept((VeraExpressionVisitor) visitor); + } + + public abstract void accept(VeraExpressionVisitor visitor); + + public String toDebugString() + { + // for expressions, default to always using the source string + return toSourceString(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionDefine.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionDefine.java new file mode 100644 index 0000000..62a1266 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionDefine.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera preprocessor #define that parses as an expression. + * + * @author Trevor Robinson + */ +public class VeraExpressionDefine + extends VeraDefine +{ + private static final long serialVersionUID = 3617576019968667959L; + + private VeraExpression expression; + + public VeraExpressionDefine(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public VeraExpression getExpression() + { + return expression; + } + + public void setExpression(VeraExpression expression) + { + this.expression = expression; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionStatement.java new file mode 100644 index 0000000..39fec7a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionStatement.java @@ -0,0 +1,55 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ExpressionStatement; + +/** + * Represents a Vera expression statement. + * + * @author Trevor Robinson + */ +public final class VeraExpressionStatement + extends VeraStatementImpl + implements ExpressionStatement +{ + private static final long serialVersionUID = 3977022838010229813L; + + private final VeraExpression expr; + + public VeraExpressionStatement(VeraExpression expr) + { + super(expr.schema); + this.expr = expr; + } + + public VeraExpression getExpression() + { + return expr; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "expression statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionVisitor.java new file mode 100644 index 0000000..f7dca79 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraExpressionVisitor.java @@ -0,0 +1,194 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera expressions. + * + * @author Trevor Robinson + */ +public interface VeraExpressionVisitor +{ + void visit(VeraAdd obj); + + void visit(VeraAndReduction obj); + + void visit(VeraArithmeticNegative obj); + + void visit(VeraArrayAccess obj); + + void visit(VeraArrayCreation obj); + + void visit(VeraArrayInitializer obj); + + void visit(VeraAssign obj); + + void visit(VeraAssignAdd obj); + + void visit(VeraAssignAnd obj); + + void visit(VeraAssignAndNot obj); + + void visit(VeraAssignDivide obj); + + void visit(VeraAssignLeftShift obj); + + void visit(VeraAssignModulo obj); + + void visit(VeraAssignMultiply obj); + + void visit(VeraAssignOr obj); + + void visit(VeraAssignOrNot obj); + + void visit(VeraAssignRightShift obj); + + void visit(VeraAssignSubtract obj); + + void visit(VeraAssignXor obj); + + void visit(VeraAssignXorNot obj); + + void visit(VeraBitSliceAccess obj); + + void visit(VeraBitVectorLiteral obj); + + void visit(VeraBitwiseAnd obj); + + void visit(VeraBitwiseAndNot obj); + + void visit(VeraBitwiseNegative obj); + + void visit(VeraBitwiseOr obj); + + void visit(VeraBitwiseOrNot obj); + + void visit(VeraBitwiseReverse obj); + + void visit(VeraBitwiseXor obj); + + void visit(VeraBitwiseXorNot obj); + + void visit(VeraConcatenation obj); + + void visit(VeraConditional obj); + + void visit(VeraConstraintSet obj); + + void visit(VeraCopyCreation obj); + + void visit(VeraDepthAccess obj); + + void visit(VeraDistSet obj); + + void visit(VeraDivide obj); + + void visit(VeraEnumValueReference obj); + + void visit(VeraEqual obj); + + void visit(VeraExactEqual obj); + + void visit(VeraExactNotEqual obj); + + void visit(VeraFunctionInvocation obj); + + void visit(VeraFunctionReference obj); + + void visit(VeraGreater obj); + + void visit(VeraGreaterOrEqual obj); + + void visit(VeraIfElseConstraint obj); + + void visit(VeraImplicationConstraint obj); + + void visit(VeraInSet obj); + + void visit(VeraInstanceCreation obj); + + void visit(VeraIntegerLiteral obj); + + void visit(VeraInterfaceReference obj); + + void visit(VeraLeftShift obj); + + void visit(VeraLess obj); + + void visit(VeraLessOrEqual obj); + + void visit(VeraLogicalAnd obj); + + void visit(VeraLogicalNegative obj); + + void visit(VeraLogicalOr obj); + + void visit(VeraMemberAccess obj); + + void visit(VeraModulo obj); + + void visit(VeraMultiply obj); + + void visit(VeraNotAndReduction obj); + + void visit(VeraNotEqual obj); + + void visit(VeraNotInSet obj); + + void visit(VeraNotOrReduction obj); + + void visit(VeraNotXorReduction obj); + + void visit(VeraNullLiteral obj); + + void visit(VeraOrReduction obj); + + void visit(VeraPostDecrement obj); + + void visit(VeraPostIncrement obj); + + void visit(VeraPreDecrement obj); + + void visit(VeraPreIncrement obj); + + void visit(VeraReplication obj); + + void visit(VeraRightShift obj); + + void visit(VeraSignalReference obj); + + void visit(VeraStringLiteral obj); + + void visit(VeraSubtract obj); + + void visit(VeraSuperReference obj); + + void visit(VeraSystemClockReference obj); + + void visit(VeraThisReference obj); + + void visit(VeraVariableReference obj); + + void visit(VeraVoidLiteral obj); + + void visit(VeraWildEqual obj); + + void visit(VeraWildNotEqual obj); + + void visit(VeraXorReduction obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedArrayType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedArrayType.java new file mode 100644 index 0000000..da3b1a7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedArrayType.java @@ -0,0 +1,116 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Arrays; + +import com.newisys.langschema.FixedArrayType; + +/** + * Represents a Vera fixed-dimension array type. + * + * @author Trevor Robinson + */ +public final class VeraFixedArrayType + extends VeraArrayType + implements FixedArrayType +{ + private static final long serialVersionUID = 3978711687920498230L; + + private final int[] dimensions; + + public VeraFixedArrayType(VeraType elementType, int[] dimensions) + { + super(elementType, createIndexTypes(elementType.schema, + dimensions.length)); + this.dimensions = dimensions; + } + + private static VeraType[] createIndexTypes(VeraSchema schema, int dimensions) + { + VeraType[] types = new VeraType[dimensions]; + Arrays.fill(types, schema.integerType); + return types; + } + + public int[] getDimensions() + { + return dimensions; + } + + public int[] getLowBounds() + { + int[] lowBounds = new int[dimensions.length]; + return lowBounds; + } + + public int[] getHighBounds() + { + int[] highBounds = new int[dimensions.length]; + for (int i = 0; i < dimensions.length; ++i) + { + highBounds[i] = dimensions[i] - 1; + } + return highBounds; + } + + public boolean equals(Object obj) + { + if (obj instanceof VeraFixedArrayType && super.equals(obj)) + { + VeraFixedArrayType other = (VeraFixedArrayType) obj; + for (int i = 0; i < dimensions.length; ++i) + { + if (dimensions[i] != other.dimensions[i]) + { + return false; + } + } + return true; + } + return false; + } + + public int hashCode() + { + int h = super.hashCode(); + for (int i = 0; i < dimensions.length; ++i) + { + h = (h * 37) ^ dimensions[i]; + } + return h; + } + + public String toReferenceString() + { + StringBuffer buf = new StringBuffer(); + buf.append(elementType); + for (int i = 0; i < dimensions.length; ++i) + { + buf.append('['); + buf.append(dimensions[i]); + buf.append(']'); + } + return buf.toString(); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedBitVectorType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedBitVectorType.java new file mode 100644 index 0000000..ef29f16 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFixedBitVectorType.java @@ -0,0 +1,68 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera fixed-size bit vector type. + * + * @author Trevor Robinson + */ +public final class VeraFixedBitVectorType + extends VeraBitVectorType +{ + private static final long serialVersionUID = 3257281452742816819L; + + private final int size; + + public VeraFixedBitVectorType(VeraSchema schema, int size) + { + super(schema); + assert (size <= MAX_SIZE); + this.size = size; + } + + public int getSize() + { + return size; + } + + public boolean equals(Object obj) + { + if (obj instanceof VeraFixedBitVectorType) + { + VeraFixedBitVectorType other = (VeraFixedBitVectorType) obj; + return size == other.size; + } + return false; + } + + public int hashCode() + { + return VeraFixedBitVectorType.class.hashCode() ^ size; + } + + public String toReferenceString() + { + return "bit[" + (size - 1) + ":0]"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraForStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraForStatement.java new file mode 100644 index 0000000..c25850f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraForStatement.java @@ -0,0 +1,99 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.Expression; +import com.newisys.langschema.ForStatement; + +/** + * Represents a Vera 'for' loop. + * + * @author Trevor Robinson + */ +public final class VeraForStatement + extends VeraStatementImpl + implements ForStatement +{ + private static final long serialVersionUID = 3256444685755954224L; + + private final List initStmtList = new LinkedList(); + private VeraExpression condition; + private final List updateStmtList = new LinkedList(); + private VeraStatement statement; + + public VeraForStatement(VeraSchema schema) + { + super(schema); + } + + public List getInitStatements() + { + return initStmtList; + } + + public void addInitStatement(VeraBlockMember stmt) + { + stmt.setContainingStatement(this); + initStmtList.add(stmt); + } + + public Expression getCondition() + { + return condition; + } + + public void setCondition(VeraExpression condition) + { + this.condition = condition; + } + + public List getUpdateStatements() + { + return updateStmtList; + } + + public void addUpdateStatement(VeraExpressionStatement stmt) + { + stmt.setContainingStatement(this); + updateStmtList.add(stmt); + } + + public VeraStatement getStatement() + { + return statement; + } + + public void setStatement(VeraStatement stmt) + { + stmt.setContainingStatement(this); + this.statement = stmt; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "for statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraForkStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraForkStatement.java new file mode 100644 index 0000000..22d3837 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraForkStatement.java @@ -0,0 +1,71 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.ForkStatement; +import com.newisys.langschema.JoinKind; + +/** + * Represents a Vera fork statement. + * + * @author Trevor Robinson + */ +public final class VeraForkStatement + extends VeraStatementImpl + implements ForkStatement +{ + private static final long serialVersionUID = 3977860670165103673L; + + private final List stmtList = new LinkedList(); + private final JoinKind joinKind; + + public VeraForkStatement(VeraSchema schema, JoinKind joinKind) + { + super(schema); + this.joinKind = joinKind; + } + + public List getForkedStatements() + { + return stmtList; + } + + public void addForkedStatements(VeraStatement stmt) + { + stmt.setContainingStatement(this); + stmtList.add(stmt); + } + + public JoinKind getJoinKind() + { + return joinKind; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "fork statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunction.java new file mode 100644 index 0000000..db3a883 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunction.java @@ -0,0 +1,108 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.Set; + +import com.newisys.langschema.Function; + +/** + * Base class for Vera functions. + * + * @author Trevor Robinson + */ +public abstract class VeraFunction + extends VeraSchemaObjectImpl + implements Function +{ + protected final VeraName name; + private final VeraFunctionType funcType; + private VeraVisibility visibility; + private VeraBlock body; + private VeraLocalVariable returnVar; + private boolean defined; + + public VeraFunction(VeraName name, VeraFunctionType funcType) + { + super(funcType.schema); + this.name = name; + this.funcType = funcType; + this.visibility = VeraVisibility.PUBLIC; + } + + public VeraName getName() + { + return name; + } + + public VeraFunctionType getType() + { + return funcType; + } + + public Set< ? extends VeraFunctionModifier> getModifiers() + { + return Collections.emptySet(); + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public VeraBlock getBody() + { + return body; + } + + public void setBody(VeraBlock body) + { + this.body = body; + } + + public VeraLocalVariable getReturnVar() + { + return returnVar; + } + + public void setReturnVar(VeraLocalVariable returnVar) + { + this.returnVar = returnVar; + } + + public boolean isDefined() + { + return defined; + } + + public void setDefined(boolean defined) + { + this.defined = defined; + } + + public String toDebugString() + { + return "function " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgument.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgument.java new file mode 100644 index 0000000..a8522d4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgument.java @@ -0,0 +1,108 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.FunctionArgument; + +/** + * Represents a Vera function argument. + * + * @author Trevor Robinson + */ +public final class VeraFunctionArgument + extends VeraVariable + implements FunctionArgument +{ + private static final long serialVersionUID = 3256727294620807729L; + + private final VeraFunction function; + private boolean optional; + private int optionalLevel; + private boolean returnsXZ; + + public VeraFunctionArgument( + VeraName name, + VeraType type, + VeraFunction function) + { + super(name, type); + this.function = function; + } + + public void setName(VeraName name) + { + this.name = name; + } + + public VeraFunction getFunction() + { + return function; + } + + public boolean isByRef() + { + return modifiers.contains(VeraFunctionArgumentModifier.VAR); + } + + public void setByRef(boolean byRef) + { + if (byRef) + { + modifiers.add(VeraFunctionArgumentModifier.VAR); + } + else + { + modifiers.remove(VeraFunctionArgumentModifier.VAR); + } + } + + public boolean isOptional() + { + return optional; + } + + public void setOptional(boolean optional) + { + this.optional = optional; + } + + public int getOptionalLevel() + { + return optionalLevel; + } + + public void setOptionalLevel(int optionalLevel) + { + this.optionalLevel = optionalLevel; + } + + public boolean isReturnsXZ() + { + return returnsXZ; + } + + public void setReturnsXZ(boolean returnsXZ) + { + this.returnsXZ = returnsXZ; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgumentModifier.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgumentModifier.java new file mode 100644 index 0000000..d379714 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionArgumentModifier.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.FunctionArgumentModifier; + +/** + * Enumeration of Vera function argument modifiers. + * + * @author Trevor Robinson + */ +public enum VeraFunctionArgumentModifier implements FunctionArgumentModifier +{ + VAR; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionInvocation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionInvocation.java new file mode 100644 index 0000000..c46e897 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionInvocation.java @@ -0,0 +1,88 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.FunctionInvocation; +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera function invocation expression. + * + * @author Trevor Robinson + */ +public final class VeraFunctionInvocation + extends VeraExpression + implements FunctionInvocation +{ + private static final long serialVersionUID = 3257283651749163573L; + + private final VeraExpression function; + private final List arguments = new LinkedList(); + private final List constraints = new LinkedList(); + + public VeraFunctionInvocation(VeraExpression function) + { + super(function.schema); + VeraType resultType = function.getResultType(); + if (!(resultType instanceof VeraFunctionType)) + { + throw new SemanticException("Function reference expected"); + } + VeraFunctionType funcType = (VeraFunctionType) resultType; + setResultType(funcType.getReturnType()); + this.function = function; + } + + public boolean isConstant() + { + return false; + } + + public VeraExpression getFunction() + { + return function; + } + + public List getArguments() + { + return arguments; + } + + public void addArgument(VeraExpression expr) + { + arguments.add(expr); + } + + public List getConstraints() + { + return constraints; + } + + public void addConstraint(VeraExpression expr) + { + constraints.add(expr); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionModifier.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionModifier.java new file mode 100644 index 0000000..55c07ce --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionModifier.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.FunctionModifier; + +/** + * Enumeration of Vera function modifiers. + * + * @author Trevor Robinson + */ +public enum VeraFunctionModifier implements FunctionModifier +{ + VIRTUAL, IMPLICIT; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionReference.java new file mode 100644 index 0000000..790c338 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionReference.java @@ -0,0 +1,56 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.FunctionReference; + +/** + * Represents a Vera function reference expression. + * + * @author Trevor Robinson + */ +public final class VeraFunctionReference + extends VeraExpression + implements FunctionReference +{ + private static final long serialVersionUID = 3257004350076170294L; + + private final VeraFunction function; + + public VeraFunctionReference(VeraFunction function) + { + super(function.schema); + setResultType(function.getType()); + this.function = function; + } + + public VeraFunction getFunction() + { + return function; + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionType.java new file mode 100644 index 0000000..92ba67d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraFunctionType.java @@ -0,0 +1,164 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.FunctionType; +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Type; +import com.newisys.langschema.util.NameTable; + +/** + * Represents a Vera function type. + * + * @author Trevor Robinson + */ +public final class VeraFunctionType + extends VeraType + implements FunctionType +{ + private static final long serialVersionUID = 3690756198181974584L; + + private final List arguments = new LinkedList(); + private final NameTable nameTable = new NameTable(); + private boolean varArgs; + private boolean varArgsByRef; + private VeraType returnType; + private boolean returnsXZ; + + public VeraFunctionType(VeraSchema schema) + { + super(schema); + } + + public VeraFunctionType(VeraType returnType, boolean returnsXZ) + { + super(returnType.schema); + this.returnType = returnType; + this.returnsXZ = returnsXZ; + } + + public List getArguments() + { + return arguments; + } + + public void addArgument(VeraFunctionArgument arg) + { + arguments.add(arg); + nameTable.addObject(arg); + } + + public void renameArgument(VeraFunctionArgument arg, VeraName newName) + { + assert (arguments.contains(arg)); + nameTable.removeObject(arg); + arg.setName(newName); + nameTable.addObject(arg); + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } + + public boolean isVarArgs() + { + return varArgs; + } + + public void setVarArgs(boolean varArgs) + { + this.varArgs = varArgs; + } + + public boolean isVarArgsByRef() + { + return varArgsByRef; + } + + public void setVarArgsByRef(boolean varArgsByRef) + { + this.varArgsByRef = varArgsByRef; + } + + public VeraType getReturnType() + { + return returnType; + } + + public void setReturnType(VeraType returnType) + { + this.returnType = returnType; + } + + public boolean isReturnsXZ() + { + return returnsXZ; + } + + public void setReturnsXZ(boolean returnsXZ) + { + this.returnsXZ = returnsXZ; + } + + public Set< ? extends VeraType> getExceptionTypes() + { + return Collections.emptySet(); + } + + public boolean isAssignableFrom(Type other) + { + // function types are used internally and never assigned + return false; + } + + public boolean equals(Object obj) + { + if (obj instanceof VeraFunctionType) + { + VeraFunctionType other = (VeraFunctionType) obj; + return returnType.equals(other.returnType); + } + return false; + } + + public int hashCode() + { + return VeraFunctionType.class.hashCode() ^ returnType.hashCode(); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } + + public String toReferenceString() + { + // since there is no way to "reference" a function type (which are + // really just introduced to simplify the schema), just return the + // source string + return toSourceString(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalFunction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalFunction.java new file mode 100644 index 0000000..e667c6a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalFunction.java @@ -0,0 +1,73 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera global function. + * + * @author Trevor Robinson + */ +public class VeraGlobalFunction + extends VeraFunction + implements VeraCompilationUnitMember, VeraSchemaMember +{ + private static final long serialVersionUID = 3688785869184120885L; + + private boolean export; + private VeraCompilationUnit compUnit; + + public VeraGlobalFunction(VeraName name, VeraFunctionType funcType) + { + super(name, funcType); + } + + public boolean isExport() + { + return export; + } + + public void setExport(boolean export) + { + this.export = export; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraSchemaMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalVariable.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalVariable.java new file mode 100644 index 0000000..0bbdb00 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGlobalVariable.java @@ -0,0 +1,73 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera global variable. + * + * @author Trevor Robinson + */ +public class VeraGlobalVariable + extends VeraVariable + implements VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3834876862458507832L; + + private boolean extern; + private VeraCompilationUnit compUnit; + + public VeraGlobalVariable(VeraName name, VeraType type) + { + super(name, type); + } + + public boolean isExtern() + { + return extern; + } + + public void setExtern(boolean extern) + { + this.extern = extern; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreater.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreater.java new file mode 100644 index 0000000..d6c25fd --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreater.java @@ -0,0 +1,87 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera greater-than operation. + * + * @author Trevor Robinson + */ +public final class VeraGreater + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3978430199958222131L; + + public VeraGreater(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Bit result; + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + VeraType commonType = getCommonIntegralType(type1, type2); + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraIntegerType) + { + return IntegerOp.greater((Integer) io1, (Integer) io2); + } + else if (commonType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) io1; + BitVector bv2 = (BitVector) io2; + if (bv1.containsXZ() || bv2.containsXZ()) + { + result = Bit.X; + } + else + { + result = bv1.compareTo(bv2) > 0 ? Bit.ONE : Bit.ZERO; + } + } + else + { + assert (getResultType() instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b1.isXZ() || b2.isXZ()) + { + result = Bit.X; + } + else + { + result = b1.getID() > b2.getID() ? Bit.ONE : Bit.ZERO; + } + } + return result; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreaterOrEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreaterOrEqual.java new file mode 100644 index 0000000..2fcb28c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraGreaterOrEqual.java @@ -0,0 +1,87 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera greater-or-equal operation. + * + * @author Trevor Robinson + */ +public final class VeraGreaterOrEqual + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3257004358716503605L; + + public VeraGreaterOrEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Bit result; + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + VeraType commonType = getCommonIntegralType(type1, type2); + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraIntegerType) + { + return IntegerOp.greaterOrEqual((Integer) io1, (Integer) io2); + } + else if (commonType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) io1; + BitVector bv2 = (BitVector) io2; + if (bv1.containsXZ() || bv2.containsXZ()) + { + result = Bit.X; + } + else + { + result = bv1.compareTo(bv2) >= 0 ? Bit.ONE : Bit.ZERO; + } + } + else + { + assert (getResultType() instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b1.isXZ() || b2.isXZ()) + { + result = Bit.X; + } + else + { + result = b1.getID() >= b2.getID() ? Bit.ONE : Bit.ZERO; + } + } + return result; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraHDLFunction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraHDLFunction.java new file mode 100644 index 0000000..4b36a04 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraHDLFunction.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera HDL function. + * + * @author Trevor Robinson + */ +public final class VeraHDLFunction + extends VeraGlobalFunction +{ + private static final long serialVersionUID = 3258134656585971512L; + + private String instPath; + + public VeraHDLFunction(VeraName name, VeraFunctionType funcType) + { + super(name, funcType); + } + + public String getInstPath() + { + return instPath; + } + + public void setInstPath(String instPath) + { + this.instPath = instPath; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfElseConstraint.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfElseConstraint.java new file mode 100644 index 0000000..c9cfa7f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfElseConstraint.java @@ -0,0 +1,74 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera if-else constraint operation. + * + * @author Trevor Robinson + */ +public final class VeraIfElseConstraint + extends VeraTernaryOperation +{ + private static final long serialVersionUID = 3689347715246994225L; + + public VeraIfElseConstraint( + VeraExpression ifExpr, + VeraExpression thenExpr, + VeraExpression elseExpr) + { + super(ifExpr, thenExpr, elseExpr); + if (!ifExpr.getResultType().isIntegralConvertible() + || !thenExpr.getResultType().isIntegralConvertible() + || (elseExpr != null && !elseExpr.getResultType() + .isIntegralConvertible())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(schema.bitType); + } + + public VeraExpression getIfExpression() + { + return op1; + } + + public VeraExpression getThenExpression() + { + return op2; + } + + public VeraExpression getElseExpression() + { + return op3; + } + + public Object evaluateConstant() + { + boolean b1 = toBoolean(op1.evaluateConstant()); + return b1 ? op2.evaluateConstant() : (op3 != null ? op3 + .evaluateConstant() : Boolean.TRUE); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfStatement.java new file mode 100644 index 0000000..c3d8d63 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIfStatement.java @@ -0,0 +1,77 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.IfStatement; + +/** + * Represents a Vera 'if' statement. + * + * @author Trevor Robinson + */ +public final class VeraIfStatement + extends VeraStatementImpl + implements IfStatement +{ + private static final long serialVersionUID = 3256718485626107440L; + + private final VeraExpression condition; + private final VeraStatement thenStatement; + private final VeraStatement elseStatement; + + public VeraIfStatement( + VeraExpression condition, + VeraStatement thenStatement, + VeraStatement elseStatement) + { + super(condition.schema); + this.condition = condition; + thenStatement.setContainingStatement(this); + this.thenStatement = thenStatement; + if (elseStatement != null) + { + elseStatement.setContainingStatement(this); + } + this.elseStatement = elseStatement; + } + + public VeraExpression getCondition() + { + return condition; + } + + public VeraStatement getThenStatement() + { + return thenStatement; + } + + public VeraStatement getElseStatement() + { + return elseStatement; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "if statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraImplicationConstraint.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraImplicationConstraint.java new file mode 100644 index 0000000..e712a37 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraImplicationConstraint.java @@ -0,0 +1,64 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera implication constraint operation. + * + * @author Trevor Robinson + */ +public final class VeraImplicationConstraint + extends VeraBinaryOperation +{ + private static final long serialVersionUID = 3257284729785955639L; + + public VeraImplicationConstraint( + VeraExpression predicate, + VeraExpression constraint) + { + super(predicate, constraint); + if (!isValidTypes(predicate.getResultType(), constraint.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(schema.bitType); + } + + public VeraExpression getPredicate() + { + return op1; + } + + public VeraExpression getConstraint() + { + return op2; + } + + public Object evaluateConstant() + { + boolean b1 = toBoolean(op1.evaluateConstant()); + return b1 ? op2.evaluateConstant() : Boolean.TRUE; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraInSet.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInSet.java new file mode 100644 index 0000000..26bf2c3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInSet.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera 'in' operation in a random constraint. + * + * @author Trevor Robinson + */ +public final class VeraInSet + extends VeraSetOperation +{ + private static final long serialVersionUID = 3618140043680561462L; + + public VeraInSet(VeraExpression expr) + { + super(expr); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraIncDecOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIncDecOperation.java new file mode 100644 index 0000000..0104577 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIncDecOperation.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera unary increment/decrement operations. + * + * @author Trevor Robinson + */ +public abstract class VeraIncDecOperation + extends VeraUnaryOperation +{ + public VeraIncDecOperation(VeraExpression op1) + { + super(op1); + if (!op1.getResultType().isIntegralConvertible()) + { + throw new SemanticException("Incorrect operand type"); + } + setResultType(op1.getResultType()); + } + + public boolean isConstant() + { + return false; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraInstanceCreation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInstanceCreation.java new file mode 100644 index 0000000..38edeca --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInstanceCreation.java @@ -0,0 +1,71 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.InstanceCreation; + +/** + * Represents a Vera instance creation expression. + * + * @author Trevor Robinson + */ +public final class VeraInstanceCreation + extends VeraExpression + implements InstanceCreation +{ + private static final long serialVersionUID = 3257850986847679796L; + + private final VeraComplexType type; + private final List arguments = new LinkedList(); + + public VeraInstanceCreation(VeraComplexType type) + { + super(type.schema); + assert (type instanceof VeraClass || type instanceof VeraPortType); + setResultType(type); + this.type = type; + } + + public boolean isConstant() + { + return false; + } + + public VeraComplexType getType() + { + return type; + } + + public List getArguments() + { + return arguments; + } + + public void addArgument(VeraExpression expr) + { + arguments.add(expr); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerLiteral.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerLiteral.java new file mode 100644 index 0000000..08c9029 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerLiteral.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Literal; + +/** + * Represents a Vera integer literal expression. + * + * @author Trevor Robinson + */ +public final class VeraIntegerLiteral + extends VeraExpression + implements Literal +{ + private static final long serialVersionUID = 3618978971086435124L; + + private final int value; + + public VeraIntegerLiteral(VeraSchema schema, int value) + { + super(schema); + setResultType(schema.integerType); + this.value = value; + } + + public int getValue() + { + return value; + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return new Integer(value); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerType.java new file mode 100644 index 0000000..13838a6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraIntegerType.java @@ -0,0 +1,64 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents the Vera integer type. + * + * @author Trevor Robinson + */ +public final class VeraIntegerType + extends VeraPrimitiveType +{ + private static final long serialVersionUID = 3544948857550025785L; + + VeraIntegerType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + return other instanceof VeraIntegerType + || other instanceof VeraBitVectorType + || other instanceof VeraBitType || other instanceof VeraEnumeration + || other instanceof VeraStringType; + } + + public boolean isStrictIntegral() + { + return true; + } + + public int getBitCount() + { + return 32; + } + + public String toReferenceString() + { + return "integer"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceReference.java new file mode 100644 index 0000000..671f1a5 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceReference.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera interface reference expression. + * + * @author Trevor Robinson + */ +public final class VeraInterfaceReference + extends VeraExpression +{ + private static final long serialVersionUID = 3257570624300725816L; + + private final VeraInterfaceType intf; + + public VeraInterfaceReference(VeraInterfaceType intf) + { + super(intf.schema); + setResultType(intf); + this.intf = intf; + } + + public VeraInterfaceType getInterface() + { + return intf; + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceSignal.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceSignal.java new file mode 100644 index 0000000..e33348c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceSignal.java @@ -0,0 +1,213 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.NamedObject; +import com.newisys.verilog.EdgeSet; + +/** + * Represents a signal declared in a Vera interface. + * + * @author Trevor Robinson + */ +public final class VeraInterfaceSignal + extends VeraSchemaObjectImpl + implements NamedObject, VeraStructuredTypeMember +{ + private static final long serialVersionUID = 3832904355660903475L; + + private final VeraName name; + private final VeraSignalKind kind; + private final VeraSignalDirection direction; + private final int width; + private final VeraType type; + private EdgeSet sampleEdges; + private int sampleSkew; + private int sampleDepth; + private EdgeSet driveEdges; + private int driveSkew; + private final List surrXParamsList; + private VeraVCAKind vcaKind; + private VeraVCAQValue vcaQValue; + private String hdlNode; + private VeraInterfaceType intf; + + public VeraInterfaceSignal( + VeraSchema schema, + VeraName name, + VeraSignalKind kind, + VeraSignalDirection direction, + int width) + { + super(schema); + this.name = name; + this.kind = kind; + this.direction = direction; + this.width = width; + this.type = new VeraFixedBitVectorType(schema, width); + this.sampleEdges = EdgeSet.NO_EDGE; + this.driveEdges = EdgeSet.NO_EDGE; + this.surrXParamsList = new LinkedList(); + this.sampleDepth = 0; + this.vcaKind = VeraVCAKind.NONE; + this.vcaQValue = VeraVCAQValue.HOLD; + } + + public VeraName getName() + { + return name; + } + + public VeraSignalKind getKind() + { + return kind; + } + + public VeraSignalDirection getDirection() + { + return direction; + } + + public int getWidth() + { + return width; + } + + public VeraType getType() + { + return type; + } + + public EdgeSet getSampleEdges() + { + return sampleEdges; + } + + public void setSampleEdges(EdgeSet sampleEdges) + { + this.sampleEdges = sampleEdges; + } + + public int getSampleSkew() + { + return sampleSkew; + } + + public void setSampleSkew(int sampleSkew) + { + this.sampleSkew = sampleSkew; + } + + public int getSampleDepth() + { + return sampleDepth; + } + + public void setSampleDepth(int depth) + { + this.sampleDepth = depth; + } + + public EdgeSet getDriveEdges() + { + return driveEdges; + } + + public void setDriveEdges(EdgeSet driveEdges) + { + this.driveEdges = driveEdges; + } + + public int getDriveSkew() + { + return driveSkew; + } + + public void setDriveSkew(int driveSkew) + { + this.driveSkew = driveSkew; + } + + public List getSurrXParamsList() + { + return surrXParamsList; + } + + public void addSurrXParams(VeraSurrXParams surrXParams) + { + surrXParamsList.add(surrXParams); + } + + public VeraVCAKind getVCAKind() + { + return vcaKind; + } + + public void setVCAKind(VeraVCAKind vcaKind) + { + this.vcaKind = vcaKind; + } + + public VeraVCAQValue getVCAQValue() + { + return vcaQValue; + } + + public void setVCAQValue(VeraVCAQValue vcaQValue) + { + this.vcaQValue = vcaQValue; + } + + public String getHDLNode() + { + return hdlNode; + } + + public void setHDLNode(String hdlNode) + { + this.hdlNode = hdlNode; + } + + public VeraInterfaceType getStructuredType() + { + return intf; + } + + public void setInterface(VeraInterfaceType intf) + { + this.intf = intf; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "interface signal " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceType.java new file mode 100644 index 0000000..294b6c1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraInterfaceType.java @@ -0,0 +1,75 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents a Vera signal interface. + * + * @author Trevor Robinson + */ +public final class VeraInterfaceType + extends VeraStructuredType + implements VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3689069556052277560L; + + private VeraCompilationUnit compUnit; + + public VeraInterfaceType(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public void addMember(VeraInterfaceSignal member) + { + member.setInterface(this); + super.addMember(member); + } + + public boolean isAssignableFrom(Type other) + { + return false; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "interface " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLeftShift.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLeftShift.java new file mode 100644 index 0000000..ebe29f3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLeftShift.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera left shift operation. + * + * @author Trevor Robinson + */ +public final class VeraLeftShift + extends VeraShiftOperation +{ + private static final long serialVersionUID = 3256722875032351027L; + + public VeraLeftShift(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Object o1 = toIntegral(op1.evaluateConstant()); + int count = getShiftCount(op2.evaluateConstant()); + if (o1 instanceof Integer) + { + int i1 = ((Integer) o1).intValue(); + return new Integer(i1 << count); + } + else if (o1 instanceof BitVector) + { + BitVector bv1 = (BitVector) o1; + return bv1.shiftLeft(count); + } + else if (o1 instanceof Bit) + { + return count == 0 ? o1 : Bit.ZERO; + } + else + { + assert (o1 == null); + return null; + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLess.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLess.java new file mode 100644 index 0000000..09550e4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLess.java @@ -0,0 +1,87 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera less-than operation. + * + * @author Trevor Robinson + */ +public final class VeraLess + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3832616270745972792L; + + public VeraLess(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Bit result; + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + VeraType commonType = getCommonIntegralType(type1, type2); + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraIntegerType) + { + return IntegerOp.less((Integer) io1, (Integer) io2); + } + else if (commonType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) io1; + BitVector bv2 = (BitVector) io2; + if (bv1.containsXZ() || bv2.containsXZ()) + { + result = Bit.X; + } + else + { + result = bv1.compareTo(bv2) < 0 ? Bit.ONE : Bit.ZERO; + } + } + else + { + assert (getResultType() instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b1.isXZ() || b2.isXZ()) + { + result = Bit.X; + } + else + { + result = b1.getID() < b2.getID() ? Bit.ONE : Bit.ZERO; + } + } + return result; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLessOrEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLessOrEqual.java new file mode 100644 index 0000000..395482e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLessOrEqual.java @@ -0,0 +1,87 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera less-or-equal operation. + * + * @author Trevor Robinson + */ +public final class VeraLessOrEqual + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3546084674452927024L; + + public VeraLessOrEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Bit result; + VeraType type1 = op1.getResultType(); + VeraType type2 = op2.getResultType(); + VeraType commonType = getCommonIntegralType(type1, type2); + Object o1 = op1.evaluateConstant(); + Object o2 = op2.evaluateConstant(); + Object io1 = toCommonIntegralType(o1, commonType); + Object io2 = toCommonIntegralType(o2, commonType); + if (commonType instanceof VeraIntegerType) + { + return IntegerOp.lessOrEqual((Integer) io1, (Integer) io2); + } + else if (commonType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) io1; + BitVector bv2 = (BitVector) io2; + if (bv1.containsXZ() || bv2.containsXZ()) + { + result = Bit.X; + } + else + { + result = bv1.compareTo(bv2) <= 0 ? Bit.ONE : Bit.ZERO; + } + } + else + { + assert (getResultType() instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b1.isXZ() || b2.isXZ()) + { + result = Bit.X; + } + else + { + result = b1.getID() <= b2.getID() ? Bit.ONE : Bit.ZERO; + } + } + return result; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLocalVariable.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLocalVariable.java new file mode 100644 index 0000000..dcd26b1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLocalVariable.java @@ -0,0 +1,57 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera local variable. + * + * @author Trevor Robinson + */ +public final class VeraLocalVariable + extends VeraVariable + implements VeraBlockMember +{ + private static final long serialVersionUID = 3258689927205304116L; + + private VeraStatement containingStatement; + + public VeraLocalVariable(VeraName name, VeraType type) + { + super(name, type); + } + + public VeraStatement getContainingStatement() + { + return containingStatement; + } + + public void setContainingStatement(VeraStatement stmt) + { + this.containingStatement = stmt; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraBlockMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalAnd.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalAnd.java new file mode 100644 index 0000000..5e3bf19 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalAnd.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera logical-and operation. + * + * @author Trevor Robinson + */ +public final class VeraLogicalAnd + extends VeraBinaryLogicalOperation +{ + private static final long serialVersionUID = 3257847684034408760L; + + public VeraLogicalAnd(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + boolean b1 = toBoolean(op1.evaluateConstant()); + boolean b2 = toBoolean(op2.evaluateConstant()); + return b1 && b2 ? INTEGER_ONE : INTEGER_ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalNegative.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalNegative.java new file mode 100644 index 0000000..31f91b3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalNegative.java @@ -0,0 +1,70 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera logical-not operation. + * + * @author Trevor Robinson + */ +public final class VeraLogicalNegative + extends VeraUnaryOperation +{ + private static final long serialVersionUID = 3762813800893658676L; + + public VeraLogicalNegative(VeraExpression op1) + { + super(op1); + if (!op1.getResultType().isIntegralConvertible()) + { + throw new SemanticException("Incorrect operand type"); + } + setResultType(schema.integerType); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.logicalNegative((Integer) o); + } + else if (o instanceof BitVector) + { + BitVector bv = (BitVector) o; + return bv.containsXZ() ? null : (bv.isZero() ? INTEGER_ONE + : INTEGER_ZERO); + } + else + { + assert (o instanceof Bit); + return o == Bit.ZERO ? INTEGER_ONE : (o == Bit.ONE ? INTEGER_ZERO + : null); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalOr.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalOr.java new file mode 100644 index 0000000..cfa9deb --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraLogicalOr.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera logical-or operation. + * + * @author Trevor Robinson + */ +public final class VeraLogicalOr + extends VeraBinaryLogicalOperation +{ + private static final long serialVersionUID = 3257288028304389430L; + + public VeraLogicalOr(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + boolean b1 = toBoolean(op1.evaluateConstant()); + boolean b2 = toBoolean(op2.evaluateConstant()); + return b1 || b2 ? INTEGER_ONE : INTEGER_ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraMagicType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMagicType.java new file mode 100644 index 0000000..b72a8f1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMagicType.java @@ -0,0 +1,57 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents the Vera "magic" type, used by the built-in tasks and functions + * that can accept or return arbitrary types. + * + * @author Trevor Robinson + */ +public final class VeraMagicType + extends VeraType +{ + private static final long serialVersionUID = 3258688806235746352L; + + VeraMagicType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + return true; + } + + public boolean isIntegralConvertible() + { + return true; + } + + public String toReferenceString() + { + return "magic"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberAccess.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberAccess.java new file mode 100644 index 0000000..be4fda1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberAccess.java @@ -0,0 +1,95 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.MemberAccess; +import com.newisys.langschema.util.SemanticException; + +/** + * Represents a Vera member access expression. + * + * @author Trevor Robinson + */ +public final class VeraMemberAccess + extends VeraExpression + implements MemberAccess +{ + private static final long serialVersionUID = 3257564022969546288L; + + private final VeraExpression object; + private final VeraStructuredTypeMember member; + + public VeraMemberAccess( + VeraExpression object, + VeraStructuredTypeMember member) + { + super(object.schema); + if (member instanceof VeraMemberFunction) + { + VeraMemberFunction func = (VeraMemberFunction) member; + setResultType(func.getType()); + } + else if (member instanceof VeraMemberVariable) + { + VeraMemberVariable var = (VeraMemberVariable) member; + setResultType(var.getType()); + } + else if (member instanceof VeraPortSignal) + { + VeraPortSignal signal = (VeraPortSignal) member; + setResultType(signal.getType()); + } + else if (member instanceof VeraInterfaceSignal) + { + VeraInterfaceSignal signal = (VeraInterfaceSignal) member; + setResultType(signal.getType()); + } + else + { + throw new SemanticException("Invalid member access to " + + member.getClass().getName()); + } + this.object = object; + this.member = member; + } + + public boolean isAssignable() + { + return !(member instanceof VeraMemberFunction); + } + + public boolean isConstant() + { + return false; + } + + public VeraExpression getObject() + { + return object; + } + + public VeraStructuredTypeMember getMember() + { + return member; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberFunction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberFunction.java new file mode 100644 index 0000000..e22f850 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberFunction.java @@ -0,0 +1,126 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import com.newisys.langschema.MemberFunction; + +/** + * Represents a Vera class member function. + * + * @author Trevor Robinson + */ +public final class VeraMemberFunction + extends VeraFunction + implements MemberFunction, VeraClassMember +{ + private static final long serialVersionUID = 3257846580261237560L; + + private boolean virtual; + private boolean pureVirtual; + private boolean implicit; + private Set modifiers; + private VeraClass cls; + + public VeraMemberFunction(VeraName name, VeraFunctionType funcType) + { + super(name, funcType); + modifiers = Collections.emptySet(); + } + + public Set getModifiers() + { + return modifiers; + } + + private void setModifier(VeraFunctionModifier modifier, boolean on) + { + if (on) + { + if (modifiers == Collections.EMPTY_SET) + { + modifiers = new HashSet(); + } + modifiers.add(modifier); + } + else if (modifiers.contains(modifier)) + { + modifiers.remove(modifier); + } + } + + public boolean isConstructor() + { + return getName().getIdentifier().equals("new"); + } + + public boolean isVirtual() + { + return virtual; + } + + public void setVirtual(boolean virtual) + { + this.virtual = virtual; + setModifier(VeraFunctionModifier.VIRTUAL, virtual); + } + + public boolean isPureVirtual() + { + return pureVirtual; + } + + public void setPureVirtual(boolean pureVirtual) + { + this.pureVirtual = pureVirtual; + } + + public boolean isImplicit() + { + return implicit; + } + + public void setImplicit(boolean implicit) + { + this.implicit = implicit; + setModifier(VeraFunctionModifier.IMPLICIT, implicit); + } + + public VeraClass getStructuredType() + { + return cls; + } + + public void setClass(VeraClass cls) + { + this.cls = cls; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraClassMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberVariable.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberVariable.java new file mode 100644 index 0000000..7e903a2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMemberVariable.java @@ -0,0 +1,92 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.MemberVariable; + +/** + * Represents a Vera class member variable. + * + * @author Trevor Robinson + */ +public final class VeraMemberVariable + extends VeraVariable + implements MemberVariable, VeraClassMember +{ + private static final long serialVersionUID = 3618142268490331448L; + + private VeraClass cls; + private VeraVisibility visibility; + private VeraExpression randomSize; + private boolean defined; + + public VeraMemberVariable(VeraName name, VeraType type) + { + super(name, type); + } + + public VeraClass getStructuredType() + { + return cls; + } + + public void setClass(VeraClass cls) + { + this.cls = cls; + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public VeraExpression getRandomSize() + { + return randomSize; + } + + public void setRandomSize(VeraExpression randomSize) + { + this.randomSize = randomSize; + } + + public boolean isDefined() + { + return defined; + } + + public void setDefined(boolean defined) + { + this.defined = defined; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraClassMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraModulo.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraModulo.java new file mode 100644 index 0000000..4209f3d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraModulo.java @@ -0,0 +1,71 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera modulo operation. + * + * @author Trevor Robinson + */ +public final class VeraModulo + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3258134652274424119L; + + public VeraModulo(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.mod((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.mod(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + if (b2 == Bit.ZERO) + { + throw new ArithmeticException("Bit divide by zero"); + } + return b1.isXZ() || b2.isXZ() ? Bit.X : Bit.ZERO; + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraMultiply.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMultiply.java new file mode 100644 index 0000000..c1a9422 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraMultiply.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera multiplication operation. + * + * @author Trevor Robinson + */ +public final class VeraMultiply + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3257281452809662518L; + + public VeraMultiply(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.multiply((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.multiply(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.and(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraName.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraName.java new file mode 100644 index 0000000..97d93ee --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraName.java @@ -0,0 +1,89 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Name; +import com.newisys.langschema.Namespace; + +/** + * Represents a Vera name. + * + * @author Trevor Robinson + */ +public final class VeraName + implements Name +{ + private static final long serialVersionUID = 3258135743162431024L; + + private final String identifier; + private final VeraNameKind kind; + private final Namespace namespace; + + public VeraName(String identifier, VeraNameKind kind, Namespace namespace) + { + this.identifier = identifier; + this.kind = kind; + this.namespace = namespace; + } + + public String getIdentifier() + { + return identifier; + } + + public VeraNameKind getKind() + { + return kind; + } + + public Namespace getNamespace() + { + return namespace; + } + + public String getCanonicalName() + { + return (namespace != null) ? namespace.getName().getCanonicalName() + + "::" + identifier : identifier; + } + + public boolean equals(Object obj) + { + if (obj instanceof VeraName) + { + VeraName other = (VeraName) obj; + return identifier.equals(other.identifier) + && kind == other.kind + && (namespace != null && other.namespace != null ? namespace + .getName().equals(other.namespace.getName()) + : namespace == other.namespace); + } + return false; + } + + public int hashCode() + { + return identifier.hashCode() ^ kind.hashCode() + ^ (namespace != null ? namespace.hashCode() : 0); + } + + public String toString() + { + return getCanonicalName(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNameKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNameKind.java new file mode 100644 index 0000000..5f684e9 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNameKind.java @@ -0,0 +1,35 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.NameKind; + +/** + * Enumeration of Vera name kinds. + * + * @author Trevor Robinson + */ +public enum VeraNameKind implements NameKind +{ + ANY, TYPE, NON_TYPE, COMP_UNIT, PREPROC; + + public boolean contains(NameKind kind) + { + return (this == ANY) ? true : (this == kind); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNaryOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNaryOperation.java new file mode 100644 index 0000000..dbefb72 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNaryOperation.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera operations of arbitrary arity. + * + * @author Trevor Robinson + */ +public abstract class VeraNaryOperation + extends VeraOperation +{ + public VeraNaryOperation(VeraSchema schema) + { + super(schema); + } + + public void addOperand(VeraExpression expr) + { + operands.add(expr); + } + + public boolean isConstant() + { + for (VeraExpression expr : operands) + { + if (!expr.isConstant()) return false; + } + return true; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotAndReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotAndReduction.java new file mode 100644 index 0000000..9834876 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotAndReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-and-not operation. + * + * @author Trevor Robinson + */ +public final class VeraNotAndReduction + extends VeraReduction +{ + private static final long serialVersionUID = 3257003250514540081L; + + public VeraNotAndReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveAndNot((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveAnd().not(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotEqual.java new file mode 100644 index 0000000..576290a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotEqual.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera inequality expression. + * + * @author Trevor Robinson + */ +public final class VeraNotEqual + extends VeraEqualOperation +{ + private static final long serialVersionUID = 3257567287144888372L; + + public VeraNotEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return isEqual().not(); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotInSet.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotInSet.java new file mode 100644 index 0000000..a70c440 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotInSet.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera '!in' operation in a random constraint. + * + * @author Trevor Robinson + */ +public final class VeraNotInSet + extends VeraSetOperation +{ + private static final long serialVersionUID = 3258130241326429746L; + + public VeraNotInSet(VeraExpression expr) + { + super(expr); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotOrReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotOrReduction.java new file mode 100644 index 0000000..d9c8688 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotOrReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-or-not operation. + * + * @author Trevor Robinson + */ +public final class VeraNotOrReduction + extends VeraReduction +{ + private static final long serialVersionUID = 3690480229370245431L; + + public VeraNotOrReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveOrNot((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveOr().not(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotXorReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotXorReduction.java new file mode 100644 index 0000000..df7917b --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNotXorReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-xor-not operation. + * + * @author Trevor Robinson + */ +public final class VeraNotXorReduction + extends VeraReduction +{ + private static final long serialVersionUID = 3835150662261813298L; + + public VeraNotXorReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveXorNot((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveXor().not(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).not(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullLiteral.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullLiteral.java new file mode 100644 index 0000000..e5f6322 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullLiteral.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Literal; + +/** + * Represents the Vera null literal. + * + * @author Trevor Robinson + */ +public final class VeraNullLiteral + extends VeraExpression + implements Literal +{ + private static final long serialVersionUID = 3545234726278149681L; + + public VeraNullLiteral(VeraSchema schema) + { + super(schema); + setResultType(schema.nullType); + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return null; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullType.java new file mode 100644 index 0000000..4a98823 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraNullType.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.NullType; +import com.newisys.langschema.Type; + +/** + * Represents the Vera null type. + * + * @author Trevor Robinson + */ +public final class VeraNullType + extends VeraType + implements NullType +{ + private static final long serialVersionUID = 3257565109646536755L; + + VeraNullType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + return other == this; + } + + public String toReferenceString() + { + return "null"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraOperation.java new file mode 100644 index 0000000..dfc65a6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraOperation.java @@ -0,0 +1,60 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.Operation; +import com.newisys.langschema.OperationModifier; + +/** + * Base class for Vera operation expressions. + * + * @author Trevor Robinson + */ +public abstract class VeraOperation + extends VeraExpression + implements Operation +{ + private static final long serialVersionUID = 3879069680342341263L; + + protected final List operands = new LinkedList(); + + public VeraOperation(VeraSchema schema) + { + super(schema); + } + + public List getOperands() + { + return operands; + } + + public VeraExpression getOperand(int index) + { + return operands.get(index); + } + + public Set< ? extends OperationModifier> getModifiers() + { + return Collections.emptySet(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraOrReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraOrReduction.java new file mode 100644 index 0000000..22b5b99 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraOrReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-or operation. + * + * @author Trevor Robinson + */ +public final class VeraOrReduction + extends VeraReduction +{ + private static final long serialVersionUID = 4049355335725035831L; + + public VeraOrReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveOr((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveOr(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).ztox(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortSignal.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortSignal.java new file mode 100644 index 0000000..127d1d9 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortSignal.java @@ -0,0 +1,76 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.NamedObject; + +/** + * Represents a signal in a Vera port. + * + * @author Trevor Robinson + */ +public final class VeraPortSignal + extends VeraSchemaObjectImpl + implements NamedObject, VeraStructuredTypeMember +{ + private static final long serialVersionUID = 3833470621362631993L; + + private final VeraName name; + private VeraPortType port; + + public VeraPortSignal(VeraSchema schema, VeraName name) + { + super(schema); + this.name = name; + } + + public VeraName getName() + { + return name; + } + + public VeraType getType() + { + return schema.bitVectorType; + } + + public VeraPortType getStructuredType() + { + return port; + } + + public void setPort(VeraPortType port) + { + this.port = port; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.PUBLIC; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "port signal " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortType.java new file mode 100644 index 0000000..8d681b8 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPortType.java @@ -0,0 +1,75 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents a Vera port type. + * + * @author Trevor Robinson + */ +public final class VeraPortType + extends VeraStructuredType + implements VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3690478008922224697L; + + private VeraCompilationUnit compUnit; + + public VeraPortType(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public void addMember(VeraPortSignal member) + { + member.setPort(this); + super.addMember(member); + } + + public boolean isAssignableFrom(Type other) + { + return other == this || other instanceof VeraNullType; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "port " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostDecrement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostDecrement.java new file mode 100644 index 0000000..2bb840c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostDecrement.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera post-decrement operation. + * + * @author Trevor Robinson + */ +public final class VeraPostDecrement + extends VeraIncDecOperation +{ + private static final long serialVersionUID = 3905806361727218738L; + + public VeraPostDecrement(VeraExpression op1) + { + super(op1); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostIncrement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostIncrement.java new file mode 100644 index 0000000..6c97822 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPostIncrement.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera post-increment operation. + * + * @author Trevor Robinson + */ +public final class VeraPostIncrement + extends VeraIncDecOperation +{ + private static final long serialVersionUID = 3256726199421253176L; + + public VeraPostIncrement(VeraExpression op1) + { + super(op1); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreDecrement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreDecrement.java new file mode 100644 index 0000000..d94f7f1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreDecrement.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera pre-decrement operation. + * + * @author Trevor Robinson + */ +public final class VeraPreDecrement + extends VeraIncDecOperation +{ + private static final long serialVersionUID = 3763101851465429559L; + + public VeraPreDecrement(VeraExpression op1) + { + super(op1); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreIncrement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreIncrement.java new file mode 100644 index 0000000..ec64e89 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPreIncrement.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera pre-increment operation. + * + * @author Trevor Robinson + */ +public final class VeraPreIncrement + extends VeraIncDecOperation +{ + private static final long serialVersionUID = 4051047449776698931L; + + public VeraPreIncrement(VeraExpression op1) + { + super(op1); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveKind.java new file mode 100644 index 0000000..c04f7bc --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveKind.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera primitive type kinds. + * + * @author Trevor Robinson + */ +public enum VeraPrimitiveKind +{ + BIT, BIT_VECTOR, EVENT, INTEGER, STRING; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveType.java new file mode 100644 index 0000000..a923165 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraPrimitiveType.java @@ -0,0 +1,35 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.PrimitiveType; + +/** + * Base class for Vera primitive types. + * + * @author Trevor Robinson + */ +public abstract class VeraPrimitiveType + extends VeraType + implements PrimitiveType +{ + public VeraPrimitiveType(VeraSchema schema) + { + super(schema); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraProgram.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraProgram.java new file mode 100644 index 0000000..d32490b --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraProgram.java @@ -0,0 +1,98 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedHashSet; +import java.util.Set; + +import com.newisys.langschema.NamedObject; + +/** + * Represents a Vera program block. + * + * @author Trevor Robinson + */ +public final class VeraProgram + extends VeraSchemaObjectImpl + implements NamedObject, VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3256719602334315829L; + + private final VeraName name; + private final VeraBlock block; + private final Set shellMembers; + private VeraCompilationUnit compUnit; + + public VeraProgram(VeraName name, VeraBlock block) + { + super(block.schema); + this.name = name; + this.block = block; + this.shellMembers = new LinkedHashSet(); + } + + public VeraName getName() + { + return name; + } + + public VeraBlock getBlock() + { + return block; + } + + public Set getShellMembers() + { + return shellMembers; + } + + public void addShellMember(VeraCompilationUnitMember member) + { + shellMembers.add(member); + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public VeraVisibility getVisibility() + { + return VeraVisibility.LOCAL; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "program " + name; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCase.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCase.java new file mode 100644 index 0000000..3fb0dab --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCase.java @@ -0,0 +1,50 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.io.Serializable; + +/** + * Represents a weighted case in a Vera randcase statement. + * + * @author Trevor Robinson + */ +public final class VeraRandCase + implements Serializable +{ + private static final long serialVersionUID = 3978983254441670965L; + + private final VeraExpression weight; + final VeraStatement statement; + + public VeraRandCase(VeraExpression weight, VeraStatement statement) + { + this.weight = weight; + this.statement = statement; + } + + public VeraExpression getWeight() + { + return weight; + } + + public VeraStatement getStatement() + { + return statement; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCaseStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCaseStatement.java new file mode 100644 index 0000000..ffa9757 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRandCaseStatement.java @@ -0,0 +1,60 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a Vera randcase statement. + * + * @author Trevor Robinson + */ +public final class VeraRandCaseStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3258128050893107250L; + + private final List caseList = new LinkedList(); + + public VeraRandCaseStatement(VeraSchema schema) + { + super(schema); + } + + public List getCaseList() + { + return caseList; + } + + public void addCase(VeraRandCase randCase) + { + randCase.statement.setContainingStatement(this); + caseList.add(randCase); + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "randcase statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRange.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRange.java new file mode 100644 index 0000000..eec0484 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRange.java @@ -0,0 +1,79 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Range; + +/** + * Represents a Vera bit slice range. This is represented as a separate object + * so that it can be linked to a #define. + * + * @author Trevor Robinson + */ +public class VeraRange + extends VeraSchemaObjectImpl + implements Range, VeraDefineReferrer +{ + private static final long serialVersionUID = 3689069556002076467L; + + private final VeraExpression from; + private final VeraExpression to; + private VeraDefineReference defineRef; + + public VeraRange(VeraSchema schema, VeraExpression from, VeraExpression to) + { + super(schema); + this.from = from; + this.to = to; + } + + public VeraExpression getFrom() + { + return from; + } + + public VeraExpression getTo() + { + return to; + } + + public boolean isConstant() + { + return from.isConstant() && to.isConstant(); + } + + public VeraDefineReference getDefineRef() + { + return defineRef; + } + + public void setDefineRef(VeraDefineReference defineRef) + { + this.defineRef = defineRef; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "range " + from + ":" + to; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRangeDefine.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRangeDefine.java new file mode 100644 index 0000000..b3a5506 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRangeDefine.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera preprocessor #define that parses as a bit slice range. + * + * @author Trevor Robinson + */ +public class VeraRangeDefine + extends VeraDefine +{ + private static final long serialVersionUID = 3834026974279577906L; + + private VeraRange range; + + public VeraRangeDefine(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public VeraRange getRange() + { + return range; + } + + public void setRange(VeraRange range) + { + this.range = range; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReduction.java new file mode 100644 index 0000000..28bc6db --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReduction.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera reduction operations. + * + * @author Trevor Robinson + */ +public abstract class VeraReduction + extends VeraUnaryOperation +{ + public VeraReduction(VeraExpression op1) + { + super(op1); + if (!op1.getResultType().isIntegralConvertible()) + { + throw new SemanticException("Incorrect operand type"); + } + setResultType(schema.bitType); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRepeatStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRepeatStatement.java new file mode 100644 index 0000000..fff4de6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRepeatStatement.java @@ -0,0 +1,60 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera repeat loop. + * + * @author Trevor Robinson + */ +public final class VeraRepeatStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3762533408148041783L; + + private final VeraExpression count; + private final VeraStatement statement; + + public VeraRepeatStatement(VeraExpression count, VeraStatement statement) + { + super(count.schema); + this.count = count; + statement.setContainingStatement(this); + this.statement = statement; + } + + public VeraExpression getCondition() + { + return count; + } + + public VeraStatement getStatement() + { + return statement; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "repeat statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraReplication.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReplication.java new file mode 100644 index 0000000..b2a5878 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReplication.java @@ -0,0 +1,101 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.BitVectorBuffer; + +/** + * Represents a Vera bit vector or string replication operation. + * + * @author Trevor Robinson + */ +public final class VeraReplication + extends VeraBinaryOperation +{ + private static final long serialVersionUID = 3689351022455631927L; + + public VeraReplication(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + if (op2.getResultType() instanceof VeraStringType) + { + setResultType(schema.stringType); + } + else + { + setResultType(schema.bitVectorType); + } + } + + protected static boolean isValidTypes(VeraType type1, VeraType type2) + { + return type1.isIntegralConvertible() + && (type2.isIntegralConvertible() || type2 instanceof VeraStringType); + } + + public Object evaluateConstant() + { + Integer i1 = toInteger(op1.evaluateConstant()); + if (i1 == null) + { + return null; + } + int count = i1.intValue(); + if (count <= 0) + { + return null; + } + Object o2 = op2.evaluateConstant(); + if (getResultType() instanceof VeraStringType) + { + String str = o2.toString(); + StringBuffer buf = new StringBuffer(str.length() * count); + for (int i = 0; i < count; ++i) + { + buf.append(str); + } + return buf.toString(); + } + else + { + BitVector bv = toBitVector(o2); + int len = bv.length(); + int size = len * count; + BitVectorBuffer buf = new BitVectorBuffer(size); + int lowBit = 0; + while (lowBit < size) + { + int highBit = lowBit + len - 1; + buf.setBits(highBit, lowBit, bv); + lowBit += len; + } + return buf.toBitVector(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraReturnStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReturnStatement.java new file mode 100644 index 0000000..3cb0ae4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraReturnStatement.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ReturnStatement; + +/** + * Represents a Vera return statement. + * + * @author Trevor Robinson + */ +public final class VeraReturnStatement + extends VeraStatementImpl + implements ReturnStatement +{ + private static final long serialVersionUID = 3546926878884900913L; + + public VeraReturnStatement(VeraSchema schema) + { + super(schema); + } + + public VeraExpression getReturnValue() + { + // Vera does not specify the return value in the 'return' statement + return null; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "repeat statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRightShift.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRightShift.java new file mode 100644 index 0000000..e1e39f7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRightShift.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera right shift operation. + * + * @author Trevor Robinson + */ +public final class VeraRightShift + extends VeraShiftOperation +{ + private static final long serialVersionUID = 3257844364058440753L; + + public VeraRightShift(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + Object o1 = toIntegral(op1.evaluateConstant()); + int count = getShiftCount(op2.evaluateConstant()); + if (o1 instanceof Integer) + { + int i1 = ((Integer) o1).intValue(); + return new Integer(i1 >> count); + } + else if (o1 instanceof BitVector) + { + BitVector bv1 = (BitVector) o1; + return bv1.shiftRight(count); + } + else if (o1 instanceof Bit) + { + return count == 0 ? o1 : Bit.ZERO; + } + else + { + assert (o1 == null); + return null; + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraRootClass.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRootClass.java new file mode 100644 index 0000000..9be25bd --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraRootClass.java @@ -0,0 +1,109 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents the (unnamed) Vera root class, which contains the built-in + * functions of every class. + * + * @author Trevor Robinson + */ +public class VeraRootClass + extends VeraSystemClass +{ + private static final long serialVersionUID = 3691034374740916534L; + + VeraRootClass(VeraSchema schema) + { + super(schema, new VeraName("", VeraNameKind.TYPE, null), null); + } + + void defineRootClass() + { + VeraMemberFunction f; + VeraFunctionArgument a; + + f = defineMemberFunction("constraint_mode", schema.integerType); + addArgument(f, "action", schema.integerType); + addOptArgument(f, "constraint_name", schema.stringType); + + f = defineMemberFunction("finalize", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("object_compare", schema.integerType); + addArgument(f, "other", schema.magicType); + + f = defineMemberFunction("object_copy", schema.magicType); + // no arguments + + f = defineMemberFunction("object_print", schema.voidType); + addOptArgument(f, "fd", 1); + addOptArgument(f, "attributes", schema.stringType); + + f = defineMemberFunction("pack", schema.integerType); + addArgument(f, "array", schema.magicType); + a = addArgument(f, "index", schema.integerType); + a.setByRef(true); + a = addArgument(f, "left", schema.integerType); + a.setByRef(true); + a = addArgument(f, "right", schema.integerType); + a.setByRef(true); + + f = defineMemberFunction("post_pack", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("post_randomize", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("post_unpack", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("pre_pack", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("pre_randomize", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("pre_unpack", schema.voidType); + f.setVirtual(true); + // no arguments + + f = defineMemberFunction("rand_mode", schema.integerType); + addArgument(f, "action", schema.integerType); + addOptArgument(f, "variable_name", schema.stringType); + addOptArgument(f, "index", schema.integerType); + + f = defineMemberFunction("randomize", schema.integerType); + // no arguments + + f = defineMemberFunction("unpack", schema.bitVector64Type); + addArgument(f, "array", schema.magicType); + a = addArgument(f, "index", schema.bitVector64Type); + a.setByRef(true); + a = addArgument(f, "left", schema.bitVector64Type); + a.setByRef(true); + a = addArgument(f, "right", schema.bitVector64Type); + a.setByRef(true); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchema.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchema.java new file mode 100644 index 0000000..b987e21 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchema.java @@ -0,0 +1,111 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Schema; +import com.newisys.langschema.util.NameTable; +import com.newisys.schemaprinter.vera.VeraSchemaPrinter; + +/** + * Represents a complete Vera schema. + * + * @author Trevor Robinson + */ +public final class VeraSchema + implements Schema +{ + private static final long serialVersionUID = 3256719580792632881L; + + private final List members = new LinkedList(); + private final NameTable nameTable = new NameTable(); + + private boolean useSourceString = true; + private transient VeraSchemaPrinter defaultPrinter; + + // define schema-singleton primitive type objects + public final VeraBitType bitType = new VeraBitType(this); + public final VeraFixedBitVectorType bitVector32Type = new VeraFixedBitVectorType( + this, 32); + public final VeraFixedBitVectorType bitVector64Type = new VeraFixedBitVectorType( + this, 64); + public final VeraUnsizedBitVectorType bitVectorType = new VeraUnsizedBitVectorType( + this); + public final VeraEventType eventType = new VeraEventType(this); + public final VeraIntegerType integerType = new VeraIntegerType(this); + public final VeraMagicType magicType = new VeraMagicType(this); + public final VeraNullType nullType = new VeraNullType(this); + public final VeraVoidType voidType = new VeraVoidType(this); + + // define schema-singleton primitive class objects + public final VeraRootClass rootClass = new VeraRootClass(this); + public final VeraStringType stringType = new VeraStringType(this, rootClass); + { + rootClass.defineRootClass(); + stringType.defineStringClass(); + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraSchemaMember member) + { + members.add(member); + if (member instanceof NamedObject) + { + nameTable.addObject((NamedObject) member); + } + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } + + public boolean isUseSourceString() + { + return useSourceString; + } + + public void setUseSourceString(boolean useSourceString) + { + this.useSourceString = useSourceString; + } + + public VeraSchemaPrinter getDefaultPrinter() + { + if (defaultPrinter == null) + { + defaultPrinter = new VeraSchemaPrinter(); + defaultPrinter.setCollapseBodies(true); + } + return defaultPrinter; + } + + public void setDefaultPrinter(VeraSchemaPrinter printer) + { + defaultPrinter = printer; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMember.java new file mode 100644 index 0000000..4f8353a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMember.java @@ -0,0 +1,31 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.SchemaMember; + +/** + * Interface implemented by Vera constructs that may be members of a schema. + * + * @author Trevor Robinson + */ +public interface VeraSchemaMember + extends SchemaMember +{ + void accept(VeraSchemaMemberVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMemberVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMemberVisitor.java new file mode 100644 index 0000000..d45e209 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaMemberVisitor.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera schema members. + * + * @author Trevor Robinson + */ +public interface VeraSchemaMemberVisitor +{ + void visit(VeraCompilationUnit obj); + + void visit(VeraGlobalFunction obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObject.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObject.java new file mode 100644 index 0000000..afbbf67 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObject.java @@ -0,0 +1,38 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collection; + +import com.newisys.langschema.Annotation; +import com.newisys.langschema.SchemaObject; + +/** + * Base interface for all Vera schema objects. + * + * @author Trevor Robinson + */ +public interface VeraSchemaObject + extends SchemaObject +{ + void addAnnotation(Annotation annotation); + + void addAnnotations(Collection c); + + void accept(VeraSchemaObjectVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectImpl.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectImpl.java new file mode 100644 index 0000000..12cfb87 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectImpl.java @@ -0,0 +1,85 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.Annotation; +import com.newisys.langschema.Schema; + +/** + * Base implementation for all Vera schema objects. + * + * @author Trevor Robinson + */ +public abstract class VeraSchemaObjectImpl + implements VeraSchemaObject +{ + protected final VeraSchema schema; + private List annotations; + + public VeraSchemaObjectImpl(VeraSchema schema) + { + this.schema = schema; + } + + public final Schema getSchema() + { + return schema; + } + + public final VeraSchema getVeraSchema() + { + return schema; + } + + public List getAnnotations() + { + if (annotations == null) return Collections.emptyList(); + return annotations; + } + + public void addAnnotation(Annotation annotation) + { + if (annotations == null) annotations = new LinkedList(); + annotations.add(annotation); + } + + public void addAnnotations(Collection c) + { + if (!c.isEmpty()) + { + if (annotations == null) + annotations = new LinkedList(); + annotations.addAll(c); + } + } + + public final String toSourceString() + { + return schema.getDefaultPrinter().toString(this); + } + + public final String toString() + { + return schema.isUseSourceString() ? toSourceString() : toDebugString(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectVisitor.java new file mode 100644 index 0000000..397b290 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSchemaObjectVisitor.java @@ -0,0 +1,43 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over all first-class Vera schema objects. + * + * @author Trevor Robinson + */ +public interface VeraSchemaObjectVisitor + extends VeraSchemaMemberVisitor, VeraCompilationUnitMemberVisitor, + VeraClassMemberVisitor, VeraBlockMemberVisitor, VeraExpressionVisitor, + VeraTypeVisitor +{ + void visit(VeraBindMember obj); + + void visit(VeraDefineArgument obj); + + void visit(VeraDefineReference obj); + + void visit(VeraFunctionArgument obj); + + void visit(VeraInterfaceSignal obj); + + void visit(VeraPortSignal obj); + + void visit(VeraRange obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetMember.java new file mode 100644 index 0000000..2c2efe1 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetMember.java @@ -0,0 +1,57 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.io.Serializable; + +/** + * Base class for Vera set members. + * + * @author Trevor Robinson + */ +public abstract class VeraSetMember + implements Serializable +{ + private VeraExpression weight; + private boolean weightPerItem; + + public VeraExpression getWeight() + { + return weight; + } + + public boolean isWeightPerItem() + { + return weightPerItem; + } + + public void setWeight(VeraExpression weight, boolean weightPerItem) + { + this.weight = weight; + this.weightPerItem = weightPerItem; + } + + protected String getWeightString() + { + if (weight != null) + { + return weight + (weightPerItem ? " := " : " :/ "); + } + return ""; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetOperation.java new file mode 100644 index 0000000..5c2e82c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetOperation.java @@ -0,0 +1,64 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Base class for Vera set membership operations. + * + * @author Trevor Robinson + */ +public abstract class VeraSetOperation + extends VeraExpression +{ + private static final long serialVersionUID = 8848261015198728687L; + + private final VeraExpression expr; + private final List members = new LinkedList(); + + public VeraSetOperation(VeraExpression expr) + { + super(expr.schema); + setResultType(schema.bitType); + this.expr = expr; + } + + public boolean isConstant() + { + // treat set operations as non-constant, because a) they are only usable + // in random constraint blocks and b) it's easier + return false; + } + + public VeraExpression getExpr() + { + return expr; + } + + public List getMembers() + { + return members; + } + + public void addMember(VeraSetMember expr) + { + members.add(expr); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetRange.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetRange.java new file mode 100644 index 0000000..7aa08d8 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetRange.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera value range set member. + * + * @author Trevor Robinson + */ +public final class VeraSetRange + extends VeraSetMember +{ + private static final long serialVersionUID = 3256726190848226871L; + + private final VeraExpression low; + private final VeraExpression high; + + public VeraSetRange(VeraExpression low, VeraExpression high) + { + this.low = low; + this.high = high; + } + + public VeraExpression getLow() + { + return low; + } + + public VeraExpression getHigh() + { + return high; + } + + public String toString() + { + return getWeightString() + low + ":" + high; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetValue.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetValue.java new file mode 100644 index 0000000..205e81e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSetValue.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera single value set member. + * + * @author Trevor Robinson + */ +public final class VeraSetValue + extends VeraSetMember +{ + private static final long serialVersionUID = 3257286915974509872L; + + private final VeraExpression value; + + public VeraSetValue(VeraExpression value) + { + this.value = value; + } + + public VeraExpression getValue() + { + return value; + } + + public String toString() + { + return getWeightString() + value; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraShiftOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraShiftOperation.java new file mode 100644 index 0000000..acfa754 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraShiftOperation.java @@ -0,0 +1,78 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Base class for Vera bitwise shift operations. + * + * @author Trevor Robinson + */ +public abstract class VeraShiftOperation + extends VeraBinaryOperation +{ + public VeraShiftOperation(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + if (!isValidTypes(op1.getResultType(), op2.getResultType())) + { + throw new SemanticException("Incorrect operand types"); + } + setResultType(getIntegralType(op1.getResultType())); + } + + protected int getShiftCount(Object o) + { + Object io = toIntegral(o); + + int count = -1; + boolean xzCount = true; + if (io instanceof Integer) + { + count = ((Integer) io).intValue(); + xzCount = false; + } + else if (io instanceof BitVector) + { + BitVector bv = (BitVector) io; + if (!bv.containsXZ()) + { + count = bv.intValue(); + xzCount = false; + } + } + else if (io instanceof Bit) + { + int id = ((Bit) io).getID(); + if (id <= 1) + { + count = id; + xzCount = false; + } + } + if (xzCount) + { + throw new ArithmeticException("X/Z in shift count"); + } + + return count; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalDirection.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalDirection.java new file mode 100644 index 0000000..d411520 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalDirection.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera signal directions. + * + * @author Trevor Robinson + */ +public enum VeraSignalDirection +{ + INPUT, OUTPUT, INOUT; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalKind.java new file mode 100644 index 0000000..8ab8ff7 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalKind.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera signal kinds. + * + * @author Trevor Robinson + */ +public enum VeraSignalKind +{ + NORMAL, CLOCK, RETURN_TO_ZERO, RETURN_TO_ONE, RETURN_TO_X, RETURN_TO_Z; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalReference.java new file mode 100644 index 0000000..9a45498 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSignalReference.java @@ -0,0 +1,58 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera signal reference expression. + * + * @author Trevor Robinson + */ +public final class VeraSignalReference + extends VeraExpression +{ + private static final long serialVersionUID = 3545521724532602681L; + + private final VeraInterfaceSignal signal; + + public VeraSignalReference(VeraInterfaceSignal signal) + { + super(signal.schema); + setResultType(signal.getType()); + this.signal = signal; + } + + public VeraInterfaceSignal getSignal() + { + return signal; + } + + public boolean isAssignable() + { + return signal.getDirection() != VeraSignalDirection.INPUT; + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatement.java new file mode 100644 index 0000000..004d96c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatement.java @@ -0,0 +1,31 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Statement; + +/** + * Base interface for Vera statements. + * + * @author Trevor Robinson + */ +public interface VeraStatement + extends Statement, VeraBlockMember, VeraDefineReferrer +{ + void accept(VeraStatementVisitor visitor); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementDefine.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementDefine.java new file mode 100644 index 0000000..083202e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementDefine.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera preprocessor #define that parses as a statement. + * + * @author Trevor Robinson + */ +public class VeraStatementDefine + extends VeraDefine +{ + private static final long serialVersionUID = 3256719589483165495L; + + private VeraStatement statement; + + public VeraStatementDefine(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public VeraStatement getStatement() + { + return statement; + } + + public void setStatement(VeraStatement statement) + { + this.statement = statement; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementImpl.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementImpl.java new file mode 100644 index 0000000..138a139 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementImpl.java @@ -0,0 +1,66 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera statements. + * + * @author Trevor Robinson + */ +public abstract class VeraStatementImpl + extends VeraSchemaObjectImpl + implements VeraStatement +{ + private VeraStatement containingStatement; + private VeraDefineReference defineRef; + + public VeraStatementImpl(VeraSchema schema) + { + super(schema); + } + + public final VeraStatement getContainingStatement() + { + return containingStatement; + } + + public final void setContainingStatement(VeraStatement stmt) + { + this.containingStatement = stmt; + } + + public VeraDefineReference getDefineRef() + { + return defineRef; + } + + public void setDefineRef(VeraDefineReference defineRef) + { + this.defineRef = defineRef; + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + accept((VeraStatementVisitor) visitor); + } + + public void accept(VeraBlockMemberVisitor visitor) + { + accept((VeraStatementVisitor) visitor); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementVisitor.java new file mode 100644 index 0000000..3def027 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStatementVisitor.java @@ -0,0 +1,60 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera statements. + * + * @author Trevor Robinson + */ +public interface VeraStatementVisitor +{ + void visit(VeraBlock obj); + + void visit(VeraBreakpointStatement obj); + + void visit(VeraBreakStatement obj); + + void visit(VeraContinueStatement obj); + + void visit(VeraDriveSampleStatement obj); + + void visit(VeraExpectStatement obj); + + void visit(VeraExpressionStatement obj); + + void visit(VeraForkStatement obj); + + void visit(VeraForStatement obj); + + void visit(VeraIfStatement obj); + + void visit(VeraRandCaseStatement obj); + + void visit(VeraRepeatStatement obj); + + void visit(VeraReturnStatement obj); + + void visit(VeraSwitchStatement obj); + + void visit(VeraSyncStatement obj); + + void visit(VeraTerminateStatement obj); + + void visit(VeraWhileStatement obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringLiteral.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringLiteral.java new file mode 100644 index 0000000..61707c4 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringLiteral.java @@ -0,0 +1,89 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Literal; + +/** + * Represents a Vera string literal expression. + * + * @author Trevor Robinson + */ +public final class VeraStringLiteral + extends VeraExpression + implements Literal +{ + private static final long serialVersionUID = 3258411737895416116L; + + private final String value; + + public VeraStringLiteral(VeraSchema schema, String value) + { + super(schema); + setResultType(schema.stringType); + this.value = value; + } + + public String getValue() + { + return value; + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return value; + } + + public static String escape(String src) + { + StringBuffer buf = new StringBuffer(); + int end = src.length(); + for (int i = 0; i < end; ++i) + { + char c = src.charAt(i); + switch (c) + { + case 0x0A: + buf.append("\\n"); + break; + case 0x09: + buf.append("\\t"); + break; + case '"': + buf.append("\\\""); + break; + case '\\': + buf.append("\\\\"); + break; + default: + buf.append(c); + } + } + return buf.toString(); + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringType.java new file mode 100644 index 0000000..94cf11d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStringType.java @@ -0,0 +1,123 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; + +/** + * Represents the Vera string type. + * + * @author Trevor Robinson + */ +public final class VeraStringType + extends VeraSystemClass +{ + private static final long serialVersionUID = 3690199823924212279L; + + VeraStringType(VeraSchema schema, VeraClass rootClass) + { + super(schema, new VeraName("string", VeraNameKind.TYPE, null), + rootClass); + } + + void defineStringClass() + { + VeraFunction f; + + f = defineMemberFunction("atobin", schema.bitVectorType); + // no arguments + + f = defineMemberFunction("atohex", schema.bitVectorType); + // no arguments + + f = defineMemberFunction("atoi", schema.integerType); + // no arguments + + f = defineMemberFunction("atooct", schema.bitVectorType); + // no arguments + + f = defineMemberFunction("backref", schema.stringType); + addArgument(f, "index", schema.integerType); + + f = defineMemberFunction("bittostr", schema.voidType); + addArgument(f, "bits", schema.bitVectorType); + + f = defineMemberFunction("compare", schema.integerType); + addArgument(f, "other", schema.stringType); + + f = defineMemberFunction("get_status", schema.integerType); + // no arguments + + f = defineMemberFunction("get_status_msg", schema.stringType); + // no arguments + + f = defineMemberFunction("getc", schema.integerType); + addArgument(f, "index", schema.integerType); + + f = defineMemberFunction("hash", schema.integerType); + addArgument(f, "size", schema.integerType); + + f = defineMemberFunction("icompare", schema.integerType); + addArgument(f, "other", schema.stringType); + + f = defineMemberFunction("itoa", schema.voidType); + addArgument(f, "i", schema.integerType); + + f = defineMemberFunction("len", schema.integerType); + // no arguments + + f = defineMemberFunction("match", schema.integerType); + addArgument(f, "pattern", schema.stringType); + + f = defineMemberFunction("postmatch", schema.stringType); + // no arguments + + f = defineMemberFunction("prematch", schema.stringType); + // no arguments + + f = defineMemberFunction("putc", schema.voidType); + addArgument(f, "index", schema.integerType); + addArgument(f, "char", schema.magicType); + + f = defineMemberFunction("search", schema.integerType); + addArgument(f, "pattern", schema.stringType); + + f = defineMemberFunction("substr", schema.stringType); + addArgument(f, "first", schema.integerType); + addOptArgument(f, "last", schema.integerType); + + f = defineMemberFunction("thismatch", schema.stringType); + // no arguments + + f = defineMemberFunction("tolower", schema.stringType); + // no arguments + + f = defineMemberFunction("toupper", schema.stringType); + // no arguments + } + + public boolean isAssignableFrom(Type other) + { + return other instanceof VeraStringType || other instanceof VeraNullType; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredType.java new file mode 100644 index 0000000..4de6969 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredType.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.StructuredType; +import com.newisys.langschema.util.NameTable; + +/** + * Base class for Vera structured types, such as classes, interfaces, and + * ports. + * + * @author Trevor Robinson + */ +public abstract class VeraStructuredType + extends VeraComplexType + implements StructuredType +{ + private static final long serialVersionUID = -2574263954949090135L; + + private final List members = new LinkedList(); + private final NameTable nameTable = new NameTable(); + + public VeraStructuredType(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public List getMembers() + { + return members; + } + + public void addMember(M member) + { + members.add(member); + if (member instanceof NamedObject) + { + nameTable.addObject((NamedObject) member); + } + } + + public Iterator lookupObjects(String identifier, NameKind kind) + { + return nameTable.lookupObjects(identifier, kind); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredTypeMember.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredTypeMember.java new file mode 100644 index 0000000..720d319 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraStructuredTypeMember.java @@ -0,0 +1,34 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.StructuredTypeMember; + +/** + * Interface implemented by Vera constructs that may be members of a + * structured type. + * + * @author Trevor Robinson + */ +public interface VeraStructuredTypeMember + extends StructuredTypeMember, VeraSchemaObject +{ + VeraStructuredType getStructuredType(); + + VeraVisibility getVisibility(); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSubtract.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSubtract.java new file mode 100644 index 0000000..12e2065 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSubtract.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera subtraction operation. + * + * @author Trevor Robinson + */ +public final class VeraSubtract + extends VeraBinaryArithmeticOperation +{ + private static final long serialVersionUID = 3258688788904751159L; + + public VeraSubtract(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + VeraType resultType = getResultType(); + Object o1 = toCommonIntegralType(op1.evaluateConstant(), resultType); + Object o2 = toCommonIntegralType(op2.evaluateConstant(), resultType); + if (resultType instanceof VeraIntegerType) + { + return IntegerOp.subtract((Integer) o1, (Integer) o2); + } + else if (resultType instanceof VeraBitVectorType) + { + BitVector bv1 = (BitVector) o1; + BitVector bv2 = (BitVector) o2; + return bv1.subtract(bv2); + } + else + { + assert (resultType instanceof VeraBitType); + Bit b1 = (Bit) o1; + Bit b2 = (Bit) o2; + return b1.xor(b2); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSuperReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSuperReference.java new file mode 100644 index 0000000..20ec329 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSuperReference.java @@ -0,0 +1,58 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.SuperReference; + +/** + * Represents a Vera super-type reference. + * + * @author Trevor Robinson + */ +public final class VeraSuperReference + extends VeraExpression + implements SuperReference +{ + private static final long serialVersionUID = 3906363818434246196L; + + private final VeraClass cls; + + public VeraSuperReference(VeraClass cls) + { + super(cls.schema); + VeraClass baseCls = cls.getBaseClass(); + assert (baseCls != null); + setResultType(baseCls); + this.cls = cls; + } + + public boolean isConstant() + { + return false; + } + + public VeraClass getType() + { + return cls; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXParams.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXParams.java new file mode 100644 index 0000000..5c7523c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXParams.java @@ -0,0 +1,66 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.io.Serializable; + +/** + * Represents Vera signal surround-by-X parameters. + * + * @author Trevor Robinson + */ +public final class VeraSurrXParams + implements Serializable +{ + private static final long serialVersionUID = 4050477915689267761L; + + private final VeraSurrXTransition transition; + private final int timeToX; + private final int timeToValue; + + public VeraSurrXParams( + VeraSurrXTransition transition, + int timeToX, + int timeToValue) + { + this.transition = transition; + this.timeToX = timeToX; + this.timeToValue = timeToValue; + } + + public VeraSurrXTransition getTransition() + { + return transition; + } + + public int getTimeToX() + { + return timeToX; + } + + public int getTimeToValue() + { + return timeToValue; + } + + public String toString() + { + return "#" + transition.getCode() + "(" + timeToX + ", " + timeToValue + + ")"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXTransition.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXTransition.java new file mode 100644 index 0000000..b9d9894 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSurrXTransition.java @@ -0,0 +1,40 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera surround-by-X transitions. + * + * @author Trevor Robinson + */ +public enum VeraSurrXTransition +{ + ANY(""), RISING("R"), FALLING("F"), FROM_Z("D"), TO_Z("Z"); + + private final String code; + + private VeraSurrXTransition(String code) + { + this.code = code; + } + + public String getCode() + { + return code; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchCase.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchCase.java new file mode 100644 index 0000000..a979389 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchCase.java @@ -0,0 +1,56 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.List; + +import com.newisys.langschema.SwitchCase; + +/** + * Base class for cases in a Vera case statement. + * + * @author Trevor Robinson + */ +public abstract class VeraSwitchCase + implements SwitchCase +{ + private final VeraSwitchStatement switchStmt; + private VeraStatement statement; + + public VeraSwitchCase(VeraSwitchStatement switchStmt) + { + this.switchStmt = switchStmt; + } + + public List getMembers() + { + return Collections.singletonList(statement); + } + + public VeraStatement getStatement() + { + return statement; + } + + public void setStatement(VeraStatement statement) + { + statement.setContainingStatement(switchStmt); + this.statement = statement; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchDefaultCase.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchDefaultCase.java new file mode 100644 index 0000000..9f132ea --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchDefaultCase.java @@ -0,0 +1,37 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.SwitchDefaultCase; + +/** + * Represents the default case in a Vera case statement. + * + * @author Trevor Robinson + */ +public final class VeraSwitchDefaultCase + extends VeraSwitchCase + implements SwitchDefaultCase +{ + private static final long serialVersionUID = 3256445823838795827L; + + public VeraSwitchDefaultCase(VeraSwitchStatement switchStmt) + { + super(switchStmt); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchStatement.java new file mode 100644 index 0000000..a4058f2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchStatement.java @@ -0,0 +1,88 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.SwitchStatement; + +/** + * Represents a Vera case/casex/casez statement. + * + * @author Trevor Robinson + */ +public final class VeraSwitchStatement + extends VeraStatementImpl + implements SwitchStatement +{ + private static final long serialVersionUID = 3256721801307631669L; + + private final VeraCaseKind caseKind; + private final VeraExpression selector; + private final List cases = new LinkedList(); + private boolean gotDefaultCase; + + public VeraSwitchStatement(VeraCaseKind caseKind, VeraExpression selector) + { + super(selector.schema); + this.caseKind = caseKind; + this.selector = selector; + } + + public VeraCaseKind getCaseKind() + { + return caseKind; + } + + public VeraExpression getSelector() + { + return selector; + } + + public List getCases() + { + return cases; + } + + public VeraSwitchValueCase newValueCase() + { + VeraSwitchValueCase _case = new VeraSwitchValueCase(this); + cases.add(_case); + return _case; + } + + public VeraSwitchDefaultCase newDefaultCase() + { + assert (!gotDefaultCase); + VeraSwitchDefaultCase _case = new VeraSwitchDefaultCase(this); + cases.add(_case); + gotDefaultCase = true; + return _case; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "case statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchValueCase.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchValueCase.java new file mode 100644 index 0000000..7368aa0 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSwitchValueCase.java @@ -0,0 +1,52 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.SwitchValueCase; + +/** + * Represents the value case in a Vera case statement. + * + * @author Trevor Robinson + */ +public final class VeraSwitchValueCase + extends VeraSwitchCase + implements SwitchValueCase +{ + private static final long serialVersionUID = 3256999939077649464L; + + private List values = new LinkedList(); + + public VeraSwitchValueCase(VeraSwitchStatement switchStmt) + { + super(switchStmt); + } + + public List getValues() + { + return values; + } + + public void addValue(VeraExpression value) + { + values.add(value); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncStatement.java new file mode 100644 index 0000000..0f521ff --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncStatement.java @@ -0,0 +1,59 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Represents a Vera signal synchronization statement. + * + * @author Trevor Robinson + */ +public final class VeraSyncStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3905806383319167795L; + + private final List terms = new LinkedList(); + + public VeraSyncStatement(VeraSchema schema) + { + super(schema); + } + + public List getTerms() + { + return terms; + } + + public void addTerm(VeraSyncTerm term) + { + terms.add(term); + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "sync statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncTerm.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncTerm.java new file mode 100644 index 0000000..b5d1faa --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSyncTerm.java @@ -0,0 +1,59 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.io.Serializable; + +import com.newisys.verilog.EdgeSet; + +/** + * Represents a term in a Vera signal synchronization statement. + * + * @author Trevor Robinson + */ +public final class VeraSyncTerm + implements Serializable +{ + private static final long serialVersionUID = 3834309527276697140L; + + private final VeraExpression signal; + private final EdgeSet edgeSet; + private final boolean async; + + public VeraSyncTerm(VeraExpression signal, EdgeSet edgeSet, boolean async) + { + this.signal = signal; + this.edgeSet = edgeSet; + this.async = async; + } + + public VeraExpression getSignal() + { + return signal; + } + + public EdgeSet getEdgeSet() + { + return edgeSet; + } + + public boolean isAsync() + { + return async; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClass.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClass.java new file mode 100644 index 0000000..010aae2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClass.java @@ -0,0 +1,97 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera built-in class types. + * + * @author Trevor Robinson + */ +public abstract class VeraSystemClass + extends VeraClass +{ + private static final long serialVersionUID = -5215031529477437697L; + + protected VeraSystemClass( + VeraSchema schema, + VeraName name, + VeraClass baseClass) + { + super(schema, name, baseClass); + } + + protected VeraMemberFunction defineMemberFunction( + String id, + VeraType returnType) + { + VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, this); + VeraFunctionType funcType = new VeraFunctionType(returnType, false); + VeraMemberFunction func = new VeraMemberFunction(name, funcType); + func.setVisibility(VeraVisibility.PUBLIC); + addMember(func); + return func; + } + + protected VeraFunctionArgument addArgument( + VeraFunction func, + String id, + VeraType type) + { + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraFunctionArgument arg = new VeraFunctionArgument(name, type, + func); + final VeraFunctionType funcType = func.getType(); + funcType.addArgument(arg); + return arg; + } + + protected VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + int defValue) + { + return addOptArgument(func, id, schema.integerType, + new VeraIntegerLiteral(schema, defValue)); + } + + protected VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + VeraType type) + { + return addOptArgument(func, id, type, null); + } + + protected VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + VeraType type, + VeraExpression defValue) + { + final VeraFunctionArgument arg = addArgument(func, id, type); + arg.setInitializer(defValue); + arg.setOptional(true); + arg.setOptionalLevel(1); + return arg; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClockReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClockReference.java new file mode 100644 index 0000000..8f92ca3 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraSystemClockReference.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a reference to the Vera system clock (CLOCK). + * + * @author Trevor Robinson + */ +public final class VeraSystemClockReference + extends VeraExpression +{ + private static final long serialVersionUID = 3256445793773827379L; + + public VeraSystemClockReference(VeraSchema schema) + { + super(schema); + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraTerminateStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTerminateStatement.java new file mode 100644 index 0000000..2e4048b --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTerminateStatement.java @@ -0,0 +1,44 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera terminate statement. + * + * @author Trevor Robinson + */ +public final class VeraTerminateStatement + extends VeraStatementImpl +{ + private static final long serialVersionUID = 3257007665774671925L; + + public VeraTerminateStatement(VeraSchema schema) + { + super(schema); + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "terminate statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraTernaryOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTernaryOperation.java new file mode 100644 index 0000000..4e0388c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTernaryOperation.java @@ -0,0 +1,50 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera ternary operations. + * + * @author Trevor Robinson + */ +public abstract class VeraTernaryOperation + extends VeraOperation +{ + protected final VeraExpression op1; + protected final VeraExpression op2; + protected final VeraExpression op3; + + public VeraTernaryOperation( + VeraExpression op1, + VeraExpression op2, + VeraExpression op3) + { + super(op1.schema); + this.op1 = op1; + operands.add(op1); + this.op2 = op2; + operands.add(op2); + this.op3 = op3; + operands.add(op3); + } + + public boolean isConstant() + { + return op1.isConstant() && op2.isConstant() && op3.isConstant(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraThisReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraThisReference.java new file mode 100644 index 0000000..52631cf --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraThisReference.java @@ -0,0 +1,56 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.ThisReference; + +/** + * Represents a Vera 'this' reference. + * + * @author Trevor Robinson + */ +public final class VeraThisReference + extends VeraExpression + implements ThisReference +{ + private static final long serialVersionUID = 3904674994327139891L; + + private final VeraClass cls; + + public VeraThisReference(VeraClass cls) + { + super(cls.schema); + setResultType(cls); + this.cls = cls; + } + + public boolean isConstant() + { + return false; + } + + public VeraClass getType() + { + return cls; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraType.java new file mode 100644 index 0000000..1524df2 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraType.java @@ -0,0 +1,88 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.Collections; +import java.util.Set; + +import com.newisys.langschema.Type; +import com.newisys.langschema.TypeModifier; + +/** + * Base class for all Vera types. + * + * @author Trevor Robinson + */ +public abstract class VeraType + extends VeraSchemaObjectImpl + implements Type, VeraDefineReferrer +{ + private VeraDefineReference defineRef; + + public VeraType(VeraSchema schema) + { + super(schema); + } + + public VeraDefineReference getDefineRef() + { + return defineRef; + } + + public void setDefineRef(VeraDefineReference defineRef) + { + this.defineRef = defineRef; + } + + public Set< ? extends TypeModifier> getModifiers() + { + return Collections.emptySet(); + } + + public boolean isStrictIntegral() + { + return false; + } + + public boolean isIntegralConvertible() + { + return isStrictIntegral(); + } + + public int getBitCount() + { + throw new UnsupportedOperationException( + "Type is not integral convertible"); + } + + public void accept(VeraSchemaObjectVisitor visitor) + { + accept((VeraTypeVisitor) visitor); + } + + public abstract void accept(VeraTypeVisitor visitor); + + public abstract String toReferenceString(); + + public String toDebugString() + { + // for non-complex types, the short string is the reference string with + // " type" appended + return toReferenceString() + " type"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeDefine.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeDefine.java new file mode 100644 index 0000000..6338293 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeDefine.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera preprocessor #define that refers to a type. + * + * @author Trevor Robinson + */ +public class VeraTypeDefine + extends VeraDefine +{ + private static final long serialVersionUID = 3835158371794891824L; + + private VeraType type; + + public VeraTypeDefine(VeraSchema schema, VeraName name) + { + super(schema, name); + } + + public VeraType getType() + { + return type; + } + + public void setType(VeraType type) + { + this.type = type; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeVisitor.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeVisitor.java new file mode 100644 index 0000000..d592a10 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraTypeVisitor.java @@ -0,0 +1,62 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Visitor over Vera types. + * + * @author Trevor Robinson + */ +public interface VeraTypeVisitor +{ + void visit(VeraAssocArrayType obj); + + void visit(VeraBitType obj); + + void visit(VeraDynamicArrayType obj); + + void visit(VeraEnumeration obj); + + void visit(VeraEventType obj); + + void visit(VeraFixedArrayType obj); + + void visit(VeraFixedBitVectorType obj); + + void visit(VeraFunctionType obj); + + void visit(VeraIntegerType obj); + + void visit(VeraInterfaceType obj); + + void visit(VeraMagicType obj); + + void visit(VeraNullType obj); + + void visit(VeraPortType obj); + + void visit(VeraStringType obj); + + void visit(VeraSystemClass obj); + + void visit(VeraUnsizedBitVectorType obj); + + void visit(VeraUserClass obj); + + void visit(VeraVoidType obj); +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraUDFFunction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUDFFunction.java new file mode 100644 index 0000000..8fa7632 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUDFFunction.java @@ -0,0 +1,51 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera UDF function. + * + * @author Trevor Robinson + */ +public final class VeraUDFFunction + extends VeraGlobalFunction +{ + private static final long serialVersionUID = 3832902139457646897L; + + private String language; + + public VeraUDFFunction(VeraName name, VeraFunctionType funcType) + { + super(name, funcType); + } + + public String getLanguage() + { + return language; + } + + public void setLanguage(String language) + { + this.language = language; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryArithmeticOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryArithmeticOperation.java new file mode 100644 index 0000000..df70e9f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryArithmeticOperation.java @@ -0,0 +1,39 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.util.SemanticException; + +/** + * Base class for Vera unary arithmetic operations. + * + * @author Trevor Robinson + */ +public abstract class VeraUnaryArithmeticOperation + extends VeraUnaryOperation +{ + public VeraUnaryArithmeticOperation(VeraExpression op1) + { + super(op1); + if (!op1.getResultType().isIntegralConvertible()) + { + throw new SemanticException("Incorrect operand type"); + } + setResultType(getIntegralType(op1.getResultType())); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryOperation.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryOperation.java new file mode 100644 index 0000000..79f4882 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnaryOperation.java @@ -0,0 +1,41 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Base class for Vera unary operations. + * + * @author Trevor Robinson + */ +public abstract class VeraUnaryOperation + extends VeraOperation +{ + protected final VeraExpression op1; + + public VeraUnaryOperation(VeraExpression op1) + { + super(op1.schema); + this.op1 = op1; + operands.add(op1); + } + + public boolean isConstant() + { + return op1.isConstant(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnsizedBitVectorType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnsizedBitVectorType.java new file mode 100644 index 0000000..b6d4367 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUnsizedBitVectorType.java @@ -0,0 +1,41 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera unsized bit vector type. This type cannot be directly + * declared in the Vera language, but is used for dynamically sized + * expressions, such as concatenation, replication, and port signals. + * + * @author Trevor Robinson + */ +public final class VeraUnsizedBitVectorType + extends VeraBitVectorType +{ + private static final long serialVersionUID = 3834875767208031545L; + + VeraUnsizedBitVectorType(VeraSchema schema) + { + super(schema); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraUserClass.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUserClass.java new file mode 100644 index 0000000..7b9069f --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraUserClass.java @@ -0,0 +1,99 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Represents a Vera user-defined class. + * + * @author Trevor Robinson + */ +public final class VeraUserClass + extends VeraClass + implements VeraCompilationUnitMember +{ + private static final long serialVersionUID = 3689069556052276532L; + + private boolean typedefOnly; + private boolean defined; + private VeraCompilationUnit compUnit; + + public VeraUserClass(VeraSchema schema, VeraName name, VeraClass baseClass) + { + super(schema, name, baseClass); + } + + public VeraUserClass(VeraSchema schema, VeraName name) + { + super(schema, name, schema.rootClass); + } + + public void setVirtual(boolean virtual) + { + this.virtual = virtual; + } + + public void setBaseClass(VeraClass baseClass) + { + this.baseClass = baseClass; + } + + public void addBaseCtorArg(VeraExpression arg) + { + baseCtorArgs.add(arg); + } + + public boolean isTypedefOnly() + { + return typedefOnly; + } + + public void setTypedefOnly(boolean declared) + { + this.typedefOnly = declared; + } + + public boolean isDefined() + { + return defined; + } + + public void setDefined(boolean defined) + { + this.defined = defined; + } + + public VeraCompilationUnit getCompilationUnit() + { + return compUnit; + } + + public void setCompilationUnit(VeraCompilationUnit compUnit) + { + this.compUnit = compUnit; + } + + public void accept(VeraCompilationUnitMemberVisitor visitor) + { + visitor.visit(this); + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAKind.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAKind.java new file mode 100644 index 0000000..35eda94 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAKind.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera Value Change Alert kinds. + * + * @author Trevor Robinson + */ +public enum VeraVCAKind +{ + NONE, ASYNC, SYNC, GLITCH; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAQValue.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAQValue.java new file mode 100644 index 0000000..44fe1a5 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVCAQValue.java @@ -0,0 +1,28 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +/** + * Enumeration of Vera Value Change Alert Q-value kinds. + * + * @author Trevor Robinson + */ +public enum VeraVCAQValue +{ + ZERO, ONE, Z, X, HOLD; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariable.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariable.java new file mode 100644 index 0000000..fa41931 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariable.java @@ -0,0 +1,87 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import java.util.HashSet; +import java.util.Set; + +import com.newisys.langschema.Variable; +import com.newisys.langschema.VariableModifier; + +/** + * Base class for Vera variables. + * + * @author Trevor Robinson + */ +public abstract class VeraVariable + extends VeraSchemaObjectImpl + implements Variable +{ + // NOTE: name is not final because function arguments can change names + protected VeraName name; + private final VeraType type; + protected final Set modifiers = new HashSet(); + private VeraExpression initializer; + + public VeraVariable(VeraName name, VeraType type) + { + super(type.schema); + this.name = name; + this.type = type; + } + + public VeraName getName() + { + return name; + } + + public VeraType getType() + { + return type; + } + + public Set getModifiers() + { + return modifiers; + } + + public boolean hasModifier(VariableModifier mod) + { + return modifiers.contains(mod); + } + + public void addModifier(M mod) + { + modifiers.add(mod); + } + + public VeraExpression getInitializer() + { + return initializer; + } + + public void setInitializer(VeraExpression initializer) + { + this.initializer = initializer; + } + + public String toDebugString() + { + return "variable " + name + " of type " + type.toReferenceString(); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableModifier.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableModifier.java new file mode 100644 index 0000000..68798cd --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableModifier.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.VariableModifier; + +/** + * Enumeration of Vera variable modifiers. + * + * @author Trevor Robinson + */ +public enum VeraVariableModifier implements VariableModifier +{ + STATIC, SHADOW, RAND, RANDC, PACKED, BIG_ENDIAN, BIT_REVERSE; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableReference.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableReference.java new file mode 100644 index 0000000..36ff2b5 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVariableReference.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.VariableReference; + +/** + * Represents a Vera variable reference expression. + * + * @author Trevor Robinson + */ +public final class VeraVariableReference + extends VeraExpression + implements VariableReference +{ + private static final long serialVersionUID = 3257289123554146615L; + + private final VeraVariable variable; + + public VeraVariableReference(VeraVariable variable) + { + super(variable.schema); + setResultType(variable.getType()); + this.variable = variable; + } + + public VeraVariable getVariable() + { + return variable; + } + + public boolean isAssignable() + { + return !(variable instanceof VeraBindVariable); + } + + public boolean isConstant() + { + return false; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVisibility.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVisibility.java new file mode 100644 index 0000000..87e1c8a --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVisibility.java @@ -0,0 +1,30 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Visibility; + +/** + * Enumeration of Vera visibility modifiers. + * + * @author Trevor Robinson + */ +public enum VeraVisibility implements Visibility +{ + PUBLIC, PROTECTED, LOCAL; +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidLiteral.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidLiteral.java new file mode 100644 index 0000000..0a667bb --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidLiteral.java @@ -0,0 +1,53 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Literal; + +/** + * Represents the Vera void literal expression. + * + * @author Trevor Robinson + */ +public final class VeraVoidLiteral + extends VeraExpression + implements Literal +{ + private static final long serialVersionUID = 3834029151811612982L; + + public VeraVoidLiteral(VeraSchema schema) + { + super(schema); + setResultType(schema.voidType); + } + + public boolean isConstant() + { + return true; + } + + public Object evaluateConstant() + { + return this; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidType.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidType.java new file mode 100644 index 0000000..2238fa6 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraVoidType.java @@ -0,0 +1,54 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.Type; +import com.newisys.langschema.VoidType; + +/** + * Represents the Vera void type. + * + * @author Trevor Robinson + */ +public final class VeraVoidType + extends VeraType + implements VoidType +{ + private static final long serialVersionUID = 4050483434621449526L; + + VeraVoidType(VeraSchema schema) + { + super(schema); + } + + public boolean isAssignableFrom(Type other) + { + // any type is assignable to void + return true; + } + + public String toReferenceString() + { + return "void"; + } + + public void accept(VeraTypeVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraWhileStatement.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWhileStatement.java new file mode 100644 index 0000000..1067c24 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWhileStatement.java @@ -0,0 +1,63 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.langschema.WhileStatement; + +/** + * Represents a Vera 'while' loop. + * + * @author Trevor Robinson + */ +public final class VeraWhileStatement + extends VeraStatementImpl + implements WhileStatement +{ + private static final long serialVersionUID = 3258688797578245433L; + + private final VeraExpression condition; + private final VeraStatement statement; + + public VeraWhileStatement(VeraExpression condition, VeraStatement statement) + { + super(condition.schema); + this.condition = condition; + statement.setContainingStatement(this); + this.statement = statement; + } + + public VeraExpression getCondition() + { + return condition; + } + + public VeraStatement getStatement() + { + return statement; + } + + public void accept(VeraStatementVisitor visitor) + { + visitor.visit(this); + } + + public String toDebugString() + { + return "while statement"; + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildEqual.java new file mode 100644 index 0000000..c503fcb --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildEqual.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; + +/** + * Represents a Vera wild equality operation. + * + * @author Trevor Robinson + */ +public final class VeraWildEqual + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3977303230755714869L; + + public VeraWildEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return isWildEqual() ? Bit.ONE : Bit.ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildNotEqual.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildNotEqual.java new file mode 100644 index 0000000..41e127b --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraWildNotEqual.java @@ -0,0 +1,46 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.verilog.util.Bit; + +/** + * Represents a Vera wild inequality operation. + * + * @author Trevor Robinson + */ +public final class VeraWildNotEqual + extends VeraComparisonOperation +{ + private static final long serialVersionUID = 3690191027780925238L; + + public VeraWildNotEqual(VeraExpression op1, VeraExpression op2) + { + super(op1, op2); + } + + public Object evaluateConstant() + { + return !isWildEqual() ? Bit.ONE : Bit.ZERO; + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/langschema/vera/VeraXorReduction.java b/java/langschema-vera/src/com/newisys/langschema/vera/VeraXorReduction.java new file mode 100644 index 0000000..d5d766e --- /dev/null +++ b/java/langschema-vera/src/com/newisys/langschema/vera/VeraXorReduction.java @@ -0,0 +1,61 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langschema.vera; + +import com.newisys.juno.runtime.IntegerOp; +import com.newisys.verilog.util.Bit; +import com.newisys.verilog.util.BitVector; + +/** + * Represents a Vera reductive-xor operation. + * + * @author Trevor Robinson + */ +public final class VeraXorReduction + extends VeraReduction +{ + private static final long serialVersionUID = 3691035474152404784L; + + public VeraXorReduction(VeraExpression op1) + { + super(op1); + } + + public Object evaluateConstant() + { + Object o = toIntegral(op1.evaluateConstant()); + if (o == null || o instanceof Integer) + { + return IntegerOp.reductiveXor((Integer) o); + } + else if (o instanceof BitVector) + { + return ((BitVector) o).reductiveXor(); + } + else + { + assert (o instanceof Bit); + return ((Bit) o).ztox(); + } + } + + public void accept(VeraExpressionVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/BlockMemberPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/BlockMemberPrinter.java new file mode 100644 index 0000000..bbb072c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/BlockMemberPrinter.java @@ -0,0 +1,530 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Collection; +import java.util.Iterator; + +import com.newisys.langschema.vera.*; +import com.newisys.util.text.TokenFormatter; +import com.newisys.verilog.EdgeSet; + +/** + * Printer module used to print Vera block members. + * + * @author Trevor Robinson + */ +public class BlockMemberPrinter + extends VeraSchemaPrinterModule + implements VeraBlockMemberVisitor +{ + public BlockMemberPrinter(TokenFormatter fmt, VeraSchemaPrinter config) + { + super(fmt, config); + } + + public void printStatement(VeraStatement stmt) + { + VeraDefineReference defineRef = stmt.getDefineRef(); + if (defineRef != null) + { + printDefineRef(defineRef, fmt); + printNewLine(); + } + else + { + stmt.accept(this); + } + } + + public void printMember(VeraBlockMember member) + { + if (member instanceof VeraStatement) + { + printStatement((VeraStatement) member); + } + else + { + member.accept(this); + } + } + + public void printMembers(Collection members) + { + Iterator iter = members.iterator(); + while (iter.hasNext()) + { + VeraBlockMember member = (VeraBlockMember) iter.next(); + printMember(member); + } + } + + private void printGuard(String token, VeraExpression expr) + { + fmt.printToken(token); + fmt.printSpace(); + fmt.printLeadingToken("("); + printExpression(expr); + fmt.printTrailingToken(")"); + } + + private void printNestedStatement(VeraStatement stmt) + { + if (stmt instanceof VeraBlock) + { + printBlock((VeraBlock) stmt); + } + else + { + fmt.incIndent(); + printStatement(stmt); + fmt.decIndent(); + } + } + + private void printPredicate(VeraStatement stmt, boolean simple) + { + if (simple) + { + fmt.printSpace(); + printStatement(stmt); + } + else + { + printNewLine(); + printNestedStatement(stmt); + } + } + + private boolean isSimpleStmt(VeraStatement stmt) + { + return stmt instanceof VeraExpressionStatement + || stmt instanceof VeraBreakpointStatement + || stmt instanceof VeraBreakStatement + || stmt instanceof VeraContinueStatement + || stmt instanceof VeraDriveSampleStatement + || stmt instanceof VeraExpectStatement + || stmt instanceof VeraReturnStatement + || stmt instanceof VeraSyncStatement + || stmt instanceof VeraTerminateStatement; + } + + public void visit(VeraLocalVariable obj) + { + printVarDecl(obj); + printVarInit(obj); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraBlock obj) + { + printBlock(obj); + } + + public void visit(VeraBreakpointStatement obj) + { + fmt.printToken("breakpoint"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraBreakStatement obj) + { + fmt.printToken("break"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraContinueStatement obj) + { + fmt.printToken("continue"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraDriveSampleStatement obj) + { + final VeraExpression delay = obj.getDelay(); + if (delay != null) + { + fmt.printLeadingToken("@"); + printExpression(delay); + fmt.printSpace(); + } + + printExpression(obj.getDestination()); + + fmt.printSpace(); + fmt.printLeadingToken(obj.isNonBlocking() ? "<=" : "="); + fmt.printSpace(); + + printExpression(obj.getSource()); + + if (obj.isSoft()) + { + fmt.printSpace(); + fmt.printToken("soft"); + } + + if (obj.isAsync()) + { + fmt.printSpace(); + fmt.printToken("async"); + } + + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraExpectStatement obj) + { + final String token; + final VeraExpectKind expectKind = obj.getExpectKind(); + if (expectKind == VeraExpectKind.SIMPLE) + { + token = "@"; + } + else if (expectKind == VeraExpectKind.FULL) + { + token = "@@"; + } + else + { + assert (expectKind == VeraExpectKind.RESTRICTED); + token = "@@@"; + } + fmt.printLeadingToken(token); + + final VeraExpression delay = obj.getDelay(); + final VeraExpression window = obj.getWindow(); + if (delay != null) + { + printExpression(delay); + if (window != null) + { + fmt.printTrailingToken(","); + printExpression(window); + } + } + else if (window != null) + { + fmt.printLeadingToken(","); + printExpression(window); + } + else + { + // delay or window is required; if none specified, use delay 0 + fmt.printToken("0"); + } + fmt.printSpace(); + + final Iterator iter = obj.getExpectTerms().iterator(); + final boolean expectAll = obj.isExpectAll(); + while (iter.hasNext()) + { + VeraExpectTerm term = (VeraExpectTerm) iter.next(); + printExpression(term.getSignal()); + fmt.printSpace(); + fmt.printLeadingToken(term.isEqual() ? "==" : "!="); + fmt.printSpace(); + printExpression(term.getValue()); + if (iter.hasNext()) + { + if (expectAll) + { + fmt.printTrailingToken(","); + } + else + { + fmt.printSpace(); + fmt.printLeadingToken("or"); + } + fmt.printSpace(); + } + } + + if (obj.isSoft()) + { + fmt.printSpace(); + fmt.printToken("soft"); + } + + if (obj.isAsync()) + { + fmt.printSpace(); + fmt.printToken("async"); + } + + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraExpressionStatement obj) + { + printExpression(obj.getExpression()); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraForkStatement obj) + { + fmt.printToken("fork"); + printNewLine(); + + Iterator iter = obj.getForkedStatements().iterator(); + while (iter.hasNext()) + { + printNestedStatement((VeraStatement) iter.next()); + } + + fmt.printToken("join"); + fmt.printToken(obj.getJoinKind().toString()); + printNewLine(); + } + + public void visit(VeraForStatement obj) + { + fmt.printToken("for"); + fmt.printSpace(); + fmt.printLeadingToken("("); + + Iterator iter = obj.getInitStatements().iterator(); + while (iter.hasNext()) + { + VeraExpressionStatement exprStmt = (VeraExpressionStatement) iter + .next(); + printExpression(exprStmt.getExpression()); + if (iter.hasNext()) + { + fmt.printTrailingToken(","); + fmt.printSpace(); + } + } + fmt.printTrailingToken(";"); + fmt.printSpace(); + + VeraExpression condExpr = (VeraExpression) obj.getCondition(); + if (condExpr != null) + { + printExpression(condExpr); + } + fmt.printTrailingToken(";"); + fmt.printSpace(); + + iter = obj.getUpdateStatements().iterator(); + while (iter.hasNext()) + { + VeraExpressionStatement exprStmt = (VeraExpressionStatement) iter + .next(); + printExpression(exprStmt.getExpression()); + if (iter.hasNext()) + { + fmt.printTrailingToken(","); + fmt.printSpace(); + } + } + + fmt.printTrailingToken(")"); + printNewLine(); + + printNestedStatement(obj.getStatement()); + } + + public void visit(VeraIfStatement obj) + { + VeraIfStatement cur = obj; + while (cur != null) + { + VeraStatement thenStmt = cur.getThenStatement(); + VeraStatement elseStmt = cur.getElseStatement(); + + printGuard("if", cur.getCondition()); + + printPredicate(thenStmt, elseStmt == null && isSimpleStmt(thenStmt)); + + cur = null; + if (elseStmt != null) + { + fmt.printToken("else"); + if (elseStmt instanceof VeraIfStatement) + { + fmt.printSpace(); + cur = (VeraIfStatement) elseStmt; + } + else + { + printNewLine(); + printNestedStatement(elseStmt); + } + } + } + } + + public void visit(VeraRandCaseStatement obj) + { + fmt.printToken("randcase"); + fmt.printToken("{"); + printNewLine(); + + final Iterator iter = obj.getCaseList().iterator(); + while (iter.hasNext()) + { + final VeraRandCase c = (VeraRandCase) iter.next(); + printExpression(c.getWeight()); + fmt.printTrailingToken(":"); + + final VeraStatement stmt = c.getStatement(); + printPredicate(stmt, isSimpleStmt(stmt)); + } + + fmt.printToken("}"); + printNewLine(); + } + + public void visit(VeraRepeatStatement obj) + { + printGuard("repeat", obj.getCondition()); + printNewLine(); + + printNestedStatement(obj.getStatement()); + } + + public void visit(VeraReturnStatement obj) + { + fmt.printToken("return"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraSwitchStatement obj) + { + final VeraCaseKind caseKind = obj.getCaseKind(); + final String caseKeyword; + if (caseKind == VeraCaseKind.X) + { + caseKeyword = "casex"; + } + else if (caseKind == VeraCaseKind.Z) + { + caseKeyword = "casez"; + } + else + { + assert (caseKind == VeraCaseKind.NORMAL); + caseKeyword = "case"; + } + printGuard(caseKeyword, obj.getSelector()); + printNewLine(); + + fmt.printToken("{"); + printNewLine(); + + final Iterator iter = obj.getCases().iterator(); + while (iter.hasNext()) + { + final VeraSwitchCase c = (VeraSwitchCase) iter.next(); + if (c instanceof VeraSwitchValueCase) + { + final VeraSwitchValueCase vc = (VeraSwitchValueCase) c; + final Iterator valueIter = vc.getValues().iterator(); + while (valueIter.hasNext()) + { + VeraExpression expr = (VeraExpression) valueIter.next(); + printExpression(expr); + if (valueIter.hasNext()) + { + fmt.printToken(","); + fmt.printSpace(); + } + } + fmt.printTrailingToken(":"); + } + else + { + assert (c instanceof VeraSwitchDefaultCase); + fmt.printToken("default"); + fmt.printTrailingToken(":"); + } + + final VeraStatement stmt = c.getStatement(); + printPredicate(stmt, isSimpleStmt(stmt)); + } + + fmt.printToken("}"); + printNewLine(); + } + + public void visit(VeraSyncStatement obj) + { + fmt.printLeadingToken("@"); + fmt.printLeadingToken("("); + + Iterator iter = obj.getTerms().iterator(); + while (iter.hasNext()) + { + VeraSyncTerm term = (VeraSyncTerm) iter.next(); + + EdgeSet edges = term.getEdgeSet(); + if (EdgeSet.POSEDGE.contains(edges)) + { + fmt.printToken("posedge"); + fmt.printSpace(); + } + else if (EdgeSet.NEGEDGE.contains(edges)) + { + fmt.printToken("negedge"); + fmt.printSpace(); + } + + printExpression(term.getSignal()); + + if (term.isAsync()) + { + fmt.printSpace(); + fmt.printToken("async"); + } + + if (iter.hasNext()) + { + fmt.printSpace(); + fmt.printToken("or"); + fmt.printSpace(); + } + } + + fmt.printTrailingToken(")"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraTerminateStatement obj) + { + fmt.printToken("terminate"); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraWhileStatement obj) + { + printGuard("while", obj.getCondition()); + printNewLine(); + + printNestedStatement(obj.getStatement()); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/ClassMemberPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/ClassMemberPrinter.java new file mode 100644 index 0000000..de96a21 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/ClassMemberPrinter.java @@ -0,0 +1,120 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Collection; +import java.util.Iterator; + +import com.newisys.langschema.vera.*; +import com.newisys.util.text.TokenFormatter; + +/** + * Printer module used to print Vera class members. + * + * @author Trevor Robinson + */ +public class ClassMemberPrinter + extends VeraSchemaPrinterModule + implements VeraClassMemberVisitor +{ + public ClassMemberPrinter(TokenFormatter fmt, VeraSchemaPrinter config) + { + super(fmt, config); + } + + public void printMembers(Collection members) + { + boolean first = true; + Iterator iter = members.iterator(); + while (iter.hasNext()) + { + VeraClassMember member = (VeraClassMember) iter.next(); + if (!first && !(member instanceof VeraMemberVariable)) + { + printNewLine(); + } + member.accept(this); + first = false; + } + } + + public void visit(VeraClassConstraint obj) + { + fmt.printToken("constraint"); + fmt.printSpace(); + printID(obj.getName()); + printNewLine(); + printConstraints(obj.getExprs()); + printNewLine(); + } + + public void visit(VeraEnumeration obj) + { + printEnum(obj); + } + + public void visit(VeraEnumerationElement obj) + { + // handled in visit(VeraEnumeration) + } + + public void visit(VeraMemberFunction obj) + { + printVisibility(obj.getVisibility(), VeraVisibility.PUBLIC); + printModifiers(obj.getModifiers()); + VeraFunctionType funcType = obj.getType(); + printFuncProlog(funcType); + printID(obj.getName()); + printFuncArgs(funcType); + if (obj.isPureVirtual()) + { + fmt.printTrailingToken(";"); + printNewLine(); + } + else + { + printBody(obj.getBody()); + } + } + + public void visit(VeraMemberVariable obj) + { + printVisibility(obj.getVisibility(), VeraVisibility.PUBLIC); + printVarDecl(obj); + VeraExpression randomSize = obj.getRandomSize(); + if (randomSize != null) + { + fmt.printSpace(); + VeraType type = obj.getType(); + if (type instanceof VeraAssocArrayType) + { + fmt.printToken("assoc_size"); + } + else + { + assert (type instanceof VeraDynamicArrayType); + fmt.printToken("dynamic_size"); + } + fmt.printSpace(); + printExpression(randomSize); + } + printVarInit(obj); + fmt.printTrailingToken(";"); + printNewLine(); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/CompilationUnitMemberPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/CompilationUnitMemberPrinter.java new file mode 100644 index 0000000..0c88a54 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/CompilationUnitMemberPrinter.java @@ -0,0 +1,257 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.newisys.langschema.vera.*; +import com.newisys.util.text.StringTokenFormatter; +import com.newisys.util.text.TokenFormatter; + +/** + * Printer module used to print Vera compilation unit members. + * + * @author Trevor Robinson + */ +public class CompilationUnitMemberPrinter + extends VeraSchemaPrinterModule + implements VeraCompilationUnitMemberVisitor +{ + public CompilationUnitMemberPrinter( + TokenFormatter fmt, + VeraSchemaPrinter config) + { + super(fmt, config); + } + + public void printMembers(Collection members) + { + boolean first = true; + Iterator iter = members.iterator(); + while (iter.hasNext()) + { + VeraCompilationUnitMember member = (VeraCompilationUnitMember) iter + .next(); + if (!first) printNewLine(); + member.accept(this); + first = false; + } + } + + public void visit(VeraBindVariable obj) + { + fmt.printToken("bind"); + fmt.printSpace(); + printName(obj.getPort().getName(), false); + fmt.printSpace(); + printID(obj.getName()); + printNewLine(); + + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraBindMember member = (VeraBindMember) iter.next(); + printBindMember(member); + } + + fmt.decIndent(); + fmt.printToken("}"); + printNewLine(); + } + + public void visit(VeraEnumeration obj) + { + printEnum(obj); + } + + public void visit(VeraEnumerationElement obj) + { + // handled in visit(VeraEnumeration) + } + + public void visit(VeraExpressionDefine obj) + { + printDefine(obj, formatDefineExpr(obj.getExpression())); + } + + private void printDefine(VeraDefine obj, String expansion) + { + StringBuffer buf = new StringBuffer(); + buf.append("#define "); + buf.append(obj.getName()); + List arguments = obj.getArguments(); + if (!arguments.isEmpty()) + { + buf.append('('); + Iterator iter = arguments.iterator(); + while (iter.hasNext()) + { + VeraDefineArgument var = (VeraDefineArgument) iter.next(); + buf.append(var.getName()); + if (iter.hasNext()) buf.append(','); + } + buf.append(')'); + } + buf.append(' '); + buf.append(expansion); + fmt.printToken(buf.toString()); + printNewLine(); + } + + private String formatDefineExpr(VeraExpression expr) + { + if (expr != null) + { + StringTokenFormatter strFmt = new StringTokenFormatter(); + printExpression(expr, 100, strFmt); + return strFmt.toString(); + } + else + { + return "/* NULL */"; + } + } + + public void visit(VeraGlobalFunction obj) + { + printGlobalFunc(obj); + } + + public void visit(VeraGlobalVariable obj) + { + // TODO: print global variables in program block + printVarDecl(obj); + printVarInit(obj); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraHDLFunction obj) + { + fmt.printToken("hdl_task"); + fmt.printSpace(); + printID(obj.getName()); + VeraFunctionType funcType = obj.getType(); + printFuncArgs(funcType); + fmt.printToken("\"" + obj.getInstPath() + "\""); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraInterfaceType obj) + { + printInterface(obj); + } + + public void visit(VeraPortType obj) + { + printPort(obj); + } + + public void visit(VeraProgram obj) + { + fmt.printToken("program"); + fmt.printSpace(); + printID(obj.getName()); + printBody(obj.getBlock()); + } + + public void visit(VeraRangeDefine obj) + { + printDefine(obj, formatDefineRange(obj.getRange())); + } + + private String formatDefineRange(VeraRange range) + { + if (range != null) + { + StringTokenFormatter strFmt = new StringTokenFormatter(); + printRange(range, strFmt); + return strFmt.toString(); + } + else + { + return "/* NULL */"; + } + } + + public void visit(VeraStatementDefine obj) + { + printDefine(obj, formatDefineStmt(obj.getStatement())); + } + + private String formatDefineStmt(VeraStatement stmt) + { + if (stmt != null) + { + StringTokenFormatter strFmt = new StringTokenFormatter(); + BlockMemberPrinter bmp = new BlockMemberPrinter(strFmt, config); + bmp.printStatement(stmt); + return strFmt.toString(); + } + else + { + return "/* NULL */"; + } + } + + public void visit(VeraTypeDefine obj) + { + printDefine(obj, formatDefineType(obj.getType())); + } + + private String formatDefineType(VeraType type) + { + if (type != null) + { + StringTokenFormatter strFmt = new StringTokenFormatter(); + printType(type, strFmt); + printArrayModifiers(type, strFmt); + return strFmt.toString(); + } + else + { + return "/* NULL */"; + } + } + + public void visit(VeraUDFFunction obj) + { + fmt.printToken("extern"); + fmt.printSpace(); + fmt.printToken("\"" + obj.getLanguage() + "\""); + fmt.printSpace(); + VeraFunctionType funcType = obj.getType(); + printFuncProlog(funcType); + printID(obj.getName()); + printFuncArgs(funcType); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void visit(VeraUserClass obj) + { + printClass(obj); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/ExpressionPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/ExpressionPrinter.java new file mode 100644 index 0000000..c345022 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/ExpressionPrinter.java @@ -0,0 +1,726 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Iterator; +import java.util.List; + +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.StructuredType; +import com.newisys.langschema.vera.*; +import com.newisys.util.text.TokenFormatter; + +/** + * Printer module used to print Vera expressions. + * + * @author Trevor Robinson + */ +public class ExpressionPrinter + extends VeraSchemaPrinterModule + implements VeraExpressionVisitor +{ + private final int parentPrecedence; + + public ExpressionPrinter( + TokenFormatter fmt, + VeraSchemaPrinter config, + int parentPrecedence) + { + super(fmt, config); + this.parentPrecedence = parentPrecedence; + } + + public ExpressionPrinter(TokenFormatter fmt, VeraSchemaPrinter config) + { + this(fmt, config, 100); + } + + // Precedence: + // 0: () + // 1: ++ -- + // 2: & ~& | ~| ^ ~^ ~ >< - ! (unary) + // 3: * / % + // 4: + - + // 5: << >> + // 6: < <= > >= in !in dist + // 7: =?= !?= == != === !== + // 8: & &~ + // 9: ^ ^~ + // 10: | |~ + // 11: && + // 12: || + // 13: ?: + // 14: => + // 15: = += -= *= /= %= + // 16: <<= >>= &= |= ^= ~&= ~|= ~^= + + private void printUnary( + VeraUnaryOperation op, + String token, + int precedence, + boolean prefix) + { + final boolean needParens = precedence > parentPrecedence; + if (needParens) fmt.printLeadingToken("("); + + if (prefix) fmt.printLeadingToken(token); + + VeraExpression op1 = op.getOperand(0); + printExpression(op1, precedence - (prefix ? 0 : 1)); + + if (!prefix) fmt.printTrailingToken(token); + + if (needParens) fmt.printTrailingToken(")"); + } + + private void printInfix(VeraBinaryOperation op, String token, int precedence) + { + final boolean needParens = precedence > parentPrecedence; + if (needParens) fmt.printLeadingToken("("); + + VeraExpression op1 = op.getOperand(0); + printExpression(op1, precedence); + + fmt.printSpace(); + fmt.printLeadingToken(token); + fmt.printSpace(); + + VeraExpression op2 = op.getOperand(1); + printExpression(op2, precedence - 1); + + if (needParens) fmt.printTrailingToken(")"); + } + + private void printSet(VeraSetOperation op, String token) + { + final int precedence = 6; + final boolean needParens = precedence > parentPrecedence; + if (needParens) fmt.printLeadingToken("("); + + printExpression(op.getExpr(), precedence); + + fmt.printSpace(); + fmt.printLeadingToken(token); + fmt.printSpace(); + + fmt.printLeadingToken("{"); + Iterator iter = op.getMembers().iterator(); + while (iter.hasNext()) + { + fmt.printSpace(); + VeraSetMember member = (VeraSetMember) iter.next(); + + VeraExpression weight = member.getWeight(); + if (weight != null) + { + printExpression(weight); + fmt.printSpace(); + fmt.printLeadingToken(member.isWeightPerItem() ? ":=" : ":/"); + fmt.printSpace(); + } + + if (member instanceof VeraSetRange) + { + VeraSetRange rangeMember = (VeraSetRange) member; + printExpression(rangeMember.getLow()); + fmt.printLeadingToken(":"); + printExpression(rangeMember.getHigh()); + } + else + { + VeraSetValue valueMember = (VeraSetValue) member; + printExpression(valueMember.getValue()); + } + + if (iter.hasNext()) fmt.printTrailingToken(","); + } + fmt.printSpace(); + fmt.printTrailingToken("}"); + + if (needParens) fmt.printTrailingToken(")"); + } + + private void printArgs(List args, boolean parensOpt) + { + if (!parensOpt || !args.isEmpty()) + { + fmt.printTrailingToken("("); + Iterator iter = args.iterator(); + while (iter.hasNext()) + { + printExpression((VeraExpression) iter.next()); + if (iter.hasNext()) + { + fmt.printTrailingToken(","); + fmt.printSpace(); + } + } + fmt.printTrailingToken(")"); + } + } + + public void visit(VeraAdd obj) + { + printInfix(obj, "+", 4); + } + + public void visit(VeraAndReduction obj) + { + printUnary(obj, "&", 2, true); + } + + public void visit(VeraArithmeticNegative obj) + { + printUnary(obj, "-", 2, true); + } + + public void visit(VeraArrayAccess obj) + { + printExpression(obj.getArray(), 0); + Iterator iter = obj.getIndices().iterator(); + while (iter.hasNext()) + { + fmt.printLeadingToken("["); + printExpression((VeraExpression) iter.next()); + fmt.printTrailingToken("]"); + } + } + + public void visit(VeraArrayCreation obj) + { + fmt.printToken("new"); + Iterator iter = obj.getDimensions().iterator(); + while (iter.hasNext()) + { + fmt.printLeadingToken("["); + printExpression((VeraExpression) iter.next()); + fmt.printTrailingToken("]"); + } + VeraExpression sourceExpr = obj.getSourceExpr(); + if (sourceExpr != null) + { + fmt.printSpace(); + fmt.printLeadingToken("("); + printExpression(sourceExpr); + fmt.printTrailingToken(")"); + } + } + + public void visit(VeraArrayInitializer obj) + { + fmt.printLeadingToken("{"); + Iterator iter = obj.getElements().iterator(); + while (iter.hasNext()) + { + fmt.printSpace(); + printExpression((VeraExpression) iter.next()); + if (iter.hasNext()) fmt.printTrailingToken(","); + } + fmt.printSpace(); + fmt.printTrailingToken("}"); + } + + public void visit(VeraAssign obj) + { + printInfix(obj, "=", 15); + } + + public void visit(VeraAssignAdd obj) + { + printInfix(obj, "+=", 15); + } + + public void visit(VeraAssignAnd obj) + { + printInfix(obj, "&=", 16); + } + + public void visit(VeraAssignAndNot obj) + { + printInfix(obj, "~&=", 16); + } + + public void visit(VeraAssignDivide obj) + { + printInfix(obj, "/=", 15); + } + + public void visit(VeraAssignLeftShift obj) + { + printInfix(obj, "<<=", 16); + } + + public void visit(VeraAssignModulo obj) + { + printInfix(obj, "%=", 15); + } + + public void visit(VeraAssignMultiply obj) + { + printInfix(obj, "*=", 15); + } + + public void visit(VeraAssignOr obj) + { + printInfix(obj, "|=", 16); + } + + public void visit(VeraAssignOrNot obj) + { + printInfix(obj, "~|=", 16); + } + + public void visit(VeraAssignRightShift obj) + { + printInfix(obj, ">>=", 16); + } + + public void visit(VeraAssignSubtract obj) + { + printInfix(obj, "-=", 15); + } + + public void visit(VeraAssignXor obj) + { + printInfix(obj, "^=", 16); + } + + public void visit(VeraAssignXorNot obj) + { + printInfix(obj, "~^=", 16); + } + + public void visit(VeraBitSliceAccess obj) + { + printExpression(obj.getArray(), 0); + fmt.printLeadingToken("["); + printRange(obj.getRange(), fmt); + fmt.printTrailingToken("]"); + } + + public void visit(VeraBitVectorLiteral obj) + { + fmt.printToken(obj.getValue().toString(obj.getRadix())); + } + + public void visit(VeraBitwiseAnd obj) + { + printInfix(obj, "&", 8); + } + + public void visit(VeraBitwiseAndNot obj) + { + printInfix(obj, "&~", 8); + } + + public void visit(VeraBitwiseNegative obj) + { + printUnary(obj, "~", 2, true); + } + + public void visit(VeraBitwiseOr obj) + { + printInfix(obj, "|", 10); + } + + public void visit(VeraBitwiseOrNot obj) + { + printInfix(obj, "|~", 10); + } + + public void visit(VeraBitwiseReverse obj) + { + printUnary(obj, "><", 2, true); + } + + public void visit(VeraBitwiseXor obj) + { + printInfix(obj, "^", 9); + } + + public void visit(VeraBitwiseXorNot obj) + { + printInfix(obj, "^~", 9); + } + + public void visit(VeraConcatenation obj) + { + fmt.printLeadingToken("{"); + Iterator iter = obj.getOperands().iterator(); + while (iter.hasNext()) + { + fmt.printSpace(); + printExpression((VeraExpression) iter.next()); + if (iter.hasNext()) fmt.printTrailingToken(","); + } + fmt.printSpace(); + fmt.printTrailingToken("}"); + } + + public void visit(VeraConditional obj) + { + final int precedence = 13; + final boolean needParens = precedence > parentPrecedence; + if (needParens) fmt.printLeadingToken("("); + + VeraExpression op1 = obj.getOperand(0); + printExpression(op1, precedence - 1); + + fmt.printSpace(); + fmt.printLeadingToken("?"); + fmt.printSpace(); + + VeraExpression op2 = obj.getOperand(1); + printExpression(op2, precedence); + + fmt.printSpace(); + fmt.printLeadingToken(":"); + fmt.printSpace(); + + VeraExpression op3 = obj.getOperand(2); + printExpression(op3, precedence); + + if (needParens) fmt.printTrailingToken(")"); + } + + public void visit(VeraConstraintSet obj) + { + List exprs = obj.getExprs(); + printConstraints(exprs); + } + + public void visit(VeraCopyCreation obj) + { + fmt.printToken("new"); + fmt.printSpace(); + printExpression(obj.getSource()); + } + + public void visit(VeraDepthAccess obj) + { + fmt.printLeadingToken("."); + fmt.printToken(String.valueOf(obj.getDepth())); + } + + public void visit(VeraDistSet obj) + { + printSet(obj, "dist"); + } + + public void visit(VeraDivide obj) + { + printInfix(obj, "/", 3); + } + + public void visit(VeraEnumValueReference obj) + { + VeraEnumerationElement elem = obj.getElement(); + // TODO: qualify names of class enum value references outside class + printName(elem.getName(), false); + } + + public void visit(VeraEqual obj) + { + printInfix(obj, "==", 7); + } + + public void visit(VeraExactEqual obj) + { + printInfix(obj, "===", 7); + } + + public void visit(VeraExactNotEqual obj) + { + printInfix(obj, "!==", 7); + } + + public void visit(VeraFunctionInvocation obj) + { + printExpression(obj.getFunction(), 0); + printArgs(obj.getArguments(), false); + final List constraints = obj.getConstraints(); + if (!constraints.isEmpty()) + { + fmt.printSpace(); + fmt.printToken("with"); + fmt.printSpace(); + printConstraints(constraints); + } + } + + public void visit(VeraFunctionReference obj) + { + printName(obj.getFunction().getName(), false); + } + + public void visit(VeraGreater obj) + { + printInfix(obj, ">", 6); + } + + public void visit(VeraGreaterOrEqual obj) + { + printInfix(obj, ">=", 6); + } + + public void visit(VeraIfElseConstraint obj) + { + fmt.printToken("if"); + fmt.printSpace(); + fmt.printLeadingToken("("); + printExpression(obj.getIfExpression()); + fmt.printTrailingToken(")"); + + final VeraExpression thenExpr = obj.getThenExpression(); + printExpression(thenExpr); + if (!endsWithSet(thenExpr)) + { + fmt.printTrailingToken(";"); + } + + final VeraExpression elseExpr = obj.getElseExpression(); + if (elseExpr != null) + { + fmt.printToken("else"); + fmt.printSpace(); + printExpression(elseExpr); + if (!endsWithSet(elseExpr)) + { + fmt.printTrailingToken(";"); + } + } + } + + public void visit(VeraImplicationConstraint obj) + { + printInfix(obj, "=>", 14); + } + + public void visit(VeraInSet obj) + { + printSet(obj, "in"); + } + + public void visit(VeraInstanceCreation obj) + { + fmt.printToken("new"); + printArgs(obj.getArguments(), true); + } + + public void visit(VeraIntegerLiteral obj) + { + fmt.printToken(Integer.toString(obj.getValue())); + } + + public void visit(VeraInterfaceReference obj) + { + printName(obj.getInterface().getName(), false); + } + + public void visit(VeraLeftShift obj) + { + printInfix(obj, "<<", 5); + } + + public void visit(VeraLess obj) + { + printInfix(obj, "<", 6); + } + + public void visit(VeraLessOrEqual obj) + { + printInfix(obj, "<=", 6); + } + + public void visit(VeraLogicalAnd obj) + { + printInfix(obj, "&&", 11); + } + + public void visit(VeraLogicalNegative obj) + { + printUnary(obj, "!", 2, true); + } + + public void visit(VeraLogicalOr obj) + { + printInfix(obj, "||", 12); + } + + public void visit(VeraMemberAccess obj) + { + printExpression(obj.getObject(), 0); + fmt.printLeadingToken("."); + NamedObject member = (NamedObject) obj.getMember(); + printID(member.getName()); + } + + public void visit(VeraModulo obj) + { + printInfix(obj, "%", 3); + } + + public void visit(VeraMultiply obj) + { + printInfix(obj, "*", 3); + } + + public void visit(VeraNotAndReduction obj) + { + printUnary(obj, "~&", 2, true); + } + + public void visit(VeraNotEqual obj) + { + printInfix(obj, "!=", 7); + } + + public void visit(VeraNotInSet obj) + { + printSet(obj, "!in"); + } + + public void visit(VeraNotOrReduction obj) + { + printUnary(obj, "~|", 2, true); + } + + public void visit(VeraNotXorReduction obj) + { + printUnary(obj, "~^", 2, true); + } + + public void visit(VeraNullLiteral obj) + { + fmt.printToken("null"); + } + + public void visit(VeraOrReduction obj) + { + printUnary(obj, "|", 2, true); + } + + public void visit(VeraPostDecrement obj) + { + printUnary(obj, "--", 1, false); + } + + public void visit(VeraPostIncrement obj) + { + printUnary(obj, "++", 1, false); + } + + public void visit(VeraPreDecrement obj) + { + printUnary(obj, "--", 1, true); + } + + public void visit(VeraPreIncrement obj) + { + printUnary(obj, "++", 1, true); + } + + public void visit(VeraReplication obj) + { + fmt.printLeadingToken("{"); + fmt.printSpace(); + printExpression(obj.getOperand(0)); + fmt.printSpace(); + + VeraExpression op2 = obj.getOperand(1); + boolean op2concat = op2 instanceof VeraConcatenation; + if (!op2concat) + { + fmt.printLeadingToken("{"); + fmt.printSpace(); + } + printExpression(op2); + if (!op2concat) + { + fmt.printSpace(); + fmt.printTrailingToken("}"); + } + + fmt.printSpace(); + fmt.printTrailingToken("}"); + } + + public void visit(VeraRightShift obj) + { + printInfix(obj, ">>", 5); + } + + public void visit(VeraSignalReference obj) + { + VeraInterfaceSignal signal = obj.getSignal(); + StructuredType intf = signal.getStructuredType(); + printName(intf.getName(), false); + fmt.printLeadingToken("."); + printID(signal.getName()); + } + + public void visit(VeraStringLiteral obj) + { + fmt.printToken('"' + VeraStringLiteral.escape(obj.getValue()) + '"'); + } + + public void visit(VeraSubtract obj) + { + printInfix(obj, "-", 4); + } + + public void visit(VeraSuperReference obj) + { + fmt.printToken("super"); + } + + public void visit(VeraSystemClockReference obj) + { + fmt.printToken("CLOCK"); + } + + public void visit(VeraThisReference obj) + { + fmt.printToken("this"); + } + + public void visit(VeraVariableReference obj) + { + printName(obj.getVariable().getName(), false); + } + + public void visit(VeraVoidLiteral obj) + { + fmt.printToken("void"); + } + + public void visit(VeraWildEqual obj) + { + printInfix(obj, "=?=", 7); + } + + public void visit(VeraWildNotEqual obj) + { + printInfix(obj, "!?=", 7); + } + + public void visit(VeraXorReduction obj) + { + printUnary(obj, "^", 2, true); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaMemberPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaMemberPrinter.java new file mode 100644 index 0000000..8057743 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaMemberPrinter.java @@ -0,0 +1,67 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Collection; +import java.util.Iterator; + +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraGlobalFunction; +import com.newisys.langschema.vera.VeraSchemaMember; +import com.newisys.langschema.vera.VeraSchemaMemberVisitor; +import com.newisys.util.text.TokenFormatter; + +/** + * Printer module used to print Vera schema members. + * + * @author Trevor Robinson + */ +public class SchemaMemberPrinter + extends VeraSchemaPrinterModule + implements VeraSchemaMemberVisitor +{ + public SchemaMemberPrinter(TokenFormatter fmt, VeraSchemaPrinter config) + { + super(fmt, config); + } + + public void printMembers(Collection members) + { + boolean first = true; + Iterator iter = members.iterator(); + while (iter.hasNext()) + { + VeraSchemaMember member = (VeraSchemaMember) iter.next(); + if (!first) printNewLine(); + member.accept(this); + first = false; + } + } + + public void visit(VeraCompilationUnit obj) + { + CompilationUnitMemberPrinter cump = new CompilationUnitMemberPrinter( + fmt, config); + cump.printMembers(obj.getMembers()); + } + + public void visit(VeraGlobalFunction obj) + { + printGlobalFunc(obj); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaObjectPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaObjectPrinter.java new file mode 100644 index 0000000..f42f872 --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/SchemaObjectPrinter.java @@ -0,0 +1,784 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import com.newisys.langschema.vera.*; +import com.newisys.util.text.TokenFormatter; + +/** + * Printer module used to print all first-class schema objects (i.e. those + * appearing in VeraSchemaObjectVisitor). + * + * @author Trevor Robinson + */ +public class SchemaObjectPrinter + extends VeraSchemaPrinterModule + implements VeraSchemaObjectVisitor +{ + public SchemaObjectPrinter(TokenFormatter fmt, VeraSchemaPrinter config) + { + super(fmt, config); + } + + private void print(VeraSchemaMember obj) + { + SchemaMemberPrinter printer = new SchemaMemberPrinter(fmt, config); + obj.accept(printer); + } + + private void print(VeraCompilationUnitMember obj) + { + CompilationUnitMemberPrinter printer = new CompilationUnitMemberPrinter( + fmt, config); + obj.accept(printer); + } + + private void print(VeraClassMember obj) + { + ClassMemberPrinter printer = new ClassMemberPrinter(fmt, config); + obj.accept(printer); + } + + private void print(VeraBlockMember obj) + { + BlockMemberPrinter printer = new BlockMemberPrinter(fmt, config); + printer.printMember(obj); + } + + private void print(VeraExpression obj) + { + ExpressionPrinter printer = new ExpressionPrinter(fmt, config); + obj.accept(printer); + } + + private void print(VeraType obj) + { + printType(obj); + } + + public void visit(VeraAdd obj) + { + print(obj); + } + + public void visit(VeraAndReduction obj) + { + print(obj); + } + + public void visit(VeraArithmeticNegative obj) + { + print(obj); + } + + public void visit(VeraArrayAccess obj) + { + print(obj); + } + + public void visit(VeraArrayCreation obj) + { + print(obj); + } + + public void visit(VeraArrayInitializer obj) + { + print(obj); + } + + public void visit(VeraAssign obj) + { + print(obj); + } + + public void visit(VeraAssignAdd obj) + { + print(obj); + } + + public void visit(VeraAssignAnd obj) + { + print(obj); + } + + public void visit(VeraAssignAndNot obj) + { + print(obj); + } + + public void visit(VeraAssignDivide obj) + { + print(obj); + } + + public void visit(VeraAssignLeftShift obj) + { + print(obj); + } + + public void visit(VeraAssignModulo obj) + { + print(obj); + } + + public void visit(VeraAssignMultiply obj) + { + print(obj); + } + + public void visit(VeraAssignOr obj) + { + print(obj); + } + + public void visit(VeraAssignOrNot obj) + { + print(obj); + } + + public void visit(VeraAssignRightShift obj) + { + print(obj); + } + + public void visit(VeraAssignSubtract obj) + { + print(obj); + } + + public void visit(VeraAssignXor obj) + { + print(obj); + } + + public void visit(VeraAssignXorNot obj) + { + print(obj); + } + + public void visit(VeraAssocArrayType obj) + { + print(obj); + } + + public void visit(VeraBindMember obj) + { + printBindMember(obj); + } + + public void visit(VeraBindVariable obj) + { + print(obj); + } + + public void visit(VeraBitSliceAccess obj) + { + print(obj); + } + + public void visit(VeraBitType obj) + { + print(obj); + } + + public void visit(VeraBitVectorLiteral obj) + { + print(obj); + } + + public void visit(VeraBitwiseAnd obj) + { + print(obj); + } + + public void visit(VeraBitwiseAndNot obj) + { + print(obj); + } + + public void visit(VeraBitwiseNegative obj) + { + print(obj); + } + + public void visit(VeraBitwiseOr obj) + { + print(obj); + } + + public void visit(VeraBitwiseOrNot obj) + { + print(obj); + } + + public void visit(VeraBitwiseReverse obj) + { + print(obj); + } + + public void visit(VeraBitwiseXor obj) + { + print(obj); + } + + public void visit(VeraBitwiseXorNot obj) + { + print(obj); + } + + public void visit(VeraBlock obj) + { + print(obj); + } + + public void visit(VeraBreakpointStatement obj) + { + print(obj); + } + + public void visit(VeraBreakStatement obj) + { + print(obj); + } + + public void visit(VeraClassConstraint obj) + { + print((VeraClassMember) obj); + } + + public void visit(VeraCompilationUnit obj) + { + print(obj); + } + + public void visit(VeraConcatenation obj) + { + print(obj); + } + + public void visit(VeraConditional obj) + { + print(obj); + } + + public void visit(VeraConstraintSet obj) + { + print(obj); + } + + public void visit(VeraContinueStatement obj) + { + print(obj); + } + + public void visit(VeraCopyCreation obj) + { + print(obj); + } + + public void visit(VeraDefineArgument obj) + { + fmt.printToken(obj.getName().getIdentifier()); + } + + public void visit(VeraDefineReference obj) + { + printDefineRef(obj, fmt); + } + + public void visit(VeraDepthAccess obj) + { + print(obj); + } + + public void visit(VeraDistSet obj) + { + print(obj); + } + + public void visit(VeraDivide obj) + { + print(obj); + } + + public void visit(VeraDriveSampleStatement obj) + { + print(obj); + } + + public void visit(VeraDynamicArrayType obj) + { + print(obj); + } + + public void visit(VeraEnumeration obj) + { + printEnum(obj); + } + + public void visit(VeraEnumerationElement obj) + { + printEnumElement(obj); + } + + public void visit(VeraEnumValueReference obj) + { + print(obj); + } + + public void visit(VeraEqual obj) + { + print(obj); + } + + public void visit(VeraEventType obj) + { + print(obj); + } + + public void visit(VeraExactEqual obj) + { + print(obj); + } + + public void visit(VeraExactNotEqual obj) + { + print(obj); + } + + public void visit(VeraExpectStatement obj) + { + print(obj); + } + + public void visit(VeraExpressionDefine obj) + { + print(obj); + } + + public void visit(VeraExpressionStatement obj) + { + print(obj); + } + + public void visit(VeraFixedArrayType obj) + { + print(obj); + } + + public void visit(VeraFixedBitVectorType obj) + { + print(obj); + } + + public void visit(VeraForkStatement obj) + { + print(obj); + } + + public void visit(VeraForStatement obj) + { + print(obj); + } + + public void visit(VeraFunctionArgument obj) + { + printFuncArg(obj); + } + + public void visit(VeraFunctionInvocation obj) + { + print(obj); + } + + public void visit(VeraFunctionReference obj) + { + print(obj); + } + + public void visit(VeraFunctionType obj) + { + printFuncProlog(obj); + printFuncArgs(obj); + } + + public void visit(VeraGlobalFunction obj) + { + print((VeraSchemaMember) obj); + } + + public void visit(VeraGlobalVariable obj) + { + print(obj); + } + + public void visit(VeraGreater obj) + { + print(obj); + } + + public void visit(VeraGreaterOrEqual obj) + { + print(obj); + } + + public void visit(VeraHDLFunction obj) + { + print((VeraCompilationUnitMember) obj); + } + + public void visit(VeraIfElseConstraint obj) + { + print(obj); + } + + public void visit(VeraIfStatement obj) + { + print(obj); + } + + public void visit(VeraImplicationConstraint obj) + { + print(obj); + } + + public void visit(VeraInSet obj) + { + print(obj); + } + + public void visit(VeraInstanceCreation obj) + { + print(obj); + } + + public void visit(VeraIntegerLiteral obj) + { + print(obj); + } + + public void visit(VeraIntegerType obj) + { + print(obj); + } + + public void visit(VeraInterfaceReference obj) + { + print(obj); + } + + public void visit(VeraInterfaceSignal obj) + { + printInterfaceSignal(obj); + } + + public void visit(VeraInterfaceType obj) + { + printInterface(obj); + } + + public void visit(VeraLeftShift obj) + { + print(obj); + } + + public void visit(VeraLess obj) + { + print(obj); + } + + public void visit(VeraLessOrEqual obj) + { + print(obj); + } + + public void visit(VeraLocalVariable obj) + { + print(obj); + } + + public void visit(VeraLogicalAnd obj) + { + print(obj); + } + + public void visit(VeraLogicalNegative obj) + { + print(obj); + } + + public void visit(VeraLogicalOr obj) + { + print(obj); + } + + public void visit(VeraMagicType obj) + { + print(obj); + } + + public void visit(VeraMemberAccess obj) + { + print(obj); + } + + public void visit(VeraMemberFunction obj) + { + print(obj); + } + + public void visit(VeraMemberVariable obj) + { + print(obj); + } + + public void visit(VeraModulo obj) + { + print(obj); + } + + public void visit(VeraMultiply obj) + { + print(obj); + } + + public void visit(VeraNotAndReduction obj) + { + print(obj); + } + + public void visit(VeraNotEqual obj) + { + print(obj); + } + + public void visit(VeraNotInSet obj) + { + print(obj); + } + + public void visit(VeraNotOrReduction obj) + { + print(obj); + } + + public void visit(VeraNotXorReduction obj) + { + print(obj); + } + + public void visit(VeraNullLiteral obj) + { + print(obj); + } + + public void visit(VeraNullType obj) + { + print(obj); + } + + public void visit(VeraOrReduction obj) + { + print(obj); + } + + public void visit(VeraPortSignal obj) + { + printPortSignal(obj); + } + + public void visit(VeraPortType obj) + { + printPort(obj); + } + + public void visit(VeraPostDecrement obj) + { + print(obj); + } + + public void visit(VeraPostIncrement obj) + { + print(obj); + } + + public void visit(VeraPreDecrement obj) + { + print(obj); + } + + public void visit(VeraPreIncrement obj) + { + print(obj); + } + + public void visit(VeraProgram obj) + { + print(obj); + } + + public void visit(VeraRandCaseStatement obj) + { + print(obj); + } + + public void visit(VeraRange obj) + { + printRange(obj, fmt); + } + + public void visit(VeraRangeDefine obj) + { + print(obj); + } + + public void visit(VeraRepeatStatement obj) + { + print(obj); + } + + public void visit(VeraReplication obj) + { + print(obj); + } + + public void visit(VeraReturnStatement obj) + { + print(obj); + } + + public void visit(VeraRightShift obj) + { + print(obj); + } + + public void visit(VeraSignalReference obj) + { + print(obj); + } + + public void visit(VeraStatementDefine obj) + { + print(obj); + } + + public void visit(VeraStringLiteral obj) + { + print(obj); + } + + public void visit(VeraStringType obj) + { + print(obj); + } + + public void visit(VeraSubtract obj) + { + print(obj); + } + + public void visit(VeraSuperReference obj) + { + print(obj); + } + + public void visit(VeraSwitchStatement obj) + { + print(obj); + } + + public void visit(VeraSyncStatement obj) + { + print(obj); + } + + public void visit(VeraSystemClass obj) + { + print(obj); + } + + public void visit(VeraSystemClockReference obj) + { + print(obj); + } + + public void visit(VeraTerminateStatement obj) + { + print(obj); + } + + public void visit(VeraThisReference obj) + { + print(obj); + } + + public void visit(VeraTypeDefine obj) + { + print(obj); + } + + public void visit(VeraUDFFunction obj) + { + print((VeraCompilationUnitMember) obj); + } + + public void visit(VeraUnsizedBitVectorType obj) + { + print(obj); + } + + public void visit(VeraUserClass obj) + { + printClass(obj); + } + + public void visit(VeraVariableReference obj) + { + print(obj); + } + + public void visit(VeraVoidLiteral obj) + { + print(obj); + } + + public void visit(VeraVoidType obj) + { + print(obj); + } + + public void visit(VeraWhileStatement obj) + { + print(obj); + } + + public void visit(VeraWildEqual obj) + { + print(obj); + } + + public void visit(VeraWildNotEqual obj) + { + print(obj); + } + + public void visit(VeraXorReduction obj) + { + print(obj); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinter.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinter.java new file mode 100644 index 0000000..f21b70c --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinter.java @@ -0,0 +1,99 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import com.newisys.langschema.vera.VeraSchema; +import com.newisys.langschema.vera.VeraSchemaObject; +import com.newisys.schemaprinter.SchemaPrinter; +import com.newisys.schemaprinter.WrappedIOException; +import com.newisys.util.text.TokenFormatter; + +/** + * Generates Vera source text corresponding to a schema. Currently, this class + * simply dumps the entire schema to an output stream; it does not attempt to + * generate individual source files, #include directives, etc. + * + * @author Trevor Robinson + */ +public class VeraSchemaPrinter + extends SchemaPrinter +{ + public void print(VeraSchema schema, Writer writer) + throws IOException + { + try + { + TokenFormatter fmt = getTokenFormatter(writer); + SchemaMemberPrinter smp = new SchemaMemberPrinter(fmt, this); + smp.printMembers(schema.getMembers()); + fmt.flush(); + } + catch (WrappedIOException e) + { + throw e.getIOException(); + } + } + + public String toString(VeraSchema schema) + { + StringWriter writer = new StringWriter(200); + try + { + print(schema, writer); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + return writer.toString(); + } + + public void print(VeraSchemaObject obj, Writer writer) + throws IOException + { + try + { + TokenFormatter fmt = getTokenFormatter(writer); + SchemaObjectPrinter smp = new SchemaObjectPrinter(fmt, this); + obj.accept(smp); + fmt.flush(); + } + catch (WrappedIOException e) + { + throw e.getIOException(); + } + } + + public String toString(VeraSchemaObject obj) + { + StringWriter writer = new StringWriter(200); + try + { + print(obj, writer); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + return writer.toString(); + } +} diff --git a/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinterModule.java b/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinterModule.java new file mode 100644 index 0000000..4af258d --- /dev/null +++ b/java/langschema-vera/src/com/newisys/schemaprinter/vera/VeraSchemaPrinterModule.java @@ -0,0 +1,661 @@ +/* + * LangSchema-Vera - Programming Language Modeling Classes for OpenVera (TM) + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemaprinter.vera; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import com.newisys.langschema.Name; +import com.newisys.langschema.Visibility; +import com.newisys.langschema.vera.*; +import com.newisys.schemaprinter.SchemaPrinterModule; +import com.newisys.util.text.TokenFormatter; +import com.newisys.verilog.EdgeSet; + +/** + * Convenience base class for Vera schema printer Visitor classes. Provides + * methods for printing schema information that is common across Visitors. + */ +public abstract class VeraSchemaPrinterModule + extends SchemaPrinterModule +{ + protected final VeraSchemaPrinter config; + + public VeraSchemaPrinterModule(TokenFormatter fmt, VeraSchemaPrinter config) + { + super(fmt); + this.config = config; + } + + public void printID(Name name) + { + fmt.printToken(name.getIdentifier()); + } + + public void printName(Name name, boolean qualify) + { + if (qualify) + { + printName(name.getNamespace().getName(), true); + fmt.printLeadingToken("::"); + } + printID(name); + } + + public void printVisibility( + Visibility visibility, + VeraVisibility defaultVisibility) + { + if (visibility != defaultVisibility) + { + fmt.printToken(visibility.toString()); + fmt.printSpace(); + } + } + + public void printModifiers(Set modifiers) + { + int count = modifiers.size(); + if (count > 0) + { + String[] strs = new String[count]; + int index = 0; + Iterator iter = modifiers.iterator(); + while (iter.hasNext()) + { + strs[index++] = iter.next().toString(); + } + + Arrays.sort(strs); + + for (index = 0; index < count; ++index) + { + fmt.printToken(strs[index]); + fmt.printSpace(); + } + } + } + + public void printType(VeraType type) + { + printType(type, fmt); + } + + public void printType(VeraType type, TokenFormatter fmt) + { + if (type instanceof VeraArrayType) + { + VeraArrayType arrayType = (VeraArrayType) type; + printType(arrayType.getElementType(), fmt); + } + else if (type instanceof VeraComplexType) + { + // TODO: qualify names of class enum references outside class + printName(((VeraComplexType) type).getName(), false); + } + else if (type instanceof VeraFixedBitVectorType) + { + int size = ((VeraFixedBitVectorType) type).getSize(); + fmt.printToken("bit"); + fmt.printLeadingToken("["); + fmt.printToken(String.valueOf(size - 1)); + fmt.printTrailingToken(":0]"); + } + else + { + fmt.printToken(type.toReferenceString()); + } + } + + public void printArrayModifiers(VeraType type) + { + printArrayModifiers(type, fmt); + } + + public void printArrayModifiers(VeraType type, TokenFormatter fmt) + { + if (!(type instanceof VeraArrayType)) return; + + if (type instanceof VeraFixedArrayType) + { + int[] dims = ((VeraFixedArrayType) type).getDimensions(); + int dimCount = dims.length; + for (int i = 0; i < dimCount; ++i) + { + fmt.printLeadingToken("["); + fmt.printToken(String.valueOf(dims[i])); + fmt.printTrailingToken("]"); + } + } + else if (type instanceof VeraAssocArrayType) + { + fmt.printLeadingToken("["); + VeraType indexType = ((VeraAssocArrayType) type).getIndexTypes()[0]; + if (!(indexType instanceof VeraBitVectorType)) + { + printType(indexType, fmt); + } + fmt.printTrailingToken("]"); + } + else + { + assert (type instanceof VeraDynamicArrayType); + fmt.printLeadingToken("["); + fmt.printToken("*"); + fmt.printTrailingToken("]"); + } + } + + public void printVarDecl(VeraVariable var) + { + printModifiers(var.getModifiers()); + VeraType type = var.getType(); + printType(type); + fmt.printSpace(); + printID(var.getName()); + printArrayModifiers(type); + } + + public void printVarInit(VeraVariable var) + { + VeraExpression initExpr = var.getInitializer(); + if (initExpr != null) + { + fmt.printSpace(); + fmt.printLeadingToken("="); + fmt.printSpace(); + printExpression(initExpr); + } + } + + public void printFuncProlog(VeraFunctionType funcType) + { + VeraType returnType = funcType.getReturnType(); + if (returnType != null && !(returnType instanceof VeraVoidType)) + { + fmt.printToken("function"); + fmt.printSpace(); + printType(returnType); + } + else + { + fmt.printToken("task"); + } + fmt.printSpace(); + } + + private int printFuncArg( + VeraFunctionArgument arg, + int curLevel, + boolean first, + boolean last) + { + int argLevel = arg.getOptionalLevel(); + if (!first) + { + while (curLevel > argLevel) + { + fmt.printTrailingToken(")"); + --curLevel; + } + fmt.printTrailingToken(","); + fmt.printSpace(); + } + while (curLevel < argLevel) + { + fmt.printLeadingToken("("); + ++curLevel; + } + printVarDecl(arg); + printVarInit(arg); + if (last) + { + while (curLevel > 0) + { + fmt.printTrailingToken(")"); + --curLevel; + } + } + return curLevel; + } + + public void printFuncArg(VeraFunctionArgument arg) + { + printFuncArg(arg, 0, true, true); + } + + public void printFuncArgs(VeraFunctionType funcType) + { + fmt.printTrailingToken("("); + boolean first = true; + boolean varArgs = funcType.isVarArgs(); + int curLevel = 0; + Iterator iter = funcType.getArguments().iterator(); + while (iter.hasNext()) + { + VeraFunctionArgument arg = (VeraFunctionArgument) iter.next(); + curLevel = printFuncArg(arg, curLevel, first, !varArgs + && !iter.hasNext()); + first = false; + } + if (varArgs) + { + if (funcType.isVarArgsByRef()) + { + fmt.printToken("var"); + fmt.printSpace(); + } + fmt.printToken("..."); + } + fmt.printTrailingToken(")"); + } + + public void printExpression(VeraExpression expr) + { + printExpression(expr, 100); + } + + public void printExpression(VeraExpression expr, int parentPrecedence) + { + printExpression(expr, parentPrecedence, fmt); + } + + public void printExpression( + VeraExpression expr, + int parentPrecedence, + TokenFormatter fmt) + { + ExpressionPrinter printer = new ExpressionPrinter(fmt, config, + parentPrecedence); + VeraDefineReference defineRef = expr.getDefineRef(); + if (defineRef != null) + { + printDefineRef(defineRef, fmt); + } + else + { + fmt.beginGroup(); + expr.accept(printer); + fmt.endGroup(); + } + } + + public void printRange(VeraRange obj, TokenFormatter fmt) + { + VeraDefineReference defineRef = obj.getDefineRef(); + if (defineRef != null) + { + printDefineRef(defineRef, fmt); + } + else + { + printExpression(obj.getFrom(), 100, fmt); + fmt.printLeadingToken(":"); + printExpression(obj.getTo(), 100, fmt); + } + } + + public void printConstraints(List exprs) + { + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + Iterator iter = exprs.iterator(); + while (iter.hasNext()) + { + fmt.printSpace(); + VeraExpression expr = (VeraExpression) iter.next(); + printExpression(expr); + if (!endsWithSet(expr)) + { + fmt.printTrailingToken(";"); + } + printNewLine(); + } + + fmt.decIndent(); + fmt.printToken("}"); + } + + public boolean endsWithSet(VeraExpression expr) + { + if (expr instanceof VeraConstraintSet) + { + return true; + } + else if (expr instanceof VeraImplicationConstraint) + { + return endsWithSet(((VeraImplicationConstraint) expr).getOperand(1)); + } + return false; + } + + public void printBlock(VeraBlock block) + { + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + if (block != null) + { + BlockMemberPrinter bmp = new BlockMemberPrinter(fmt, config); + bmp.printMembers(block.getMembers()); + } + else + { + // while complete schemas should never have null blocks, + // we support them here for dumping intermediate schemas + fmt.printToken("// NULL BLOCK"); + printNewLine(); + } + + fmt.decIndent(); + fmt.printToken("}"); + printNewLine(); + } + + public void printBody(VeraBlock body) + { + if (config.isCollapseBodies()) + { + fmt.printTrailingToken("..."); + printNewLine(); + } + else + { + printNewLine(); + printBlock(body); + } + } + + public void printEnum(VeraEnumeration obj) + { + fmt.printToken("enum"); + fmt.printSpace(); + printID(obj.getName()); + fmt.printSpace(); + fmt.printToken("="); + fmt.printSpace(); + + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraEnumerationElement member = (VeraEnumerationElement) iter + .next(); + printEnumElement(member); + if (iter.hasNext()) + { + fmt.printTrailingToken(","); + fmt.printSpace(); + } + } + + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void printEnumElement(VeraEnumerationElement member) + { + printID(member.getName()); + fmt.printSpace(); + fmt.printToken("="); + fmt.printSpace(); + fmt.printToken(String.valueOf(member.getValue())); + } + + public void printClass(VeraClass obj) + { + printVisibility(obj.getVisibility(), VeraVisibility.PUBLIC); + + if (obj.isVirtual()) + { + fmt.printToken("virtual"); + fmt.printSpace(); + } + + fmt.printToken("class"); + fmt.printSpace(); + printID(obj.getName()); + printNewLine(); + + VeraClass baseCls = obj.getBaseClass(); + if (baseCls != null) + { + Name name = baseCls.getName(); + if (!name.getCanonicalName().equals("")) + { + fmt.incIndent(); + fmt.printToken("extends"); + fmt.printSpace(); + printID(name); + printNewLine(); + fmt.decIndent(); + } + } + + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + ClassMemberPrinter cmp = new ClassMemberPrinter(fmt, config); + cmp.printMembers(obj.getMembers()); + + fmt.decIndent(); + fmt.printToken("}"); + printNewLine(); + } + + public void printGlobalFunc(VeraGlobalFunction obj) + { + if (obj.isExport()) + { + fmt.printToken("export"); + fmt.printSpace(); + } + printVisibility(obj.getVisibility(), VeraVisibility.PUBLIC); + VeraFunctionType funcType = obj.getType(); + printFuncProlog(funcType); + printID(obj.getName()); + printFuncArgs(funcType); + printBody(obj.getBody()); + } + + public void printBindMember(VeraBindMember member) + { + printID(member.getPortSignal().getName()); + fmt.printSpace(); + printExpression(member.getInterfaceExpr()); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void printInterface(VeraInterfaceType obj) + { + fmt.printToken("interface"); + fmt.printSpace(); + printID(obj.getName()); + printNewLine(); + + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraInterfaceSignal member = (VeraInterfaceSignal) iter.next(); + printInterfaceSignal(member); + } + + fmt.decIndent(); + fmt.printToken("}"); + printNewLine(); + } + + public void printInterfaceSignal(VeraInterfaceSignal member) + { + VeraSignalDirection direction = member.getDirection(); + fmt.printToken(direction.toString()); + + int width = member.getWidth(); + if (width > 1) + { + fmt.printLeadingToken("["); + fmt.printToken(String.valueOf(width - 1)); + fmt.printTrailingToken(":0]"); + } + + fmt.printSpace(); + printID(member.getName()); + + VeraSignalKind kind = member.getKind(); + if (kind == VeraSignalKind.CLOCK) + { + fmt.printSpace(); + fmt.printToken("CLOCK"); + } + else if (kind == VeraSignalKind.NORMAL) + { + EdgeSet sampleEdges = member.getSampleEdges(); + if (sampleEdges.contains(EdgeSet.POSEDGE)) + { + fmt.printSpace(); + fmt.printToken("PSAMPLE"); + } + if (sampleEdges.contains(EdgeSet.NEGEDGE)) + { + fmt.printSpace(); + fmt.printToken("NSAMPLE"); + } + int sampleSkew = member.getSampleSkew(); + if (sampleSkew != 0) + { + fmt.printSpace(); + fmt.printLeadingToken("#"); + fmt.printToken(String.valueOf(sampleSkew)); + } + + EdgeSet driveEdges = member.getDriveEdges(); + if (driveEdges.contains(EdgeSet.POSEDGE)) + { + fmt.printSpace(); + fmt.printToken("PHOLD"); + } + if (driveEdges.contains(EdgeSet.NEGEDGE)) + { + fmt.printSpace(); + fmt.printToken("NHOLD"); + } + int driveSkew = member.getDriveSkew(); + if (driveSkew != 0) + { + fmt.printSpace(); + fmt.printLeadingToken("#"); + fmt.printToken(String.valueOf(driveSkew)); + } + } + else + { + // TODO: return-to-? signals + assert false; + } + + int depth = member.getSampleDepth(); + if (depth > 0) + { + fmt.printSpace(); + fmt.printToken("depth"); + fmt.printSpace(); + fmt.printToken(String.valueOf(depth)); + } + + VeraVCAKind vcaKind = member.getVCAKind(); + if (vcaKind != VeraVCAKind.NONE) + { + // TODO: signal VCA + fmt.printSpace(); + fmt.printToken("/* VCA */"); + } + + String node = member.getHDLNode(); + if (node != null) + { + fmt.printSpace(); + fmt.printToken("hdl_node"); + fmt.printSpace(); + fmt.printToken("\"" + node + "\""); + } + + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void printPort(VeraPortType obj) + { + fmt.printToken("port"); + fmt.printSpace(); + printID(obj.getName()); + printNewLine(); + + fmt.printToken("{"); + printNewLine(); + fmt.incIndent(); + + Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + VeraPortSignal member = (VeraPortSignal) iter.next(); + printPortSignal(member); + } + + fmt.decIndent(); + fmt.printToken("}"); + printNewLine(); + } + + public void printPortSignal(VeraPortSignal member) + { + printID(member.getName()); + fmt.printTrailingToken(";"); + printNewLine(); + } + + public void printDefineRef(VeraDefineReference obj, TokenFormatter fmt) + { + fmt.printToken(obj.getDefine().getName().getIdentifier()); + List arguments = obj.getArguments(); + if (!arguments.isEmpty()) + { + fmt.printTrailingToken("("); + Iterator iter = arguments.iterator(); + while (iter.hasNext()) + { + printExpression((VeraExpression) iter.next(), 100, fmt); + if (iter.hasNext()) + { + fmt.printTrailingToken(","); + fmt.printSpace(); + } + } + fmt.printTrailingToken(")"); + } + } +} diff --git a/java/langsource/build.xml b/java/langsource/build.xml new file mode 100644 index 0000000..e416ffe --- /dev/null +++ b/java/langsource/build.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/langsource/manifest.mf b/java/langsource/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/langsource/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/langsource/src/com/newisys/langsource/SourceObject.java b/java/langsource/src/com/newisys/langsource/SourceObject.java new file mode 100644 index 0000000..fad0108 --- /dev/null +++ b/java/langsource/src/com/newisys/langsource/SourceObject.java @@ -0,0 +1,59 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource; + +import java.util.List; + +import com.newisys.io.IndentPrintWriter; +import com.newisys.langschema.Annotation; +import com.newisys.parser.util.IncludeLocation; + +/** + * Base interface for all source objects. + * + * @author Trevor Robinson + */ +public interface SourceObject +{ + void setBeginLocation(String filename, int line, int column); + + String getBeginFilename(); + + int getBeginLine(); + + int getBeginColumn(); + + void setEndLocation(String filename, int line, int column); + + String getEndFilename(); + + int getEndLine(); + + int getEndColumn(); + + void setIncludeLocation(IncludeLocation includeLocation); + + IncludeLocation getIncludeLocation(); + + void addAnnotation(Annotation comment); + + boolean hasAnnotations(); + + List getAnnotations(); + + void dump(IndentPrintWriter out); +} diff --git a/java/langsource/src/com/newisys/langsource/SourceObjectImpl.java b/java/langsource/src/com/newisys/langsource/SourceObjectImpl.java new file mode 100644 index 0000000..7286771 --- /dev/null +++ b/java/langsource/src/com/newisys/langsource/SourceObjectImpl.java @@ -0,0 +1,303 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource; + +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.io.IndentPrintWriter; +import com.newisys.langschema.Annotation; +import com.newisys.langschema.Comment; +import com.newisys.parser.util.IncludeLocation; + +/** + * Base implementation for source objects. + * + * @author Trevor Robinson + */ +public class SourceObjectImpl + implements SourceObject +{ + private String beginFilename; + private int beginLine; + private int beginColumn; + private String endFilename; + private int endLine; + private int endColumn; + private IncludeLocation includeLocation; + private List annotations; + + public void setBeginLocation(String filename, int line, int column) + { + this.beginFilename = filename; + this.beginLine = line; + this.beginColumn = column; + } + + public String getBeginFilename() + { + return beginFilename; + } + + public int getBeginLine() + { + return beginLine; + } + + public int getBeginColumn() + { + return beginColumn; + } + + public String getEndFilename() + { + return endFilename; + } + + public void setEndLocation(String filename, int line, int column) + { + this.endFilename = filename; + this.endLine = line; + this.endColumn = column; + } + + public int getEndLine() + { + return endLine; + } + + public int getEndColumn() + { + return endColumn; + } + + public void setIncludeLocation(IncludeLocation includeLocation) + { + this.includeLocation = includeLocation; + } + + public IncludeLocation getIncludeLocation() + { + return includeLocation; + } + + public void addAnnotation(Annotation annotation) + { + checkAnnotations(); + annotations.add(annotation); + } + + public boolean hasAnnotations() + { + return annotations != null; + } + + public List getAnnotations() + { + checkAnnotations(); + return annotations; + } + + private void checkAnnotations() + { + if (annotations == null) + { + annotations = new LinkedList(); + } + } + + public void copyMetadata(SourceObjectImpl other) + { + beginFilename = other.beginFilename; + beginLine = other.beginLine; + beginColumn = other.beginColumn; + endFilename = other.endFilename; + endLine = other.endLine; + endColumn = other.endColumn; + includeLocation = other.includeLocation; + if (other.annotations != null) + { + checkAnnotations(); + annotations.addAll(other.annotations); + } + } + + protected void dumpComments(PrintWriter out) + { + if (annotations != null) + { + Iterator iter = annotations.iterator(); + while (iter.hasNext()) + { + Annotation annotation = (Annotation) iter.next(); + if (annotation instanceof Comment) + { + out.print("/*"); + out.print(((Comment) annotation).getText()); + out.println("*/"); + } + } + } + } + + protected static void dumpCollection(IndentPrintWriter out, Collection c) + { + boolean onNewLine = false; + out.incIndent(); + try + { + Iterator iter = c.iterator(); + while (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof SourceObject) + { + if (!onNewLine) + { + out.println(); + } + ((SourceObject) obj).dump(out); + onNewLine = true; + } + else + { + out.print(obj); + if (iter.hasNext()) + { + out.print(", "); + } + onNewLine = false; + } + } + } + finally + { + if (!onNewLine) + { + out.println(); + } + out.decIndent(); + } + } + + private static void dumpFields( + IndentPrintWriter out, + Object obj, + Class cls, + Class stopClass) + { + if (cls != null && !cls.equals(stopClass)) + { + dumpFields(out, obj, cls.getSuperclass(), stopClass); + + Field[] fields = cls.getDeclaredFields(); + for (int i = 0; i < fields.length; ++i) + { + Field field = fields[i]; + if (Modifier.isStatic(field.getModifiers())) continue; + String name = field.getName(); + try + { + Class type = field.getType(); + String accessorPrefix = type.equals(boolean.class) ? "is" + : "get"; + String accessorName = accessorPrefix + + Character.toUpperCase(name.charAt(0)) + + name.substring(1); + Method accessor = cls.getMethod(accessorName); + Object value = accessor.invoke(obj); + if (value instanceof Collection) + { + Collection c = (Collection) value; + if (!c.isEmpty()) + { + out.print(name); + out.print(": "); + dumpCollection(out, c); + } + } + else if (value instanceof SourceObject) + { + out.print(name); + out.println(":"); + out.incIndent(); + try + { + ((SourceObject) value).dump(out); + } + finally + { + out.decIndent(); + } + } + else if (value != null) + { + out.print(name); + out.print(": "); + out.println(value); + } + } + catch (Exception e) + { + // ignored + } + } + } + } + + private static String getUnqualifiedName(String name) + { + int lastDot = name.lastIndexOf('.'); + if (lastDot >= 0) + { + return name.substring(lastDot + 1); + } + else + { + return name; + } + } + + protected void dumpContents(IndentPrintWriter out) + { + out.println(); + out.incIndent(); + try + { + dumpComments(out); + dumpFields(out, this, getClass(), SourceObjectImpl.class); + } + finally + { + out.decIndent(); + } + } + + public void dump(IndentPrintWriter out) + { + Class cls = getClass(); + out.print(getUnqualifiedName(cls.getName())); + out.print(": "); + dumpContents(out); + } +} diff --git a/java/langsource/src/com/newisys/parser/util/FunctionMacro.java b/java/langsource/src/com/newisys/parser/util/FunctionMacro.java new file mode 100644 index 0000000..fa7ebd8 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/FunctionMacro.java @@ -0,0 +1,33 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +import java.util.List; +import java.util.Map; + +/** + * Represents a function-style preprocessor macro. + * + * @author Trevor Robinson + */ +public interface FunctionMacro + extends Macro +{ + List getArgumentNames(); + + String expand(Map argValues); +} diff --git a/java/langsource/src/com/newisys/parser/util/IncludeLocation.java b/java/langsource/src/com/newisys/parser/util/IncludeLocation.java new file mode 100644 index 0000000..464ee47 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/IncludeLocation.java @@ -0,0 +1,62 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +/** + * Indicates the location of the #include directive that caused a particular + * file to be included. + * + * @author Trevor Robinson + */ +public class IncludeLocation +{ + /** + * The name of the file that #included the refering file. + */ + public final String filename; + + /** + * The line number of the line containing the #include token. + */ + public final int line; + + /** + * Location this file was #included from, or null if not included. + */ + public final IncludeLocation includedFrom; + + public IncludeLocation( + String filename, + int line, + IncludeLocation includedFrom) + { + this.filename = filename; + this.line = line; + this.includedFrom = includedFrom; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() + { + String thisLoc = filename + ":" + line; + return includedFrom != null ? thisLoc + " included from " + + includedFrom : thisLoc; + } +} diff --git a/java/langsource/src/com/newisys/parser/util/Macro.java b/java/langsource/src/com/newisys/parser/util/Macro.java new file mode 100644 index 0000000..319f8a4 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/Macro.java @@ -0,0 +1,29 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +/** + * Represents a preprocessor macro. + * + * @author Trevor Robinson + */ +public interface Macro +{ + String getName(); + + String expand(); +} diff --git a/java/langsource/src/com/newisys/parser/util/MacroRef.java b/java/langsource/src/com/newisys/parser/util/MacroRef.java new file mode 100644 index 0000000..eb7f022 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/MacroRef.java @@ -0,0 +1,29 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +/** + * Represents a particular reference to a preprocessor macro. + * + * @author Trevor Robinson + */ +public interface MacroRef +{ + Macro getMacro(); + + MacroRef getExpandedFrom(); +} diff --git a/java/langsource/src/com/newisys/parser/util/MacroRefUtil.java b/java/langsource/src/com/newisys/parser/util/MacroRefUtil.java new file mode 100644 index 0000000..493f53d --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/MacroRefUtil.java @@ -0,0 +1,98 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +/** + * Utility methods for handling macro references. + * + * @author Trevor Robinson + */ +public final class MacroRefUtil +{ + private MacroRefUtil() + { + } + + public static MacroRef getCommonMacroRef(MacroRef begin, MacroRef end) + { + MacroRef result; + if (begin == end) + { + result = begin; + } + else if (begin != null && end != null) + { + int beginDepth = getExpansionDepth(begin); + int endDepth = getExpansionDepth(end); + if (endDepth > beginDepth) + { + end = getExpansionAtDepth(end, endDepth - beginDepth); + } + else if (beginDepth > endDepth) + { + begin = getExpansionAtDepth(begin, beginDepth - endDepth); + } + while (begin != end && begin != null && end != null) + { + begin = begin.getExpandedFrom(); + end = end.getExpandedFrom(); + } + result = (begin == end) ? begin : null; + } + else + { + result = null; + } + return result; + } + + public static int getExpansionDepth(MacroRef ref) + { + return getExpansionDepth(ref, null); + } + + public static int getExpansionDepth(MacroRef from, MacroRef to) + { + int depth = 0; + while (from != to && from != null) + { + from = from.getExpandedFrom(); + ++depth; + } + return depth; + } + + public static MacroRef getExpansionAtDepth(MacroRef ref, int depth) + { + while (depth > 0) + { + if (ref != null) ref = ref.getExpandedFrom(); + --depth; + } + return ref; + } + + public static boolean expansionContains(MacroRef ref, MacroRef test) + { + while (ref != null) + { + if (ref == test) return true; + ref = ref.getExpandedFrom(); + } + return false; + } +} diff --git a/java/langsource/src/com/newisys/parser/util/ParseException.java b/java/langsource/src/com/newisys/parser/util/ParseException.java new file mode 100644 index 0000000..f6c4a7c --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/ParseException.java @@ -0,0 +1,221 @@ +/* + * Based on source code generated by JavaCC (TM). + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * See the supplied LICENSE-javacc.txt file for license information. + */ + +package com.newisys.parser.util; + +/** + * This exception is thrown when parse errors are encountered. + * You can explicitly create objects of this exception type by + * calling the method generateParseException in the generated + * parser. + * + * You can modify this class to customize your error reporting + * mechanisms so long as you retain the public fields. + */ +public class ParseException + extends Exception +{ + + /** + * This constructor is used by the method "generateParseException" + * in the generated parser. Calling this constructor generates + * a new object of this type with the fields "currentToken", + * "expectedTokenSequences", and "tokenImage" set. The boolean + * flag "specialConstructor" is also set to true to indicate that + * this constructor was used to create this object. + * This constructor calls its super class with the empty string + * to force the "toString" method of parent class "Throwable" to + * print the error message in the form: + * ParseException: + */ + public ParseException( + Token currentTokenVal, + int[][] expectedTokenSequencesVal, + String[] tokenImageVal) + { + super(""); + specialConstructor = true; + currentToken = currentTokenVal; + expectedTokenSequences = expectedTokenSequencesVal; + tokenImage = tokenImageVal; + } + + /** + * The following constructors are for use by you for whatever + * purpose you can think of. Constructing the exception in this + * manner makes the exception behave in the normal way - i.e., as + * documented in the class "Throwable". The fields "errorToken", + * "expectedTokenSequences", and "tokenImage" do not contain + * relevant information. The JavaCC generated code does not use + * these constructors. + */ + + public ParseException() + { + super(); + specialConstructor = false; + } + + public ParseException(String message) + { + super(message); + specialConstructor = false; + } + + /** + * This variable determines which constructor was used to create + * this object and thereby affects the semantics of the + * "getMessage" method (see below). + */ + protected boolean specialConstructor; + + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * following this token will (therefore) be the first error token. + */ + public Token currentToken; + + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + + /** + * This method has the standard behavior when this object has been + * created using the standard constructors. Otherwise, it uses + * "currentToken" and "expectedTokenSequences" to generate a parse + * error message and returns it. If this object has been created + * due to a parse error, and you do not catch it (it gets thrown + * from the parser), then this method is called during the printing + * of the final stack trace, and hence the correct error message + * gets displayed. + */ + public String getMessage() + { + if (!specialConstructor) + { + return super.getMessage(); + } + String expected = ""; + int maxSize = 0; + for (int i = 0; i < expectedTokenSequences.length; i++) + { + if (maxSize < expectedTokenSequences[i].length) + { + maxSize = expectedTokenSequences[i].length; + } + for (int j = 0; j < expectedTokenSequences[i].length; j++) + { + expected += tokenImage[expectedTokenSequences[i][j]] + " "; + } + if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) + { + expected += "..."; + } + expected += eol + " "; + } + String retval = "Encountered \""; + Token tok = currentToken.next; + for (int i = 0; i < maxSize; i++) + { + if (i != 0) retval += " "; + if (tok.kind == 0) + { + retval += tokenImage[0]; + break; + } + retval += add_escapes(tok.image); + tok = tok.next; + } + retval += "\" at line " + currentToken.next.beginLine + ", column " + + currentToken.next.beginColumn; + retval += "." + eol; + if (expectedTokenSequences.length == 1) + { + retval += "Was expecting:" + eol + " "; + } + else + { + retval += "Was expecting one of:" + eol + " "; + } + retval += expected; + return retval; + } + + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + + /** + * Used to convert raw characters to their escaped version + * when these raw version cannot be used as part of an ASCII + * string literal. + */ + protected String add_escapes(String str) + { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) + { + switch (str.charAt(i)) + { + case 0: + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) + { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + + s.substring(s.length() - 4, s.length())); + } + else + { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + +} diff --git a/java/langsource/src/com/newisys/parser/util/PreprocessedToken.java b/java/langsource/src/com/newisys/parser/util/PreprocessedToken.java new file mode 100644 index 0000000..a71f272 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/PreprocessedToken.java @@ -0,0 +1,69 @@ +/* + * LangSource - Generic Programming Language Source Modeling Tools + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.util; + +/** + * Represents a parser token that was the result of preprocessing. + * It includes information about the #include and macro expansion chains. + * + * @author Trevor Robinson + */ +public class PreprocessedToken + extends Token + implements Cloneable +{ + /** + * The name of the file this token is from. + */ + public String filename; + + /** + * Location this file was #included from, or null if not included. + */ + public IncludeLocation includedFrom; + + /** + * Macro this token was expanded from, or null if not from a macro. + */ + public MacroRef expandedFrom; + + public Object clone() + { + try + { + return super.clone(); + } + catch (CloneNotSupportedException e) + { + // should never happen + throw new Error(e); + } + } + + public void assignFrom(PreprocessedToken other) + { + kind = other.kind; + beginLine = other.beginLine; + beginColumn = other.beginColumn; + endLine = other.endLine; + endColumn = other.endColumn; + image = other.image; + filename = other.filename; + includedFrom = other.includedFrom; + expandedFrom = other.expandedFrom; + } +} diff --git a/java/langsource/src/com/newisys/parser/util/Token.java b/java/langsource/src/com/newisys/parser/util/Token.java new file mode 100644 index 0000000..fb611d1 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/Token.java @@ -0,0 +1,90 @@ +/* + * Based on source code generated by JavaCC (TM). + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * See the supplied LICENSE-javacc.txt file for license information. + */ + +package com.newisys.parser.util; + +/** + * Describes the input token stream. + */ + +public class Token +{ + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** + * beginLine and beginColumn describe the position of the first character + * of this token; endLine and endColumn describe the position of the + * last character of this token. + */ + public int beginLine, beginColumn, endLine, endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * Returns the image. + */ + public String toString() + { + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simlpy add something like : + * + * case MyParserConstants.ID : return new IDToken(); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use it in your lexical actions. + */ + public static final Token newToken(int ofKind) + { + switch (ofKind) + { + default: + return new PreprocessedToken(); + } + } + +} diff --git a/java/langsource/src/com/newisys/parser/util/TokenManager.java b/java/langsource/src/com/newisys/parser/util/TokenManager.java new file mode 100644 index 0000000..4150fb0 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/TokenManager.java @@ -0,0 +1,25 @@ +/* + * Based on source code generated by JavaCC (TM). + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * See the supplied LICENSE-javacc.txt file for license information. + */ + +package com.newisys.parser.util; + +/** + * An implementation for this interface is generated by + * JavaCCParser. The user is free to use any implementation + * of their choice. + */ + +public interface TokenManager +{ + + /** This gets the next token from the input stream. + * A token of kind 0 () should be returned on EOF. + */ + public Token getNextToken(); + +} diff --git a/java/langsource/src/com/newisys/parser/util/TokenMgrError.java b/java/langsource/src/com/newisys/parser/util/TokenMgrError.java new file mode 100644 index 0000000..f975da2 --- /dev/null +++ b/java/langsource/src/com/newisys/parser/util/TokenMgrError.java @@ -0,0 +1,170 @@ +/* + * Based on source code generated by JavaCC (TM). + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * See the supplied LICENSE-javacc.txt file for license information. + */ + +package com.newisys.parser.util; + +public class TokenMgrError + extends Error +{ + /* + * Ordinals for various reasons why an Error of this type can be thrown. + */ + + /** + * Lexical error occured. + */ + public static final int LEXICAL_ERROR = 0; + + /** + * An attempt wass made to create a second instance of a static token manager. + */ + public static final int STATIC_LEXER_ERROR = 1; + + /** + * Tried to change to an invalid lexical state. + */ + public static final int INVALID_LEXICAL_STATE = 2; + + /** + * Detected (and bailed out of) an infinite loop in the token manager. + */ + public static final int LOOP_DETECTED = 3; + + /** + * Indicates the reason why the exception is thrown. It will have + * one of the above 4 values. + */ + int errorCode; + + /** + * Replaces unprintable characters by their espaced (or unicode escaped) + * equivalents in the given string + */ + protected static final String addEscapes(String str) + { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) + { + switch (str.charAt(i)) + { + case 0: + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) + { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + + s.substring(s.length() - 4, s.length())); + } + else + { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + + /** + * Returns a detailed message for the Error when it is thrown by the + * token manager to indicate a lexical error. + * Parameters : + * EOFSeen : indicates if EOF caused the lexicl error + * curLexState : lexical state in which this error occured + * errorLine : line number when the error occured + * errorColumn : column number when the error occured + * errorAfter : prefix that was seen before this error occured + * curchar : the offending character + * Note: You can customize the lexical error message by modifying this method. + */ + protected static String LexicalError( + boolean EOFSeen, + int lexState, + int errorLine, + int errorColumn, + String errorAfter, + char curChar) + { + return ("Lexical error at line " + + errorLine + + ", column " + + errorColumn + + ". Encountered: " + + (EOFSeen ? " " + : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + + (int) curChar + "), ") + "after : \"" + + addEscapes(errorAfter) + "\""); + } + + /** + * You can also modify the body of this method to customize your error messages. + * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not + * of end-users concern, so you can return something like : + * + * "Internal Error : Please file a bug report .... " + * + * from this method for such cases in the release version of your parser. + */ + public String getMessage() + { + return super.getMessage(); + } + + /* + * Constructors of various flavors follow. + */ + + public TokenMgrError() + { + } + + public TokenMgrError(String message, int reason) + { + super(message); + errorCode = reason; + } + + public TokenMgrError( + boolean EOFSeen, + int lexState, + int errorLine, + int errorColumn, + String errorAfter, + char curChar, + int reason) + { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, + errorAfter, curChar), reason); + } +} diff --git a/java/make-parser/build.xml b/java/make-parser/build.xml new file mode 100644 index 0000000..7663ffa --- /dev/null +++ b/java/make-parser/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/make-parser/manifest.mf b/java/make-parser/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/make-parser/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/make-parser/src/com/newisys/parser/make/AbstractTokenizer.java b/java/make-parser/src/com/newisys/parser/make/AbstractTokenizer.java new file mode 100644 index 0000000..dfd36bf --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/AbstractTokenizer.java @@ -0,0 +1,104 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.LinkedList; +import java.util.List; + +/** + * Base implementation of a character sequence tokenizer. + * + * @author Trevor Robinson + */ +abstract class AbstractTokenizer +{ + protected final CharSequence line; + protected int lineEnd; + protected int tokenStart; + protected int tokenEnd; + + public AbstractTokenizer(CharSequence line) + { + this(line, 0, line.length()); + } + + public AbstractTokenizer(CharSequence line, int lineStart, int lineEnd) + { + this.line = line; + this.lineEnd = lineEnd; + this.tokenEnd = lineStart; + } + + public boolean hasNextToken() + { + return tokenStart < lineEnd; + } + + public int getLineEnd() + { + return lineEnd; + } + + public int getNextTokenStart() + { + return tokenStart; + } + + public String nextToken() + { + if (hasNextToken()) + { + String token = line.subSequence(tokenStart, tokenEnd).toString(); + findNextToken(); + return token; + } + else + { + return ""; + } + } + + public String restOfLine() + { + String token = line.subSequence(tokenStart, lineEnd).toString(); + tokenStart = lineEnd; + return token; + } + + public String restOfLineTrimmed() + { + int tokenEnd = lineEnd; + while (tokenEnd > tokenStart + && MakeUtil.isBlank(line.charAt(tokenEnd - 1))) + --tokenEnd; + String token = line.subSequence(tokenStart, tokenEnd).toString(); + tokenStart = lineEnd; + return token; + } + + protected abstract void findNextToken(); + + public List extractTokens() + { + List tokenList = new LinkedList(); + while (hasNextToken()) + { + tokenList.add(nextToken()); + } + return tokenList; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/BlankTokenizer.java b/java/make-parser/src/com/newisys/parser/make/BlankTokenizer.java new file mode 100644 index 0000000..661983e --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/BlankTokenizer.java @@ -0,0 +1,53 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Character sequence tokenizer that uses blanks as delimiters. + * + * @author Trevor Robinson + */ +final class BlankTokenizer + extends AbstractTokenizer +{ + public BlankTokenizer(CharSequence line) + { + super(line); + findNextToken(); + } + + public BlankTokenizer(CharSequence line, int lineStart, int lineEnd) + { + super(line, lineStart, lineEnd); + findNextToken(); + } + + protected void findNextToken() + { + tokenStart = tokenEnd; + while (tokenStart < lineEnd + && MakeUtil.isBlank(line.charAt(tokenStart))) + ++tokenStart; + if (tokenStart < lineEnd) + { + tokenEnd = tokenStart + 1; + while (tokenEnd < lineEnd + && !MakeUtil.isBlank(line.charAt(tokenEnd))) + ++tokenEnd; + } + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/FileGlobber.java b/java/make-parser/src/com/newisys/parser/make/FileGlobber.java new file mode 100644 index 0000000..31877b2 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/FileGlobber.java @@ -0,0 +1,167 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.io.File; +import java.io.FilenameFilter; + +/** + * Utility method for expanding makefile file globs into actual paths. + * + * @author Trevor Robinson + */ +final class FileGlobber +{ + private FileGlobber() + { + } + + public static String[] glob(String path) + { + final File file = new File(path); + + // split path into directory and filename glob + final String dir = file.getParent(); + final String glob = file.getName(); + + // determine whether glob contains wildcards + final int globLen = glob.length(); + boolean wild = false; + for (int i = 0; i < globLen; ++i) + { + if (isGlobChar(glob.charAt(i))) + { + wild = true; + break; + } + } + + if (!wild) + { + // no wildcards; simply check if path describes an existing file + return file.exists() ? new String[] { path } : new String[0]; + } + else + { + // search directory for files matching glob + File parent = file.getParentFile(); + if (parent == null) + { + String cwd = System.getProperty("user.dir"); + parent = new File(cwd); + } + File[] files = parent.listFiles(new FilenameFilter() + { + public boolean accept(File dir, String name) + { + return matchesGlob(name, glob); + } + }); + + // convert File[] into String[] + int count = (files != null) ? files.length : 0; + String[] paths = new String[count]; + for (int i = 0; i < count; ++i) + { + String name = files[i].getName(); + paths[i] = dir != null ? dir + File.separatorChar + name : name; + } + return paths; + } + } + + // default access for efficient access by inner class + static boolean matchesGlob(String name, String glob) + { + return matchesGlob(name, 0, glob, 0); + } + + private static boolean matchesGlob( + String name, + int namePos, + String glob, + int globPos) + { + int nameLen = name.length(); + int globLen = glob.length(); + while (namePos < nameLen || globPos < globLen) + { + int staticPos = globPos; + globPos = nextGlob(glob, globPos); + if (globPos > staticPos) + { + int staticLen = globPos - staticPos; + if (!name.regionMatches(namePos, glob, staticPos, staticLen)) + return false; + namePos += staticLen; + } + if (globPos == globLen) break; + + switch (glob.charAt(globPos++)) + { + case '*': + while (globPos < globLen) + { + char globChar = glob.charAt(globPos); + if (globChar == '?') + { + if (++namePos == nameLen) return false; + } + else if (globChar != '*') + { + break; + } + ++globPos; + } + while (namePos < nameLen) + { + if (matchesGlob(name, namePos, glob, globPos)) return true; + ++namePos; + } + return false; + case '?': + if (namePos == nameLen) return false; + ++namePos; + break; + case '[': + if (namePos == nameLen) return false; + int charsPos = globPos; + while (globPos < globLen && glob.charAt(globPos) != ']') + ++globPos; + if (globPos == globLen) return false; + String chars = glob.substring(charsPos, globPos++); + if (chars.indexOf(name.charAt(namePos)) < 0) return false; + ++namePos; + break; + } + } + return namePos == nameLen && globPos == globLen; + } + + private static int nextGlob(String glob, int pos) + { + int len = glob.length(); + while (pos < len && !isGlobChar(glob.charAt(pos))) + ++pos; + return pos; + } + + private static boolean isGlobChar(char c) + { + return c == '*' || c == '?' || c == '['; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeDatabase.java b/java/make-parser/src/com/newisys/parser/make/MakeDatabase.java new file mode 100644 index 0000000..7719d32 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeDatabase.java @@ -0,0 +1,552 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.*; + +import com.newisys.util.system.SystemUtil; + +/** + * Represents all the variables and rules in a makefile. + * + * @author Trevor Robinson + */ +public final class MakeDatabase +{ + private final MakeVariableScope globalScope = new MakeVariableScope(); + private MakeVariableScope currentScope = globalScope; + private final Stack scopeStack = new Stack(); + private boolean exportAll; + private final List vpaths = new LinkedList(); + private final Map files = new LinkedHashMap(); + private final List staticRules = new LinkedList(); + private final List patternRules = new LinkedList(); + + public MakeDatabase() + { + defineAutoVariables(); + } + + private void defineAutoVariables() + { + defineVariable("MAKEFILES", MakeVariableOrigin.DEFAULT, false, ""); + + String[] shellArgs = SystemUtil.getShellArgs(""); + defineVariable("SHELL", MakeVariableOrigin.DEFAULT, false, shellArgs[0]); + + defineAutoVariable("@D", "$(patsubst %/,%,$(dir $@))"); + defineAutoVariable("%D", "$(patsubst %/,%,$(dir $%))"); + defineAutoVariable("*D", "$(patsubst %/,%,$(dir $*))"); + defineAutoVariable("= 0) + { + dir = target.substring(0, slashPos + 1); + name = target.substring(slashPos + 1); + } + else + { + dir = null; + name = target; + } + + // make a list of matching rules + Map matchingRules = new LinkedHashMap(); + Map ntmaRules = new LinkedHashMap(); + boolean gotNotMatchAny = false; + Iterator ruleIter = patternRules.iterator(); + while (ruleIter.hasNext()) + { + MakePatternRule rule = (MakePatternRule) ruleIter.next(); + boolean hasCommands = rule.getCommand() != null; + Iterator patIter = rule.getTargetPatterns().iterator(); + while (patIter.hasNext()) + { + MakePattern pat = (MakePattern) patIter.next(); + boolean hasSlash = pat.toString().indexOf('/') >= 0; + if (pat.matchesAny()) + { + if (hasCommands) + { + if (!rule.isDoubleColon()) + { + ntmaRules.put(rule, pat); + } + else + { + matchingRules.put(rule, pat); + } + } + } + else if (pat.matches(hasSlash ? target : name)) + { + gotNotMatchAny = true; + if (hasCommands) + { + matchingRules.put(rule, pat); + } + break; + } + } + } + if (!gotNotMatchAny) + { + matchingRules.putAll(ntmaRules); + } + + // find rule with prerequisites that exist or ought to exist (passes 1 + // and 2) or can be made by an implicit rule (pass 2 only) + for (int pass = 1; pass <= 2; ++pass) + { + ruleIter = matchingRules.entrySet().iterator(); + while (ruleIter.hasNext()) + { + Map.Entry entry = (Map.Entry) ruleIter.next(); + MakePatternRule rule = (MakePatternRule) entry.getKey(); + MakePattern matchingPat = (MakePattern) entry.getValue(); + boolean hasSlash = matchingPat.toString().indexOf('/') >= 0; + String stub = matchingPat.extractStub(hasSlash ? target : name); + + boolean depsOkay = true; + List staticDeps = new LinkedList(); + Iterator depIter = rule.getDependencyPatterns().iterator(); + while (depIter.hasNext()) + { + MakePattern depPat = (MakePattern) depIter.next(); + String depName = depPat.replaceStub(stub); + if (!hasSlash && dir != null) depName = dir + depName; + MakeFileInfo depFileInfo = getFile(depName); + if (depFileInfo == null) + { + depFileInfo = new MakeFileInfo(depName); + addFile(depFileInfo); + depFileInfo.setIntermediate(true); + } + if (depFileInfo.exists() || !depFileInfo.isIntermediate()) + { + staticDeps.add(depFileInfo); + continue; + } + else if (pass == 2 && !activeRules.contains(rule)) + { + MakeStaticRule depRule = depFileInfo.getRule(); + if (depRule == null) + { + activeRules.add(rule); + depRule = applyPatternRules(depName, null, + activeRules); + activeRules.remove(rule); + } + if (depRule != null) + { + staticDeps.add(depFileInfo); + continue; + } + } + depsOkay = false; + break; + } + + if (depsOkay) + { + MakeFileInfo targetFileInfo = getOrCreateFile(target); + MakeStaticRule staticRule; + if (baseRule != null) + { + staticRule = new MakeStaticRule(baseRule); + } + else + { + staticRule = new MakeStaticRule(targetFileInfo); + } + staticRule.addDependencies(staticDeps); + staticRule.setCommand(rule.getCommand()); + targetFileInfo.setRule(staticRule); + return staticRule; + } + } + } + + // no matching pattern rule found + return baseRule; + } + + /** + * Scans the database for special targets and applies their associated + * attributes to each of their dependencies. + */ + public void applySpecialTargets() + { + MakeStaticRule rule = getStaticRule(".PHONY"); + if (rule != null) + { + Iterator iter = rule.getDependencies().iterator(); + while (iter.hasNext()) + { + MakeFileInfo depFileInfo = (MakeFileInfo) iter.next(); + depFileInfo.setPhony(true); + } + } + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeFileInfo.java b/java/make-parser/src/com/newisys/parser/make/MakeFileInfo.java new file mode 100644 index 0000000..d7028e0 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeFileInfo.java @@ -0,0 +1,87 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.io.File; + +/** + * Used to track information about a particular filename referenced in a + * makefile. + * + * @author Trevor Robinson + */ +public final class MakeFileInfo +{ + private final String path; + private final File file; + private boolean exists; + private boolean phony; + private boolean intermediate; + private MakeStaticRule rule; + + public MakeFileInfo(String path) + { + this.path = path; + file = new File(path); + exists = file.exists(); + } + + public String getPath() + { + return path; + } + + public boolean exists() + { + return exists; + } + + public boolean isPhony() + { + return phony; + } + + public void setPhony(boolean phony) + { + this.phony = phony; + } + + public boolean isIntermediate() + { + return intermediate; + } + + public void setIntermediate(boolean intermediate) + { + this.intermediate = intermediate; + } + + public MakeStaticRule getRule() + { + return rule; + } + + public void setRule(MakeStaticRule rule) + { + this.rule = rule; + } + + public String toString() + { + return path; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeFunction.java b/java/make-parser/src/com/newisys/parser/make/MakeFunction.java new file mode 100644 index 0000000..174d05b --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeFunction.java @@ -0,0 +1,958 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.util.Arrays; + +import com.newisys.util.system.SystemUtil; + +/** + * Base class for built-in makefile functions. + * + * @author Trevor Robinson + */ +public abstract class MakeFunction +{ + private final boolean expandArgs; + private final int maximumArgs; + private final int minimumArgs; + private final String name; + + public MakeFunction( + String name, + int minimumArgs, + int maximumArgs, + boolean expandArgs) + { + this.name = name; + this.minimumArgs = minimumArgs; + this.maximumArgs = maximumArgs; + this.expandArgs = expandArgs; + } + + public String getName() + { + return name; + } + + public int getMinimumArgs() + { + return minimumArgs; + } + + public int getMaximumArgs() + { + return maximumArgs; + } + + public boolean isExpandArgs() + { + return expandArgs; + } + + protected void checkArgCount(String[] args) + throws MakeParseException + { + if (args.length < minimumArgs) + { + throw new MakeParseException("Not enough arguments to function '" + + name + "'; " + minimumArgs + " expected"); + } + } + + public abstract String expand(MakeParser parser, String[] args) + throws MakeParseException; + + public static class Addprefix + extends MakeFunction + { + public Addprefix() + { + super("addprefix", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public static String expand(final String prefix, String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + return prefix + s; + } + }); + } + } + + public static class Addsuffix + extends MakeFunction + { + public Addsuffix() + { + super("addsuffix", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public static String expand(final String suffix, String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + return s + suffix; + } + }); + } + } + + public static class Basename + extends MakeFunction + { + public Basename() + { + super("basename", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + int periodPos = s.lastIndexOf('.'); + return (periodPos >= 0) ? s.substring(0, periodPos) : s; + } + }); + } + } + + public static class Call + extends MakeFunction + { + public Call() + { + super("call", 1, -1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + String funcName = args[0].trim(); + + // check for built-in function + MakeFunction func = MakeParser.getFunction(funcName); + if (func != null) + { + String[] funcArgs = new String[args.length - 1]; + System.arraycopy(args, 1, funcArgs, 0, args.length - 1); + return func.expand(parser, funcArgs); + } + + MakeDatabase database = parser.getDatabase(); + database.pushNewVariableScope(); + try + { + // create variables for arguments + for (int i = 0; i < args.length; ++i) + { + MakeVariable var = new MakeVariable(String.valueOf(i), + MakeVariableOrigin.AUTOMATIC, false); + var.setValue(args[i]); + database.addVariable(var); + } + + // expand function + return parser.expandVariable(funcName); + } + finally + { + database.popVariableScope(); + } + } + } + + public static class Dir + extends MakeFunction + { + public Dir() + { + super("dir", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + int slashPos = MakeUtil.indexOfLastSlash(s); + return (slashPos >= 0) ? s.substring(0, slashPos + 1) + : "./"; + } + }); + } + } + + public static class Error + extends MakeFunction + { + public Error() + { + super("error", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + parser.error(args[0]); + return ""; + } + } + + public static class Eval + extends MakeFunction + { + public Eval() + { + super("eval", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + MakeParser evalParser = new MakeParser(parser.getDatabase(), + new StringReader(args[0]), "eval"); + try + { + evalParser.parse(); + } + catch (IOException e) + { + throw new MakeParseException("I/O error processing 'eval'", e); + } + return ""; + } + } + + public static class Filter + extends MakeFunction + { + public Filter() + { + super("filter", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public static String expand(String patternsText, String text) + throws MakeParseException + { + return filter(text, patternsText, false); + } + } + + public static class FilterOut + extends MakeFunction + { + public FilterOut() + { + super("filter-out", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public static String expand(String patternsText, String text) + throws MakeParseException + { + return filter(text, patternsText, true); + } + } + + public static class Findstring + extends MakeFunction + { + public Findstring() + { + super("findstring", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public static String expand(String pattern, String text) + { + return text.indexOf(pattern) >= 0 ? pattern : ""; + } + } + + public static class Firstword + extends MakeFunction + { + public Firstword() + { + super("firstword", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return Wordlist.expand(0, 0, args[0]); + } + } + + public static class Foreach + extends MakeFunction + { + public Foreach() + { + super("foreach", 3, 3, false); + } + + public String expand(final MakeParser parser, final String[] args) + throws MakeParseException + { + checkArgCount(args); + final String varName = parser.expandVariables(args[0]); + return filter(parser.expandVariables(args[1]), new WordCallback() + { + public String expand(String s) + throws MakeParseException + { + MakeDatabase database = parser.getDatabase(); + database.pushNewVariableScope(); + try + { + MakeVariable var = new MakeVariable(varName, + MakeVariableOrigin.AUTOMATIC, false); + var.setValue(s); + database.addVariable(var); + + return parser.expandVariables(args[2]); + } + finally + { + database.popVariableScope(); + } + } + }); + } + } + + public static class If + extends MakeFunction + { + public If() + { + super("if", 2, 3, false); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + boolean cond = parser.expandVariables(args[0].trim()).length() > 0; + String text = cond ? args[1] : (args.length > 2 ? args[2] : null); + return (text != null) ? parser.expandVariables(text) : ""; + } + } + + public static class Join + extends MakeFunction + { + public Join() + { + super("join", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1]); + } + + public String expand(String list1, String list2) + { + String[] words1 = split(list1); + String[] words2 = split(list2); + int count = Math.max(words1.length, words2.length); + StringBuffer result = new StringBuffer(list1.length() + + list2.length()); + for (int i = 0; i < count; ++i) + { + String word1 = (i < words1.length) ? words1[i] : ""; + String word2 = (i < words2.length) ? words2[i] : ""; + if (i > 0) result.append(' '); + result.append(word1 + word2); + } + return result.toString(); + } + } + + public static class Notdir + extends MakeFunction + { + public Notdir() + { + super("notdir", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + int slashPos = MakeUtil.indexOfLastSlash(s); + return (slashPos >= 0) ? s.substring(slashPos + 1) : s; + } + }); + } + } + + public static class Origin + extends MakeFunction + { + public Origin() + { + super("origin", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + String varName = args[0]; + MakeVariable var = parser.getDatabase().getVariable(varName); + return (var != null) ? var.getOrigin().toString() : "undefined"; + } + } + + public static class Patsubst + extends MakeFunction + { + public Patsubst() + { + super("patsubst", 3, 3, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1], args[2]); + } + + public static String expand(String pattern, String replace, String text) + { + return expand(MakePattern.parse(pattern), MakePattern + .parse(replace), text); + } + + public static String expand( + MakePattern pattern, + MakePattern replace, + String text) + { + String[] words = split(text); + StringBuffer result = new StringBuffer(); + for (int i = 0; i < words.length; ++i) + { + if (pattern.matches(words[i])) + { + if (result.length() > 0) result.append(' '); + String stub = pattern.extractStub(words[i]); + result.append(replace.replaceStub(stub)); + } + } + return result.toString(); + } + } + + public static class Shell + extends MakeFunction + { + public Shell() + { + super("shell", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + String value; + try + { + Process process = SystemUtil.execShell(args[0]); + StringBuffer buffer = new StringBuffer(1024); + InputStreamReader isr = new InputStreamReader(process + .getInputStream()); + BufferedReader br = new BufferedReader(isr); + while (true) + { + String line = br.readLine(); + if (line == null) break; + if (buffer.length() > 0) buffer.append(' '); + buffer.append(line); + } + value = buffer.toString(); + } + catch (Exception e) + { + parser.warning(e.getMessage()); + value = ""; + } + return value; + } + } + + public static class Sort + extends MakeFunction + { + public Sort() + { + super("sort", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + { + String[] words = split(text); + Arrays.sort(words); + return join(words); + } + } + + public static class Strip + extends MakeFunction + { + public Strip() + { + super("strip", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + { + int len = text.length(); + StringBuffer result = new StringBuffer(len); + boolean gotBlank = false; + boolean gotNonBlank = false; + int pos = 0; + while (pos < len) + { + char c = text.charAt(pos); + if (MakeUtil.isBlank(c)) + { + gotBlank = gotNonBlank; + } + else + { + if (gotBlank) + { + result.append(' '); + gotBlank = false; + } + result.append(c); + gotNonBlank = true; + } + } + return result.toString(); + } + } + + public static class Subst + extends MakeFunction + { + public Subst() + { + super("subst", 3, 3, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0], args[1], args[2]); + } + + public static String expand(String pattern, String replace, String text) + { + int len = text.length(); + int patLen = pattern.length(); + StringBuffer result = new StringBuffer(len); + int start = 0; + while (start < len) + { + // look for next instance of pattern + int pos = text.indexOf(pattern, start); + if (pos < 0) + { + // pattern not found; copy rest of text to result and exit + result.append(text.substring(start)); + break; + } + else if (pos > start) + { + // pattern found; copy preceding text to result + result.append(text.substring(start, pos)); + } + + // copy replacement to result + result.append(replace); + + // advance search position past pattern + start = pos + patLen; + } + return result.toString(); + } + } + + public static class Suffix + extends MakeFunction + { + public Suffix() + { + super("suffix", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + int periodPos = s.lastIndexOf('.'); + return (periodPos >= 0) ? s.substring(periodPos) : null; + } + }); + } + } + + public static class Value + extends MakeFunction + { + public Value() + { + super("value", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + String varName = args[0]; + MakeVariable var = parser.getDatabase().getVariable(varName); + return (var != null) ? var.getValue() : ""; + } + } + + public static class Warning + extends MakeFunction + { + public Warning() + { + super("warning", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + parser.warning(args[0]); + return ""; + } + } + + public static class Wildcard + extends MakeFunction + { + public Wildcard() + { + super("wildcard", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + throws MakeParseException + { + return filter(text, new WordCallback() + { + public String expand(String s) + { + return join(FileGlobber.glob(s)); + } + }); + } + } + + public static class Word + extends MakeFunction + { + public Word() + { + super("word", 2, 2, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + try + { + int index = Integer.parseInt(args[0]) - 1; + return Wordlist.expand(index, index, args[1]); + } + catch (NumberFormatException e) + { + throw new MakeParseException( + "Non-numeric argument 1 in 'word' function"); + } + } + } + + public static class Wordlist + extends MakeFunction + { + public Wordlist() + { + super("wordlist", 3, 3, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + int curArg = 1; + try + { + int start = Integer.parseInt(args[0]) - 1; + curArg = 2; + int end = Integer.parseInt(args[1]) - 1; + return expand(start, end, args[2]); + } + catch (NumberFormatException e) + { + throw new MakeParseException("Non-numeric argument " + curArg + + " in 'wordlist' function"); + } + } + + public static String expand(int start, int end, String text) + { + String[] words = split(text); + end = Math.min(end, words.length - 1); + return (start >= 0 && end >= start) ? join(words, start, end) : ""; + } + } + + public static class Words + extends MakeFunction + { + public Words() + { + super("words", 1, 1, true); + } + + public String expand(MakeParser parser, String[] args) + throws MakeParseException + { + checkArgCount(args); + return expand(args[0]); + } + + public static String expand(String text) + { + String[] words = split(text); + return String.valueOf(words.length); + } + } + + static String[] split(String s) + { + return s.split("\\s+"); + } + + static String join(String[] words) + { + return join(words, 0, words.length - 1); + } + + static String join(String[] words, int start, int end) + { + int len = 0; + for (int i = start; i <= end; ++i) + { + if (i > start) ++len; + len += words[i].length(); + } + + StringBuffer result = new StringBuffer(len); + for (int i = start; i <= end; ++i) + { + if (i > start) result.append(' '); + result.append(words[i]); + } + return result.toString(); + } + + private interface WordCallback + { + String expand(String s) + throws MakeParseException; + } + + static String filter(String text, WordCallback cb) + throws MakeParseException + { + String[] words = split(text); + StringBuffer result = new StringBuffer(text.length()); + for (int i = 0; i < words.length; ++i) + { + String word = cb.expand(words[i]); + if (word != null && word.length() > 0) + { + if (result.length() > 0) result.append(' '); + result.append(word); + } + } + return result.toString(); + } + + static String filter( + String text, + String patternsText, + final boolean filterOut) + throws MakeParseException + { + final MakePattern[] patterns = parsePatterns(patternsText); + return filter(text, new WordCallback() + { + public String expand(String s) + { + return matchesPatterns(s, patterns) != filterOut ? s : null; + } + }); + } + + private static MakePattern[] parsePatterns(String text) + { + String[] words = split(text); + MakePattern[] patterns = new MakePattern[words.length]; + for (int i = 0; i < words.length; ++i) + { + patterns[i] = MakePattern.parse(words[i]); + } + return patterns; + } + + static boolean matchesPatterns(String text, MakePattern[] patterns) + { + for (int i = 0; i < patterns.length; ++i) + { + if (patterns[i].matches(text)) return true; + } + return false; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeParseException.java b/java/make-parser/src/com/newisys/parser/make/MakeParseException.java new file mode 100644 index 0000000..ff2e547 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeParseException.java @@ -0,0 +1,94 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Exception thrown when a fatal error is encountered parsing a makefile. + * + * @author Trevor Robinson + */ +public class MakeParseException + extends Exception +{ + private String filename; + private int lineNumber = -1; + + public MakeParseException() + { + super(); + } + + public MakeParseException(String message) + { + super(message); + } + + public MakeParseException(Throwable cause) + { + super(cause); + } + + public MakeParseException(String message, Throwable cause) + { + super(message, cause); + } + + public String getFilename() + { + return filename; + } + + public void setFilename(String filename) + { + this.filename = filename; + } + + public int getLineNumber() + { + return lineNumber; + } + + public void setLineNumber(int lineNumber) + { + this.lineNumber = lineNumber; + } + + public String getMessage() + { + return formatMessage(filename, lineNumber, super.getMessage()); + } + + public static String formatMessage( + String filename, + int lineNumber, + String message) + { + StringBuffer result = new StringBuffer(); + if (filename != null) + { + result.append(filename); + result.append(':'); + } + if (lineNumber >= 0) + { + result.append(lineNumber); + result.append(':'); + } + result.append(message); + return result.toString(); + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeParser.java b/java/make-parser/src/com/newisys/parser/make/MakeParser.java new file mode 100644 index 0000000..2977d2e --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeParser.java @@ -0,0 +1,1515 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.Reader; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Parses the give makefile and updates the given makefile database with the + * definitions in it. + * + * @author Trevor Robinson + */ +public class MakeParser +{ + private final MakeDatabase database; + private final LineNumberReader reader; + private final String filename; + private int condDepth; + private int skipDepth; + + private static final Map functions = new LinkedHashMap(); + + public static MakeFunction getFunction(String name) + { + return (MakeFunction) functions.get(name); + } + + private static void addFunction(MakeFunction func) + { + functions.put(func.getName(), func); + } + + static + { + addFunction(new MakeFunction.Addprefix()); + addFunction(new MakeFunction.Addsuffix()); + addFunction(new MakeFunction.Basename()); + addFunction(new MakeFunction.Call()); + addFunction(new MakeFunction.Dir()); + addFunction(new MakeFunction.Error()); + addFunction(new MakeFunction.Eval()); + addFunction(new MakeFunction.Filter()); + addFunction(new MakeFunction.FilterOut()); + addFunction(new MakeFunction.Findstring()); + addFunction(new MakeFunction.Firstword()); + addFunction(new MakeFunction.Foreach()); + addFunction(new MakeFunction.If()); + addFunction(new MakeFunction.Join()); + addFunction(new MakeFunction.Notdir()); + addFunction(new MakeFunction.Origin()); + addFunction(new MakeFunction.Patsubst()); + addFunction(new MakeFunction.Shell()); + addFunction(new MakeFunction.Sort()); + addFunction(new MakeFunction.Strip()); + addFunction(new MakeFunction.Subst()); + addFunction(new MakeFunction.Suffix()); + addFunction(new MakeFunction.Value()); + addFunction(new MakeFunction.Warning()); + addFunction(new MakeFunction.Wildcard()); + addFunction(new MakeFunction.Word()); + addFunction(new MakeFunction.Wordlist()); + addFunction(new MakeFunction.Words()); + } + + public MakeParser(MakeDatabase database, String filename) + throws FileNotFoundException + { + this(database, new FileReader(filename), filename); + } + + public MakeParser(MakeDatabase database, Reader reader, String filename) + { + this.database = database; + this.reader = new LineNumberReader(reader); + this.reader.setLineNumber(1); + this.filename = filename; + } + + public MakeDatabase getDatabase() + { + return database; + } + + public String getFilename() + { + return filename; + } + + public void parse() + throws IOException, MakeParseException + { + Set activeRules = new HashSet(); + StringBuffer commandBuffer = null; + + while (true) + { + // read the next line, + // collapsing any backslash-newline continuations + int lineNo = reader.getLineNumber(); + String line = readLine(); + + // done if we hit EOF + if (line == null) break; + + // continue with next line if this one is empty + if (line.length() == 0) continue; + + try + { + // process commands (if expected) + if (line.charAt(0) == '\t' && commandBuffer != null) + { + if (skipDepth == 0) + { + BlankTokenizer bt = new BlankTokenizer(line); + if (bt.hasNextToken()) + { + String command = bt.restOfLine(); + if (commandBuffer.length() > 0) + commandBuffer.append('\n'); + commandBuffer.append(command); + } + } + continue; + } + + // ignore line after comments (for now; if line contains a rule + // with a semicolon, we'll need the whole line) + StringBuffer lineBuffer = new StringBuffer(line); + int commentStart = MakeUtil.unescapeIndexOf(lineBuffer, '#'); + if (commentStart >= 0) + { + lineBuffer.setLength(commentStart); + } + int lineBufferEnd = lineBuffer.length(); + + // get first token + BlankTokenizer bt = new BlankTokenizer(lineBuffer, 0, + lineBufferEnd); + if (!bt.hasNextToken()) + { + // line contains only spaces + continue; + } + String token1 = bt.nextToken(); + + boolean inverse = false; + if (token1.equals("ifdef") + || (token1.equals("ifndef") && (inverse = true))) + { + // get variable name + if (!bt.hasNextToken()) + { + throw new MakeParseException( + "Variable name expected after " + token1); + } + String varText = bt.nextToken(); + + // check for extraneous text + if (bt.hasNextToken()) + { + throw new MakeParseException("Extraneous text after " + + token1); + } + + // handle conditional + ++condDepth; + if (skipDepth > 0 || isDefined(varText) == inverse) + { + ++skipDepth; + } + + // done with line + continue; + } + else if (token1.equals("ifeq") + || (token1.equals("ifneq") && (inverse = true))) + { + // find opening delimiter + int ts = bt.getNextTokenStart(); + char openParen = (ts < lineBufferEnd) ? lineBuffer + .charAt(ts) : 0; + if (openParen != '(' && openParen != '\'' + && openParen != '"') + { + throw new MakeParseException( + "Delimiter expected after " + token1); + } + + // extract argument 1 + int argPos1 = ts + 1; + int argEndPos1; + if (openParen == '(') + { + // search for comma delimiter + argEndPos1 = MakeUtil.indexOfArgumentEnd(lineBuffer, + '(', ')', argPos1, lineBufferEnd); + if (argEndPos1 < lineBufferEnd) + { + // trim trailing blanks from argument 1 + while (MakeUtil.isBlank(lineBuffer + .charAt(argEndPos1 - 1))) + --argEndPos1; + } + else + { + // comma delimiter not found + argEndPos1 = -1; + } + } + else + { + // search for quote delimiter + argEndPos1 = MakeUtil.indexOfChar(lineBuffer, + openParen, argPos1); + } + if (argEndPos1 < 0) + { + throw new MakeParseException( + "Delimiter not found after " + token1 + + " argument 1"); + } + String arg1 = lineBuffer.substring(argPos1, argEndPos1); + + // extract argument 2 + int argPos2 = argEndPos1 + 1; + while (argPos2 < lineBufferEnd + && MakeUtil.isBlank(lineBuffer.charAt(argPos2))) + ++argPos2; + int argEndPos2; + if (openParen == '(') + { + // search for closing parenthesis delimiter + int parenCount = 0; + for (argEndPos2 = argPos2; argEndPos2 < lineBufferEnd; ++argEndPos2) + { + char c = lineBuffer.charAt(argEndPos2); + if (c == '(') + { + ++parenCount; + } + else if (c == ')' && --parenCount < 0) + { + break; + } + } + if (argEndPos2 == lineBufferEnd) + { + // closing parenthesis delimiter not found + argEndPos1 = -1; + } + } + else + { + // find opening delimiter + openParen = (argPos2 < lineBufferEnd) ? lineBuffer + .charAt(argPos2) : 0; + if (openParen != '\'' && openParen != '"') + { + throw new MakeParseException( + "Delimiter not found before " + token1 + + " argument 2"); + } + ++argPos2; + + // search for quote delimiter + argEndPos2 = MakeUtil.indexOfChar(lineBuffer, + openParen, argPos2); + } + if (argEndPos2 < 0) + { + throw new MakeParseException( + "Delimiter not found after " + token1 + + " argument 2"); + } + String arg2 = lineBuffer.substring(argPos2, argEndPos2); + + // check for extraneous text + do + { + ++argEndPos2; + } + while (argEndPos2 < lineBufferEnd + && MakeUtil.isBlank(lineBuffer.charAt(argEndPos2))); + if (argEndPos2 < lineBufferEnd) + { + throw new MakeParseException("Extraneous text after " + + token1); + } + + // handle conditional + ++condDepth; + if (skipDepth > 0 || isEqual(arg1, arg2) == inverse) + { + ++skipDepth; + } + + // done with line + continue; + } + else if (token1.equals("else")) + { + // check for extraneous text + if (bt.hasNextToken()) + { + throw new MakeParseException("Extraneous text after " + + token1); + } + + // handle conditional + if (condDepth == 0) + { + throw new MakeParseException("else without if"); + } + if (skipDepth <= 1) + { + skipDepth ^= 1; + } + + // done with line + continue; + } + else if (token1.equals("endif")) + { + // check for extraneous text + if (bt.hasNextToken()) + { + throw new MakeParseException("Extraneous text after " + + token1); + } + + // handle conditional + if (condDepth == 0) + { + throw new MakeParseException("endif without if"); + } + --condDepth; + if (skipDepth > 0) + { + --skipDepth; + } + + // done with line + continue; + } + else if (token1.equals("define")) + { + processDefine(bt, MakeVariableOrigin.FILE); + + // done with line + continue; + } + else if (token1.equals("endef")) + { + // valid endefs are handled by processDefine() + throw new MakeParseException("Extraneous endef"); + } + else if (token1.equals("override")) + { + // get next token + if (!bt.hasNextToken()) + { + throw new MakeParseException("Empty override"); + } + int ts2 = bt.getNextTokenStart(); + String token2 = bt.nextToken(); + + // handle define or assignment + if (token2.equals("define")) + { + processDefine(bt, MakeVariableOrigin.OVERRIDE); + } + else + { + MakeVariable var = processAssignment(lineBuffer, ts2, + lineBufferEnd, MakeVariableOrigin.OVERRIDE); + if (var == null) + { + throw new MakeParseException( + "Invalid override syntax"); + } + } + + // done with line + continue; + } + + // only conditionals and defines are processed inside skipped + // conditional blocks + if (skipDepth > 0) + { + continue; + } + + boolean gotDirective = true; + if (token1.equals("export")) + { + if (!bt.hasNextToken()) + { + // no more tokens; export all variables + database.setExportAll(true); + } + else + { + // look for exported assignment + MakeVariable var = processAssignment(lineBuffer, bt + .getNextTokenStart(), lineBufferEnd, + MakeVariableOrigin.FILE); + if (var != null) + { + var.setExported(true); + } + else + { + // tokens represent a list of variables to export + String varText = bt.restOfLine(); + processExportList(varText, true); + } + } + } + else if (token1.equals("unexport")) + { + // look for a token + if (!bt.hasNextToken()) + { + // no more tokens; unexport all variables + database.setExportAll(false); + } + else + { + // tokens represent a list of variables to unexport + String varText = bt.restOfLine(); + processExportList(varText, false); + } + } + else if (token1.equals("vpath")) + { + String argStr = expandVariables(bt.restOfLine()); + StringBuffer buffer = new StringBuffer(argStr); + PathTokenizer pt = new PathTokenizer(buffer); + if (pt.hasNextToken()) + { + String patternStr = pt.nextToken(); + if (pt.hasNextToken()) + { + // 'vpath ' means associate given + // search paths with given pattern + MakePattern pattern = MakePattern.parse(patternStr); + do + { + String path = pt.nextToken(); + database.addVPath(pattern, path); + } + while (pt.hasNextToken()); + } + else + { + // 'vpath ' (no paths) means remove vpaths + // with the given pattern + database.removeVPaths(patternStr); + } + } + else + { + // 'vpath' (no arguments) means remove all vpaths + database.removeAllVPaths(); + } + } + else if (token1.equals("include") || token1.equals("-include") + || token1.equals("sinclude")) + { + boolean ignoreNotFound = token1.charAt(0) != 'i'; + + // get filename string + String filenames = expandVariables(bt.restOfLine()); + if (filenames.length() == 0) + { + throw new MakeParseException("Filename expected after " + + token1); + } + + // build list of globbed filenames + StringBuffer buffer = new StringBuffer(filenames); + PathTokenizer pt = new PathTokenizer(buffer); + List fileList = globPaths(pt.extractTokens()); + + // process included files + Iterator fileIter = fileList.iterator(); + while (fileIter.hasNext()) + { + String includeFile = (String) fileIter.next(); + try + { + MakeParser parser = new MakeParser(database, + includeFile); + parser.parse(); + } + catch (FileNotFoundException e1) + { + if (!ignoreNotFound) + { + throw new MakeParseException( + "Included file not found: " + includeFile); + } + } + } + } + else + { + // check whether line is an assignment + MakeVariable var = processAssignment(lineBuffer, 0, + lineBufferEnd, MakeVariableOrigin.FILE); + gotDirective = (var != null); + } + + // complete last rule, if any + if (commandBuffer != null) + { + if (commandBuffer.length() > 0) + { + applyCommand(activeRules, commandBuffer.toString()); + } + commandBuffer = null; + } + + if (!gotDirective) + { + if (line.charAt(0) == '\t') + { + // line started with a tab, but we have not seen a rule + // and the line was not a directive + throw new MakeParseException("Commands without rule"); + } + + // line must be a rule + commandBuffer = new StringBuffer(); + activeRules.clear(); + processRule(line, activeRules, commandBuffer); + } + } + catch (MakeParseException e) + { + if (e.getFilename() == null) + { + e.setFilename(filename); + e.setLineNumber(lineNo); + } + throw e; + } + } + + if (commandBuffer != null && commandBuffer.length() > 0) + { + applyCommand(activeRules, commandBuffer.toString()); + } + + if (condDepth > 0) + { + throw new MakeParseException("Missing endif"); + } + } + + private void applyCommand(Collection activeRules, String command) + { + Iterator iter = activeRules.iterator(); + while (iter.hasNext()) + { + MakeRule rule = (MakeRule) iter.next(); + if (rule.getCommand() != null) + { + warning("Overriding commands for target '" + + rule.getTargetNames() + "'"); + } + rule.setCommand(command); + } + } + + private boolean isDefined(String varText) + throws MakeParseException + { + String varName = expandVariables(varText); + MakeVariable var = database.getVariable(varName); + return var != null; + } + + private boolean isEqual(String arg1, String arg2) + throws MakeParseException + { + String exp1 = expandVariables(arg1); + String exp2 = expandVariables(arg2); + return exp1.equals(exp2); + } + + private MakeVariable processAssignment( + StringBuffer line, + int start, + int end, + MakeVariableOrigin origin) + throws MakeParseException + { + int len = line.length(); + + // look for assignment operator + boolean found = false; + boolean cond = false; + boolean append = false; + boolean recursive = true; + int namePos = -1; + int nameEndPos = -1; + int pos = start; + while (pos < len) + { + char c1 = line.charAt(pos++); + char c2 = (pos < len) ? line.charAt(pos) : 0; + if (c1 == '=') + { + // recursive assignment + found = true; + break; + } + else if (c1 == ':') + { + if (c2 == '=') + { + // simple assignment + found = true; + recursive = false; + ++pos; + break; + } + else + { + // ':' without '=' indicates a rule + return null; + } + } + else if (c1 == '+' && c2 == '=') + { + // append assignment + found = true; + append = true; + ++pos; + break; + } + else if (c1 == '?' && c2 == '=') + { + // conditional assignment + found = true; + cond = true; + ++pos; + break; + } + else if (c1 == '$' && (c2 == '(' || c2 == '{')) + { + // variable reference; advance past matching parenthesis + char closeParen = (c2 == '(') ? ')' : '}'; + int matchPos = MakeUtil.indexOfMatchingDelimiter(line, c2, + closeParen, pos + 1, end); + pos = (matchPos < 0) ? len : matchPos + 1; + } + else if (!MakeUtil.isBlank(c1)) + { + // remember first non-blank as start of variable name + if (namePos < 0) + { + namePos = pos - 1; + } + // remember last non-blank as end of variable name + nameEndPos = pos; + } + } + if (!found || namePos < 0) + { + // reached end of line without finding assignment operator + // or found assignment operator without variable name + return null; + } + + // extract and expand variable name + String varText = line.substring(namePos, nameEndPos); + String varName = expandVariables(varText); + if (varName.length() == 0) + { + throw new MakeParseException("Empty variable name"); + } + + // look up existing variable with same name + MakeVariable existingVar = database.getVariable(varName); + if (append && existingVar != null) + { + // '+=' is immediate if existing variable is non-recursive + recursive = existingVar.isRecursive(); + } + + // extract variable value + while (pos < len && MakeUtil.isBlank(line.charAt(pos))) + ++pos; + String value = line.substring(pos); + + // expand variable value for simple variables + if (!recursive && skipDepth == 0) + { + value = expandVariables(value); + } + + // create variable + MakeVariable var = new MakeVariable(varName, origin, recursive); + var.setValue(value); + + // add variable to database if not in ignored conditional + if (skipDepth == 0) + { + assignVariable(var, cond, append, existingVar); + } + + return var; + } + + private void processDefine(BlankTokenizer bt, MakeVariableOrigin origin) + throws MakeParseException, IOException + { + // get variable name + if (!bt.hasNextToken()) + { + throw new MakeParseException("Variable name expected after define"); + } + String varText = bt.restOfLineTrimmed(); + + // expand variables in variable name; an empty variable name after + // expansion is allowed for defines + String varName = expandVariables(varText); + + // process the define up to the matching endef + MakeVariable var = processDefineBody(varName, origin); + + // add variable to database if not in ignored conditional + if (skipDepth == 0) + { + assignVariable(var, false, false); + } + } + + private MakeVariable processDefineBody( + String varName, + MakeVariableOrigin origin) + throws IOException, MakeParseException + { + StringBuffer buffer = new StringBuffer(); + int defineLevel = 1; + while (true) + { + // read the next line, + // collapsing any backslash-newline continuations + String line = readLine(); + if (line == null) break; + + // look for endef or nested define + if (line.charAt(0) != '\t') + { + // find first token + BlankTokenizer bt = new BlankTokenizer(line); + String token1 = bt.hasNextToken() ? bt.nextToken() : ""; + if (token1.equals("define")) + { + ++defineLevel; + } + else if (token1.equals("endef")) + { + // check for extraneous text (not including comments) + if (bt.hasNextToken() + && line.charAt(bt.getNextTokenStart()) != '#') + { + throw new MakeParseException("Extraneous text after " + + token1); + } + + // handle endef + if (--defineLevel == 0) + { + MakeVariable var = new MakeVariable(varName, origin, + true); + var.setValue(buffer.toString()); + return var; + } + } + } + + // separate lines with newline characters + if (buffer.length() > 0) + { + buffer.append('\n'); + } + + // append line to value + buffer.append(line); + } + + throw new MakeParseException("Missing endef after define"); + } + + private void processExportList(String varText, boolean export) + throws MakeParseException + { + String varNames = expandVariables(varText); + BlankTokenizer bt = new BlankTokenizer(varNames); + while (bt.hasNextToken()) + { + // get next variable name + String varName = bt.nextToken(); + + // look up variable name in database + MakeVariable var = database.getVariable(varName); + + // if variable does not exist, create an empty simple variable + if (var == null) + { + var = new MakeVariable(varName, MakeVariableOrigin.FILE, false); + database.addVariable(var); + } + + // flag variable to be exported + var.setExported(export); + } + } + + private void processRule( + String line, + Set activeRules, + StringBuffer commandBuffer) + throws MakeParseException + { + String semiCmd = null; + + // rule ends at first semicolon or comment, if present + StringBuffer lineBuffer = new StringBuffer(line); + int ruleEndPos = MakeUtil.unescapeIndexOf(lineBuffer, ';', '#'); + if (ruleEndPos >= 0) + { + if (lineBuffer.charAt(ruleEndPos) == ';') + { + semiCmd = lineBuffer.substring(ruleEndPos + 1); + } + lineBuffer.setLength(ruleEndPos); + } + int lineBufferEnd = lineBuffer.length(); + + // expand target tokens until we find a (double) colon + StringBuffer targetBuffer = new StringBuffer(); + StringBuffer depBuffer = new StringBuffer(); + boolean gotColon = false; + boolean doubleColon = false; + RuleTokenizer rt = new RuleTokenizer(lineBuffer, 0, lineBufferEnd); + while (rt.hasNextToken() && !gotColon) + { + RuleTokenType tokenType = rt.getNextTokenType(); + String token = rt.nextToken(); + + // done if we found a literal (double) colon + doubleColon = tokenType == RuleTokenType.DOUBLE_COLON; + if (tokenType == RuleTokenType.COLON || doubleColon) + { + gotColon = true; + break; + } + + // expand any variables in the token + StringBuffer expansion = new StringBuffer(expandVariables(token)); + + // check for a semicolon command in the expansion + boolean gotSemiCmd = false; + if (semiCmd == null) + { + ruleEndPos = MakeUtil.unescapeIndexOf(expansion, ';'); + if (ruleEndPos >= 0) + { + // split expansion around semicolon and include + // rest of line (expanded) in semicolon command + semiCmd = expansion.substring(ruleEndPos + 1) + + expandVariables(rt.restOfLine()); + expansion.setLength(ruleEndPos); + gotSemiCmd = true; + } + } + + // check for a (double) colon in the expansion + int colonPos = MakeUtil.unescapeIndexOf(expansion, ':'); + if (colonPos >= 0) + { + // check for double colon + int prereqPos = colonPos + 1; + if (expansion.charAt(colonPos + 1) == ':') + { + doubleColon = true; + ++prereqPos; + } + + // split expansion around (double) colon + depBuffer.append(expansion.substring(prereqPos)); + expansion.setLength(colonPos); + gotColon = true; + } + else if (gotSemiCmd) + { + // expansion contained a semicolon without a preceding colon + break; + } + + targetBuffer.append(expansion); + targetBuffer.append(' '); + } + PathTokenizer pt = new PathTokenizer(targetBuffer); + + // we did not find a rule; make sure line was empty + if (!gotColon) + { + if (pt.hasNextToken()) + { + throw new MakeParseException("Colon not found in rule"); + } + if (semiCmd != null) + { + throw new MakeParseException( + "Missing rule before semicolon command"); + } + return; + } + + // ignore rules with empty target list + if (!pt.hasNextToken()) return; + + // build target list + List targetNameList = globPaths(pt.extractTokens()); + + // check for target-specific variable + StringBuffer targetVarBuffer = new StringBuffer(); + targetVarBuffer.append(depBuffer); + targetVarBuffer.append(lineBuffer.substring(rt.getNextTokenStart())); + if (semiCmd != null) targetVarBuffer.append(semiCmd); + if (processTargetVariable(targetNameList, targetVarBuffer)) + { + return; + } + + // expand dependencies + depBuffer.append(rt.restOfLine()); + MakeUtil.unescapeIndexOf(depBuffer, '='); + depBuffer = new StringBuffer(expandVariables(depBuffer.toString())); + + // check for a semicolon command in the expansion + if (semiCmd == null) + { + ruleEndPos = MakeUtil.unescapeIndexOf(depBuffer, ';'); + if (ruleEndPos >= 0) + { + // split expansion around semicolon + semiCmd = depBuffer.substring(ruleEndPos + 1); + depBuffer.setLength(ruleEndPos); + } + } + + // extract paths for target pattern or dependencies + pt = new PathTokenizer(depBuffer, ':'); + List tempList = pt.extractTokens(); + + // check for static pattern rule + MakePattern staticPattern = null; + if (pt.isHitStopChar()) + { + // get target pattern + int size = tempList.size(); + if (size == 0) + { + throw new MakeParseException("Missing target pattern"); + } + else if (size > 1) + { + throw new MakeParseException("Multiple target patterns"); + } + String patternString = (String) tempList.get(0); + staticPattern = MakePattern.parse(patternString); + + // extract paths for dependencies + pt = new PathTokenizer(depBuffer, pt.getLineEnd() + 1, depBuffer + .length()); + tempList = pt.extractTokens(); + } + + // build dependency list + List depNameList = globPaths(tempList); + + boolean firstTarget = true; + MakePatternRule patternRule = null; + List depList = null; + Iterator targetNameIter = targetNameList.iterator(); + while (targetNameIter.hasNext()) + { + String targetName = (String) targetNameIter.next(); + MakePattern targetPattern = MakePattern.parse(targetName); + boolean isPatternRule = !targetPattern.isStatic(); + + // check for invalid combination of target specifiers + if (firstTarget) + { + if (isPatternRule && staticPattern != null) + { + throw new MakeParseException( + "Mixed implicit and static pattern rules"); + } + } + else + { + if (isPatternRule != (patternRule != null)) + { + throw new MakeParseException( + "Mixed implicit and normal rules"); + } + } + + if (isPatternRule) + { + if (patternRule == null) + { + patternRule = new MakePatternRule(); + patternRule.setDoubleColon(doubleColon); + } + patternRule.addTargetPattern(targetPattern); + } + else + { + if (staticPattern != null) + { + if (!staticPattern.matches(targetName)) + { + throw new MakeParseException("Target '" + targetName + + "' does not match pattern '" + staticPattern + + "'"); + } + String stub = staticPattern.extractStub(targetName); + depList = buildDepList(depNameList, stub); + } + else if (depList == null) + { + depList = buildDepList(depNameList, null); + } + + MakeFileInfo target = database.getOrCreateFile(targetName); + MakeStaticRule existingRule = target.getRule(); + if (existingRule != null + && existingRule.isDoubleColon() != doubleColon) + { + throw new MakeParseException("Target '" + targetName + + "' has both : and :: rules"); + } + MakeStaticRule rule = existingRule; + if (existingRule == null || doubleColon) + { + rule = new MakeStaticRule(target); + rule.setDoubleColon(doubleColon); + if (existingRule == null) + { + target.setRule(rule); + database.addStaticRule(rule); + } + else + { + existingRule.addDoubleColonRule(rule); + } + } + rule.addDependencies(depList); + activeRules.add(rule); + } + + firstTarget = false; + } + if (patternRule != null) + { + Iterator depNameIter = depNameList.iterator(); + while (depNameIter.hasNext()) + { + String depName = (String) depNameIter.next(); + MakePattern depPattern = MakePattern.parse(depName); + patternRule.addDependencyPattern(depPattern); + } + database.addPatternRule(patternRule); + activeRules.add(patternRule); + } + if (semiCmd != null) + { + commandBuffer.append(semiCmd); + } + } + + private List buildDepList(List depNameList, String patternStub) + { + List depList = new LinkedList(); + Iterator iter = depNameList.iterator(); + while (iter.hasNext()) + { + String depName = (String) iter.next(); + if (patternStub != null) + { + MakePattern depPattern = MakePattern.parse(depName); + depName = depPattern.replaceStub(patternStub); + } + MakeFileInfo depFileInfo = database.getOrCreateFile(depName); + depList.add(depFileInfo); + } + return depList; + } + + private List globPaths(List origList) + { + List newList = new LinkedList(); + Iterator iter = origList.iterator(); + while (iter.hasNext()) + { + String path = (String) iter.next(); + String[] paths = FileGlobber.glob(path); + if (paths.length > 0) + { + for (int i = 0; i < paths.length; ++i) + { + newList.add(paths[i]); + } + } + else + { + newList.add(path); + } + } + return newList; + } + + private boolean processTargetVariable( + List targetList, + StringBuffer lineBuffer) + { + RuleTokenizer rt = new RuleTokenizer(lineBuffer); + + MakeVariableOrigin origin = MakeVariableOrigin.FILE; + RuleTokenType tokenType = rt.getNextTokenType(); + String token = rt.nextToken(); + + if (tokenType == RuleTokenType.TEXT && token.equals("override")) + { + origin = MakeVariableOrigin.OVERRIDE; + tokenType = rt.getNextTokenType(); + token = rt.nextToken(); + } + + tokenType = rt.getNextTokenType(); + token = rt.nextToken(); + if (tokenType == RuleTokenType.ASSIGN_OP) + { + String value = rt.restOfLine(); + + // TODO: handle target variable + warning("target variables not currently supported"); + + return true; + } + return false; + } + + private void assignVariable(MakeVariable var, boolean cond, boolean append) + { + MakeVariable existingVar = database.getVariable(var.getName()); + assignVariable(var, cond, append, existingVar); + } + + private void assignVariable( + MakeVariable var, + boolean cond, + boolean append, + MakeVariable existingVar) + { + if (existingVar == null + || (!cond && var.getOrigin().overrides(existingVar.getOrigin()))) + { + if (append) + { + existingVar.setValue(existingVar.getValue() + var.getValue()); + } + else + { + database.addVariable(var); + } + } + } + + public String expandVariables(String s) + throws MakeParseException + { + return expandVariables(s, null); + } + + private String expandVariables(String s, Set expandingVars) + throws MakeParseException + { + int start = 0; + int len = s.length(); + StringBuffer result = new StringBuffer(len); + while (start < len) + { + // look for next variable reference + int pos = s.indexOf('$', start); + + // substring between starting position and '$'? + if (pos > start) + { + // append substring before '$' to result + result.append(s.substring(start, pos)); + } + // '$' not found? + else if (pos < 0) + { + // append rest of input string to result and exit + result.append(s.substring(start)); + break; + } + + // advance position past '$'; break if end of string + if (++pos >= len) + { + break; + } + + // look at first character of reference + char c = s.charAt(pos++); + switch (c) + { + case '$': + result.append(c); + break; + case '(': + case '{': + // find first terminating character + char closeParen = (c == '(') ? ')' : '}'; + int closePos = s.indexOf(closeParen, pos); + if (closePos < 0) + { + throw new MakeParseException( + "Unterminated variable reference"); + } + + // look for function name + int funcEndPos = pos; + while (MakeUtil.isFuncChar(s.charAt(funcEndPos))) + ++funcEndPos; + if (MakeUtil.isBlank(s.charAt(funcEndPos))) + { + String funcName = s.substring(pos, funcEndPos); + MakeFunction func = getFunction(funcName); + if (func != null) + { + // find matching delimiter + int matchPos = MakeUtil.indexOfMatchingDelimiter(s, c, + closeParen, pos, len); + if (matchPos < 0) + { + throw new MakeParseException( + "Unterminated call to function '" + funcName + + "'"); + } + pos = matchPos + 1; + + // parse arguments + int argPos = funcEndPos + 1; + while (MakeUtil.isBlank(s.charAt(argPos))) + ++argPos; + List argList = new LinkedList(); + int argCount = 0; + int maxArgs = func.getMaximumArgs(); + while (argPos < matchPos) + { + int argEnd; + if (++argCount < maxArgs || maxArgs < 0) + { + argEnd = MakeUtil.indexOfArgumentEnd(s, c, + closeParen, argPos, matchPos); + } + else + { + // if this function has a maximum argument count + // and it is reached, treat all remaining text + // as the final argument + argEnd = matchPos; + } + String arg = s.substring(argPos, argEnd); + if (func.isExpandArgs()) + { + arg = expandVariables(arg, expandingVars); + } + argList.add(arg); + argPos = argEnd + 1; + } + + // add blank argument if none found + if (argCount == 0) + { + argList.add(""); + ++argCount; + } + + // invoke the function + String[] args = new String[argCount]; + argList.toArray(args); + result.append(func.expand(this, args)); + break; + } + } + + // look for nested variable reference + String varName = null; + int refPos = s.indexOf('$', pos); + if (refPos >= 0) + { + // find matching delimiter and expand contents + int matchPos = MakeUtil.indexOfMatchingDelimiter(s, c, + closeParen, pos, len); + if (matchPos >= 0) + { + varName = expandVariables(s.substring(pos, matchPos)); + pos = matchPos + 1; + } + } + + // no nested references or unmatched opening parentheses; + // use string up to first closing parenthesis as variable name + if (varName == null) + { + varName = s.substring(pos, closePos); + pos = closePos + 1; + } + + // check for substitution reference: $(xy:x=y) -> yy + int colonPos = varName.indexOf(':'); + if (colonPos >= 0) + { + int equalPos = varName.indexOf('=', colonPos + 1); + if (equalPos >= 0) + { + // extract parts: varName:pattern=replace + String patternText = varName.substring(colonPos + 1, + equalPos); + String replaceText = varName.substring(equalPos + 1); + varName = varName.substring(0, colonPos); + + // look up variable + MakeVariable var = database.getVariable(varName); + if (var != null) + { + String value = expandVariable(var, expandingVars); + MakePattern pattern = MakePattern + .parse(patternText); + if (!pattern.isStatic()) + { + MakePattern replace = MakePattern + .parse(replaceText); + value = MakeFunction.Patsubst.expand(pattern, + replace, value); + } + else + { + value = MakeFunction.Subst.expand(patternText, + replaceText, value); + } + result.append(value); + } + else + { + // undefined variable + } + break; + } + } + + // not a substitution reference; simply expand + MakeVariable var = database.getVariable(varName); + if (var != null) + { + String value = expandVariable(var, expandingVars); + result.append(value); + } + else + { + // undefined variable + } + break; + default: + } + + // current position becomes starting position of next iteration + start = pos; + } + return result.toString(); + } + + private String expandVariables( + String s, + Set expandingVars, + MakeVariable addVar) + throws MakeParseException + { + if (expandingVars == null) + { + expandingVars = new HashSet(); + } + expandingVars.add(addVar); + return expandVariables(s, expandingVars); + } + + public String expandVariable(String varName) + throws MakeParseException + { + MakeVariable var = database.getVariable(varName); + return (var != null) ? expandVariable(var, null) : ""; + } + + private String expandVariable(MakeVariable var, Set expandingVars) + throws MakeParseException + { + String value = var.getValue(); + if (var.isRecursive()) + { + if (expandingVars != null && expandingVars.contains(var)) + { + throw new MakeParseException("Recursive variable '" + + var.getName() + "' references itself"); + } + value = expandVariables(value, expandingVars, var); + } + return value; + } + + public void warning(String message) + { + System.err.println(MakeParseException.formatMessage(filename, reader + .getLineNumber(), message)); + } + + public void error(String message) + throws MakeParseException + { + throw new MakeParseException(message); + } + + private String readLine() + throws IOException + { + String result = null; + + // loop in case line is continued with backslash-newline + while (true) + { + // read a line from the file + final String line = reader.readLine(); + + // done if EOF + if (line == null) break; + + final int len = line.length(); + + // append line onto current result + if (result == null) + { + // first iteration; not handling continuation + result = line; + } + else + { + // handling continuation; join lines with a single space + int end = result.length(); + while (--end > 0 && MakeUtil.isBlank(result.charAt(end - 1))); + int start = 0; + while (start < len && MakeUtil.isBlank(line.charAt(start))) + ++start; + result = result.substring(0, end) + ' ' + line.substring(start); + } + + // done if end of line is not escaped by a backslash + if (!MakeUtil.isEscaped(line, len)) break; + + // read another line + } + + return result; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeParserTest.java b/java/make-parser/src/com/newisys/parser/make/MakeParserTest.java new file mode 100644 index 0000000..5aec328 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeParserTest.java @@ -0,0 +1,108 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.Collection; +import java.util.Iterator; + +/** + * A simple debugging/test program for the makefile parser. + * + * @author Trevor Robinson + */ +public final class MakeParserTest +{ + public static void main(String[] args) + { + MakeDatabase database = new MakeDatabase(); + try + { + MakeParser parser = new MakeParser(database, args[0]); + parser.parse(); + + database.applySpecialTargets(); + dumpVariables(database.getGlobalVariables()); + dumpRules("Static", database.getStaticRules()); + dumpRules("Pattern", database.getPatternRules()); + } + catch (MakeParseException e) + { + System.err.println(e.getMessage()); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + private static void defineCmdLineVar( + MakeDatabase database, + String name, + String value) + { + MakeVariable var = new MakeVariable(name, + MakeVariableOrigin.COMMAND_LINE, false); + var.setValue(value); + database.addVariable(var); + } + + private static void dumpVariables(Collection vars) + { + System.out.println("Variables:"); + Iterator iter = vars.iterator(); + while (iter.hasNext()) + { + MakeVariable var = (MakeVariable) iter.next(); + System.out.println(" " + var.getName() + " [" + var.getOrigin() + + "] " + (var.isRecursive() ? "= " : ":= ") + var.getValue()); + } + } + + private static void dumpRules(String type, Collection rules) + { + System.out.println(type + " rules:"); + Iterator iter = rules.iterator(); + while (iter.hasNext()) + { + MakeRule rule = (MakeRule) iter.next(); + dumpRule(rule); + if (rule.isDoubleColon() && rule instanceof MakeStaticRule) + { + MakeStaticRule cur = (MakeStaticRule) rule, next; + while ((next = cur.getNextDoubleColonRule()) != null) + { + dumpRule(next); + cur = next; + } + } + } + } + + private static void dumpRule(MakeRule rule) + { + System.out.println(" " + rule); + String command = rule.getCommand(); + if (command != null) + { + String[] commands = command.split("\n"); + for (int i = 0; i < commands.length; ++i) + { + System.out.println(" " + commands[i]); + } + } + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakePattern.java b/java/make-parser/src/com/newisys/parser/make/MakePattern.java new file mode 100644 index 0000000..ab57c0c --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakePattern.java @@ -0,0 +1,156 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Base class for representing makefile patterns. + * + * @author Trevor Robinson + */ +public abstract class MakePattern +{ + public static MakePattern parse(String pattern) + { + StringBuffer buffer = new StringBuffer(pattern); + int pctPos = MakeUtil.unescapeIndexOf(buffer, '%'); + pattern = buffer.toString(); + if (pctPos >= 0) + { + String prefix = pattern.substring(0, pctPos); + String suffix = pattern.substring(pctPos + 1); + return new RealPattern(pattern, prefix, suffix); + } + else + { + return new StaticPattern(pattern); + } + } + + protected final String pattern; + + protected MakePattern(String pattern) + { + this.pattern = pattern; + } + + public String getPattern() + { + return pattern; + } + + public String toString() + { + return pattern; + } + + public abstract boolean isStatic(); + + public abstract boolean matchesAny(); + + public abstract boolean matches(String s); + + public abstract String extractStub(String s); + + public abstract String replaceStub(String s); + + /** + * Represents a makefile pattern that actually contains a wildcard. + * + * @author Trevor Robinson + */ + private static final class RealPattern + extends MakePattern + { + private final String prefix; + private final int prefixLen; + private final String suffix; + private final int suffixLen; + + RealPattern(String pattern, String prefix, String suffix) + { + super(pattern); + this.prefix = prefix; + prefixLen = prefix.length(); + this.suffix = suffix; + suffixLen = suffix.length(); + } + + public boolean isStatic() + { + return false; + } + + public boolean matchesAny() + { + return prefixLen == 0 && suffixLen == 0; + } + + public boolean matches(String s) + { + return s.startsWith(prefix) && s.endsWith(suffix); + } + + public String extractStub(String s) + { + return s.substring(prefixLen, s.length() - suffixLen); + } + + public String replaceStub(String s) + { + return prefix + s + suffix; + } + } + + /** + * Represents a makefile pattern that contains no wildcard. + * + * @author Trevor Robinson + */ + private static final class StaticPattern + extends MakePattern + { + StaticPattern(String pattern) + { + super(pattern); + } + + public boolean isStatic() + { + return true; + } + + public boolean matchesAny() + { + return false; + } + + public boolean matches(String s) + { + return s.equals(pattern); + } + + public String extractStub(String s) + { + return ""; + } + + public String replaceStub(String s) + { + return pattern; + } + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakePatternRule.java b/java/make-parser/src/com/newisys/parser/make/MakePatternRule.java new file mode 100644 index 0000000..f28c588 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakePatternRule.java @@ -0,0 +1,65 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.util.text.TextUtil; + +/** + * Represents a makefile pattern rule. + * + * @author Trevor Robinson + */ +public final class MakePatternRule + extends MakeRule +{ + private final List targetPatterns = new LinkedList(); + private final List dependencyPatterns = new LinkedList(); + + public String getTargetNames() + { + return TextUtil.toString(targetPatterns.iterator(), null, null, " "); + } + + public List getTargetPatterns() + { + return targetPatterns; + } + + public void addTargetPattern(MakePattern pattern) + { + targetPatterns.add(pattern); + } + + public String getDependencyNames() + { + return TextUtil + .toString(dependencyPatterns.iterator(), null, null, " "); + } + + public List getDependencyPatterns() + { + return dependencyPatterns; + } + + public void addDependencyPattern(MakePattern pattern) + { + dependencyPatterns.add(pattern); + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeRule.java b/java/make-parser/src/com/newisys/parser/make/MakeRule.java new file mode 100644 index 0000000..8a2729b --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeRule.java @@ -0,0 +1,58 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Base class for representing makefile rules. + * + * @author Trevor Robinson + */ +public abstract class MakeRule +{ + protected String command; + protected boolean doubleColon; + + public abstract String getTargetNames(); + + public abstract String getDependencyNames(); + + public String getCommand() + { + return command; + } + + public void setCommand(String command) + { + this.command = command; + } + + public boolean isDoubleColon() + { + return doubleColon; + } + + public void setDoubleColon(boolean doubleColon) + { + this.doubleColon = doubleColon; + } + + public String toString() + { + return getTargetNames() + (doubleColon ? ":: " : ": ") + + getDependencyNames(); + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeStaticRule.java b/java/make-parser/src/com/newisys/parser/make/MakeStaticRule.java new file mode 100644 index 0000000..5ec2a2b --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeStaticRule.java @@ -0,0 +1,98 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.util.text.TextUtil; + +/** + * Represents a makefile static rule. + * + * @author Trevor Robinson + */ +public final class MakeStaticRule + extends MakeRule +{ + private final MakeFileInfo target; + private final List dependencies = new LinkedList(); + private MakeStaticRule nextDoubleColonRule; + + public MakeStaticRule(MakeFileInfo target) + { + this.target = target; + } + + public MakeStaticRule(MakeStaticRule other) + { + this(other.target); + dependencies.addAll(other.dependencies); + } + + public String getTargetNames() + { + return target.getPath(); + } + + public MakeFileInfo getTarget() + { + return target; + } + + public String getDependencyNames() + { + return TextUtil.toString(dependencies.iterator(), null, null, " "); + } + + public List getDependencies() + { + return dependencies; + } + + public void addDependency(MakeFileInfo fileInfo) + { + dependencies.add(fileInfo); + } + + public void addDependencies(Collection deps) + { + Iterator iter = deps.iterator(); + while (iter.hasNext()) + { + MakeFileInfo depFileInfo = (MakeFileInfo) iter.next(); + dependencies.add(depFileInfo); + } + } + + public MakeStaticRule getNextDoubleColonRule() + { + return nextDoubleColonRule; + } + + public void addDoubleColonRule(MakeStaticRule rule) + { + MakeStaticRule lastRule = this; + while (lastRule.nextDoubleColonRule != null) + { + lastRule = lastRule.nextDoubleColonRule; + } + lastRule.nextDoubleColonRule = rule; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeUtil.java b/java/make-parser/src/com/newisys/parser/make/MakeUtil.java new file mode 100644 index 0000000..c858bc6 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeUtil.java @@ -0,0 +1,220 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Utilities methods for parsing makefiles. + * + * @author Trevor Robinson + */ +final class MakeUtil +{ + private MakeUtil() + { + } + + public static int indexOfChar(CharSequence s, char c, int start) + { + int end = s.length(); + while (start < end) + { + if (s.charAt(start) == c) return start; + ++start; + } + return -1; + } + + public static int indexOfLastSlash(String text) + { + int slashPos1 = text.lastIndexOf('/'); + int slashPos2 = text.lastIndexOf('\\'); + int slashPos = Math.max(slashPos1, slashPos2); + return slashPos; + } + + public static int indexOfMatchingDelimiter( + CharSequence s, + char openChar, + char closeChar, + int start, + int end) + { + int count = 0; + for (int i = start; i < end; ++i) + { + char c = s.charAt(i); + if (c == closeChar && --count < 0) + { + return i; + } + else if (c == openChar) + { + ++count; + } + } + return -1; + } + + public static int indexOfArgumentEnd( + CharSequence s, + char openParen, + char closeParen, + int start, + int end) + { + int parenCount = 0; + for (int i = start; i < end; ++i) + { + char c = s.charAt(i); + if (c == openParen) + { + ++parenCount; + } + else if (c == closeParen) + { + --parenCount; + } + else if (c == ',' && parenCount <= 0) + { + return i; + } + } + return end; + } + + public static int indexOfUnescaped(CharSequence s, char c) + { + int start = 0; + while (true) + { + int pos = indexOfChar(s, c, start); + if (!isEscaped(s, pos)) + { + return pos; + } + start = pos + 1; + } + } + + public static boolean isEscaped(CharSequence s, int pos) + { + boolean escaped = false; + for (int i = pos - 1; i >= 0 && s.charAt(i) == '\\'; --i) + { + escaped = !escaped; + } + return escaped; + } + + public static boolean isDriveColon(CharSequence s, int pos) + { + int len = s.length(); + if (pos > 0 && pos < len - 1) + { + char before = s.charAt(pos - 1); + char after = s.charAt(pos + 1); + return (after == '/' || after == '\\') + && Character.isLetter(before); + } + return false; + } + + public static int unescapeIndexOf(StringBuffer s, char c) + { + return unescapeIndexOf(s, c, (char) 0, false); + } + + public static int unescapeIndexOf(StringBuffer s, char c1, char c2) + { + return unescapeIndexOf(s, c1, c2, false); + } + + public static int unescapeIndexOf( + StringBuffer s, + char c1, + char c2, + boolean blank) + { + return unescapeIndexOf(s, 0, s.length(), c1, c2, blank); + } + + public static int unescapeIndexOf( + final StringBuffer s, + final int start, + int end, + final char c1, + final char c2, + final boolean blank) + { + int pos = start; + while (true) + { + // remember where this iteration started + int iterStart = pos; + + // scan to position of first occurrence of end of line, c1, c2, or + // a blank (if blank is specified as a delimiter) + char c; + while (pos < end && (c = s.charAt(pos)) != c1 && c != c2 + && !(blank && isBlank(c))) + ++pos; + + // done if found end of line + if (pos == end) + { + pos = -1; + break; + } + + // check for escaped delimiter + if (pos > iterStart && s.charAt(pos - 1) == '\\') + { + // find first leading backslash + int slashPos = pos - 2; + while (slashPos >= iterStart && s.charAt(slashPos) == '\\') + --slashPos; + ++slashPos; + + // remove any backslashes used to escape backslashes + int slashes = pos - slashPos; + int keepSlashes = slashes / 2; + pos -= keepSlashes; + s.delete(slashPos, pos); + end -= slashes - keepSlashes; + + // an even number of backslashes does not escape the delimiter + if ((slashes & 1) == 0) break; + } + else + { + // delimiter was not escaped; return its position + break; + } + } + return pos; + } + + public static boolean isBlank(char c) + { + return c == ' ' || c == '\t'; + } + + public static boolean isFuncChar(char c) + { + return Character.isLowerCase(c) || c == '-'; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeVariable.java b/java/make-parser/src/com/newisys/parser/make/MakeVariable.java new file mode 100644 index 0000000..0ce65a2 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeVariable.java @@ -0,0 +1,93 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Represents a makefile variable. + * + * @author Trevor Robinson + */ +public class MakeVariable +{ + private final String name; + private MakeVariableOrigin origin; + private boolean recursive; + private boolean exported; + private String value; + + public MakeVariable( + String name, + MakeVariableOrigin origin, + boolean recursive) + { + this.name = name; + this.origin = origin; + this.recursive = recursive; + this.exported = false; + this.value = ""; + } + + public String getName() + { + return name; + } + + public MakeVariableOrigin getOrigin() + { + return origin; + } + + public void setOrigin(MakeVariableOrigin origin) + { + this.origin = origin; + } + + public boolean isRecursive() + { + return recursive; + } + + public void setRecursive(boolean recursive) + { + this.recursive = recursive; + } + + public boolean isExported() + { + return exported; + } + + public void setExported(boolean exported) + { + this.exported = exported; + } + + public String getValue() + { + return value; + } + + public void setValue(String value) + { + this.value = value; + } + + public String toString() + { + return value; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeVariableOrigin.java b/java/make-parser/src/com/newisys/parser/make/MakeVariableOrigin.java new file mode 100644 index 0000000..cc9c057 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeVariableOrigin.java @@ -0,0 +1,61 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Enumeration of makefile variable origins. + * + * @author Trevor Robinson + */ +public final class MakeVariableOrigin +{ + private final String str; + private final int level; + + private MakeVariableOrigin(String str, int level) + { + this.str = str; + this.level = level; + } + + public boolean overrides(MakeVariableOrigin other) + { + return level >= other.level; + } + + public String toString() + { + return str; + } + + // IMPORTANT: These strings are dictated by the 'origin' function! + + public static final MakeVariableOrigin DEFAULT = new MakeVariableOrigin( + "default", 0); + public static final MakeVariableOrigin ENVIRONMENT = new MakeVariableOrigin( + "environment", 1); + public static final MakeVariableOrigin FILE = new MakeVariableOrigin( + "file", 2); + public static final MakeVariableOrigin ENVIRONMENT_OVERRIDE = new MakeVariableOrigin( + "environment override", 3); + public static final MakeVariableOrigin COMMAND_LINE = new MakeVariableOrigin( + "command line", 4); + public static final MakeVariableOrigin OVERRIDE = new MakeVariableOrigin( + "override", 5); + public static final MakeVariableOrigin AUTOMATIC = new MakeVariableOrigin( + "automatic", 6); +} diff --git a/java/make-parser/src/com/newisys/parser/make/MakeVariableScope.java b/java/make-parser/src/com/newisys/parser/make/MakeVariableScope.java new file mode 100644 index 0000000..feb7726 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/MakeVariableScope.java @@ -0,0 +1,64 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Contains all the variables defined in a particular scope. + * + * @author Trevor Robinson + */ +final class MakeVariableScope +{ + private final Map variables = new LinkedHashMap(); + + /** + * Returns all of the variables defined in this scope. + * + * @return Collection of MakeVariable + */ + public Collection getVariables() + { + return variables.values(); + } + + /** + * Returns the variable from this scope with the given name, or null if no + * such variable exists. + * + * @param name String + * @return MakeVariable + */ + public MakeVariable getVariable(String name) + { + return (MakeVariable) variables.get(name); + } + + /** + * Adds the given variable to this scope. If a variable with the same name + * already exists, it is overwritten. + * + * @param var MakeVariable + */ + public void addVariable(MakeVariable var) + { + variables.put(var.getName(), var); + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/PathTokenizer.java b/java/make-parser/src/com/newisys/parser/make/PathTokenizer.java new file mode 100644 index 0000000..d4e2a04 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/PathTokenizer.java @@ -0,0 +1,110 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Character sequence tokenizer that tokenizes a path list with the given + * delimiter. It implements special GNU Make handling of escaped delimiters, + * colon delimiters with DOS/Windows paths, and leading ".///". + * + * @author Trevor Robinson + */ +final class PathTokenizer + extends AbstractTokenizer +{ + private final StringBuffer buffer; + private final char stopChar; + private boolean hitStopChar; + + public PathTokenizer(StringBuffer buffer) + { + this(buffer, 0, buffer.length(), (char) 0); + } + + public PathTokenizer(StringBuffer buffer, char stopChar) + { + this(buffer, 0, buffer.length(), stopChar); + } + + public PathTokenizer(StringBuffer buffer, int lineStart, int lineEnd) + { + this(buffer, lineStart, lineEnd, (char) 0); + } + + public PathTokenizer( + StringBuffer buffer, + int lineStart, + int lineEnd, + char stopChar) + { + super(buffer, lineStart, lineEnd); + this.buffer = buffer; + this.stopChar = stopChar; + findNextToken(); + } + + public boolean isHitStopChar() + { + return hitStopChar; + } + + protected void findNextToken() + { + tokenStart = tokenEnd; + + // skip leading blanks + char c = 0; + while (tokenStart < lineEnd + && MakeUtil.isBlank(c = line.charAt(tokenStart))) + ++tokenStart; + if (tokenStart == lineEnd) return; + if (c == stopChar) + { + lineEnd = tokenStart; + hitStopChar = true; + return; + } + + // find end of next path + do + { + tokenEnd = MakeUtil.unescapeIndexOf(buffer, tokenStart, lineEnd, + stopChar, (char) 0, true); + lineEnd = buffer.length(); + if (tokenEnd < 0) tokenEnd = lineEnd; + } + while (stopChar == ':' && tokenEnd < lineEnd + && buffer.charAt(tokenEnd) == ':' + && MakeUtil.isDriveColon(buffer, tokenEnd)); + + // skip leading ".///" + if (tokenEnd - tokenStart > 2 && buffer.charAt(tokenStart) == '.' + && buffer.charAt(tokenStart + 1) == '/') + { + tokenStart += 2; + while (tokenStart < tokenEnd && buffer.charAt(tokenStart) == '/') + ++tokenStart; + } + + // if ".///" became "", replace with "./" + if (tokenStart == tokenEnd) + { + tokenStart -= 2; + buffer.replace(tokenStart, tokenEnd, "./"); + } + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/RuleTokenType.java b/java/make-parser/src/com/newisys/parser/make/RuleTokenType.java new file mode 100644 index 0000000..d336377 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/RuleTokenType.java @@ -0,0 +1,37 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Enumeration of makefile rule token types. + * + * @author Trevor Robinson + */ +final class RuleTokenType +{ + private RuleTokenType() + { + } + + public static final RuleTokenType EOL = new RuleTokenType(); + public static final RuleTokenType COLON = new RuleTokenType(); + public static final RuleTokenType DOUBLE_COLON = new RuleTokenType(); + public static final RuleTokenType SEMICOLON = new RuleTokenType(); + public static final RuleTokenType ASSIGN_OP = new RuleTokenType(); + public static final RuleTokenType TEXT = new RuleTokenType(); + public static final RuleTokenType VAR_REF = new RuleTokenType(); +} diff --git a/java/make-parser/src/com/newisys/parser/make/RuleTokenizer.java b/java/make-parser/src/com/newisys/parser/make/RuleTokenizer.java new file mode 100644 index 0000000..9fb6092 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/RuleTokenizer.java @@ -0,0 +1,161 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Character sequence tokenizer for GNU Make rules. + * + * @author Trevor Robinson + */ +final class RuleTokenizer + extends AbstractTokenizer +{ + private RuleTokenType tokenType; + + public RuleTokenizer(CharSequence line) + { + super(line); + findNextToken(); + } + + public RuleTokenizer(CharSequence line, int lineStart, int lineEnd) + { + super(line, lineStart, lineEnd); + findNextToken(); + } + + public RuleTokenType getNextTokenType() + { + return tokenType; + } + + protected void findNextToken() + { + tokenStart = tokenEnd; + + // skip leading blanks + char c = 0; + while (tokenStart < lineEnd + && MakeUtil.isBlank(c = line.charAt(tokenStart))) + ++tokenStart; + + // look for operator + tokenEnd = tokenStart + 1; + switch (c) + { + case 0: + tokenType = RuleTokenType.EOL; + break; + case ':': + char c1 = getChar(tokenEnd); + switch (c1) + { + case ':': + tokenType = RuleTokenType.DOUBLE_COLON; + ++tokenEnd; + break; + case '=': + tokenType = RuleTokenType.ASSIGN_OP; + ++tokenEnd; + break; + default: + tokenType = RuleTokenType.COLON; + } + break; + case ';': + tokenType = RuleTokenType.SEMICOLON; + break; + case '=': + tokenType = RuleTokenType.ASSIGN_OP; + break; + case '+': + case '?': + if (getChar(tokenEnd) == '=') + { + tokenType = RuleTokenType.ASSIGN_OP; + ++tokenEnd; + break; + } + default: + tokenType = null; + } + if (tokenType != null) return; + + // look for static text or a variable reference + tokenType = RuleTokenType.TEXT; + loop: while (true) + { + char c1 = getChar(tokenEnd); + switch (c) + { + case 0: + case ' ': + case '\t': + case '=': + // end text at EOL, blanks, or assignment + break loop; + case '+': + case '?': + if (c1 == '=') + { + // end text at assignment + ++tokenEnd; + break loop; + } + break; + case ':': + // allow colon in text if it looks like a DOS/Windows drivespec + if (tokenEnd - tokenStart == 2 && (c1 == '/' || c1 == '\\') + && Character.isLetter(line.charAt(tokenStart))) + { + break; + } + // end text at (non-drivespec) colon + break loop; + case '$': + ++tokenEnd; + if (c1 != '$') + { + // token contains a variable reference + tokenType = RuleTokenType.VAR_REF; + if (c1 == '(' || c1 == '{') + { + char closeParen = (c1 == '(') ? ')' : '}'; + int matchPos = MakeUtil.indexOfMatchingDelimiter(line, + c1, closeParen, tokenEnd, lineEnd); + tokenEnd = (matchPos >= 0) ? matchPos + 1 : lineEnd; + } + } + break; + case '\\': + if (c1 == ':' || c1 == ';' || c1 == '=' || c1 == '\\') + { + // allow escaped colon, semicolon, or assignment + ++tokenEnd; + } + break; + } + c = getChar(tokenEnd++); + } + --tokenEnd; + } + + private char getChar(int pos) + { + return (pos < lineEnd) ? line.charAt(pos) : 0; + } +} diff --git a/java/make-parser/src/com/newisys/parser/make/VPathEntry.java b/java/make-parser/src/com/newisys/parser/make/VPathEntry.java new file mode 100644 index 0000000..6817486 --- /dev/null +++ b/java/make-parser/src/com/newisys/parser/make/VPathEntry.java @@ -0,0 +1,54 @@ +/* + * Makefile Parser and Model Builder + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.make; + +/** + * Represents a vpath declaration. + * + * @author Trevor Robinson + */ +final class VPathEntry +{ + private final MakePattern pattern; + private final String path; + + public VPathEntry(MakePattern pattern, String path) + { + this.pattern = pattern; + this.path = path; + } + + public String getPattern() + { + return pattern.getPattern(); + } + + public boolean patternMatches(String s) + { + return pattern.matches(s); + } + + public String getPath() + { + return path; + } + + public String toString() + { + return pattern + " " + path; + } +} diff --git a/java/vera-parser/build-token-xlat-table.pl b/java/vera-parser/build-token-xlat-table.pl new file mode 100644 index 0000000..1defc74 --- /dev/null +++ b/java/vera-parser/build-token-xlat-table.pl @@ -0,0 +1,100 @@ +#!/usr/local/bin/perl + +use strict; +use warnings; +use IO::File; + +$0 =~ /(.*\/)?(.*)/; +my $progname = $2; + +die "Syntax: $progname " if $#ARGV != 3; + +my $srcconst = shift @ARGV; +my $tgtconst = shift @ARGV; +my $outtable = shift @ARGV; +my $outclass = shift @ARGV; + +my %srcmap; +read_constants($srcconst, \%srcmap); + +my %tgtmap; +my $tgtpkg; +read_constants($tgtconst, \%tgtmap, \$tgtpkg); + +my @outarray; +while (my ($tgtname, $tgtvalue) = each %tgtmap) +{ + die "$tgtname not defined in source constants" if !exists $srcmap{$tgtname}; + my $srcvalue = $srcmap{$tgtname}; + $outarray[$srcvalue] = $tgtvalue; +} + +write_mapping($outtable, \@outarray, $tgtpkg, $outclass); + +exit 0; + +sub read_constants +{ + my $filename = shift; + my $map_ref = shift or die; + my $package_ref = shift; + + print "Reading constants from $filename\n"; + my $fh = new IO::File($filename, "r"); + die "$! opening $filename" if !defined($fh); + + while (<$fh>) { + if (/^\s*int\s*(\w+)\s*=\s*(\d+)\s*;/) { + $map_ref->{$1} = $2; + } + elsif (/^\s*package\s*(\w+(?:\s*\.\s*\w+)*)\s*;/) { + $$package_ref = $1 if defined($package_ref); + } + } +} + +sub write_mapping +{ + my $filename = shift; + my $array_ref = shift or die; + my $pkg = shift or die; + my $cls = shift or die; + + print "Writing mapping table to $filename\n"; + my $fh = new IO::File($filename, "w"); + die "$! opening $filename" if !defined($fh); + + print $fh "// Generated by $progname\n\n"; + print $fh "package $pkg;\n\n"; + print $fh "final class $cls\n{\n"; + print $fh " private static final int[] mapping = {\n"; + + my $last = $#$array_ref; + my $srcvalue; + my $linepos = 0; + foreach $srcvalue (0..$last) { + my $tgtvalue = $array_ref->[$srcvalue]; + $tgtvalue = -1 if !defined $tgtvalue; + print $fh " " if $linepos == 0; + print $fh " $tgtvalue,"; + if (++$linepos == 10) { + print $fh "\n"; + $linepos = 0; + } + } + if ($linepos > 0) { + print $fh "\n"; + } + + print $fh " };\n\n"; + print $fh " public static int translate(int src) {\n"; + print $fh " int tgt = mapping[src];\n"; + print $fh " if (tgt < 0) {\n"; + print $fh " throw new IllegalArgumentException(\n"; + print $fh " \"No target token kind for source kind \" + src);\n"; + print $fh " }\n"; + print $fh " return tgt;\n"; + print $fh " }\n"; + print $fh "}\n"; +} + diff --git a/java/vera-parser/build.xml b/java/vera-parser/build.xml new file mode 100644 index 0000000..ca7404a --- /dev/null +++ b/java/vera-parser/build.xml @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/vera-parser/manifest.mf b/java/vera-parser/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/vera-parser/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/vera-parser/src/com/newisys/langsource/vera/AbsFuncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/AbsFuncDecl.java new file mode 100644 index 0000000..edd8c84 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/AbsFuncDecl.java @@ -0,0 +1,88 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Abstract function declaration. + * + * @author Trevor Robinson + */ +public abstract class AbsFuncDecl + extends VeraSourceObjectImpl +{ + private String identifier; + private TypeRef returnType; + private List params; // List + private boolean export; + private boolean extern; + + public AbsFuncDecl() + { + this.params = new LinkedList(); + this.export = false; + this.extern = false; + } + + public final String getIdentifier() + { + return identifier; + } + + public final void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public final TypeRef getReturnType() + { + return returnType; + } + + public final void setReturnType(TypeRef returnType) + { + this.returnType = returnType; + } + + public final List getParams() + { + return params; + } + + public final boolean isExport() + { + return export; + } + + public final void setExport(boolean export) + { + this.export = export; + } + + public final boolean isExtern() + { + return extern; + } + + public final void setExtern(boolean extern) + { + this.extern = extern; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/AbsVarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/AbsVarDecl.java new file mode 100644 index 0000000..408416c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/AbsVarDecl.java @@ -0,0 +1,63 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Abstract variable declaration. + * + * @author Trevor Robinson + */ +public abstract class AbsVarDecl + extends VeraSourceObjectImpl + implements Cloneable +{ + private String identifier; + private TypeRef typeRef; + + public final String getIdentifier() + { + return identifier; + } + + public final void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public final TypeRef getTypeRef() + { + return typeRef; + } + + public final void setTypeRef(TypeRef typeRef) + { + this.typeRef = typeRef; + } + + public Object clone() + { + try + { + return super.clone(); + } + catch (CloneNotSupportedException e) + { + throw new RuntimeException("Unexpected exception", e); + } + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ArrayAccessDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ArrayAccessDecl.java new file mode 100644 index 0000000..f618e77 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ArrayAccessDecl.java @@ -0,0 +1,79 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Array access expression. + * + * @author Trevor Robinson + */ +public final class ArrayAccessDecl + extends ExpressionDecl +{ + private ExpressionDecl arrayExpr; + private List indexExprs; // List + + public ArrayAccessDecl(ExpressionDecl arrayExpr) + { + this.arrayExpr = arrayExpr; + this.indexExprs = new LinkedList(); + } + + public ExpressionDecl getArrayExpr() + { + return arrayExpr; + } + + public void setArrayExpr(ExpressionDecl object) + { + this.arrayExpr = object; + } + + public List getIndexExprs() + { + return indexExprs; + } + + public void addIndexExpr(ExpressionDecl indexExpr) + { + indexExprs.add(indexExpr); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append(arrayExpr); + Iterator iter = indexExprs.iterator(); + while (iter.hasNext()) + { + buf.append('['); + buf.append(iter.next()); + buf.append(']'); + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ArrayInitDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ArrayInitDecl.java new file mode 100644 index 0000000..91773c0 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ArrayInitDecl.java @@ -0,0 +1,47 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Array initializer expression. + * + * @author Trevor Robinson + */ +public final class ArrayInitDecl + extends ExpressionDecl +{ + private List elements = new LinkedList(); // List + + public List getElements() + { + return elements; + } + + public void addElement(ExpressionDecl elem) + { + elements.add(elem); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ArrayKind.java b/java/vera-parser/src/com/newisys/langsource/vera/ArrayKind.java new file mode 100644 index 0000000..d9a1e7a --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ArrayKind.java @@ -0,0 +1,45 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of array kinds. + * + * @author Trevor Robinson + */ +public final class ArrayKind +{ + private final String str; + + private ArrayKind(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final ArrayKind FIXED = new ArrayKind("fixed"); + public static final ArrayKind BIT_ASSOCIATIVE = new ArrayKind( + "bit-associative"); + public static final ArrayKind STRING_ASSOCIATIVE = new ArrayKind( + "string-associative"); + public static final ArrayKind DYNAMIC = new ArrayKind("dynamic"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ArrayTypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/ArrayTypeRef.java new file mode 100644 index 0000000..0a65d75 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ArrayTypeRef.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Array type references. + * + * @author Trevor Robinson + */ +public class ArrayTypeRef + extends TypeRef +{ + private ArrayKind arrayKind; + protected TypeRef elementTypeRef; + + public ArrayTypeRef(ArrayKind arrayKind, TypeRef elementTypeRef) + { + super(TypeRefKind.ARRAY); + this.arrayKind = arrayKind; + this.elementTypeRef = elementTypeRef; + } + + public final ArrayKind getArrayKind() + { + return arrayKind; + } + + public final TypeRef getElementTypeRef() + { + return elementTypeRef; + } + + public String toString() + { + String suffix; + if (arrayKind == ArrayKind.DYNAMIC) + { + suffix = "[*]"; + } + else if (arrayKind == ArrayKind.STRING_ASSOCIATIVE) + { + suffix = "[string]"; + } + else + { + suffix = "[]"; + } + return elementTypeRef.toString() + suffix; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BindDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BindDecl.java new file mode 100644 index 0000000..359fee4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BindDecl.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Bind declaration. + * + * @author Trevor Robinson + */ +public final class BindDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + private String portIdentifier; + private final List signals = new LinkedList(); // List + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public String getPortIdentifier() + { + return portIdentifier; + } + + public void setPortIdentifier(String portIdentifier) + { + this.portIdentifier = portIdentifier; + } + + public void addSignal(BindSignalDecl signal) + { + signals.add(signal); + } + + public List getSignals() + { + return signals; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BindSignalDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BindSignalDecl.java new file mode 100644 index 0000000..032dd7b --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BindSignalDecl.java @@ -0,0 +1,58 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Bind signal declaration. + * + * @author Trevor Robinson + */ +public final class BindSignalDecl + extends VeraSourceObjectImpl +{ + private String portMember; + private final List signalRanges = new LinkedList(); // List + + public String getPortMember() + { + return portMember; + } + + public void setPortMember(String portMember) + { + this.portMember = portMember; + } + + public void addSignalRange(SignalRangeDecl signalRange) + { + signalRanges.add(signalRange); + } + + public List getSignalRanges() + { + return signalRanges; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BitSliceAccessDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BitSliceAccessDecl.java new file mode 100644 index 0000000..c489901 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BitSliceAccessDecl.java @@ -0,0 +1,66 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Bit slice access expression. + * + * @author Trevor Robinson + */ +public final class BitSliceAccessDecl + extends ExpressionDecl +{ + private ExpressionDecl bitExpr; + private RangeDecl range; + + public BitSliceAccessDecl(ExpressionDecl arrayExpr, RangeDecl range) + { + this.bitExpr = arrayExpr; + this.range = range; + } + + public ExpressionDecl getBitExpr() + { + return bitExpr; + } + + public void setBitExpr(ExpressionDecl object) + { + this.bitExpr = object; + } + + public RangeDecl getRange() + { + return range; + } + + public void setRange(RangeDecl range) + { + this.range = range; + } + + public String toString() + { + return bitExpr + "[" + range.getFrom() + ":" + range.getTo() + "]"; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BitVectorLiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BitVectorLiteralDecl.java new file mode 100644 index 0000000..4aa758e --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BitVectorLiteralDecl.java @@ -0,0 +1,96 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.verilog.util.BitVector; + +/** + * Bit vector literal expression. + * + * @author Trevor Robinson + */ +public final class BitVectorLiteralDecl + extends LiteralDecl +{ + private BitVector value; + private int radix; + + public BitVectorLiteralDecl(BitVector value) + { + super(LiteralKind.BIT_VECTOR); + this.value = value; + this.radix = 10; + } + + public BitVector getValue() + { + return value; + } + + public void setValue(BitVector value) + { + this.value = value; + } + + public int getRadix() + { + return radix; + } + + public void setRadix(int radix) + { + this.radix = radix; + } + + public String toString() + { + return value.toString(); + } + + public static BitVectorLiteralDecl parse(String src) + { + BitVector bv = new BitVector(src); + BitVectorLiteralDecl result = new BitVectorLiteralDecl(bv); + + int tickPos = src.indexOf('\''); + if (tickPos >= 0) + { + int radix = 10; + switch (src.charAt(tickPos + 1)) + { + case 'h': + radix = 16; + break; + case 'o': + radix = 8; + break; + case 'b': + radix = 2; + break; + } + result.setRadix(radix); + } + + return result; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BitVectorTypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/BitVectorTypeRef.java new file mode 100644 index 0000000..3da6b7a --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BitVectorTypeRef.java @@ -0,0 +1,52 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.vera.VeraPrimitiveKind; + +/** + * Bit vector type reference. + * + * @author Trevor Robinson + */ +public final class BitVectorTypeRef + extends PrimitiveTypeRef +{ + private ExpressionDecl highBitExpr; + + public BitVectorTypeRef(ExpressionDecl highBitExpr) + { + super(VeraPrimitiveKind.BIT_VECTOR); + this.highBitExpr = highBitExpr; + } + + public ExpressionDecl getHighBitExpr() + { + return highBitExpr; + } + + public String toString() + { + return "bit[" + highBitExpr + ":0]"; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BlockDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BlockDecl.java new file mode 100644 index 0000000..5bd5ca9 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BlockDecl.java @@ -0,0 +1,86 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Statement block. + * + * @author Trevor Robinson + */ +public final class BlockDecl + extends StatementDecl +{ + private List localVars; // List + private List statements; // List + + public BlockDecl() + { + localVars = new LinkedList(); + statements = new LinkedList(); + } + + public void addLocalVar(LocalVarDecl var) + { + localVars.add(var); + } + + public List getLocalVars() + { + return localVars; + } + + public void addStatement(StatementDecl stmt) + { + statements.add(stmt); + } + + public List getStatements() + { + return statements; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append("{ "); + boolean first = false; + Iterator iter = localVars.iterator(); + while (iter.hasNext()) + { + if (!first) buf.append(' '); + buf.append(iter.next()); + } + iter = statements.iterator(); + while (iter.hasNext()) + { + if (!first) buf.append(' '); + buf.append(iter.next()); + } + buf.append(" }"); + return buf.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BreakDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BreakDecl.java new file mode 100644 index 0000000..4a40765 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BreakDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Break statement. + * + * @author Trevor Robinson + */ +public final class BreakDecl + extends StatementDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "break;"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/BreakpointDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/BreakpointDecl.java new file mode 100644 index 0000000..e321f22 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/BreakpointDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Breakpoint statement. + * + * @author Trevor Robinson + */ +public final class BreakpointDecl + extends StatementDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "breakpoint;"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/CaseDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/CaseDecl.java new file mode 100644 index 0000000..2ad593a --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/CaseDecl.java @@ -0,0 +1,82 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.vera.VeraCaseKind; + +/** + * Case statement. + * + * @author Trevor Robinson + */ +public final class CaseDecl + extends StatementDecl +{ + private VeraCaseKind caseKind; + private ExpressionDecl caseExpr; + private final List caseMembers = new LinkedList(); // List + private StatementDecl defaultStatement; + + public VeraCaseKind getCaseKind() + { + return caseKind; + } + + public void setCaseKind(VeraCaseKind caseKind) + { + this.caseKind = caseKind; + } + + public ExpressionDecl getCaseExpr() + { + return caseExpr; + } + + public void setCaseExpr(ExpressionDecl caseExpr) + { + this.caseExpr = caseExpr; + } + + public void addCaseMember(CaseMemberDecl member) + { + caseMembers.add(member); + } + + public List getCaseMembers() + { + return caseMembers; + } + + public StatementDecl getDefaultStatement() + { + return defaultStatement; + } + + public void setDefaultStatement(StatementDecl defaultStatement) + { + this.defaultStatement = defaultStatement; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/CaseMemberDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/CaseMemberDecl.java new file mode 100644 index 0000000..f41b32a --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/CaseMemberDecl.java @@ -0,0 +1,58 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Case statement member. + * + * @author Trevor Robinson + */ +public final class CaseMemberDecl + extends VeraSourceObjectImpl +{ + private List exprs; // List + private StatementDecl statement; + + public CaseMemberDecl() + { + exprs = new LinkedList(); + } + + public List getExprs() + { + return exprs; + } + + public StatementDecl getStatement() + { + return statement; + } + + public void setStatement(StatementDecl statementDecl) + { + this.statement = statementDecl; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassConstraintDecl.java new file mode 100644 index 0000000..0c2d351 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassConstraintDecl.java @@ -0,0 +1,45 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Class random constraint declaration. + * + * @author Trevor Robinson + */ +public final class ClassConstraintDecl + extends NamedConstraintDecl + implements ClassDeclMember +{ + private boolean extern; + + public boolean isExtern() + { + return extern; + } + + public void setExtern(boolean extern) + { + this.extern = extern; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassDecl.java new file mode 100644 index 0000000..8dd39e4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassDecl.java @@ -0,0 +1,160 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Class declaration. + * + * @author Trevor Robinson + */ +public final class ClassDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + private boolean extern; + private boolean virtual; + private boolean local; + private String baseClassIdentifer; + private List baseCtorArgs; // List + private List classEnums; // List + private List classVars; // List + private List classConstraints; // List + private List classFuncs; // List + + public ClassDecl() + { + super(); + this.extern = false; + this.virtual = false; + this.local = false; + this.baseCtorArgs = new LinkedList(); + this.classEnums = new LinkedList(); + this.classVars = new LinkedList(); + this.classConstraints = new LinkedList(); + this.classFuncs = new LinkedList(); + } + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public boolean isExtern() + { + return extern; + } + + public void setExtern(boolean extern) + { + this.extern = extern; + } + + public boolean isVirtual() + { + return virtual; + } + + public void setVirtual(boolean virtual) + { + this.virtual = virtual; + } + + public String getBaseClassIdentifer() + { + return baseClassIdentifer; + } + + public boolean isLocal() + { + return local; + } + + public void setLocal(boolean local) + { + this.local = local; + } + + public void setBaseClassIdentifer(String baseClassIdentifer) + { + this.baseClassIdentifer = baseClassIdentifer; + } + + public void addBaseCtorArg(ExpressionDecl arg) + { + baseCtorArgs.add(arg); + } + + public List getBaseCtorArgs() + { + return baseCtorArgs; + } + + public void addClassEnum(EnumDecl enumeration) + { + classEnums.add(enumeration); + } + + public List getClassEnums() + { + return classEnums; + } + + public void addClassVar(ClassVarDecl var) + { + classVars.add(var); + } + + public List getClassVars() + { + return classVars; + } + + public void addClassConstraint(ClassConstraintDecl cons) + { + classConstraints.add(cons); + } + + public List getClassConstraints() + { + return classConstraints; + } + + public void addClassFunc(ClassFuncDecl func) + { + classFuncs.add(func); + } + + public List getClassFuncs() + { + return classFuncs; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassDeclMember.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassDeclMember.java new file mode 100644 index 0000000..6835970 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassDeclMember.java @@ -0,0 +1,29 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Tag interface for class members. + * + * @author Trevor Robinson + */ +public interface ClassDeclMember + extends VeraSourceObject +{ + // tag interface +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassFuncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassFuncDecl.java new file mode 100644 index 0000000..bc62f73 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassFuncDecl.java @@ -0,0 +1,64 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.vera.VeraVisibility; + +/** + * Class function declaration. + * + * @author Trevor Robinson + */ +public final class ClassFuncDecl + extends VeraFuncDecl + implements ClassDeclMember +{ + private boolean virtual; + private VeraVisibility visibility; + + public ClassFuncDecl() + { + this.virtual = false; + this.visibility = VeraVisibility.PUBLIC; + } + + public boolean isVirtual() + { + return virtual; + } + + public void setVirtual(boolean virtual) + { + this.virtual = virtual; + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassModifier.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassModifier.java new file mode 100644 index 0000000..d656642 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassModifier.java @@ -0,0 +1,40 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of class modifiers. + * + * @author Trevor Robinson + */ +public final class ClassModifier +{ + private final String str; + + private ClassModifier(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final ClassModifier VIRTUAL = new ClassModifier("virtual"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ClassVarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ClassVarDecl.java new file mode 100644 index 0000000..5d069cc --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ClassVarDecl.java @@ -0,0 +1,123 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.vera.VeraVisibility; + +/** + * Class variable declaration. + * + * @author Trevor Robinson + */ +public final class ClassVarDecl + extends VarDecl + implements ClassDeclMember +{ + private VeraVisibility visibility; + private ExpressionDecl randomSizeExpr; + private boolean staticVar; + private RandMode randMode; + private boolean packed; + private boolean bigEndian; + private boolean bitReverse; + + public ClassVarDecl() + { + this.staticVar = false; + this.visibility = VeraVisibility.PUBLIC; + this.randMode = RandMode.NON_RAND; + this.packed = false; + this.bigEndian = false; + this.bitReverse = false; + } + + public VeraVisibility getVisibility() + { + return visibility; + } + + public void setVisibility(VeraVisibility visibility) + { + this.visibility = visibility; + } + + public final ExpressionDecl getRandomSizeExpr() + { + return randomSizeExpr; + } + + public final void setRandomSizeExpr(ExpressionDecl randomSizeExpr) + { + this.randomSizeExpr = randomSizeExpr; + } + + public boolean isStaticVar() + { + return staticVar; + } + + public void setStaticVar(boolean staticVar) + { + this.staticVar = staticVar; + } + + public RandMode getRandMode() + { + return randMode; + } + + public void setRandMode(RandMode randMode) + { + this.randMode = randMode; + } + + public boolean isPacked() + { + return packed; + } + + public void setPacked(boolean packed) + { + this.packed = packed; + } + + public boolean isBigEndian() + { + return bigEndian; + } + + public void setBigEndian(boolean bigEndian) + { + this.bigEndian = bigEndian; + } + + public boolean isBitReverse() + { + return bitReverse; + } + + public void setBitReverse(boolean bitReverse) + { + this.bitReverse = bitReverse; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDecl.java new file mode 100644 index 0000000..6dadf9f --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDecl.java @@ -0,0 +1,60 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Compilation unit. + * + * @author Trevor Robinson + */ +public class CompilationUnitDecl + extends VeraSourceObjectImpl +{ + private final String path; + private final List members = new LinkedList(); + + // List + + public CompilationUnitDecl(String path) + { + this.path = path; + } + + public String getPath() + { + return path; + } + + public void addMember(CompilationUnitDeclMember member) + { + members.add(member); + } + + public List getMembers() + { + return members; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDeclMember.java b/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDeclMember.java new file mode 100644 index 0000000..ec4472b --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/CompilationUnitDeclMember.java @@ -0,0 +1,29 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Tag interface for compilation unit members. + * + * @author Trevor Robinson + */ +public interface CompilationUnitDeclMember + extends VeraSourceObject +{ + // tag interface +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ConstraintDecl.java new file mode 100644 index 0000000..d78f03b --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ConstraintDecl.java @@ -0,0 +1,69 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Random constraint expression list. + * + * @author Trevor Robinson + */ +public class ConstraintDecl + extends ExpressionDecl +{ + private List constraintExprs; // List + + public ConstraintDecl() + { + this.constraintExprs = new LinkedList(); + } + + public void addConstraintExpr(ExpressionDecl expr) + { + constraintExprs.add(expr); + } + + public final List getConstraintExprs() + { + return constraintExprs; + } + + public String toString() + { + StringBuffer buf = new StringBuffer("{ "); + Iterator iter = constraintExprs.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) + { + buf.append("; "); + } + } + buf.append(" }"); + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ContinueDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ContinueDecl.java new file mode 100644 index 0000000..5373557 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ContinueDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Continue statement. + * + * @author Trevor Robinson + */ +public final class ContinueDecl + extends StatementDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "continue;"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/DefaultValueDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/DefaultValueDecl.java new file mode 100644 index 0000000..b95ec3e --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/DefaultValueDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Function argument default value expression. + * + * @author Trevor Robinson + */ +public final class DefaultValueDecl + extends ExpressionDecl +{ + public String toString() + { + return "*"; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/DefineDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/DefineDecl.java new file mode 100644 index 0000000..64185c1 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/DefineDecl.java @@ -0,0 +1,74 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.parser.util.Macro; + +/** + * Preprocessor #define. + * + * @author Trevor Robinson + */ +public final class DefineDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private Macro macro; + private boolean local; + private boolean verilogImport; + + public DefineDecl(Macro macro) + { + this.macro = macro; + } + + public Macro getMacro() + { + return macro; + } + + public boolean isLocal() + { + return local; + } + + public void setLocal(boolean local) + { + this.local = local; + } + + public boolean isVerilogImport() + { + return verilogImport; + } + + public void setVerilogImport(boolean verilogImport) + { + this.verilogImport = verilogImport; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "#define " + macro.getName() + " " + macro.expand(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/DepthAccessDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/DepthAccessDecl.java new file mode 100644 index 0000000..cd3991f --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/DepthAccessDecl.java @@ -0,0 +1,71 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Signal back-reference expression. + * + * @author Trevor Robinson + */ +public final class DepthAccessDecl + extends ExpressionDecl +{ + private ExpressionDecl signalExpr; + private int depth; + + public DepthAccessDecl(ExpressionDecl objectExpr) + { + this.signalExpr = objectExpr; + } + + public DepthAccessDecl(ExpressionDecl objectExpr, int depth) + { + this.signalExpr = objectExpr; + this.depth = depth; + } + + public ExpressionDecl getSignalExpr() + { + return signalExpr; + } + + public void setSignalExpr(ExpressionDecl object) + { + this.signalExpr = object; + } + + public int getDepth() + { + return depth; + } + + public void setDepth(int depth) + { + this.depth = depth; + } + + public String toString() + { + return signalExpr + "." + depth; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/DriveSampleDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/DriveSampleDecl.java new file mode 100644 index 0000000..fcbd6e4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/DriveSampleDecl.java @@ -0,0 +1,99 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Signal drive/sample statement. + * + * @author Trevor Robinson + */ +public final class DriveSampleDecl + extends StatementDecl +{ + private ExpressionDecl delayExpr; + private ExpressionDecl destExpr; + private Operator operator; + private ExpressionDecl valueExpr; + private boolean soft = false; + private boolean async = false; + + public ExpressionDecl getDelayExpr() + { + return delayExpr; + } + + public void setDelayExpr(ExpressionDecl delayExpr) + { + this.delayExpr = delayExpr; + } + + public ExpressionDecl getDestExpr() + { + return destExpr; + } + + public void setDestExpr(ExpressionDecl destExpr) + { + this.destExpr = destExpr; + } + + public Operator getOperator() + { + return operator; + } + + public void setOperator(Operator operator) + { + this.operator = operator; + } + + public ExpressionDecl getValueExpr() + { + return valueExpr; + } + + public void setValueExpr(ExpressionDecl valueExpr) + { + this.valueExpr = valueExpr; + } + + public boolean isSoft() + { + return soft; + } + + public void setSoft(boolean soft) + { + this.soft = soft; + } + + public boolean isAsync() + { + return async; + } + + public void setAsync(boolean async) + { + this.async = async; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/DummyDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/DummyDecl.java new file mode 100644 index 0000000..b631c2c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/DummyDecl.java @@ -0,0 +1,33 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Temporary source object used to accumulate metadata before the actual + * source object type has been determined. + * + * @author Trevor Robinson + */ +public final class DummyDecl + extends VeraSourceObjectImpl +{ + public void accept(VeraSourceVisitor visitor) + { + throw new UnsupportedOperationException(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/EnumDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/EnumDecl.java new file mode 100644 index 0000000..ce56f8e --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/EnumDecl.java @@ -0,0 +1,59 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Enum declaration. + * + * @author Trevor Robinson + */ +public final class EnumDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember, ClassDeclMember +{ + private String identifier; + private List elements = new LinkedList(); // List + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public void addElement(EnumElementDecl elem) + { + elements.add(elem); + } + + public List getElements() + { + return elements; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/EnumElementDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/EnumElementDecl.java new file mode 100644 index 0000000..b0664f3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/EnumElementDecl.java @@ -0,0 +1,77 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enum element declaration. + * + * @author Trevor Robinson + */ +public final class EnumElementDecl + extends VeraSourceObjectImpl +{ + private String identifier; + private ExpressionDecl value; + private ExpressionDecl firstSuffix; + private ExpressionDecl lastSuffix; + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public ExpressionDecl getValue() + { + return value; + } + + public void setValue(ExpressionDecl value) + { + this.value = value; + } + + public ExpressionDecl getFirstSuffix() + { + return firstSuffix; + } + + public void setFirstSuffix(ExpressionDecl firstSuffix) + { + this.firstSuffix = firstSuffix; + } + + public ExpressionDecl getLastSuffix() + { + return lastSuffix; + } + + public void setLastSuffix(ExpressionDecl lastSuffix) + { + this.lastSuffix = lastSuffix; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExpectDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExpectDecl.java new file mode 100644 index 0000000..b7780be --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExpectDecl.java @@ -0,0 +1,115 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.vera.VeraExpectKind; + +/** + * Expect statement. + * + * @author Trevor Robinson + */ +public final class ExpectDecl + extends StatementDecl +{ + private VeraExpectKind expectKind = VeraExpectKind.SIMPLE; + private ExpressionDecl delayExpr; + private ExpressionDecl windowExpr; + private final List expectExprs = new LinkedList(); // List + private boolean expectAll = true; + private boolean soft = false; + private boolean async = false; + + public VeraExpectKind getExpectKind() + { + return expectKind; + } + + public void setExpectKind(VeraExpectKind expectKind) + { + this.expectKind = expectKind; + } + + public ExpressionDecl getDelayExpr() + { + return delayExpr; + } + + public void setDelayExpr(ExpressionDecl delayExpr) + { + this.delayExpr = delayExpr; + } + + public ExpressionDecl getWindowExpr() + { + return windowExpr; + } + + public void setWindowExpr(ExpressionDecl windowExpr) + { + this.windowExpr = windowExpr; + } + + public void addExpectExpr(ExpectExprDecl expr) + { + expectExprs.add(expr); + } + + public List getExpectExprs() + { + return expectExprs; + } + + public boolean isExpectAll() + { + return expectAll; + } + + public void setExpectAll(boolean expectAll) + { + this.expectAll = expectAll; + } + + public boolean isSoft() + { + return soft; + } + + public void setSoft(boolean soft) + { + this.soft = soft; + } + + public boolean isAsync() + { + return async; + } + + public void setAsync(boolean async) + { + this.async = async; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExpectExprDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExpectExprDecl.java new file mode 100644 index 0000000..27066d3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExpectExprDecl.java @@ -0,0 +1,67 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Expect statement expression. + * + * @author Trevor Robinson + */ +public final class ExpectExprDecl + extends VeraSourceObjectImpl +{ + private ExpressionDecl signalExpr; + private Operator operator; + private ExpressionDecl valueExpr; + + public ExpressionDecl getSignalExpr() + { + return signalExpr; + } + + public void setSignalExpr(ExpressionDecl signalExpr) + { + this.signalExpr = signalExpr; + } + + public Operator getOperator() + { + return operator; + } + + public void setOperator(Operator operator) + { + assert (operator == Operator.EQUAL || operator == Operator.NOT_EQUAL); + this.operator = operator; + } + + public ExpressionDecl getValueExpr() + { + return valueExpr; + } + + public void setValueExpr(ExpressionDecl valueExpr) + { + this.valueExpr = valueExpr; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExpressionDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExpressionDecl.java new file mode 100644 index 0000000..0ef3e74 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExpressionDecl.java @@ -0,0 +1,55 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.io.IndentPrintWriter; +import com.newisys.parser.util.MacroRef; + +/** + * Base class for expressions. + * + * @author Trevor Robinson + */ +public abstract class ExpressionDecl + extends VeraSourceObjectImpl + implements MacroDecl +{ + private MacroRef firstRef; + private MacroRef lastRef; + + public MacroRef getFirstExpandedFrom() + { + return firstRef; + } + + public MacroRef getLastExpandedFrom() + { + return lastRef; + } + + public void setExpandedFrom(MacroRef firstRef, MacroRef lastRef) + { + this.firstRef = firstRef; + this.lastRef = lastRef; + } + + protected void dumpContents(IndentPrintWriter out) + { + out.println(toString()); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExpressionStatementDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExpressionStatementDecl.java new file mode 100644 index 0000000..250de75 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExpressionStatementDecl.java @@ -0,0 +1,49 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Expression statement. + * + * @author Trevor Robinson + */ +public final class ExpressionStatementDecl + extends StatementDecl +{ + private ExpressionDecl expr; + + public ExpressionDecl getExpr() + { + return expr; + } + + public void setExpr(ExpressionDecl expr) + { + this.expr = expr; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return expr + ";"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExtConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExtConstraintDecl.java new file mode 100644 index 0000000..46d5b40 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExtConstraintDecl.java @@ -0,0 +1,45 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Extern class constraint declaration. + * + * @author Trevor Robinson + */ +public final class ExtConstraintDecl + extends NamedConstraintDecl + implements CompilationUnitDeclMember +{ + private String classIdentifier; + + public String getClassIdentifier() + { + return classIdentifier; + } + + public void setClassIdentifier(String classIdentifier) + { + this.classIdentifier = classIdentifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ExternVarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ExternVarDecl.java new file mode 100644 index 0000000..3958516 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ExternVarDecl.java @@ -0,0 +1,33 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Extern variable declaration. + * + * @author Trevor Robinson + */ +public final class ExternVarDecl + extends AbsVarDecl + implements CompilationUnitDeclMember +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/FixedArrayTypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/FixedArrayTypeRef.java new file mode 100644 index 0000000..8731fb3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/FixedArrayTypeRef.java @@ -0,0 +1,67 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Fixed array type reference. + * + * @author Trevor Robinson + */ +public final class FixedArrayTypeRef + extends ArrayTypeRef +{ + private List dimensions; // List + + public FixedArrayTypeRef(TypeRef elementTypeRef) + { + super(ArrayKind.FIXED, elementTypeRef); + this.dimensions = new LinkedList(); + } + + public List getDimensions() + { + return dimensions; + } + + public void addDimension(ExpressionDecl expr) + { + dimensions.add(expr); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(elementTypeRef.toString()); + Iterator iter = dimensions.iterator(); + while (iter.hasNext()) + { + buf.append('['); + buf.append(iter.next()); + buf.append(']'); + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ForDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ForDecl.java new file mode 100644 index 0000000..ce2d186 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ForDecl.java @@ -0,0 +1,54 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * For loop. + * + * @author Trevor Robinson + */ +public final class ForDecl + extends LoopDecl +{ + private List initExprs; // List + private List updateExprs; // List + + public ForDecl() + { + initExprs = new LinkedList(); + updateExprs = new LinkedList(); + } + + public List getInitExprs() + { + return initExprs; + } + + public List getUpdateExprs() + { + return updateExprs; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ForkJoinDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ForkJoinDecl.java new file mode 100644 index 0000000..d1f7986 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ForkJoinDecl.java @@ -0,0 +1,82 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.JoinKind; + +/** + * Fork/join statement. + * + * @author Trevor Robinson + */ +public final class ForkJoinDecl + extends StatementDecl +{ + private final List statements; // List + private JoinKind joinKind; + + public ForkJoinDecl() + { + statements = new LinkedList(); + joinKind = JoinKind.ALL; + } + + public void addStatement(StatementDecl stmt) + { + statements.add(stmt); + } + + public List getStatements() + { + return statements; + } + + public JoinKind getJoinKind() + { + return joinKind; + } + + public void setJoinKind(JoinKind joinKind) + { + this.joinKind = joinKind; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append("fork "); + Iterator iter = statements.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + buf.append(' '); + } + buf.append("join "); + buf.append(joinKind); + return buf.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/FuncCallDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/FuncCallDecl.java new file mode 100644 index 0000000..f0f8a31 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/FuncCallDecl.java @@ -0,0 +1,84 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Function call expression. + * + * @author Trevor Robinson + */ +public final class FuncCallDecl + extends ExpressionDecl +{ + private ExpressionDecl function; + private List arguments; // List + private ConstraintDecl constraints; + + public FuncCallDecl(ExpressionDecl function) + { + this.function = function; + this.arguments = new LinkedList(); + } + + public ExpressionDecl getFunction() + { + return function; + } + + public List getArguments() + { + return arguments; + } + + public ConstraintDecl getConstraints() + { + return constraints; + } + + public void setConstraints(ConstraintDecl constraints) + { + this.constraints = constraints; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append(function); + buf.append('('); + Iterator iter = arguments.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) + { + buf.append(','); + } + } + buf.append(')'); + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/FuncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/FuncDecl.java new file mode 100644 index 0000000..622732e --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/FuncDecl.java @@ -0,0 +1,56 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Function declaration. + * + * @author Trevor Robinson + */ +public final class FuncDecl + extends VeraFuncDecl + implements CompilationUnitDeclMember +{ + private boolean local; + private String classIdentifier; + + public boolean isLocal() + { + return local; + } + + public void setLocal(boolean local) + { + this.local = local; + } + + public String getClassIdentifier() + { + return classIdentifier; + } + + public void setClassIdentifier(String classIdentifier) + { + this.classIdentifier = classIdentifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/GlobalVarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/GlobalVarDecl.java new file mode 100644 index 0000000..dd465f3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/GlobalVarDecl.java @@ -0,0 +1,32 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Global variable declaration. + * + * @author Trevor Robinson + */ +public final class GlobalVarDecl + extends VarDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/HDLTaskDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/HDLTaskDecl.java new file mode 100644 index 0000000..9b6155c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/HDLTaskDecl.java @@ -0,0 +1,49 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * HDL task declaration. + * + * @author Trevor Robinson + */ +public final class HDLTaskDecl + extends AbsFuncDecl + implements CompilationUnitDeclMember +{ + private String instPath; + + public HDLTaskDecl() + { + } + + public String getInstPath() + { + return instPath; + } + + public void setInstPath(String instPath) + { + this.instPath = instPath; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/IfElseConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/IfElseConstraintDecl.java new file mode 100644 index 0000000..a11e853 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/IfElseConstraintDecl.java @@ -0,0 +1,80 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * If-else constraint expression. + * + * @author Trevor Robinson + */ +public final class IfElseConstraintDecl + extends ExpressionDecl +{ + private ExpressionDecl ifExpr; + private ExpressionDecl thenExpr; + private ExpressionDecl elseExpr; + + public IfElseConstraintDecl( + ExpressionDecl ifExpr, + ExpressionDecl thenExpr, + ExpressionDecl elseExpr) + { + this.ifExpr = ifExpr; + this.thenExpr = thenExpr; + this.elseExpr = elseExpr; + } + + public ExpressionDecl getIfExpr() + { + return ifExpr; + } + + public ExpressionDecl getThenExpr() + { + return thenExpr; + } + + public ExpressionDecl getElseExpr() + { + return elseExpr; + } + + public void setElseExpr(ExpressionDecl elseExpr) + { + this.elseExpr = elseExpr; + } + + public String toString() + { + StringBuffer buf = new StringBuffer("if ("); + buf.append(ifExpr); + buf.append(") "); + buf.append(thenExpr); + if (elseExpr != null) + { + buf.append(" else "); + buf.append(elseExpr); + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/IfElseDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/IfElseDecl.java new file mode 100644 index 0000000..6da5620 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/IfElseDecl.java @@ -0,0 +1,81 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * If-else statement. + * + * @author Trevor Robinson + */ +public final class IfElseDecl + extends StatementDecl +{ + private ExpressionDecl ifExpr; + private StatementDecl thenStatement; + private StatementDecl elseStatement; + + public ExpressionDecl getIfExpr() + { + return ifExpr; + } + + public void setIfExpr(ExpressionDecl ifExpr) + { + this.ifExpr = ifExpr; + } + + public StatementDecl getThenStatement() + { + return thenStatement; + } + + public void setThenStatement(StatementDecl thenStatement) + { + this.thenStatement = thenStatement; + } + + public StatementDecl getElseStatement() + { + return elseStatement; + } + + public void setElseStatement(StatementDecl elseStatement) + { + this.elseStatement = elseStatement; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append("if ("); + buf.append(ifExpr); + buf.append(") "); + buf.append(thenStatement); + if (elseStatement != null) + { + buf.append(" else "); + buf.append(elseStatement); + } + return buf.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ImplicationConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ImplicationConstraintDecl.java new file mode 100644 index 0000000..bcafdb9 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ImplicationConstraintDecl.java @@ -0,0 +1,58 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Implication constraint expression. + * + * @author Trevor Robinson + */ +public final class ImplicationConstraintDecl + extends ExpressionDecl +{ + private ExpressionDecl predicateExpr; + private ExpressionDecl constraintExpr; + + public ImplicationConstraintDecl( + ExpressionDecl predicateExpr, + ExpressionDecl constraintExpr) + { + this.predicateExpr = predicateExpr; + this.constraintExpr = constraintExpr; + } + + public ExpressionDecl getPredicateExpr() + { + return predicateExpr; + } + + public ExpressionDecl getConstraintExpr() + { + return constraintExpr; + } + + public String toString() + { + return predicateExpr + " => " + constraintExpr; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/IntegerLiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/IntegerLiteralDecl.java new file mode 100644 index 0000000..3e98397 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/IntegerLiteralDecl.java @@ -0,0 +1,82 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Integer literal expression. + * + * @author Trevor Robinson + */ +public final class IntegerLiteralDecl + extends LiteralDecl +{ + private int value; + + public IntegerLiteralDecl(int value) + { + super(LiteralKind.INTEGER); + this.value = value; + } + + public int getValue() + { + return value; + } + + public void setValue(int value) + { + this.value = value; + } + + public String toString() + { + return String.valueOf(value); + } + + public static int parse(String src) + { + int value = 0; + int len = src.length(); + for (int i = 0; i < len; ++i) + { + char c = src.charAt(i); + if (c == '_') continue; + + int digit = Character.digit(c, 10); + if (digit < 0) + { + throw new NumberFormatException("Invalid digit in '" + src + + "'"); + } + + int prevValue = value; + value = value * 10 + digit; + if (value < prevValue) + { + throw new NumberFormatException("Integer overflow for '" + src + + "'"); + } + } + return value; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/InterfaceDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/InterfaceDecl.java new file mode 100644 index 0000000..09621d4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/InterfaceDecl.java @@ -0,0 +1,59 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Signal interface declaration. + * + * @author Trevor Robinson + */ +public final class InterfaceDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + private final List signals = new LinkedList(); // List + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public void addSignal(SignalDecl signal) + { + signals.add(signal); + } + + public List getSignals() + { + return signals; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/LiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/LiteralDecl.java new file mode 100644 index 0000000..a6180fd --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/LiteralDecl.java @@ -0,0 +1,44 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Base class for literal expressions. + * + * @author Trevor Robinson + */ +public abstract class LiteralDecl + extends ExpressionDecl +{ + private LiteralKind literalKind; + + public LiteralDecl(LiteralKind literalKind) + { + this.literalKind = literalKind; + } + + public final LiteralKind getLiteralKind() + { + return literalKind; + } + + public String toString() + { + return literalKind.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/LiteralKind.java b/java/vera-parser/src/com/newisys/langsource/vera/LiteralKind.java new file mode 100644 index 0000000..fa207fd --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/LiteralKind.java @@ -0,0 +1,44 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of kinds of literal expressions. + * + * @author Trevor Robinson + */ +public final class LiteralKind +{ + private final String str; + + private LiteralKind(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final LiteralKind STRING = new LiteralKind("string"); + public static final LiteralKind INTEGER = new LiteralKind("integer"); + public static final LiteralKind BIT_VECTOR = new LiteralKind("bit[?:0]"); + public static final LiteralKind NULL = new LiteralKind("null"); + public static final LiteralKind VOID = new LiteralKind("void"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/LocalVarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/LocalVarDecl.java new file mode 100644 index 0000000..e936756 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/LocalVarDecl.java @@ -0,0 +1,52 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Collection; +import java.util.LinkedList; + +/** + * Local variable declaration. + * + * @author Trevor Robinson + */ +public final class LocalVarDecl + extends VarDecl +{ + private Collection modifiers; // Collection + + public LocalVarDecl() + { + this.modifiers = new LinkedList(); + } + + public void addModifier(LocalVarModifier mod) + { + modifiers.add(mod); + } + + public Collection getModifiers() + { + return modifiers; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/LocalVarModifier.java b/java/vera-parser/src/com/newisys/langsource/vera/LocalVarModifier.java new file mode 100644 index 0000000..f7992ee --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/LocalVarModifier.java @@ -0,0 +1,41 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of local variable modifiers. + * + * @author Trevor Robinson + */ +public final class LocalVarModifier +{ + private final String str; + + private LocalVarModifier(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final LocalVarModifier STATIC = new LocalVarModifier("static"); + public static final LocalVarModifier SHADOW = new LocalVarModifier("shadow"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/LoopDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/LoopDecl.java new file mode 100644 index 0000000..13af85a --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/LoopDecl.java @@ -0,0 +1,50 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Base class for loop statements. + * + * @author Trevor Robinson + */ +public abstract class LoopDecl + extends StatementDecl +{ + private ExpressionDecl condition; + private StatementDecl statement; + + public ExpressionDecl getCondition() + { + return condition; + } + + public void setCondition(ExpressionDecl condition) + { + this.condition = condition; + } + + public StatementDecl getStatement() + { + return statement; + } + + public void setStatement(StatementDecl statement) + { + this.statement = statement; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/MacroDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/MacroDecl.java new file mode 100644 index 0000000..00b6674 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/MacroDecl.java @@ -0,0 +1,35 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.parser.util.MacroRef; + +/** + * Interface implemented by source object that can be directly expanded from + * macros. + * + * @author Trevor Robinson + */ +public interface MacroDecl +{ + MacroRef getFirstExpandedFrom(); + + MacroRef getLastExpandedFrom(); + + void setExpandedFrom(MacroRef firstRef, MacroRef lastRef); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/MemberAccessDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/MemberAccessDecl.java new file mode 100644 index 0000000..25c54db --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/MemberAccessDecl.java @@ -0,0 +1,71 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Member access expression. + * + * @author Trevor Robinson + */ +public final class MemberAccessDecl + extends ExpressionDecl +{ + private ExpressionDecl objectExpr; + private String identifier; + + public MemberAccessDecl(ExpressionDecl objectExpr) + { + this.objectExpr = objectExpr; + } + + public MemberAccessDecl(ExpressionDecl objectExpr, String identifier) + { + this.objectExpr = objectExpr; + this.identifier = identifier; + } + + public ExpressionDecl getObjectExpr() + { + return objectExpr; + } + + public void setObjectExpr(ExpressionDecl object) + { + this.objectExpr = object; + } + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public String toString() + { + return objectExpr + "." + identifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/NamedConstraintDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/NamedConstraintDecl.java new file mode 100644 index 0000000..0bb31f8 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/NamedConstraintDecl.java @@ -0,0 +1,39 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Named random constraint declaration. + * + * @author Trevor Robinson + */ +public abstract class NamedConstraintDecl + extends ConstraintDecl +{ + private String identifier; + + public final String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/NewArrayDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/NewArrayDecl.java new file mode 100644 index 0000000..269dcee --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/NewArrayDecl.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Array creation expression. + * + * @author Trevor Robinson + */ +public final class NewArrayDecl + extends ExpressionDecl +{ + ExpressionDecl sizeExpr; + ExpressionDecl sourceExpr; + + public NewArrayDecl(ExpressionDecl sizeExpr) + { + this.sizeExpr = sizeExpr; + } + + public ExpressionDecl getSizeExpr() + { + return sizeExpr; + } + + public ExpressionDecl getSourceExpr() + { + return sourceExpr; + } + + public void setSourceExpr(ExpressionDecl sourceExpr) + { + this.sourceExpr = sourceExpr; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append("new ["); + buf.append(sizeExpr); + buf.append(']'); + if (sourceExpr != null) + { + buf.append(" ("); + buf.append(sourceExpr); + buf.append(')'); + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/NewCopyDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/NewCopyDecl.java new file mode 100644 index 0000000..a6478a8 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/NewCopyDecl.java @@ -0,0 +1,58 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Copy creation expression. + * + * @author Trevor Robinson + */ +public final class NewCopyDecl + extends ExpressionDecl +{ + ExpressionDecl sourceExpr; + + public NewCopyDecl() + { + } + + public NewCopyDecl(ExpressionDecl sourceExpr) + { + this.sourceExpr = sourceExpr; + } + + public ExpressionDecl getSourceExpr() + { + return sourceExpr; + } + + public void setSourceExpr(ExpressionDecl sourceExpr) + { + this.sourceExpr = sourceExpr; + } + + public String toString() + { + return "new " + sourceExpr; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/NewDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/NewDecl.java new file mode 100644 index 0000000..40a0ce7 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/NewDecl.java @@ -0,0 +1,65 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Instance creation expression. + * + * @author Trevor Robinson + */ +public final class NewDecl + extends ExpressionDecl +{ + private List arguments; // List + + public NewDecl() + { + this.arguments = new LinkedList(); + } + + public List getArguments() + { + return arguments; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append("new("); + Iterator iter = arguments.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) + { + buf.append(','); + } + } + buf.append(')'); + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/NullLiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/NullLiteralDecl.java new file mode 100644 index 0000000..8fa7e3c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/NullLiteralDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Null literal expression. + * + * @author Trevor Robinson + */ +public final class NullLiteralDecl + extends LiteralDecl +{ + public NullLiteralDecl() + { + super(LiteralKind.NULL); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/OperationDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/OperationDecl.java new file mode 100644 index 0000000..28797ee --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/OperationDecl.java @@ -0,0 +1,154 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Operation expression. + * + * @author Trevor Robinson + */ +public final class OperationDecl + extends ExpressionDecl +{ + private Operator operator; + private final List operands = new LinkedList(); // List + + public OperationDecl() + { + } + + public OperationDecl(Operator operator) + { + this.operator = operator; + } + + public OperationDecl(Operator operator, ExpressionDecl op1) + { + this(operator); + operands.add(op1); + } + + public OperationDecl( + Operator operator, + ExpressionDecl op1, + ExpressionDecl op2) + { + this(operator); + operands.add(op1); + operands.add(op2); + } + + public OperationDecl( + Operator operator, + ExpressionDecl op1, + ExpressionDecl op2, + ExpressionDecl op3) + { + this(operator); + operands.add(op1); + operands.add(op2); + operands.add(op3); + } + + public Operator getOperator() + { + return operator; + } + + public void setOperator(Operator operator) + { + this.operator = operator; + } + + public void addOperand(ExpressionDecl op) + { + operands.add(op); + } + + public List getOperands() + { + return operands; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + if (operator == Operator.CONDITIONAL) + { + assert (operands.size() == 3); + buf.append(operands.get(0)); + buf.append('?'); + buf.append(operands.get(1)); + buf.append(':'); + buf.append(operands.get(2)); + } + else if (operator == Operator.CONCATENATION) + { + buf.append('{'); + Iterator iter = operands.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) + { + buf.append(','); + } + } + buf.append('}'); + } + else if (operator == Operator.REPLICATION) + { + assert (operands.size() == 2); + buf.append('{'); + buf.append(operands.get(0)); + buf.append(operands.get(1)); + buf.append('}'); + } + else + { + OperatorPosition pos = operator.getPosition(); + if (pos == OperatorPosition.PREFIX) + { + buf.append(operator); + } + Iterator iter = operands.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (pos == OperatorPosition.INFIX && iter.hasNext()) + { + buf.append(operator); + } + } + if (pos == OperatorPosition.POSTFIX) + { + buf.append(operator); + } + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/Operator.java b/java/vera-parser/src/com/newisys/langsource/vera/Operator.java new file mode 100644 index 0000000..c765a63 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/Operator.java @@ -0,0 +1,122 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of operators. + * + * @author Trevor Robinson + */ +public final class Operator +{ + private final String str; + private final OperatorPosition position; + + private Operator(String str) + { + this.str = str; + this.position = OperatorPosition.INFIX; + } + + public Operator(String str, boolean prefix) + { + this.str = str; + this.position = prefix ? OperatorPosition.PREFIX + : OperatorPosition.POSTFIX; + } + + public OperatorPosition getPosition() + { + return position; + } + + public String toString() + { + return str; + } + + // n-ary operators + public static final Operator CONCATENATION = new Operator("{X,X}"); + + // tertiary operators + public static final Operator CONDITIONAL = new Operator("?:"); + + // binary operators + public static final Operator LOGICAL_OR = new Operator("||"); + public static final Operator LOGICAL_AND = new Operator("&&"); + public static final Operator BITWISE_OR = new Operator("|"); + public static final Operator BITWISE_NOR = new Operator("|~"); + public static final Operator BITWISE_XOR = new Operator("^"); + public static final Operator BITWISE_XNOR = new Operator("^~"); + public static final Operator BITWISE_AND = new Operator("&"); + public static final Operator BITWISE_NAND = new Operator("&~"); + public static final Operator EQUAL = new Operator("=="); + public static final Operator NOT_EQUAL = new Operator("!="); + public static final Operator EXACT_EQUAL = new Operator("==="); + public static final Operator EXACT_NOT_EQUAL = new Operator("!=="); + public static final Operator WILD_EQUAL = new Operator("=?="); + public static final Operator WILD_NOT_EQUAL = new Operator("!?="); + public static final Operator LESS = new Operator("<"); + public static final Operator LESS_OR_EQUAL = new Operator("<="); + public static final Operator GREATER = new Operator(">"); + public static final Operator GREATER_OR_EQUAL = new Operator(">="); + public static final Operator IN = new Operator("in"); + public static final Operator NOT_IN = new Operator("!in"); + public static final Operator DIST = new Operator("dist"); + public static final Operator LEFT_SHIFT = new Operator("<<"); + public static final Operator RIGHT_SHIFT = new Operator(">>"); + public static final Operator ADD = new Operator("+"); + public static final Operator SUBTRACT = new Operator("-"); + public static final Operator MULTIPLY = new Operator("*"); + public static final Operator DIVIDE = new Operator("/"); + public static final Operator MODULO = new Operator("%"); + public static final Operator REPLICATION = new Operator("{N{X}}"); + + // (binary) assignment operators + public static final Operator ASSIGN = new Operator("="); + public static final Operator NONBLOCKING_ASSIGN = new Operator("<="); + public static final Operator ADD_ASSIGN = new Operator("+="); + public static final Operator SUBTRACT_ASSIGN = new Operator("-="); + public static final Operator MULTIPLY_ASSIGN = new Operator("*="); + public static final Operator DIVIDE_ASSIGN = new Operator("/="); + public static final Operator MODULO_ASSIGN = new Operator("%="); + public static final Operator LEFT_SHIFT_ASSIGN = new Operator("<<="); + public static final Operator RIGHT_SHIFT_ASSIGN = new Operator(">>="); + public static final Operator AND_ASSIGN = new Operator("&="); + public static final Operator OR_ASSIGN = new Operator("|="); + public static final Operator XOR_ASSIGN = new Operator("^="); + public static final Operator NAND_ASSIGN = new Operator("~&="); + public static final Operator NOR_ASSIGN = new Operator("~|="); + public static final Operator XNOR_ASSIGN = new Operator("~^="); + + // unary operators + public static final Operator NEGATIVE = new Operator("-", true); + public static final Operator LOGICAL_NEGATIVE = new Operator("!", true); + public static final Operator BITWISE_NEGATIVE = new Operator("~", true); + public static final Operator AND_REDUCTION = new Operator("&", true); + public static final Operator NAND_REDUCTION = new Operator("~&", true); + public static final Operator OR_REDUCTION = new Operator("|", true); + public static final Operator NOR_REDUCTION = new Operator("~|", true); + public static final Operator XOR_REDUCTION = new Operator("^", true); + public static final Operator XNOR_REDUCTION = new Operator("~^", true); + public static final Operator BITWISE_REVERSE = new Operator("><", true); + public static final Operator PRE_INCREMENT = new Operator("++", true); + public static final Operator PRE_DECREMENT = new Operator("--", true); + public static final Operator POST_INCREMENT = new Operator("++", false); + public static final Operator POST_DECREMENT = new Operator("--", false); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/OperatorPosition.java b/java/vera-parser/src/com/newisys/langsource/vera/OperatorPosition.java new file mode 100644 index 0000000..02d3fe4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/OperatorPosition.java @@ -0,0 +1,43 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of operator positions. + * + * @author Trevor Robinson + */ +public final class OperatorPosition +{ + private final String str; + + private OperatorPosition(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final OperatorPosition PREFIX = new OperatorPosition("prefix"); + public static final OperatorPosition INFIX = new OperatorPosition("infix"); + public static final OperatorPosition POSTFIX = new OperatorPosition( + "postfix"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ParamDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ParamDecl.java new file mode 100644 index 0000000..ed16442 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ParamDecl.java @@ -0,0 +1,66 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Function parameter declaration. + * + * @author Trevor Robinson + */ +public final class ParamDecl + extends AbsVarDecl +{ + private boolean byRef; + private ExpressionDecl defaultExpr; + private int optLevel; + + public boolean isByRef() + { + return byRef; + } + + public void setByRef(boolean byRef) + { + this.byRef = byRef; + } + + public ExpressionDecl getDefaultExpr() + { + return defaultExpr; + } + + public void setDefaultExpr(ExpressionDecl defaultExpr) + { + this.defaultExpr = defaultExpr; + } + + public int getOptLevel() + { + return optLevel; + } + + public void setOptLevel(int optLevel) + { + this.optLevel = optLevel; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/PortDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/PortDecl.java new file mode 100644 index 0000000..b2fed24 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/PortDecl.java @@ -0,0 +1,59 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Signal port declaration. + * + * @author Trevor Robinson + */ +public final class PortDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + private final List members = new LinkedList(); // List + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public void addMember(String member) + { + members.add(member); + } + + public List getMembers() + { + return members; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/PragmaDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/PragmaDecl.java new file mode 100644 index 0000000..a8def03 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/PragmaDecl.java @@ -0,0 +1,45 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Preprocessor #pragma. + * + * @author Trevor Robinson + */ +public final class PragmaDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String text; + + public PragmaDecl(String text) + { + this.text = text; + } + + public String getText() + { + return text; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/PrimitiveTypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/PrimitiveTypeRef.java new file mode 100644 index 0000000..95de5cc --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/PrimitiveTypeRef.java @@ -0,0 +1,52 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.vera.VeraPrimitiveKind; + +/** + * Primitive type reference. + * + * @author Trevor Robinson + */ +public class PrimitiveTypeRef + extends TypeRef +{ + private VeraPrimitiveKind primitiveKind; + + public PrimitiveTypeRef(VeraPrimitiveKind primitiveKind) + { + super(TypeRefKind.PRIMITIVE); + this.primitiveKind = primitiveKind; + } + + public final VeraPrimitiveKind getPrimitiveKind() + { + return primitiveKind; + } + + public String toString() + { + return primitiveKind.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ProgramDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ProgramDecl.java new file mode 100644 index 0000000..733ea36 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ProgramDecl.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Program block. + * + * @author Trevor Robinson + */ +public final class ProgramDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + private final List globalVars = new LinkedList(); // List + private final List statements = new LinkedList(); // List + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public void addGlobalVar(GlobalVarDecl var) + { + globalVars.add(var); + } + + public List getGlobalVars() + { + return globalVars; + } + + public void addStatement(StatementDecl stmt) + { + statements.add(stmt); + } + + public List getStatements() + { + return statements; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RandCaseDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/RandCaseDecl.java new file mode 100644 index 0000000..9b75cb5 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RandCaseDecl.java @@ -0,0 +1,52 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Randcase statement. + * + * @author Trevor Robinson + */ +public final class RandCaseDecl + extends StatementDecl +{ + private List caseMembers; // List + + public RandCaseDecl() + { + this.caseMembers = new LinkedList(); + } + + public void addCaseMember(RandCaseMemberDecl member) + { + caseMembers.add(member); + } + + public List getCaseMembers() + { + return caseMembers; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RandCaseMemberDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/RandCaseMemberDecl.java new file mode 100644 index 0000000..ae8aa88 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RandCaseMemberDecl.java @@ -0,0 +1,55 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Randcase statement member. + * + * @author Trevor Robinson + */ +public final class RandCaseMemberDecl + extends VeraSourceObjectImpl +{ + private ExpressionDecl weightExpr; + private StatementDecl statementDecl; + + public ExpressionDecl getWeightExpr() + { + return weightExpr; + } + + public void setWeightExpr(ExpressionDecl weightExpr) + { + this.weightExpr = weightExpr; + } + + public StatementDecl getStatementDecl() + { + return statementDecl; + } + + public void setStatementDecl(StatementDecl statementDecl) + { + this.statementDecl = statementDecl; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RandMode.java b/java/vera-parser/src/com/newisys/langsource/vera/RandMode.java new file mode 100644 index 0000000..d4cacd8 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RandMode.java @@ -0,0 +1,42 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Member variable randomization mode. + * + * @author Trevor Robinson + */ +public final class RandMode +{ + private final String str; + + private RandMode(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final RandMode RAND = new RandMode("rand"); + public static final RandMode RANDC = new RandMode("randc"); + public static final RandMode NON_RAND = new RandMode("non_rand"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RangeDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/RangeDecl.java new file mode 100644 index 0000000..afdf81b --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RangeDecl.java @@ -0,0 +1,81 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.parser.util.MacroRef; + +/** + * Bit or value range. + * + * @author Trevor Robinson + */ +public class RangeDecl + extends VeraSourceObjectImpl + implements MacroDecl +{ + protected ExpressionDecl from; + protected ExpressionDecl to; + private MacroRef firstRef; + private MacroRef lastRef; + + public final ExpressionDecl getFrom() + { + return from; + } + + public void setFrom(ExpressionDecl low) + { + this.from = low; + } + + public final ExpressionDecl getTo() + { + return to; + } + + public void setTo(ExpressionDecl high) + { + this.to = high; + } + + public MacroRef getFirstExpandedFrom() + { + return firstRef; + } + + public MacroRef getLastExpandedFrom() + { + return lastRef; + } + + public void setExpandedFrom(MacroRef firstRef, MacroRef lastRef) + { + this.firstRef = firstRef; + this.lastRef = lastRef; + } + + public String toString() + { + return (from == to) ? from.toString() : from + ":" + to; + } + + public void accept(VeraSourceVisitor visitor) + { + // do nothing + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RangeListDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/RangeListDecl.java new file mode 100644 index 0000000..cf1fac7 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RangeListDecl.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Value range list. + * + * @author Trevor Robinson + */ +public final class RangeListDecl + extends VeraSourceObjectImpl +{ + private List ranges; // List + + public RangeListDecl() + { + ranges = new LinkedList(); + } + + public void addRange(RangeDecl range) + { + ranges.add(range); + } + + public List getRanges() + { + return ranges; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append('{'); + Iterator iter = ranges.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) + { + buf.append(','); + } + } + buf.append('}'); + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + // do nothing + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/RepeatDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/RepeatDecl.java new file mode 100644 index 0000000..4dd8238 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/RepeatDecl.java @@ -0,0 +1,32 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Repeat loop. + * + * @author Trevor Robinson + */ +public final class RepeatDecl + extends LoopDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ReturnDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ReturnDecl.java new file mode 100644 index 0000000..1c78641 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ReturnDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Randcase statement. + * + * @author Trevor Robinson + */ +public final class ReturnDecl + extends StatementDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "return;"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SetOperationDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SetOperationDecl.java new file mode 100644 index 0000000..84f9929 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SetOperationDecl.java @@ -0,0 +1,82 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Set operation. + * + * @author Trevor Robinson + */ +public final class SetOperationDecl + extends ExpressionDecl +{ + private ExpressionDecl expr; + private Operator operator; + private RangeListDecl ranges; + + public SetOperationDecl(ExpressionDecl expr) + { + this.expr = expr; + } + + public SetOperationDecl(ExpressionDecl expr, Operator operator) + { + this.expr = expr; + this.operator = operator; + } + + public ExpressionDecl getExpr() + { + return expr; + } + + public void setExpr(ExpressionDecl expr) + { + this.expr = expr; + } + + public Operator getOperator() + { + return operator; + } + + public void setOperator(Operator operator) + { + this.operator = operator; + } + + public RangeListDecl getRanges() + { + return ranges; + } + + public void setRanges(RangeListDecl ranges) + { + this.ranges = ranges; + } + + public String toString() + { + return expr + " " + operator + " " + ranges; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SignalDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SignalDecl.java new file mode 100644 index 0000000..8fc78ec --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SignalDecl.java @@ -0,0 +1,163 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langschema.vera.VeraSignalDirection; +import com.newisys.langschema.vera.VeraSignalKind; +import com.newisys.langschema.vera.VeraVCAKind; +import com.newisys.langschema.vera.VeraVCAQValue; +import com.newisys.verilog.EdgeSet; + +/** + * Interface signal declaration. + * + * @author Trevor Robinson + */ +public final class SignalDecl + extends VeraSourceObjectImpl +{ + private VeraSignalDirection direction; + private ExpressionDecl highBitExpr; + private String identifier; + private VeraSignalKind kind; + private EdgeSet sampleEdges = EdgeSet.NO_EDGE; + private EdgeSet driveEdges = EdgeSet.NO_EDGE; + private final List skews = new LinkedList(); // List + private ExpressionDecl depthExpr; + private VeraVCAKind vcaKind = VeraVCAKind.NONE; + private VeraVCAQValue vcaQValue = VeraVCAQValue.HOLD; + private String hdlNode; + + public VeraSignalDirection getDirection() + { + return direction; + } + + public void setDirection(VeraSignalDirection direction) + { + this.direction = direction; + } + + public ExpressionDecl getHighBitExpr() + { + return highBitExpr; + } + + public void setHighBitExpr(ExpressionDecl highBitExpr) + { + this.highBitExpr = highBitExpr; + } + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public VeraSignalKind getKind() + { + return kind; + } + + public void setKind(VeraSignalKind kind) + { + this.kind = kind; + } + + public EdgeSet getSampleEdges() + { + return sampleEdges; + } + + public void setSampleEdges(EdgeSet sampleEdges) + { + this.sampleEdges = sampleEdges; + } + + public EdgeSet getDriveEdges() + { + return driveEdges; + } + + public void setDriveEdges(EdgeSet driveEdges) + { + this.driveEdges = driveEdges; + } + + public void addSkew(SignalSkewDecl skew) + { + skews.add(skew); + } + + public List getSkews() + { + return skews; + } + + public ExpressionDecl getDepthExpr() + { + return depthExpr; + } + + public void setDepthExpr(ExpressionDecl depthExpr) + { + this.depthExpr = depthExpr; + } + + public VeraVCAKind getVCAKind() + { + return vcaKind; + } + + public void setVCAKind(VeraVCAKind vcaKind) + { + this.vcaKind = vcaKind; + } + + public VeraVCAQValue getVCAQValue() + { + return vcaQValue; + } + + public void setVCAQValue(VeraVCAQValue vcaQValue) + { + this.vcaQValue = vcaQValue; + } + + public String getHDLNode() + { + return hdlNode; + } + + public void setHDLNode(String hdlNode) + { + this.hdlNode = hdlNode; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SignalRangeDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SignalRangeDecl.java new file mode 100644 index 0000000..212bbf9 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SignalRangeDecl.java @@ -0,0 +1,66 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Bind signal range. + * + * @author Trevor Robinson + */ +public final class SignalRangeDecl + extends VeraSourceObjectImpl +{ + private String interfaceIdentifier; + private String signalIdentifier; + private RangeDecl bitfield; + + public String getInterfaceIdentifier() + { + return interfaceIdentifier; + } + + public void setInterfaceIdentifier(String interfaceIdentifier) + { + this.interfaceIdentifier = interfaceIdentifier; + } + + public String getSignalIdentifier() + { + return signalIdentifier; + } + + public void setSignalIdentifier(String signalIdentifier) + { + this.signalIdentifier = signalIdentifier; + } + + public RangeDecl getBitfield() + { + return bitfield; + } + + public void setBitfield(RangeDecl bitfield) + { + this.bitfield = bitfield; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SignalSkewDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SignalSkewDecl.java new file mode 100644 index 0000000..5cc05b7 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SignalSkewDecl.java @@ -0,0 +1,69 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.vera.VeraSurrXTransition; + +/** + * Signal skew declaration. + * + * @author Trevor Robinson + */ +public final class SignalSkewDecl + extends VeraSourceObjectImpl +{ + private VeraSurrXTransition transitionKind; + private ExpressionDecl timeToXExpr; + private ExpressionDecl timeToValueExpr; + + public SignalSkewDecl(ExpressionDecl timeToValueExpr) + { + this.transitionKind = VeraSurrXTransition.ANY; + this.timeToValueExpr = timeToValueExpr; + } + + public SignalSkewDecl( + VeraSurrXTransition transitionKind, + ExpressionDecl timeToXExpr, + ExpressionDecl timeToValueExpr) + { + this.transitionKind = transitionKind; + this.timeToXExpr = timeToXExpr; + this.timeToValueExpr = timeToValueExpr; + } + + public VeraSurrXTransition getTransitionKind() + { + return transitionKind; + } + + public ExpressionDecl getTimeToXExpr() + { + return timeToXExpr; + } + + public ExpressionDecl getTimeToValueExpr() + { + return timeToValueExpr; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/StatementDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/StatementDecl.java new file mode 100644 index 0000000..65d7d4c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/StatementDecl.java @@ -0,0 +1,49 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.parser.util.MacroRef; + +/** + * Base class for statements. + * + * @author Trevor Robinson + */ +public abstract class StatementDecl + extends VeraSourceObjectImpl + implements MacroDecl +{ + private MacroRef firstRef; + private MacroRef lastRef; + + public MacroRef getFirstExpandedFrom() + { + return firstRef; + } + + public MacroRef getLastExpandedFrom() + { + return lastRef; + } + + public void setExpandedFrom(MacroRef firstRef, MacroRef lastRef) + { + this.firstRef = firstRef; + this.lastRef = lastRef; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/StringLiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/StringLiteralDecl.java new file mode 100644 index 0000000..cf9ea95 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/StringLiteralDecl.java @@ -0,0 +1,175 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * String literal expression. + * + * @author Trevor Robinson + */ +public final class StringLiteralDecl + extends LiteralDecl +{ + private String value; + + public StringLiteralDecl(String text) + { + super(LiteralKind.STRING); + this.value = text; + } + + public String getValue() + { + return value; + } + + public void setValue(String text) + { + this.value = text; + } + + public String toString() + { + return '"' + escape(value) + '"'; + } + + public static String parse(String src) + { + if (!src.startsWith("\"") || !src.endsWith("\"")) + { + throw new IllegalArgumentException( + "Double-quote delimited string expected"); + } + + // strip out escaped newlines + StringBuffer buf = new StringBuffer(); + int end = src.length() - 1; + for (int i = 1; i < end; ++i) + { + char c = src.charAt(i); + if (c == '\\' && i + 1 < end) + { + char c2 = src.charAt(i + 1); + if (c2 == '\n') + { + ++i; + continue; + } + else if (c2 == '\r') + { + ++i; + if (i + 1 < end && src.charAt(i + 1) == '\n') + { + ++i; + } + continue; + } + } + buf.append(c); + } + return buf.toString(); + } + + public static String unescape(String src) + { + StringBuffer buf = new StringBuffer(); + int end = src.length(); + for (int i = 0; i < end; ++i) + { + char c = src.charAt(i); + if (c == '\\' && ++i < end) + { + char c2 = src.charAt(i); + switch (c2) + { + case 'b': + c2 = 0x08; + break; + case 't': + c2 = 0x09; + break; + case 'n': + c2 = 0x0A; + break; + case 'f': + c2 = 0x0C; + break; + case 'r': + c2 = 0x0D; + break; + } + c = c2; + } + buf.append(c); + } + return buf.toString(); + } + + public static String escape(String src) + { + StringBuffer buf = new StringBuffer(); + int end = src.length(); + for (int i = 0; i < end; ++i) + { + char c = src.charAt(i); + switch (c) + { + case 0x08: + buf.append("\\b"); + break; + case 0x09: + buf.append("\\t"); + break; + case 0x0A: + buf.append("\\n"); + break; + case 0x0C: + buf.append("\\f"); + break; + case 0x0D: + buf.append("\\r"); + break; + case '"': + buf.append("\\\""); + break; + case '\\': + buf.append("\\\\"); + break; + default: + if (c < 0x20 || c >= 0x007F) + { + buf.append("\\u"); + buf.append(Character.forDigit((c >> 12) & 0xF, 16)); + buf.append(Character.forDigit((c >> 8) & 0xF, 16)); + buf.append(Character.forDigit((c >> 4) & 0xF, 16)); + buf.append(Character.forDigit((c >> 0) & 0xF, 16)); + } + else + { + buf.append(c); + } + } + } + return buf.toString(); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SuperRefDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SuperRefDecl.java new file mode 100644 index 0000000..3c78070 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SuperRefDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Super type reference expression. + * + * @author Trevor Robinson + */ +public final class SuperRefDecl + extends ExpressionDecl +{ + public String toString() + { + return "super"; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SyncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/SyncDecl.java new file mode 100644 index 0000000..58a33bf --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SyncDecl.java @@ -0,0 +1,51 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import java.util.LinkedList; +import java.util.List; + +/** + * Signal synchronization statement. + * + * @author Trevor Robinson + */ +public final class SyncDecl + extends StatementDecl +{ + private final List terms = new LinkedList(); + + public SyncDecl() + { + } + + public List getTerms() + { + return terms; + } + + public void addTerm(SyncTerm term) + { + terms.add(term); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SyncEdge.java b/java/vera-parser/src/com/newisys/langsource/vera/SyncEdge.java new file mode 100644 index 0000000..f438227 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SyncEdge.java @@ -0,0 +1,42 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of synchronization edges. + * + * @author Trevor Robinson + */ +public final class SyncEdge +{ + private final String str; + + private SyncEdge(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final SyncEdge ANYEDGE = new SyncEdge("anyedge"); + public static final SyncEdge POSEDGE = new SyncEdge("posedge"); + public static final SyncEdge NEGEDGE = new SyncEdge("negedge"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/SyncTerm.java b/java/vera-parser/src/com/newisys/langsource/vera/SyncTerm.java new file mode 100644 index 0000000..52b55f2 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/SyncTerm.java @@ -0,0 +1,79 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Synchronization statement term. + * + * @author Trevor Robinson + */ +public final class SyncTerm + extends VeraSourceObjectImpl +{ + private SyncEdge edge; + private ExpressionDecl signal; // null for CLOCK + private boolean async; + + public SyncTerm() + { + edge = SyncEdge.ANYEDGE; + async = false; + } + + public SyncTerm(SyncEdge edge, ExpressionDecl signal, boolean async) + { + this.edge = edge; + this.signal = signal; + this.async = async; + } + + public SyncEdge getEdge() + { + return edge; + } + + public void setEdge(SyncEdge edge) + { + this.edge = edge; + } + + public ExpressionDecl getSignal() + { + return signal; + } + + public void setSignal(ExpressionDecl signal) + { + this.signal = signal; + } + + public boolean isAsync() + { + return async; + } + + public void setAsync(boolean async) + { + this.async = async; + } + + public void accept(VeraSourceVisitor visitor) + { + // do nothing; visitor should handle terms in SyncDecl + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/TerminateDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/TerminateDecl.java new file mode 100644 index 0000000..fea43e2 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/TerminateDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Terminate statement. + * + * @author Trevor Robinson + */ +public final class TerminateDecl + extends StatementDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } + + public String toString() + { + return "terminate;"; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/ThisRefDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/ThisRefDecl.java new file mode 100644 index 0000000..8ada9f4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/ThisRefDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * This object reference expression. + * + * @author Trevor Robinson + */ +public final class ThisRefDecl + extends ExpressionDecl +{ + public String toString() + { + return "this"; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/TypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/TypeRef.java new file mode 100644 index 0000000..ba5a004 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/TypeRef.java @@ -0,0 +1,60 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.parser.util.MacroRef; + +/** + * Base class for type references. + * + * @author Trevor Robinson + */ +public abstract class TypeRef + extends VeraSourceObjectImpl + implements MacroDecl +{ + private TypeRefKind typeRefKind; + private MacroRef firstRef; + private MacroRef lastRef; + + public TypeRef(TypeRefKind typeRefKind) + { + this.typeRefKind = typeRefKind; + } + + public final TypeRefKind getTypeRefKind() + { + return typeRefKind; + } + + public MacroRef getFirstExpandedFrom() + { + return firstRef; + } + + public MacroRef getLastExpandedFrom() + { + return lastRef; + } + + public void setExpandedFrom(MacroRef firstRef, MacroRef lastRef) + { + this.firstRef = firstRef; + this.lastRef = lastRef; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/TypeRefKind.java b/java/vera-parser/src/com/newisys/langsource/vera/TypeRefKind.java new file mode 100644 index 0000000..691efe3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/TypeRefKind.java @@ -0,0 +1,42 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Enumeration of type reference kinds. + * + * @author Trevor Robinson + */ +public final class TypeRefKind +{ + private final String str; + + private TypeRefKind(String str) + { + this.str = str; + } + + public String toString() + { + return str; + } + + public static final TypeRefKind PRIMITIVE = new TypeRefKind("PRIMITIVE"); + public static final TypeRefKind USER = new TypeRefKind("USER"); + public static final TypeRefKind ARRAY = new TypeRefKind("ARRAY"); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/TypedefDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/TypedefDecl.java new file mode 100644 index 0000000..75b06c5 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/TypedefDecl.java @@ -0,0 +1,45 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Typedef declaration. + * + * @author Trevor Robinson + */ +public final class TypedefDecl + extends VeraSourceObjectImpl + implements CompilationUnitDeclMember +{ + private String identifier; + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/UDFFuncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/UDFFuncDecl.java new file mode 100644 index 0000000..cb65842 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/UDFFuncDecl.java @@ -0,0 +1,61 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * UDF function declaration. + * + * @author Trevor Robinson + */ +public final class UDFFuncDecl + extends AbsFuncDecl + implements CompilationUnitDeclMember +{ + private String language; + private boolean varArgs; + + public UDFFuncDecl() + { + setExtern(true); + } + + public String getLanguage() + { + return language; + } + + public void setLanguage(String language) + { + this.language = language; + } + + public boolean isVarArgs() + { + return varArgs; + } + + public void setVarArgs(boolean varArgs) + { + this.varArgs = varArgs; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/UserTypeRef.java b/java/vera-parser/src/com/newisys/langsource/vera/UserTypeRef.java new file mode 100644 index 0000000..aa29ec4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/UserTypeRef.java @@ -0,0 +1,54 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * User-defined type reference. + * + * @author Trevor Robinson + */ +public final class UserTypeRef + extends TypeRef +{ + private String identifier; + + public UserTypeRef() + { + super(TypeRefKind.USER); + } + + public String getIdentifier() + { + return identifier; + } + + public void setIdentifier(String identifier) + { + this.identifier = identifier; + } + + public String toString() + { + return identifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VarDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/VarDecl.java new file mode 100644 index 0000000..290c2d3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VarDecl.java @@ -0,0 +1,39 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Base class for variable declarations supporting an initializer. + * + * @author Trevor Robinson + */ +public abstract class VarDecl + extends AbsVarDecl +{ + private ExpressionDecl initExpr; + + public final ExpressionDecl getInitExpr() + { + return initExpr; + } + + public final void setInitExpr(ExpressionDecl initExpr) + { + this.initExpr = initExpr; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VarRefDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/VarRefDecl.java new file mode 100644 index 0000000..65ef77d --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VarRefDecl.java @@ -0,0 +1,73 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Variable reference expression. + * + * @author Trevor Robinson + */ +public final class VarRefDecl + extends ExpressionDecl +{ + private String identifier; + private String classIdentifier; + private boolean functionCall; + + public VarRefDecl(String identifier) + { + this(identifier, null); + } + + public VarRefDecl(String identifier, String classIdentifier) + { + this.identifier = identifier; + this.classIdentifier = classIdentifier; + } + + public String getIdentifier() + { + return identifier; + } + + public String getClassIdentifier() + { + return classIdentifier; + } + + public boolean isFunctionCall() + { + return functionCall; + } + + public void setFunctionCall(boolean functionCall) + { + this.functionCall = functionCall; + } + + public String toString() + { + return (classIdentifier != null) ? classIdentifier + "::" + identifier + : identifier; + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VeraFuncDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/VeraFuncDecl.java new file mode 100644 index 0000000..a2cb57c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VeraFuncDecl.java @@ -0,0 +1,39 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Base class for non-external function declarations. + * + * @author Trevor Robinson + */ +public abstract class VeraFuncDecl + extends AbsFuncDecl +{ + private BlockDecl block; + + public BlockDecl getBlock() + { + return block; + } + + public void setBlock(BlockDecl block) + { + this.block = block; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObject.java b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObject.java new file mode 100644 index 0000000..593f617 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObject.java @@ -0,0 +1,46 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langsource.SourceObject; +import com.newisys.parser.util.Token; + +/** + * Base interface for Vera source objects. + * + * @author Trevor Robinson + */ +public interface VeraSourceObject + extends SourceObject +{ + void setBeginLocation(Token beginToken); + + void setBeginLocation(VeraSourceObject beginObject); + + void setEndLocation(Token endToken); + + void setEndLocation(VeraSourceObject endObject); + + void applyCommentsFrom(Token realToken, boolean blanks); + + void applyCommentsFrom(Token firstToken, Token lastToken, boolean blanks); + + void applyComment(Token specialToken, boolean leading, boolean blanks); + + void accept(VeraSourceVisitor visitor); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObjectImpl.java b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObjectImpl.java new file mode 100644 index 0000000..82d6d45 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceObjectImpl.java @@ -0,0 +1,146 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +import com.newisys.langschema.BlankLine; +import com.newisys.langschema.BlockComment; +import com.newisys.langschema.InlineComment; +import com.newisys.langsource.SourceObjectImpl; +import com.newisys.parser.util.PreprocessedToken; +import com.newisys.parser.util.Token; +import com.newisys.parser.vera.VeraToken; + +/** + * Base implementation for Vera source objects. + * + * @author Trevor Robinson + */ +public abstract class VeraSourceObjectImpl + extends SourceObjectImpl + implements VeraSourceObject +{ + public void setBeginLocation(Token beginToken) + { + // only accept the first call + if (getBeginLine() == 0) + { + setBeginLocation(((PreprocessedToken) beginToken).filename, + beginToken.beginLine, beginToken.beginColumn); + setIncludeLocation(((PreprocessedToken) beginToken).includedFrom); + } + } + + public void setBeginLocation(VeraSourceObject beginObject) + { + // only accept the first call + if (getBeginLine() == 0) + { + setBeginLocation(beginObject.getBeginFilename(), beginObject + .getBeginLine(), beginObject.getBeginColumn()); + setIncludeLocation(beginObject.getIncludeLocation()); + } + } + + public void setEndLocation(Token endToken) + { + // subsequent calls override previous location + setEndLocation(((PreprocessedToken) endToken).filename, + endToken.endLine, endToken.endColumn); + } + + public void setEndLocation(VeraSourceObject endObject) + { + // subsequent calls override previous location + setEndLocation(endObject.getEndFilename(), endObject.getEndLine(), + endObject.getEndColumn()); + } + + public void applyCommentsFrom(Token realToken, boolean blanks) + { + VeraToken t = (VeraToken) realToken; + applyCommentChain(t.leadingComments, true, blanks); + applyCommentChain(t.trailingComments, false, blanks); + } + + public void applyCommentsFrom( + Token firstToken, + Token lastToken, + boolean blanks) + { + VeraToken t = (VeraToken) firstToken; + while (t != lastToken && t != null) + { + applyCommentsFrom(t, blanks); + firstToken = (VeraToken) firstToken.next; + } + } + + private void applyCommentChain( + Token specialToken, + boolean leading, + boolean blanks) + { + while (specialToken != null) + { + applyComment(specialToken, leading, blanks); + specialToken = specialToken.next; + } + } + + public void applyComment(Token specialToken, boolean leading, boolean blanks) + { + String s = specialToken.image; + char c; + if (s.startsWith("//")) + { + int eol = s.length(); + while ((c = s.charAt(eol - 1)) == '\r' || c == '\n') + --eol; + addAnnotation(new BlockComment(s.substring(2, eol), leading)); + } + else if (s.startsWith("/*")) + { + assert (s.endsWith("*/")); + InlineComment comment = new InlineComment(leading); + int start = 2; + while (true) + { + int eol = start; + char c0 = s.charAt(eol), c1 = s.charAt(eol + 1); + while (c0 != '\r' && c0 != '\n' && (c0 != '*' || c1 != '/')) + { + ++eol; + c0 = c1; + c1 = s.charAt(eol + 1); + } + comment.addLine(s.substring(start, eol)); + if (c0 == '*') break; + if (c0 == '\r' && c1 == '\n') ++eol; + start = eol + 1; + } + addAnnotation(comment); + } + else if (s.length() > 0 && ((c = s.charAt(0)) == '\r' || c == '\n')) + { + if (blanks) + { + addAnnotation(leading ? BlankLine.LEADING : BlankLine.TRAILING); + } + } + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceVisitor.java b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceVisitor.java new file mode 100644 index 0000000..7f24f1c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VeraSourceVisitor.java @@ -0,0 +1,174 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Visitor over Vera source objects. + * + * @author Trevor Robinson + */ +public interface VeraSourceVisitor +{ + void visit(ArrayAccessDecl obj); + + void visit(ArrayInitDecl obj); + + void visit(ArrayTypeRef obj); + + void visit(BindDecl obj); + + void visit(BindSignalDecl obj); + + void visit(BitSliceAccessDecl obj); + + void visit(BitVectorLiteralDecl obj); + + void visit(BitVectorTypeRef obj); + + void visit(BlockDecl obj); + + void visit(BreakDecl obj); + + void visit(BreakpointDecl obj); + + void visit(CaseDecl obj); + + void visit(CaseMemberDecl obj); + + void visit(ClassConstraintDecl obj); + + void visit(ClassDecl obj); + + void visit(ClassFuncDecl obj); + + void visit(ClassVarDecl obj); + + void visit(CompilationUnitDecl obj); + + void visit(ConstraintDecl obj); + + void visit(ContinueDecl obj); + + void visit(DefaultValueDecl obj); + + void visit(DefineDecl obj); + + void visit(DepthAccessDecl obj); + + void visit(DriveSampleDecl obj); + + void visit(EnumDecl obj); + + void visit(EnumElementDecl obj); + + void visit(ExpectDecl obj); + + void visit(ExpectExprDecl obj); + + void visit(ExpressionStatementDecl obj); + + void visit(ExtConstraintDecl obj); + + void visit(ExternVarDecl obj); + + void visit(FixedArrayTypeRef obj); + + void visit(ForDecl obj); + + void visit(ForkJoinDecl obj); + + void visit(FuncCallDecl obj); + + void visit(FuncDecl obj); + + void visit(GlobalVarDecl decl); + + void visit(HDLTaskDecl obj); + + void visit(IfElseConstraintDecl obj); + + void visit(IfElseDecl obj); + + void visit(ImplicationConstraintDecl obj); + + void visit(IntegerLiteralDecl obj); + + void visit(InterfaceDecl obj); + + void visit(LocalVarDecl obj); + + void visit(MemberAccessDecl obj); + + void visit(NewArrayDecl obj); + + void visit(NewCopyDecl obj); + + void visit(NewDecl obj); + + void visit(NullLiteralDecl obj); + + void visit(OperationDecl obj); + + void visit(ParamDecl obj); + + void visit(PortDecl obj); + + void visit(PragmaDecl obj); + + void visit(PrimitiveTypeRef obj); + + void visit(ProgramDecl obj); + + void visit(RandCaseDecl obj); + + void visit(RandCaseMemberDecl obj); + + void visit(RepeatDecl obj); + + void visit(ReturnDecl obj); + + void visit(SetOperationDecl obj); + + void visit(SignalDecl obj); + + void visit(SignalRangeDecl obj); + + void visit(SignalSkewDecl obj); + + void visit(StringLiteralDecl obj); + + void visit(SuperRefDecl obj); + + void visit(SyncDecl obj); + + void visit(TerminateDecl obj); + + void visit(ThisRefDecl obj); + + void visit(TypedefDecl obj); + + void visit(UDFFuncDecl obj); + + void visit(UserTypeRef obj); + + void visit(VarRefDecl obj); + + void visit(VoidLiteralDecl obj); + + void visit(WhileDecl obj); +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/VoidLiteralDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/VoidLiteralDecl.java new file mode 100644 index 0000000..fe70116 --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/VoidLiteralDecl.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Void literal expression. + * + * @author Trevor Robinson + */ +public final class VoidLiteralDecl + extends LiteralDecl +{ + public VoidLiteralDecl() + { + super(LiteralKind.VOID); + } + + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/WeightedRangeDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/WeightedRangeDecl.java new file mode 100644 index 0000000..0e2716c --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/WeightedRangeDecl.java @@ -0,0 +1,55 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * Weighted value range. + * + * @author Trevor Robinson + */ +public class WeightedRangeDecl + extends RangeDecl +{ + private ExpressionDecl weight; + private boolean weightPerItem; + + public ExpressionDecl getWeight() + { + return weight; + } + + public void setWeight(ExpressionDecl weight) + { + this.weight = weight; + } + + public boolean isWeightPerItem() + { + return weightPerItem; + } + + public void setWeightPerItem(boolean weightPerItem) + { + this.weightPerItem = weightPerItem; + } + + public String toString() + { + return super.toString() + (weightPerItem ? ":=" : ":/") + weight; + } +} diff --git a/java/vera-parser/src/com/newisys/langsource/vera/WhileDecl.java b/java/vera-parser/src/com/newisys/langsource/vera/WhileDecl.java new file mode 100644 index 0000000..913629d --- /dev/null +++ b/java/vera-parser/src/com/newisys/langsource/vera/WhileDecl.java @@ -0,0 +1,32 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.langsource.vera; + +/** + * While loop. + * + * @author Trevor Robinson + */ +public final class WhileDecl + extends LoopDecl +{ + public void accept(VeraSourceVisitor visitor) + { + visitor.visit(this); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParser.jj b/java/vera-parser/src/com/newisys/parser/vera/VeraParser.jj new file mode 100644 index 0000000..b71b46d --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParser.jj @@ -0,0 +1,3302 @@ +/* + * JavaCC (TM) parser definition for the OpenVera (TM) language + * Copyright (C) 2003 Trevor A. Robinson + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +options { + STATIC = false; + USER_TOKEN_MANAGER = true; + TOKEN_CONSUMED_HOOK = true; +} + +PARSER_BEGIN(VeraParser) + +package com.newisys.parser.vera; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import com.newisys.langschema.*; +import com.newisys.langschema.vera.*; +import com.newisys.langsource.vera.*; +import com.newisys.parser.util.*; +import com.newisys.verilog.EdgeSet; + +/** + * JavaCC parser for the OpenVera (TM) language. + * + * Unimplemented features: foreach, do-while, smart queues, randseq, aspect + * oriented extensions, functional coverage, bind_var (obsolete), with port + * construct (obsolete) + * + * @author Trevor Robinson + */ +public class VeraParser +{ + private VeraSourceObject curDecl; + private boolean firstToken; + private final LinkedList declStack = new LinkedList(); + private final LinkedList tokenStack = new LinkedList(); + + private void beginCapture(VeraSourceObject obj) + { + declStack.addLast(curDecl); + curDecl = obj; + firstToken = true; + } + + private void endCapture(VeraSourceObject obj) + { + assert (obj == curDecl); + curDecl = (VeraSourceObject) declStack.removeLast(); + } + + private void beginLocation(VeraSourceObject obj) + { + obj.setBeginLocation(getToken(1)); + } + + private void endLocation(VeraSourceObject obj) + { + obj.setEndLocation(getToken(0)); + } + + private void beginDecl(VeraSourceObject obj) + { + beginCapture(obj); + if (obj != null) beginLocation(obj); + } + + private void endDecl(VeraSourceObject obj) + { + endCapture(obj); + if (obj != null) endLocation(obj); + } + + private void beginMacro() + { + Token preToken = getToken(0); + if (preToken.kind == 0) preToken = null; + Token beginToken = getToken(1); + tokenStack.addLast(preToken); + tokenStack.addLast(beginToken); + } + + private void endMacro(MacroDecl decl, boolean apply, boolean pop) + { + VeraToken beginToken, preToken; + if (pop) { + beginToken = (VeraToken) tokenStack.removeLast(); + preToken = (VeraToken) tokenStack.removeLast(); + } else { + ListIterator iter = tokenStack.listIterator(tokenStack.size()); + beginToken = (VeraToken) iter.previous(); + preToken = (VeraToken) iter.previous(); + } + if (apply) { + VeraToken endToken = (VeraToken) getToken(0); + VeraToken postToken = (VeraToken) getToken(1); + MacroRef lastRef = MacroRefUtil.getCommonMacroRef( + beginToken.expandedFrom, endToken.expandedFrom); + if (lastRef != null && testMacroBoundaries(lastRef, preToken, postToken)) + { + MacroRef firstRef = lastRef; + while (true) { + MacroRef nextRef = firstRef.getExpandedFrom(); + if (nextRef == null || !testMacroBoundaries( + nextRef, preToken, postToken)) break; + firstRef = nextRef; + } + decl.setExpandedFrom(firstRef, lastRef); + } + } + } + + private static boolean testMacroBoundaries(MacroRef macroRef, + VeraToken preToken, VeraToken postToken) + { + return (preToken == null || + !MacroRefUtil.expansionContains(preToken.expandedFrom, macroRef)) && + !MacroRefUtil.expansionContains(postToken.expandedFrom, macroRef); + } + + private void endMacro(MacroDecl decl, boolean apply) + { + endMacro(decl, apply, true); + } + + private void endMacroSuffix(MacroDecl decl) + { + endMacro(decl, true, false); + } + + private void jj_token_consumed(Token t) + { + if (false) { + System.out.print(t.image); + MacroRef macroRef = ((VeraToken) t).expandedFrom; + while (macroRef != null) { + System.out.print(" <- " + macroRef); + macroRef = macroRef.getExpandedFrom(); + } + System.out.println(); + } + + if (curDecl != null) + { + curDecl.applyCommentsFrom(t, firstToken); + firstToken = false; + } + } +} + +PARSER_END(VeraParser) + +/* GRAMMAR */ + +void compilation_unit(CompilationUnitDecl compUnit) : +{ + beginDecl(compUnit); +} +{ + ( + top_level_decl(compUnit) + )* + + { + endDecl(compUnit); + } +} + +MacroDecl macro_defn() : +{ + MacroDecl decl; +} +{ + ( + LOOKAHEAD( cond_expr() ) + decl = cond_expr() + | + LOOKAHEAD( cond_expr() ) + decl = range() + | + LOOKAHEAD( statement_lookahead() ) + decl = statement() + | + decl = primitive_type() + ) + + { + return decl; + } +} + +void top_level_decl(CompilationUnitDecl compUnit) : +{ + Token ft = getToken(0); + CompilationUnitDeclMember member = null; +} +{ + ( + member = program_decl() + | + LOOKAHEAD( extern_var_decl_lookahead() ) + extern_var_decl(compUnit.getMembers()) + | + member = typedef_decl() + | + LOOKAHEAD( class_decl_lookahead() ) + member = class_decl() + | + LOOKAHEAD( ctor_decl_lookahead() ) + member = ctor_decl() + | + LOOKAHEAD( func_decl_lookahead() ) + member = func_decl() + | + member = ext_constraint_decl() + | + LOOKAHEAD( udf_func_decl_lookahead() ) + member = udf_func_decl() + | + LOOKAHEAD( directc_func_decl_lookahead() ) + member = directc_func_decl() + | + LOOKAHEAD( hdl_task_decl_lookahead() ) + member = hdl_task_decl() + | + member = enum_decl() + | + member = intf_decl() + | + member = port_decl() + | + member = bind_decl() + ) + { + // scan member tokens for associated preprocessor directives + Token lt = getToken(0); + Token t = ft; + while (t != lt) + { + if (t instanceof VeraToken) + { + VeraToken vt = (VeraToken) t; + if (vt.preprocDecls != null) + { + Iterator iter = vt.preprocDecls.iterator(); + while (iter.hasNext()) + { + CompilationUnitDeclMember obj = (CompilationUnitDeclMember) iter.next(); + compUnit.addMember(obj); + } + } + } + t = t.next; + } + + if (member != null) compUnit.addMember(member); + } +} + +ProgramDecl program_decl() : +{ + String id; + ProgramDecl program = new ProgramDecl(); + beginDecl(program); +} +{ + id = identifier() { program.setIdentifier(id); } + ( + program_block_body(program) + | + program_block_body(program) + ) + { + endDecl(program); + return program; + } +} + +// see also: block_body() +void program_block_body(ProgramDecl program) : +{ + List globalVars = program.getGlobalVars(); + StatementDecl stmt; +} +{ + ( LOOKAHEAD( global_var_decl_lookahead() ) global_var_decl(globalVars) )* + ( stmt = statement() { program.addStatement(stmt); } )* +} + +void global_var_decl_lookahead() : +{} +{ + type() +} + +// class_var_decl without var_decl_array_size +void global_var_decl(List globalVars) : +{ + TypeRef typeRef; + GlobalVarDecl var = new GlobalVarDecl(); + beginDecl(var); +} +{ + typeRef = type() + { + var.setTypeRef(typeRef); + } + var_decl_id(var) + var_decl_init(var) + { + endDecl(var); + globalVars.add(var); + } + ( + + { + var = new GlobalVarDecl(); + beginDecl(var); + var.setTypeRef(typeRef); + } + var_decl_id(var) + var_decl_init(var) + { + endDecl(var); + globalVars.add(var); + } + )* + { beginCapture(var); } { endCapture(var); } +} + +void extern_var_decl_lookahead() : +{} +{ + type() +} + +// global_var_decl without var_decl_init +void extern_var_decl(List compUnitMembers) : +{ + TypeRef typeRef; + ExternVarDecl var = new ExternVarDecl(); + beginDecl(var); +} +{ + typeRef = type() + { + var.setTypeRef(typeRef); + } + var_decl_id(var) + { + endDecl(var); + compUnitMembers.add(var); + } + ( + { beginCapture(var); } { endCapture(var); } + { + var = new ExternVarDecl(); + beginDecl(var); + var.setTypeRef(typeRef); + } + var_decl_id(var) + { + endDecl(var); + compUnitMembers.add(var); + } + )* + { beginCapture(var); } { endCapture(var); } +} + +TypedefDecl typedef_decl() : +{ + String id; + TypedefDecl typedef = new TypedefDecl(); + beginDecl(typedef); +} +{ + id = identifier() { typedef.setIdentifier(id); } + { + endDecl(typedef); + return typedef; + } +} + +void class_decl_lookahead() : +{} +{ + [ ] ( | )* +} + +ClassDecl class_decl() : +{ + String id; + ClassDecl cls = new ClassDecl(); + beginDecl(cls); +} +{ + [ { cls.setExtern(true); } ] + ( + { cls.setLocal(true); } + | + { cls.setVirtual(true); } + )* + id = identifier() { cls.setIdentifier(id); } + [ + { String baseID; } + baseID = identifier() { cls.setBaseClassIdentifer(baseID); } + [ call_args(cls.getBaseCtorArgs()) ] + ] + ( + class_body(cls) + | + class_body(cls) + ) + { + endDecl(cls); + return cls; + } +} + +void class_body(ClassDecl cls) : +{ + EnumDecl enumeration; + ClassConstraintDecl cons; + ClassFuncDecl func; +} +{ + // since enumerations can appear anywhere in the class, + // it's best just to use semantic checking to enforce + // variable-constraint-function declaration order + ( + enumeration = enum_decl() + { cls.addClassEnum(enumeration); } + | + LOOKAHEAD( member_var_decl_lookahead() ) + member_var_decl(cls, null) + | + cons = constraint_decl() + { cls.addClassConstraint(cons); } + | + func = member_func_decl() + { cls.addClassFunc(func); } + )* +} + +void member_var_decl_lookahead() : +{} +{ + member_var_attrs(null) + ( + + | + + | + type() + ) +} + +void member_var_decl(ClassDecl cls, ClassVarDecl var) : +{ + if (var == null) { + var = new ClassVarDecl(); + } else { + var = (ClassVarDecl) var.clone(); + } + beginDecl(var); +} +{ + member_var_attrs(var) + ( + ( member_var_decl(cls, var) )+ + | + ( member_var_decl(cls, var) )+ + | + class_var_decl(var, cls.getClassVars()) + ) + { + endDecl(var); + } +} + +void member_var_attrs(ClassVarDecl var) : +{} +{ + ( + { var.setVisibility(VeraVisibility.LOCAL); } + | + { var.setVisibility(VeraVisibility.PROTECTED); } + | + { var.setVisibility(VeraVisibility.PUBLIC); } + | + { var.setStaticVar(true); } + | + { var.setRandMode(RandMode.RAND); } + | + { var.setRandMode(RandMode.RANDC); } + | + { var.setRandMode(RandMode.NON_RAND); } + | + { var.setPacked(true); } + | + { var.setPacked(false); } + | + { var.setBigEndian(false); } + | + { var.setBigEndian(true); } + | + { var.setBitReverse(false); } + | + { var.setBitReverse(true); } + )* +} + +void class_var_decl(ClassVarDecl protoVar, List vars) : +{ + TypeRef typeRef; + ClassVarDecl var = (ClassVarDecl) protoVar.clone(); + beginDecl(var); +} +{ + typeRef = type() + { + var.setTypeRef(typeRef); + } + var_decl_id(var) + var_decl_array_size(var) + var_decl_init(var) + { + endDecl(var); + vars.add(var); + } + ( + { beginCapture(var); } { endCapture(var); } + { + var = (ClassVarDecl) protoVar.clone(); + beginDecl(var); + var.setTypeRef(typeRef); + } + var_decl_id(var) + var_decl_array_size(var) + var_decl_init(var) + { + endDecl(var); + vars.add(var); + } + )* + { beginCapture(var); } { endCapture(var); } +} + +void var_decl_array_size(ClassVarDecl var) : +{ + ExpressionDecl expr; +} +{ + [ + // semantic check: size keyword must match array type + ( | ) + expr = cond_expr() + { + var.setRandomSizeExpr(expr); + } + ] +} + +ClassConstraintDecl constraint_decl() : +{ + String id; + ClassConstraintDecl cons = new ClassConstraintDecl(); + beginDecl(cons); +} +{ + id = identifier() { cons.setIdentifier(id); } + ( + constraint_block(cons) + | + { cons.setExtern(true); } + ) + { + endDecl(cons); + return cons; + } +} + +ExtConstraintDecl ext_constraint_decl() : +{ + String classID, id; + ExtConstraintDecl cons = new ExtConstraintDecl(); + beginDecl(cons); +} +{ + classID = identifier() { cons.setClassIdentifier(classID); } + id = identifier() { cons.setIdentifier(id); } + constraint_block(cons) + { + endDecl(cons); + return cons; + } +} + +void constraint_block(ConstraintDecl cons) : +{ + ExpressionDecl consExpr; +} +{ + ( + ( + consExpr = constraint_expr() + { cons.addConstraintExpr(consExpr); } + )* + | + ( + consExpr = constraint_expr() + { cons.addConstraintExpr(consExpr); } + )* + ) +} + +void constraint_block_lookahead() : +{} +{ + ( | ) constraint_expr() +} + +ExpressionDecl constraint_expr() : +{ + ExpressionDecl result, predExpr, thenExpr, elseExpr = null; + DummyDecl dummy = new DummyDecl(); + beginDecl(dummy); +} +{ + ( + // nested constraint block + LOOKAHEAD( constraint_block_lookahead() ) + { + ConstraintDecl cons = new ConstraintDecl(); + result = cons; + } + constraint_block(cons) + | + // if-else constraint + predExpr = cond_expr() + + thenExpr = constraint_expr() + + [ + LOOKAHEAD(1) + elseExpr = constraint_expr() + ] + + { + result = new IfElseConstraintDecl(predExpr, thenExpr, elseExpr); + } + | + // simple constraint or implication predicate + predExpr = cond_expr() + ( + // implication constraint + + thenExpr = constraint_expr() + { + result = new ImplicationConstraintDecl(predExpr, thenExpr); + } + | + // simple constraint + + { + result = predExpr; + } + ) + ) + { + endDecl(dummy); + result.copyMetadata(dummy); + return result; + } +} + +ClassFuncDecl member_func_decl() : +{ + BlockDecl blk; + ClassFuncDecl func = new ClassFuncDecl(); + beginDecl(func); +} +{ + { + func.setBeginLocation(getToken(1)); + } + ( + { func.setVisibility(VeraVisibility.LOCAL); } + | + { func.setVisibility(VeraVisibility.PROTECTED); } + | + { func.setVisibility(VeraVisibility.PUBLIC); } + | + { func.setVirtual(true); } + )* + ( + LOOKAHEAD( ) + ctor_proto(func) + ( blk = ctor_block() { func.setBlock(blk); } | ) + | + func_proto(func) + ( blk = block() { func.setBlock(blk); } | ) + ) + { + endDecl(func); + return func; + } +} + +void ctor_decl_lookahead() : +{} +{ + +} + +FuncDecl ctor_decl() : +{ + String classID; + Token t; + BlockDecl blk; + FuncDecl ctor = new FuncDecl(); + beginDecl(ctor); +} +{ + + classID = identifier() { ctor.setClassIdentifier(classID); } + t = { ctor.setIdentifier(t.image); } + [ formal_param_list(ctor.getParams(), 0) ] + blk = ctor_block() { ctor.setBlock(blk); } + { + endDecl(ctor); + return ctor; + } +} + +void ctor_proto(AbsFuncDecl ctor) : +{ + Token t; +} +{ + + t = { ctor.setIdentifier(t.image); } + [ formal_param_list(ctor.getParams(), 0) ] +} + +void func_decl_lookahead() : +{} +{ + | ( [ | ] ( | type() ) ) +} + +FuncDecl func_decl() : +{ + TypeRef returnType; + String classID, id; + BlockDecl blk; + FuncDecl func = new FuncDecl(); + beginDecl(func); +} +{ + [ { func.setExport(true); } ] + ( + { func.setExtern(true); } + func_proto(func) + | + [ { func.setLocal(true); } ] + ( | returnType = type() { func.setReturnType(returnType); } ) + [ + LOOKAHEAD(2) + classID = identifier() { func.setClassIdentifier(classID); } + ] + id = identifier() { func.setIdentifier(id); } + [ formal_param_list(func.getParams(), 0) ] + blk = block() { func.setBlock(blk); } + ) + { + endDecl(func); + return func; + } +} + +void func_proto(AbsFuncDecl func) : +{ + TypeRef returnType; + String id; +} +{ + ( | returnType = type() { func.setReturnType(returnType); } ) + id = identifier() { func.setIdentifier(id); } + [ formal_param_list(func.getParams(), 0) ] +} + +void udf_func_decl_lookahead() : +{} +{ + ( | type() ) +} + +UDFFuncDecl udf_func_decl() : +{ + TypeRef returnType; + Token t; + UDFFuncDecl func = new UDFFuncDecl(); + beginDecl(func); +} +{ + ( | returnType = type() { func.setReturnType(returnType); } ) + t = { func.setIdentifier(t.image); } + + [ + { func.setVarArgs(true); } + | + formal_param_list(func.getParams(), 0) + ] + + { + endDecl(func); + return func; + } +} + +void directc_func_decl_lookahead() : +{} +{ + +} + +UDFFuncDecl directc_func_decl() : +{ + String lang; + TypeRef returnType; + String id; + UDFFuncDecl func = new UDFFuncDecl(); + beginDecl(func); +} +{ + lang = string() { func.setLanguage(lang); } + ( | returnType = type() { func.setReturnType(returnType); } ) + id = identifier() { func.setIdentifier(id); } + [ formal_param_list(func.getParams(), 0) ] + { + endDecl(func); + return func; + } +} + +void hdl_task_decl_lookahead() : +{} +{ + [ ] +} + +HDLTaskDecl hdl_task_decl() : +{ + String instPath; + HDLTaskDecl task = new HDLTaskDecl(); + beginDecl(task); +} +{ + ( + { task.setExtern(true); } + hdl_task_proto(task) + | + hdl_task_proto(task) instPath = string() + { task.setInstPath(instPath); } + ) + + { + endDecl(task); + return task; + } +} + +void hdl_task_proto(HDLTaskDecl task) : +{ + String id; +} +{ + id = identifier() { task.setIdentifier(id); } + [ formal_param_list(task.getParams(), 0) ] +} + +EnumDecl enum_decl() : +{ + String id; + EnumElementDecl elem; + EnumDecl _enum = new EnumDecl(); + beginDecl(_enum); +} +{ + id = identifier() { _enum.setIdentifier(id); } + ( + elem = enum_list(_enum) + | + elem = enum_list(_enum) + | + elem = enum_list(_enum) + ) + { beginCapture(elem); } { endCapture(elem); } + { + endDecl(_enum); + return _enum; + } +} + +EnumElementDecl enum_list(EnumDecl _enum) : +{ + EnumElementDecl elem; +} +{ + elem = enum_elem() { _enum.addElement(elem); } + ( + { beginCapture(elem); } { endCapture(elem); } + elem = enum_elem() { _enum.addElement(elem); } + )* + { return elem; } +} + +EnumElementDecl enum_elem() : +{ + String id; + ExpressionDecl value, firstSuffix, lastSuffix; + EnumElementDecl elem = new EnumElementDecl(); + beginDecl(elem); +} +{ + id = identifier() { elem.setIdentifier(id); } + [ + firstSuffix = const_expr() { elem.setFirstSuffix(firstSuffix); } + [ lastSuffix = const_expr() { elem.setLastSuffix(lastSuffix); } ] + + ] + [ + value = const_expr() { elem.setValue(value); } + ] + { + endDecl(elem); + return elem; + } +} + +InterfaceDecl intf_decl() : +{ + String id; + InterfaceDecl intf = new InterfaceDecl(); + beginDecl(intf); +} +{ + id = identifier() { intf.setIdentifier(id); } + ( + ( signal_decl(intf) )* + | + ( signal_decl(intf) )* + ) + { + endDecl(intf); + return intf; + } +} + +void signal_decl(InterfaceDecl intf) : +{ + ExpressionDecl highBitExpr; + String id; + SignalDecl signal = new SignalDecl(); + beginDecl(signal); +} +{ + ( + { signal.setDirection(VeraSignalDirection.INPUT); } + | + { signal.setDirection(VeraSignalDirection.OUTPUT); } + | + { signal.setDirection(VeraSignalDirection.INOUT); } + ) + [ highBitExpr = vector() { signal.setHighBitExpr(highBitExpr); } ] + id = identifier() { signal.setIdentifier(id); } + signal_type(signal) + [ + { ExpressionDecl depthExpr; } + depthExpr = const_expr() + { signal.setDepthExpr(depthExpr); } + ] + [ + { String vcaType; } + vcaType = identifier() + { + VeraVCAKind vcaKind; + int qvpos; + if (vcaType.startsWith("s")) { + vcaKind = VeraVCAKind.SYNC; + qvpos = 1; + } + else if (vcaType.startsWith("g")) { + vcaKind = VeraVCAKind.GLITCH; + qvpos = 1; + } + else { + vcaKind = VeraVCAKind.ASYNC; + qvpos = 0; + } + signal.setVCAKind(vcaKind); + + VeraVCAQValue vcaQValue; + String qvstr = vcaType.substring(qvpos); + if (qvstr.equals("r1")) vcaQValue = VeraVCAQValue.ONE; + else if (qvstr.equals("r0")) vcaQValue = VeraVCAQValue.ZERO; + else if (qvstr.equals("rz")) vcaQValue = VeraVCAQValue.Z; + else if (qvstr.equals("rx")) vcaQValue = VeraVCAQValue.X; + else if (qvstr.equals("nr")) vcaQValue = VeraVCAQValue.HOLD; + else throw new ParseException("Unknown VCA type: " + vcaType); + signal.setVCAQValue(vcaQValue); + } + ] + [ + { String node; } + node = string() + { signal.setHDLNode(node); } + ] + + { + endDecl(signal); + intf.addSignal(signal); + } +} + +void signal_type(SignalDecl signal) : +{ +} +{ + ( + { signal.setKind(VeraSignalKind.CLOCK); } + | + // semantic check: contains exactly one posedge and/or + // exactly one negedge sample type for input/inout signal + // semantic check: contains exactly one posedge and/or + // exactly one negedge drive type for output/inout signal + // semantic check: contains at most one non-positive skew + // for input/inout signal + // semantic check: contains at most one non-negative skew + // for output/inout signal + // semantic check: no zero skews for inout signal + { + VeraSignalKind kind = VeraSignalKind.NORMAL; + EdgeSet sampleEdges = EdgeSet.NO_EDGE; + EdgeSet driveEdges = EdgeSet.NO_EDGE; + } + ( + { String attr; } + attr = identifier() + { + VeraSignalKind attrKind; + EdgeSet attrSampleEdge = EdgeSet.NO_EDGE; + EdgeSet attrDriveEdge = EdgeSet.NO_EDGE; + if (attr.equals("NHOLD")) { + attrKind = VeraSignalKind.NORMAL; + attrDriveEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("PHOLD")) { + attrKind = VeraSignalKind.NORMAL; + attrDriveEdge = EdgeSet.POSEDGE; + } + else if (attr.equals("NR0")) { + attrKind = VeraSignalKind.RETURN_TO_ZERO; + attrDriveEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("NR1")) { + attrKind = VeraSignalKind.RETURN_TO_ONE; + attrDriveEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("NRX")) { + attrKind = VeraSignalKind.RETURN_TO_X; + attrDriveEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("NRZ")) { + attrKind = VeraSignalKind.RETURN_TO_Z; + attrDriveEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("PR0")) { + attrKind = VeraSignalKind.RETURN_TO_ZERO; + attrDriveEdge = EdgeSet.POSEDGE; + } + else if (attr.equals("PR1")) { + attrKind = VeraSignalKind.RETURN_TO_ONE; + attrDriveEdge = EdgeSet.POSEDGE; + } + else if (attr.equals("PRX")) { + attrKind = VeraSignalKind.RETURN_TO_X; + attrDriveEdge = EdgeSet.POSEDGE; + } + else if (attr.equals("PRZ")) { + attrKind = VeraSignalKind.RETURN_TO_Z; + attrDriveEdge = EdgeSet.POSEDGE; + } + else if (attr.equals("NSAMPLE")) { + attrKind = VeraSignalKind.NORMAL; + attrSampleEdge = EdgeSet.NEGEDGE; + } + else if (attr.equals("PSAMPLE")) { + attrKind = VeraSignalKind.NORMAL; + attrSampleEdge = EdgeSet.POSEDGE; + } + else { + throw new ParseException("Unknown signal type: " + attr); + } + if (attrKind != kind && kind != VeraSignalKind.NORMAL) { + throw new ParseException("Conflicting signal types: " + + kind + ", " + attrKind); + } + kind = attrKind; + sampleEdges = sampleEdges.union(attrSampleEdge); + driveEdges = driveEdges.union(attrDriveEdge); + } + | + { SignalSkewDecl skew; } + skew = skew_decl() + { signal.addSkew(skew); } + )+ + { + signal.setKind(kind); + signal.setSampleEdges(sampleEdges); + signal.setDriveEdges(driveEdges); + } + ) +} + +SignalSkewDecl skew_decl() : +{ + Token bt, et; + SignalSkewDecl skew; + VeraSurrXTransition transitionKind; + ExpressionDecl timeToXExpr; + ExpressionDecl timeToValueExpr; +} +{ + ( + // surround-by-X + LOOKAHEAD( trans_type() const_expr() ) + bt = transitionKind = trans_type() + timeToXExpr = const_expr() timeToValueExpr = const_expr() et = + { + skew = new SignalSkewDecl(transitionKind, timeToXExpr, timeToValueExpr); + skew.setBeginLocation(bt); + skew.setEndLocation(et); + } + | + // simple skew + bt = timeToValueExpr = const_expr() + { + skew = new SignalSkewDecl(timeToValueExpr); + skew.setBeginLocation(bt); + skew.setEndLocation(timeToValueExpr); + } + ) + { return skew; } +} + +VeraSurrXTransition trans_type() : +{ + VeraSurrXTransition trans = VeraSurrXTransition.ANY; + String str; +} +{ + // [ | | | ] + [ + str = identifier() + { + if (str.equals("R")) trans = VeraSurrXTransition.RISING; + else if (str.equals("F")) trans = VeraSurrXTransition.FALLING; + else if (str.equals("D")) trans = VeraSurrXTransition.FROM_Z; + else if (str.equals("Z")) trans = VeraSurrXTransition.TO_Z; + else throw new ParseException("Unknown Surround-by-X transition: " + str); + } + ] + { return trans; } +} + +PortDecl port_decl() : +{ + String id, memberID; + PortDecl port = new PortDecl(); + beginDecl(port); +} +{ + id = identifier() { port.setIdentifier(id); } + ( + ( memberID = identifier() { port.addMember(memberID); } )* + | + ( memberID = identifier() { port.addMember(memberID); } )* + ) + { + endDecl(port); + return port; + } +} + +BindDecl bind_decl() : +{ + String portID, id; + BindDecl bind = new BindDecl(); + beginDecl(bind); +} +{ + portID = identifier() id = identifier() + { + bind.setPortIdentifier(portID); + bind.setIdentifier(id); + } + ( + ( bind_signal_decl(bind) )* + | + ( bind_signal_decl(bind) )* + ) + { + endDecl(bind); + return bind; + } +} + +void bind_signal_decl(BindDecl bind) : +{ + String id; + BindSignalDecl signal = new BindSignalDecl(); + beginDecl(signal); +} +{ + id = identifier() { signal.setPortMember(id); } + bind_signal_group(signal) + { + endDecl(signal); + bind.addSignal(signal); + } +} + +void bind_signal_group(BindSignalDecl signal) : +{ + SignalRangeDecl signalRange; +} +{ + +| + + signalRange = bind_signal() { signal.addSignalRange(signalRange); } + ( signalRange = bind_signal() { signal.addSignalRange(signalRange); } )* + +| + signalRange = bind_signal() { signal.addSignalRange(signalRange); } +} + +SignalRangeDecl bind_signal() : +{ + String intfID, signalID; + RangeDecl range; + SignalRangeDecl signalRange = new SignalRangeDecl(); + beginDecl(signalRange); +} +{ + intfID = identifier() { signalRange.setInterfaceIdentifier(intfID); } + + signalID = identifier() { signalRange.setSignalIdentifier(signalID); } + [ range = bitfield() { signalRange.setBitfield(range); } ] + { + endDecl(signalRange); + return signalRange; + } +} + +ParamDecl formal_param_list(List params, int optLevel) : +{ + ParamDecl param; +} +{ + param = formal_param_group(params, optLevel) + ( + { beginCapture(param); } { endCapture(param); } + param = formal_param_group(params, optLevel) + )* + { return param; } +} + +ParamDecl formal_param_group(List params, int optLevel) : +{ + ParamDecl param; +} +{ + ( + param = formal_param_list(params, optLevel + 1) + | + param = formal_param() + { + param.setOptLevel(optLevel); + params.add(param); + } + ) + { return param; } +} + +ParamDecl formal_param() : +{ + TypeRef typeRef; + ExpressionDecl defExpr; + ParamDecl param = new ParamDecl(); + beginDecl(param); +} +{ + [ { param.setByRef(true); } ] + typeRef = type() { param.setTypeRef(typeRef); } + var_decl_id(param) + [ defExpr = cond_expr() { param.setDefaultExpr(defExpr); } ] + { + endDecl(param); + return param; + } +} + +TypeRef type() : +{ + String id; + TypeRef typeRef; + beginMacro(); +} +{ + ( + typeRef = primitive_type() + | + { + UserTypeRef userTypeRef = new UserTypeRef(); + beginLocation(userTypeRef); + } + id = identifier() + { + userTypeRef.setIdentifier(id); + endLocation(userTypeRef); + typeRef = userTypeRef; + } + ) + { + endMacro(typeRef, true); + return typeRef; + } +} + +PrimitiveTypeRef primitive_type() : +{ + PrimitiveTypeRef typeRef; + DummyDecl dummy = new DummyDecl(); + beginLocation(dummy); +} +{ + ( + ( + ( | ) { typeRef = new PrimitiveTypeRef(VeraPrimitiveKind.BIT); } + [ + { ExpressionDecl highBitExpr; } + highBitExpr = vector() + { typeRef = new BitVectorTypeRef(highBitExpr); } + ] + ) + | + { typeRef = new PrimitiveTypeRef(VeraPrimitiveKind.EVENT); } + | + { typeRef = new PrimitiveTypeRef(VeraPrimitiveKind.INTEGER); } + | + { typeRef = new PrimitiveTypeRef(VeraPrimitiveKind.STRING); } + ) + { + endLocation(dummy); + typeRef.copyMetadata(dummy); + return typeRef; + } +} + +ExpressionDecl vector() : +{ + ExpressionDecl highBitExpr; + Token t; +} +{ + + highBitExpr = const_expr() + + t = + { if (!t.image.equals("0")) throw new ParseException("0 expected"); } + + { return highBitExpr; } +} + +RangeDecl bitfield() : +{ + RangeDecl r = new RangeDecl(); + beginDecl(r); +} +{ + + { beginMacro(); } + internal_range(r) + { endMacro(r, true); } + + { + endDecl(r); + return r; + } +} + +void var_decl_id(AbsVarDecl decl) : +{ + String id; + Token bt, et; +} +{ + id = identifier() { decl.setIdentifier(id); } + [ + bt = + { + TypeRef elemType = decl.getTypeRef(); + ArrayTypeRef arrayType; + } + ( + // bit-associative array + [ | ] et = + { arrayType = new ArrayTypeRef(ArrayKind.BIT_ASSOCIATIVE, elemType); } + | + // string-associative array + et = + { arrayType = new ArrayTypeRef(ArrayKind.STRING_ASSOCIATIVE, elemType); } + | + // dynamic array + et = { arrayType = new ArrayTypeRef(ArrayKind.DYNAMIC, elemType); } + | + { + FixedArrayTypeRef fixedArrayType = new FixedArrayTypeRef(elemType); + ExpressionDecl expr; + } + // fixed or multi-dimensional array + expr = const_expr() et = { fixedArrayType.addDimension(expr); } + ( + expr = const_expr() et = { fixedArrayType.addDimension(expr); } + )* + { arrayType = fixedArrayType; } + ) + { + arrayType.setBeginLocation(bt); + arrayType.setEndLocation(et); + decl.setTypeRef(arrayType); + } + ] +} + +void var_decl_init(VarDecl decl) : +{ + ExpressionDecl expr; +} +{ + [ + + ( + expr = new_expr() + | + // use semantic lookahead to avoid conflict with concatenation + LOOKAHEAD( { decl.getTypeRef() instanceof ArrayTypeRef } ) + expr = array_init() + | + expr = cond_expr() + ) + { + decl.setInitExpr(expr); + } + ] +} + +ExpressionDecl array_init() : +{ + ExpressionDecl elem; + ArrayInitDecl init = new ArrayInitDecl(); + beginDecl(init); +} +{ + + elem = array_init_elem() { init.addElement(elem); } + ( + { beginCapture(elem); } { endCapture(elem); } + elem = array_init_elem() { init.addElement(elem); } + )* + + { + endDecl(init); + return init; + } +} + +ExpressionDecl array_init_elem() : +{ + ExpressionDecl elem; +} +{ + ( + // force nested array initializer to win over concatenation + LOOKAHEAD( ) + elem = array_init() + | + elem = const_expr() + ) + { return elem; } +} + +BlockDecl block() : +{ + BlockDecl blk = new BlockDecl(); + beginDecl(blk); +} +{ + ( + block_body(blk) + | + block_body(blk) + ) + { + endDecl(blk); + return blk; + } +} + +BlockDecl ctor_block() : +{ + BlockDecl blk = new BlockDecl(); + beginDecl(blk); +} +{ + ( + ctor_block_body(blk) + | + ctor_block_body(blk) + ) + { + endDecl(blk); + return blk; + } +} + +void block_body(BlockDecl blk) : +{ + List localVars = blk.getLocalVars(); + StatementDecl stmt; +} +{ + ( LOOKAHEAD( local_var_decl_lookahead() ) local_var_decl(localVars) )* + ( stmt = statement() { blk.addStatement(stmt); } )* +} + +void ctor_block_body(BlockDecl blk) : +{ + List localVars = blk.getLocalVars(); + StatementDecl stmt; +} +{ + ( LOOKAHEAD( local_var_decl_lookahead() ) local_var_decl(localVars) )* + [ + LOOKAHEAD( explicit_ctor_call_lookahead() ) + stmt = explicit_ctor_call() { blk.addStatement(stmt); } + ] + ( stmt = statement() { blk.addStatement(stmt); } )* +} + +void local_var_decl_lookahead() : +{} +{ + [ | ] + type() +} + +// class_var_decl without var_decl_array_size +void local_var_decl(List localVars) : +{ + LocalVarModifier mod = null;; + TypeRef typeRef; + LocalVarDecl var = new LocalVarDecl(); + beginDecl(var); +} +{ + [ + { mod = LocalVarModifier.STATIC; } + | + { mod = LocalVarModifier.SHADOW; } + ] + typeRef = type() + { + var.setTypeRef(typeRef); + if (mod != null) var.addModifier(mod); + } + var_decl_id(var) + var_decl_init(var) + { + endDecl(var); + localVars.add(var); + } + ( + { beginCapture(var); } { endCapture(var); } + { + var = new LocalVarDecl(); + beginDecl(var); + var.setTypeRef(typeRef); + if (mod != null) var.addModifier(mod); + } + var_decl_id(var) + var_decl_init(var) + { + endDecl(var); + localVars.add(var); + } + )* + { beginCapture(var); } { endCapture(var); } +} + +void explicit_ctor_call_lookahead() : +{} +{ + +} + +StatementDecl explicit_ctor_call() : +{ + Token bt, et; + ExpressionStatementDecl stmt = new ExpressionStatementDecl(); + beginDecl(stmt); +} +{ + bt = et = + { + ExpressionDecl superExpr = new SuperRefDecl(); + superExpr.setBeginLocation(bt); + superExpr.setEndLocation(bt); + ExpressionDecl ctorExpr = new MemberAccessDecl(superExpr, "new"); + ctorExpr.setBeginLocation(bt); + ctorExpr.setEndLocation(et); + FuncCallDecl callExpr = new FuncCallDecl(ctorExpr); + callExpr.setBeginLocation(bt); + beginCapture(callExpr); + } + call_args(callExpr.getArguments()) + { + endDecl(callExpr); + } + + { + stmt.setExpr(callExpr); + endDecl(stmt); + return stmt; + } +} + +void statement_lookahead() : +{ +} +{ + | | + | + | + | | | + | + | + | + | + | + | + | + | + | + /* sync, drive, or expect */ + + /* call */ + | + /* expect */ + | + | + /* assign */ + | + | | + /* call, drive, expect, or assign */ + var_ref() + ( + | /* call */ + | /* drive */ + | | /* expect */ + | | | compound_assign_oper() /* assign */ + ) +} + +StatementDecl statement() : +{ + StatementDecl stmt; + beginMacro(); +} +{ + ( + LOOKAHEAD(1) + stmt = block() + | + stmt = fork_statement() + | + stmt = if_statement() + | + stmt = case_statement() + | + stmt = randcase_statement() + | + stmt = repeat_statement() + | + stmt = for_statement() + | + stmt = while_statement() + | + stmt = return_statement() + | + stmt = break_statement() + | + stmt = continue_statement() + | + stmt = terminate_statement() + | + stmt = breakpoint_statement() + | + LOOKAHEAD( call_lookahead() ) + stmt = call_statement() + | + LOOKAHEAD( sync_statement() ) + stmt = sync_statement() + | + LOOKAHEAD( drive_lookahead() ) + stmt = drive_statement() + | + LOOKAHEAD( expect_lookahead() ) + stmt = expect_statement() + | + stmt = assign_statement() + ) + { + endMacro(stmt, true); + return stmt; + } +} + +void call_lookahead() : +{} +{ + | var_ref() +} + +ExpressionStatementDecl call_statement() : +{ + ExpressionDecl expr; + ExpressionStatementDecl stmt = new ExpressionStatementDecl(); + beginDecl(stmt); +} +{ + ( + expr = cond_expr() + | + expr = var_ref() + { + if (expr instanceof VarRefDecl) { + ((VarRefDecl) expr).setFunctionCall(true); + } + FuncCallDecl callExpr = new FuncCallDecl(expr); + callExpr.setBeginLocation(expr); + beginCapture(callExpr); + } + call_args(callExpr.getArguments()) + call_constraints(callExpr) + { + endDecl(callExpr); + expr = callExpr; + } + ) + + { + stmt.setExpr(expr); + endDecl(stmt); + return stmt; + } +} + +ForkJoinDecl fork_statement() : +{ + StatementDecl stmt; + ForkJoinDecl forkDecl = new ForkJoinDecl(); + beginDecl(forkDecl); +} +{ + + ( stmt = statement() { forkDecl.addStatement(stmt); } )+ + + [ + { forkDecl.setJoinKind(JoinKind.ALL); } + | + { forkDecl.setJoinKind(JoinKind.ANY); } + | + { forkDecl.setJoinKind(JoinKind.NONE); } + ] + { + endDecl(forkDecl); + return forkDecl; + } +} + +IfElseDecl if_statement() : +{ + ExpressionDecl expr; + StatementDecl stmt; + IfElseDecl ifElseDecl = new IfElseDecl(); + beginDecl(ifElseDecl); +} +{ + expr = cond_expr() { ifElseDecl.setIfExpr(expr); } + stmt = statement() { ifElseDecl.setThenStatement(stmt); } + [ LOOKAHEAD(1) stmt = statement() { ifElseDecl.setElseStatement(stmt); } ] + { + endDecl(ifElseDecl); + return ifElseDecl; + } +} + +CaseDecl case_statement() : +{ + ExpressionDecl expr; + CaseDecl caseDecl = new CaseDecl(); + beginDecl(caseDecl); +} +{ + ( + { caseDecl.setCaseKind(VeraCaseKind.NORMAL); } + | + { caseDecl.setCaseKind(VeraCaseKind.X); } + | + { caseDecl.setCaseKind(VeraCaseKind.Z); } + ) + expr = cond_expr() { caseDecl.setCaseExpr(expr); } + ( + case_body(caseDecl) + | + case_body(caseDecl) + ) + { + endDecl(caseDecl); + return caseDecl; + } +} + +void case_body(CaseDecl caseDecl) : +{ + StatementDecl stmt; +} +{ + ( + ( + <_DEFAULT> stmt = statement() + { caseDecl.setDefaultStatement(stmt); } + | + { + CaseMemberDecl member = new CaseMemberDecl(); + beginDecl(member); + } + cond_expr_list(member.getExprs()) stmt = statement() + { + member.setStatement(stmt); + endDecl(member); + caseDecl.addCaseMember(member); + } + ) + )+ +} + +RandCaseDecl randcase_statement() : +{ + RandCaseDecl randCaseDecl = new RandCaseDecl(); + beginDecl(randCaseDecl); +} +{ + + ( + randcase_body(randCaseDecl) + | + randcase_body(randCaseDecl) + ) + { + endDecl(randCaseDecl); + return randCaseDecl; + } +} + +void randcase_body(RandCaseDecl randCaseDecl) : +{ + ExpressionDecl expr; + StatementDecl stmt; +} +{ + ( + { + RandCaseMemberDecl member = new RandCaseMemberDecl(); + beginDecl(member); + } + expr = cond_expr() stmt = statement() + { + member.setWeightExpr(expr); + member.setStatementDecl(stmt); + endDecl(member); + randCaseDecl.addCaseMember(member); + } + )+ +} + +RepeatDecl repeat_statement() : +{ + ExpressionDecl expr; + StatementDecl stmt; + RepeatDecl repeat = new RepeatDecl(); + beginDecl(repeat); +} +{ + expr = cond_expr() stmt = statement() + { + repeat.setCondition(expr); + repeat.setStatement(stmt); + endDecl(repeat); + return repeat; + } +} + +ForDecl for_statement() : +{ + ExpressionDecl expr; + StatementDecl stmt; + ForDecl forDecl = new ForDecl(); + beginDecl(forDecl); +} +{ + + [ assign_expr_list(forDecl.getInitExprs()) ] + [ expr = cond_expr() { forDecl.setCondition(expr); } ] + [ assign_expr_list(forDecl.getUpdateExprs()) ] + stmt = statement() + { + forDecl.setStatement(stmt); + endDecl(forDecl); + return forDecl; + } +} + +WhileDecl while_statement() : +{ + ExpressionDecl expr; + StatementDecl stmt; + WhileDecl whileStmt = new WhileDecl(); + beginDecl(whileStmt); +} +{ + expr = cond_expr() stmt = statement() + { + whileStmt.setCondition(expr); + whileStmt.setStatement(stmt); + endDecl(whileStmt); + return whileStmt; + } +} + +ReturnDecl return_statement() : +{ + ReturnDecl returnStmt = new ReturnDecl(); + beginDecl(returnStmt); +} +{ + + { + endDecl(returnStmt); + return returnStmt; + } +} + +BreakDecl break_statement() : +{ + BreakDecl breakStmt = new BreakDecl(); + beginDecl(breakStmt); +} +{ + + { + endDecl(breakStmt); + return breakStmt; + } +} + +ContinueDecl continue_statement() : +{ + ContinueDecl continueStmt = new ContinueDecl(); + beginDecl(continueStmt); +} +{ + + { + endDecl(continueStmt); + return continueStmt; + } +} + +TerminateDecl terminate_statement() : +{ + TerminateDecl terminateStmt = new TerminateDecl(); + beginDecl(terminateStmt); +} +{ + + { + endDecl(terminateStmt); + return terminateStmt; + } +} + +BreakpointDecl breakpoint_statement() : +{ + BreakpointDecl breakpointStmt = new BreakpointDecl(); + beginDecl(breakpointStmt); +} +{ + + { + endDecl(breakpointStmt); + return breakpointStmt; + } +} + +SyncDecl sync_statement() : +{ + SyncTerm syncTerm; + SyncDecl syncDecl = new SyncDecl(); + beginDecl(syncDecl); +} +{ + + syncTerm = sync_term() { syncDecl.addTerm(syncTerm); } + ( + syncTerm = sync_term() { syncDecl.addTerm(syncTerm); } + )* + + { + endDecl(syncDecl); + return syncDecl; + } +} + +SyncTerm sync_term() : +{ + ExpressionDecl signal; + SyncTerm syncTerm = new SyncTerm(); + beginDecl(syncTerm); +} +{ + [ + { syncTerm.setEdge(SyncEdge.POSEDGE); } + | + { syncTerm.setEdge(SyncEdge.NEGEDGE); } + ] + ( + + | + signal = var_ref() { syncTerm.setSignal(signal); } + [ { syncTerm.setAsync(true); } ] + ) + { + endDecl(syncTerm); + return syncTerm; + } +} + +void drive_lookahead() : +{} +{ + ( + cond_expr() var_ref() ( | ) + | + var_ref() ( | cond_expr() ( | ) ) + ) +} + +DriveSampleDecl drive_statement() : +{ + ExpressionDecl delay, signal, value; + DriveSampleDecl driveDecl = new DriveSampleDecl(); + beginDecl(driveDecl); +} +{ + [ delay = cond_expr() { driveDecl.setDelayExpr(delay); } ] + signal = var_ref() { driveDecl.setDestExpr(signal); } + ( + { driveDecl.setOperator(Operator.ASSIGN); } + | + { driveDecl.setOperator(Operator.NONBLOCKING_ASSIGN); } + ) + value = cond_expr() { driveDecl.setValueExpr(value); } + ( + { driveDecl.setSoft(true); } + | + { driveDecl.setAsync(true); } + )* + + { + endDecl(driveDecl); + return driveDecl; + } +} + +void expect_lookahead() : +{} +{ + + ( + + | + cond_expr() + ( + + | + var_ref() ( | ) + ) + ) +| + +| + +| + var_ref() ( | ) +} + +ExpectDecl expect_statement() : +{ + VeraExpectKind kind = VeraExpectKind.SIMPLE; + ExpressionDecl delay = null, window = null; + ExpectDecl expectDecl = new ExpectDecl(); + beginDecl(expectDecl); +} +{ + [ + ( + { kind = VeraExpectKind.SIMPLE; } + | + { kind = VeraExpectKind.FULL; } + | + { kind = VeraExpectKind.RESTRICTED; } + ) + ( + window = cond_expr() + | + { ExpressionDecl expr; } + expr = cond_expr() + ( + window = cond_expr() + { delay = expr; } + | + { + if (kind == VeraExpectKind.SIMPLE) { + delay = expr; + } else { + window = expr; + } + } + ) + ) + { + expectDecl.setDelayExpr(delay); + expectDecl.setWindowExpr(window); + } + ] + { + expectDecl.setExpectKind(kind); + } + expect_expr_list(expectDecl) + ( + { expectDecl.setSoft(true); } + | + { expectDecl.setAsync(true); } + )* + + { + endDecl(expectDecl); + return expectDecl; + } +} + +void expect_expr_list(ExpectDecl expectDecl) : +{ + ExpectExprDecl expr; +} +{ + expr = expect_expr() + { + expectDecl.addExpectExpr(expr); + expectDecl.setBeginLocation(expr); + } + ( + // semantic check: cannot mix ',' and 'or' + { beginCapture(expr); } + ( | { expectDecl.setExpectAll(false); } ) + { endCapture(expr); } + expr = expect_expr() { expectDecl.addExpectExpr(expr); } + )* +} + +ExpectExprDecl expect_expr() : +{ + ExpressionDecl signal, value; + ExpectExprDecl expectExpr = new ExpectExprDecl(); + beginDecl(expectExpr); +} +{ + signal = var_ref() { expectExpr.setSignalExpr(signal); } + ( + { expectExpr.setOperator(Operator.EQUAL); } + | + { expectExpr.setOperator(Operator.NOT_EQUAL); } + ) + value = cond_expr() + { + expectExpr.setValueExpr(value); + endDecl(expectExpr); + return expectExpr; + } +} + +void assign_lookahead() : +{ +} +{ + | + | | + var_ref() ( | | | compound_assign_oper() ) +} + +ExpressionStatementDecl assign_statement() : +{ + ExpressionDecl expr; + ExpressionStatementDecl stmt = new ExpressionStatementDecl(); + beginDecl(stmt); +} +{ + expr = assign_expr() + { + stmt.setExpr(expr); + endDecl(stmt); + return stmt; + } +} + +ExpressionDecl assign_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + OperationDecl opExpr = new OperationDecl(); + beginDecl(opExpr); +} +{ + ( + // LHS concatenation: '{ x, y } = z + LOOKAHEAD( ) + expr1 = lcat_expr() { opExpr.addOperand(expr1); } + { opExpr.setOperator(Operator.ASSIGN); } + expr2 = cond_expr() { opExpr.addOperand(expr2); } + | + // pre-increment/decrement: ++x, --x + ( + { opExpr.setOperator(Operator.PRE_INCREMENT); } + | + { opExpr.setOperator(Operator.PRE_DECREMENT); } + ) + expr1 = var_ref() { opExpr.addOperand(expr1); } + | + expr1 = var_ref() { opExpr.addOperand(expr1); } + ( + // post-increment/decrement: x++, x-- + ( + { opExpr.setOperator(Operator.POST_INCREMENT); } + | + { opExpr.setOperator(Operator.POST_DECREMENT); } + ) + | + // assignment: x = y, x = new + { opExpr.setOperator(Operator.ASSIGN); } + ( expr2 = new_expr() | expr2 = cond_expr() ) { opExpr.addOperand(expr2); } + | + // compound assignment: x += y, x -= y, ... + op = compound_assign_oper() { opExpr.setOperator(op); } + expr2 = cond_expr() { opExpr.addOperand(expr2); } + ) + ) + { + endDecl(opExpr); + return opExpr; + } +} + +void assign_expr_list(List exprs) : +{ + ExpressionDecl expr; +} +{ + expr = assign_expr() { exprs.add(expr); } + ( + { beginCapture(expr); } { endCapture(expr); } + expr = assign_expr() { exprs.add(expr); } + )* +} + +OperationDecl lcat_expr() : +{ + ExpressionDecl expr; + OperationDecl lcatExpr = new OperationDecl(Operator.CONCATENATION); + beginDecl(lcatExpr); +} +{ + // semantic check: signals not allowed + + expr = var_ref() { lcatExpr.addOperand(expr); } + ( + { beginCapture(expr); } { endCapture(expr); } + expr = var_ref() { lcatExpr.addOperand(expr); } + )* + + { + endDecl(lcatExpr); + return lcatExpr; + } +} + +Operator compound_assign_oper() : +{ + Operator op; +} +{ + ( + { op = Operator.ADD_ASSIGN; } + | + { op = Operator.SUBTRACT_ASSIGN; } + | + { op = Operator.MULTIPLY_ASSIGN; } + | + { op = Operator.DIVIDE_ASSIGN; } + | + { op = Operator.MODULO_ASSIGN; } + | + { op = Operator.LEFT_SHIFT_ASSIGN; } + | + { op = Operator.RIGHT_SHIFT_ASSIGN; } + | + { op = Operator.AND_ASSIGN; } + | + { op = Operator.OR_ASSIGN; } + | + { op = Operator.XOR_ASSIGN; } + | + { op = Operator.NAND_ASSIGN; } + | + { op = Operator.NOR_ASSIGN; } + | + { op = Operator.XNOR_ASSIGN; } + ) + { return op; } +} + +ExpressionDecl new_expr() : +{ + ExpressionDecl expr; + NewDecl newExpr = new NewDecl(); + beginDecl(newExpr); + ExpressionDecl resultExpr = newExpr; +} +{ + + ( + // constructor arguments + LOOKAHEAD( ) + call_args(newExpr.getArguments()) + | + // copy construction + expr = var_ref() + { resultExpr = new NewCopyDecl(expr); } + | + // dynamic array creation + // semantic check: size must be integer + expr = cond_expr() + { NewArrayDecl newArrayExpr = new NewArrayDecl(expr); } + // semantic check: source must be dynamic array of same type + [ expr = var_ref() { newArrayExpr.setSourceExpr(expr); } ] + { resultExpr = newArrayExpr; } + | + // no-argument object construction + { } + ) + { + endDecl(newExpr); + if (resultExpr != newExpr) resultExpr.copyMetadata(newExpr); + return resultExpr; + } +} + +ExpressionDecl const_expr() : +{ + ExpressionDecl expr; +} +{ + // semantic check: no variable references or function calls + expr = cond_expr() + { return expr; } +} + +void cond_expr_list(List exprs) : +{ + ExpressionDecl expr; +} +{ + expr = cond_expr() { exprs.add(expr); } + ( + { beginCapture(expr); } { endCapture(expr); } + expr = cond_expr() { exprs.add(expr); } + )* +} + +ExpressionDecl cond_expr() : +{ + ExpressionDecl expr1, expr2, expr3; + beginMacro(); +} +{ + expr1 = log_or_expr() + [ + { + OperationDecl opExpr = new OperationDecl(Operator.CONDITIONAL, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + expr2 = cond_expr() expr3 = cond_expr() + { + opExpr.addOperand(expr2); + opExpr.addOperand(expr3); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + ] + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl log_or_expr() : +{ + ExpressionDecl expr1, expr2; + beginMacro(); +} +{ + expr1 = log_and_expr() + ( + { + OperationDecl opExpr = new OperationDecl(Operator.LOGICAL_OR, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + expr2 = log_and_expr() + { + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl log_and_expr() : +{ + ExpressionDecl expr1, expr2; + beginMacro(); +} +{ + expr1 = bit_or_expr() + ( + { + OperationDecl opExpr = new OperationDecl(Operator.LOGICAL_AND, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + expr2 = bit_or_expr() + { + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl bit_or_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = bit_xor_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.BITWISE_OR; } + | + { op = Operator.BITWISE_NOR; } + ) + expr2 = bit_xor_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl bit_xor_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = bit_and_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.BITWISE_XOR; } + | + { op = Operator.BITWISE_XNOR; } + ) + expr2 = bit_and_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl bit_and_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = equal_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.BITWISE_AND; } + | + { op = Operator.BITWISE_NAND; } + ) + expr2 = equal_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl equal_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = rel_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.EQUAL; } + | + { op = Operator.NOT_EQUAL; } + | + { op = Operator.EXACT_EQUAL; } + | + { op = Operator.EXACT_NOT_EQUAL; } + | + { op = Operator.WILD_EQUAL; } + | + { op = Operator.WILD_NOT_EQUAL; } + ) + expr2 = rel_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl rel_expr() : +{ + ExpressionDecl expr1, expr2; + RangeListDecl ranges; + Operator op; + beginMacro(); +} +{ + expr1 = shift_expr() + // semantic check: set expressions only allowed in constraint blocks + // semantic check: dist set expressions must be at top level of a constraint + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.LESS; } + | + { op = Operator.LESS_OR_EQUAL; } + | + { op = Operator.GREATER; } + | + { op = Operator.GREATER_OR_EQUAL; } + ) + expr2 = shift_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + | + { + SetOperationDecl inExpr = new SetOperationDecl(expr1); + inExpr.setBeginLocation(expr1); + beginCapture(inExpr); + } + ( { op = Operator.NOT_IN; } | { op = Operator.IN; } ) + ranges = range_list() + { + inExpr.setOperator(op); + inExpr.setRanges(ranges); + endDecl(inExpr); + endMacroSuffix(inExpr); + expr1 = inExpr; + } + | + { + SetOperationDecl distExpr = new SetOperationDecl(expr1, Operator.DIST); + distExpr.setBeginLocation(expr1); + beginCapture(distExpr); + } + ranges = dist_range_list() + { + distExpr.setRanges(ranges); + endDecl(distExpr); + endMacroSuffix(distExpr); + expr1 = distExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +RangeListDecl range_list() : +{ + RangeDecl r; + RangeListDecl ranges = new RangeListDecl(); + beginDecl(ranges); +} +{ + + r = range() { ranges.addRange(r); } + ( + { beginCapture(r); } { endCapture(r); } + r = range() { ranges.addRange(r); } + )* + + { + endDecl(ranges); + return ranges; + } +} + +RangeDecl range() : +{ + RangeDecl r = new RangeDecl(); + beginDecl(r); +} +{ + internal_range(r) + { + endDecl(r); + return r; + } +} + +void internal_range(RangeDecl r) : +{ + ExpressionDecl from, to; + beginMacro(); +} +{ + from = cond_expr() { r.setFrom(from); } + ( to = cond_expr() | { to = from; } ) { r.setTo(to); } + { endMacro(r, true); } +} + +RangeListDecl dist_range_list() : +{ + RangeDecl r; + RangeListDecl ranges = new RangeListDecl(); + beginDecl(ranges); +} +{ + + r = dist_range() { ranges.addRange(r); } + ( + { beginCapture(r); } { endCapture(r); } + r = dist_range() { ranges.addRange(r); } + )* + + { + endDecl(ranges); + return ranges; + } +} + +RangeDecl dist_range() : +{ + RangeDecl r; + ExpressionDecl weight; + boolean weightPerItem;; +} +{ + r = range() + [ + { + WeightedRangeDecl wr = new WeightedRangeDecl(); + wr.setFrom(r.getFrom()); + wr.setTo(r.getTo()); + wr.copyMetadata(r); + beginDecl(wr); + } + ( + { wr.setWeightPerItem(true); } + | + { wr.setWeightPerItem(false); } + ) + weight = cond_expr() + { + wr.setWeight(weight); + endDecl(wr); + r = wr; + } + ] + { return r; } +} + +ExpressionDecl shift_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = add_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.LEFT_SHIFT; } + | + { op = Operator.RIGHT_SHIFT; } + ) + expr2 = add_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl add_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = mul_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.ADD; } + | + { op = Operator.SUBTRACT; } + ) + expr2 = mul_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl mul_expr() : +{ + ExpressionDecl expr1, expr2; + Operator op; + beginMacro(); +} +{ + expr1 = unary_expr() + ( + { + OperationDecl opExpr = new OperationDecl(null, expr1); + opExpr.setBeginLocation(expr1); + beginCapture(opExpr); + } + ( + { op = Operator.MULTIPLY; } + | + { op = Operator.DIVIDE; } + | + { op = Operator.MODULO; } + ) + expr2 = unary_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr2); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr1 = opExpr; + } + )* + { + endMacro(expr1, false); + return expr1; + } +} + +ExpressionDecl unary_expr() : +{ + ExpressionDecl expr; + Operator op; + beginMacro(); +} +{ + ( + { + OperationDecl opExpr = new OperationDecl(); + beginDecl(opExpr); + } + ( + { op = Operator.NEGATIVE; } + | + { op = Operator.LOGICAL_NEGATIVE; } + | + { op = Operator.BITWISE_NEGATIVE; } + | + { op = Operator.AND_REDUCTION; } + | + { op = Operator.NAND_REDUCTION; } + | + { op = Operator.OR_REDUCTION; } + | + { op = Operator.NOR_REDUCTION; } + | + { op = Operator.XOR_REDUCTION; } + | + { op = Operator.XNOR_REDUCTION; } + | + { op = Operator.BITWISE_REVERSE; } + ) + expr = unary_expr() + { + opExpr.setOperator(op); + opExpr.addOperand(expr); + endDecl(opExpr); + endMacroSuffix(opExpr); + expr = opExpr; + } + | + { + OperationDecl preExpr = new OperationDecl(); + beginDecl(preExpr); + } + ( + { op = Operator.PRE_INCREMENT; } + | + { op = Operator.PRE_DECREMENT; } + ) + expr = var_ref() + { + preExpr.setOperator(op); + preExpr.addOperand(expr); + endDecl(preExpr); + endMacroSuffix(preExpr); + expr = preExpr; + } + | + expr = var_ref() + [ + { + OperationDecl postExpr = new OperationDecl(null, expr); + postExpr.setBeginLocation(expr); + beginCapture(postExpr); + } + ( + { op = Operator.POST_INCREMENT; } + | + { op = Operator.POST_DECREMENT; } + ) + { + postExpr.setOperator(op); + endDecl(postExpr); + endMacroSuffix(postExpr); + expr = postExpr; + } + | + { + if (expr instanceof VarRefDecl) { + ((VarRefDecl) expr).setFunctionCall(true); + } + FuncCallDecl callExpr = new FuncCallDecl(expr); + callExpr.setBeginLocation(expr); + beginCapture(callExpr); + } + call_args(callExpr.getArguments()) + call_constraints(callExpr) + { + endDecl(callExpr); + endMacroSuffix(callExpr); + expr = callExpr; + } + ] + | + expr = literal() + | + expr = rcat_expr() + | + expr = cond_expr() + ) + { + endMacro(expr, false); + return expr; + } +} + +ExpressionDecl var_ref() : +{ + ExpressionDecl expr, varExpr; + String scope = null, id; + DummyDecl dummy = new DummyDecl(); + beginDecl(dummy); + beginMacro(); +} +{ + ( + { varExpr = new ThisRefDecl(); } + | + { varExpr = new SuperRefDecl(); } + | + [ LOOKAHEAD(2) scope = identifier() ] + id = identifierExt() + { varExpr = new VarRefDecl(id, scope); } + ) + { + endDecl(dummy); + varExpr.copyMetadata(dummy); + endMacroSuffix(varExpr); + expr = varExpr; + } + ( expr = var_ref_suffix(expr) )* + { + endMacro(expr, false); + return expr; + } +} + +ExpressionDecl var_ref_suffix(ExpressionDecl expr) : +{ + String id; + Token t; + ExpressionDecl index; +} +{ + ( + // member access + { + MemberAccessDecl memberExpr = new MemberAccessDecl(expr); + memberExpr.setBeginLocation(expr); + beginCapture(memberExpr); + } + id = identifierExt() + { + memberExpr.setIdentifier(id); + endDecl(memberExpr); + endMacroSuffix(memberExpr); + expr = memberExpr; + } + [ + // sample depth access + LOOKAHEAD(2) + { + DepthAccessDecl depthExpr = new DepthAccessDecl(expr); + depthExpr.setBeginLocation(expr); + beginCapture(depthExpr); + } + t = + { + int depth = IntegerLiteralDecl.parse(t.image); + depthExpr.setDepth(depth); + endDecl(depthExpr); + endMacroSuffix(depthExpr); + expr = depthExpr; + } + ] + | + // array and bit slice access + { + RangeDecl r; + DummyDecl dummy = new DummyDecl(); + dummy.setBeginLocation(expr); + beginCapture(dummy); + } + + ( + LOOKAHEAD( cond_expr() ) + r = range() + { + expr = new BitSliceAccessDecl(expr, r); + } + | + index = cond_expr() + { + ArrayAccessDecl arrayAccess = new ArrayAccessDecl(expr); + arrayAccess.addIndexExpr(index); + expr = arrayAccess; + } + ( + // NOTE: The lookahead directive below is used to indicate + // that this production is greedy and to suppress the JavaCC + // warning that '[' is a common prefix of this expansion + // and the following expansion (also var_ref_suffix). + // This grammar mirrors Vera limitation that bit slice + // access cannot follow array access. + LOOKAHEAD(1) + index = cond_expr() + { + arrayAccess.addIndexExpr(index); + } + )* + ) + { + endDecl(dummy); + expr.copyMetadata(dummy); + endMacroSuffix(expr); + } + ) + { return expr; } +} + +void call_args(List args) : +{ + ExpressionDecl expr; +} +{ + + [ + expr = call_arg() { args.add(expr); } + ( + { beginCapture(expr); } { endCapture(expr); } + expr = call_arg() { args.add(expr); } + )* + ] + +} + +void call_constraints(FuncCallDecl callExpr) : +{ +} +{ + [ + { + ConstraintDecl cons = new ConstraintDecl(); + callExpr.setConstraints(cons); + } + constraint_block(cons) + ] +} + +ExpressionDecl call_arg() : +{ + ExpressionDecl expr; +} +{ + ( + { + expr = new DefaultValueDecl(); + beginDecl(expr); + } + + { + endDecl(expr); + } + | + expr = cond_expr() + ) + { return expr; } +} + +LiteralDecl literal() : +{ + LiteralDecl expr; + Token t; + beginMacro(); +} +{ + ( + t = + { expr = new StringLiteralDecl(StringLiteralDecl.parse(t.image)); } + | + t = + { expr = new IntegerLiteralDecl(IntegerLiteralDecl.parse(t.image)); } + | + t = + { expr = BitVectorLiteralDecl.parse(t.image); } + | + t = + { expr = new NullLiteralDecl(); } + | + t = + { expr = new VoidLiteralDecl(); } + ) + { + expr.setBeginLocation(t); + expr.setEndLocation(t); + expr.applyCommentsFrom(t, true); + endMacro(expr, true); + return expr; + } +} + +ExpressionDecl rcat_expr() : +{ + ExpressionDecl expr1, expr2; + OperationDecl opExpr = new OperationDecl(); + beginDecl(opExpr); + beginMacro(); +} +{ + expr1 = cond_expr() + [ + expr2 = rcat_expr() + { + opExpr.setOperator(Operator.REPLICATION); + opExpr.addOperand(expr1); + opExpr.addOperand(expr2); + expr1 = opExpr; + } + | + { + opExpr.setOperator(Operator.CONCATENATION); + opExpr.addOperand(expr1); + expr2 = expr1; + expr1 = opExpr; + } + ( + { beginCapture(expr2); } { endCapture(expr2); } + expr2 = cond_expr() { opExpr.addOperand(expr2); } + )+ + ] + + { + endDecl(opExpr); + if (expr1 != opExpr) expr1.copyMetadata(opExpr); + endMacro(expr1, expr1 == opExpr); + return expr1; + } +} + +String identifier() : +{ + Token t; +} +{ + t = + { return t.image; } +} + +String identifierExt() : +{ + Token t; +} +{ + ( t = | t = ) + { return t.image; } +} + +String string() : +{ + Token t; +} +{ + t = + { return StringLiteralDecl.parse(t.image); } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParserBasePPHandler.java b/java/vera-parser/src/com/newisys/parser/vera/VeraParserBasePPHandler.java new file mode 100644 index 0000000..396009a --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParserBasePPHandler.java @@ -0,0 +1,78 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import java.util.Map; + +import com.newisys.parser.util.PreprocessedToken; +import com.newisys.parser.verapp.VeraPPBaseHandler; +import com.newisys.parser.verapp.VeraPPMacro; +import com.newisys.parser.verapp.VeraPPParser; +import com.newisys.parser.verapp.VeraPPParserConstants; + +/** + * Vera parser base handler for Vera preprocessor callbacks. Simply extends + * VeraPPBaseHandler with the ability to push translated tokens from the + * preprocessor into the VeraParserTokenManager. + * + * @author Trevor Robinson + */ +public class VeraParserBasePPHandler + extends VeraPPBaseHandler +{ + protected final VeraParserTokenManager tm; + + public VeraParserBasePPHandler(VeraParserTokenManager tm) + { + this.tm = tm; + } + + public VeraParserBasePPHandler( + VeraParserTokenManager tm, + Map defines) + { + super(defines); + this.tm = tm; + } + + public void processToken(VeraPPParser parser, PreprocessedToken t) + { + if (!isSkipped() && t.kind != VeraPPParserConstants.WS) + { + tm.pushToken(translateToken(parser, t)); + } + } + + public void processEndOfFile(VeraPPParser parser, PreprocessedToken t) + { + // ignore EOF of included files + if (getIncludeDepth() == 0) + { + tm.pushToken(translateToken(parser, t)); + } + } + + protected VeraToken translateToken(VeraPPParser parser, PreprocessedToken t) + { + fillInPreprocessedToken(parser, t); + VeraToken t2 = new VeraToken(); + t2.assignFrom(t); + t2.kind = TokenTranslationTable.translate(t.kind); + return t2; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParserBoundedTokenManager.java b/java/vera-parser/src/com/newisys/parser/vera/VeraParserBoundedTokenManager.java new file mode 100644 index 0000000..1e2f580 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParserBoundedTokenManager.java @@ -0,0 +1,111 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import com.newisys.parser.util.Token; + +/** + * Bounded buffer implementation of VeraParserTokenManager. Designed to be used + * between separate preprocessor and parser threads. + * + * @author Trevor Robinson + */ +public class VeraParserBoundedTokenManager + implements VeraParserTokenManager +{ + private static final int BUF_SIZE = 1024; + + private final VeraToken[] buffer = new VeraToken[BUF_SIZE]; + private int count; + private int readIndex; + private int writeIndex; + + public void pushToken(VeraToken t) + { + while (true) + { + synchronized (buffer) + { + // write to next position in buffer if not full + if (count < BUF_SIZE) + { + buffer[writeIndex++] = t; + if (writeIndex >= BUF_SIZE) + { + writeIndex = 0; + } + // if buffer was empty, notify potentially waiting reader + if (count == 0) + { + buffer.notify(); + } + ++count; + break; + } + + // buffer is full; wait for notification from reader + try + { + buffer.wait(); + } + catch (InterruptedException e) + { + throw new RuntimeException(e); + } + } + } + } + + public Token getNextToken() + { + VeraToken t; + while (true) + { + synchronized (buffer) + { + // read from next position in buffer if not empty + if (count > 0) + { + t = buffer[readIndex++]; + if (readIndex >= BUF_SIZE) + { + readIndex = 0; + } + // if buffer was full, notify potentially waiting writer + if (count == BUF_SIZE) + { + buffer.notify(); + } + --count; + break; + } + + // buffer is empty; wait for notification from writer + try + { + buffer.wait(); + } + catch (InterruptedException e) + { + throw new RuntimeException(e); + } + } + } + return t; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParserPPHandler.java b/java/vera-parser/src/com/newisys/parser/vera/VeraParserPPHandler.java new file mode 100644 index 0000000..d6400b3 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParserPPHandler.java @@ -0,0 +1,315 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langsource.vera.CompilationUnitDeclMember; +import com.newisys.langsource.vera.DefineDecl; +import com.newisys.langsource.vera.PragmaDecl; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.util.PreprocessedToken; +import com.newisys.parser.util.Token; +import com.newisys.parser.verapp.VeraPPMacro; +import com.newisys.parser.verapp.VeraPPParser; +import com.newisys.parser.verapp.VeraPPParserConstants; + +/** + * Vera parser handler for Vera preprocessor callbacks. Adds comment and + * preprocessor #define tracking to VeraParserBasePPHandler. + * + * @author Trevor Robinson + */ +public class VeraParserPPHandler + extends VeraParserBasePPHandler +{ + private final List preprocDecls; + private VeraToken nextToken; + private PreprocessedToken firstCommentToken; + private PreprocessedToken prevCommentToken; + private CompilationUnitDeclMember preprocDeclOnLine; + private boolean tokenOrCommentOnLine; + + protected boolean markDefinesLocal; + protected boolean markVerilogImport; + + public VeraParserPPHandler(VeraParserTokenManager tm) + { + super(tm); + preprocDecls = new LinkedList(); + } + + public void processToken(VeraPPParser parser, PreprocessedToken t) + { + // preprocessor directives should be separated from tokens by newline + assert (preprocDeclOnLine == null); + + if (!isSkipped() && t.kind != VeraPPParserConstants.WS) + { + if (nextToken != null) + { + tm.pushToken(nextToken); + } + nextToken = translateToken(parser, t); + tokenOrCommentOnLine = true; + } + } + + public void processComment(VeraPPParser parser, PreprocessedToken t) + { + if (!isSkipped()) + { + addCommentToken(parser, t); + } + } + + public void processEndOfLine(VeraPPParser parser, PreprocessedToken t) + { + if (preprocDeclOnLine != null) + { + applyPreprocComments(false); + } + preprocDeclOnLine = null; + + if (nextToken != null) + { + nextToken.trailingComments = firstCommentToken; + clearCommentTokens(); + tm.pushToken(nextToken); + nextToken = null; + } + else if (!tokenOrCommentOnLine + && (prevCommentToken == null || prevCommentToken.kind != t.kind)) + { + addCommentToken(parser, t); + } + tokenOrCommentOnLine = false; + } + + public void processEndOfFile(VeraPPParser parser, PreprocessedToken t) + { + // treat EOF like EOL for purposes of comment/token handling + processEndOfLine(parser, t); + + // don't want to apply comments across files + clearCommentTokens(); + + super.processEndOfFile(parser, t); + } + + public void processInclude( + VeraPPParser parser, + String path, + boolean sysPath, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + super.processInclude(parser, path, sysPath, t1, t2); + clearCommentTokens(); + } + + public void processDefine( + VeraPPParser parser, + VeraPPMacro macro, + PreprocessedToken t1, + PreprocessedToken t2) + { + // preprocessor directives should be separated from tokens by newline + assert (nextToken == null); + + super.processDefine(parser, macro, t1, t2); + if (!isSkipped()) + { + DefineDecl defineDecl = new DefineDecl(macro); + defineDecl.setLocal(markDefinesLocal); + defineDecl.setVerilogImport(markVerilogImport); + fillInPreprocessedToken(parser, t1); + defineDecl.setBeginLocation(t1); + fillInPreprocessedToken(parser, t2); + defineDecl.setEndLocation(t2); + preprocDeclOnLine = defineDecl; + applyPreprocComments(true); + preprocDecls.add(preprocDeclOnLine); + } + clearCommentTokens(); + } + + public void processUndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processUndef(parser, name, t1, t2); + clearCommentTokens(); + } + + public void processIfdef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processIfdef(parser, name, t1, t2); + clearCommentTokens(); + } + + public void processIfndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processIfndef(parser, name, t1, t2); + clearCommentTokens(); + } + + public void processIf( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processIf(parser, condition, t1, t2); + clearCommentTokens(); + } + + public void processElif( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + super.processElif(parser, condition, t1, t2); + clearCommentTokens(); + } + + public void processElse(VeraPPParser parser, PreprocessedToken t) + throws ParseException + { + super.processElse(parser, t); + clearCommentTokens(); + } + + public void processEndif(VeraPPParser parser, PreprocessedToken t) + throws ParseException + { + super.processEndif(parser, t); + clearCommentTokens(); + } + + public void processPragma( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + { + // preprocessor directives should be separated from tokens by newline + assert (nextToken == null); + + super.processPragma(parser, text, t1, t2); + if (!isSkipped()) + { + PragmaDecl pragmaDecl = new PragmaDecl(text); + fillInPreprocessedToken(parser, t1); + pragmaDecl.setBeginLocation(t1); + fillInPreprocessedToken(parser, t2); + pragmaDecl.setEndLocation(t2); + preprocDeclOnLine = pragmaDecl; + applyPreprocComments(true); + preprocDecls.add(preprocDeclOnLine); + } + clearCommentTokens(); + } + + public void processLine( + VeraPPParser parser, + int lineNo, + String path, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processLine(parser, lineNo, path, t1, t2); + clearCommentTokens(); + } + + public void processError( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + super.processError(parser, text, t1, t2); + clearCommentTokens(); + } + + public void processWarning( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + { + super.processWarning(parser, text, t1, t2); + clearCommentTokens(); + } + + protected VeraToken translateToken(VeraPPParser parser, PreprocessedToken t) + { + VeraToken t2 = super.translateToken(parser, t); + t2.leadingComments = firstCommentToken; + if (!preprocDecls.isEmpty()) + { + t2.addPreprocDecls(preprocDecls); + preprocDecls.clear(); + } + clearCommentTokens(); + return t2; + } + + private void applyPreprocComments(boolean leading) + { + Token ct = firstCommentToken; + while (ct != null) + { + preprocDeclOnLine.applyComment(ct, leading, true); + ct = ct.next; + } + clearCommentTokens(); + } + + private void addCommentToken(VeraPPParser parser, PreprocessedToken t) + { + fillInPreprocessedToken(parser, t); + PreprocessedToken t2 = (PreprocessedToken) t.clone(); + t2.next = null; + t2.specialToken = prevCommentToken; + if (prevCommentToken != null) prevCommentToken.next = t2; + prevCommentToken = t2; + if (firstCommentToken == null) firstCommentToken = t2; + tokenOrCommentOnLine = true; + } + + private void clearCommentTokens() + { + firstCommentToken = prevCommentToken = null; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParserReusableTokenManager.java b/java/vera-parser/src/com/newisys/parser/vera/VeraParserReusableTokenManager.java new file mode 100644 index 0000000..741b0c0 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParserReusableTokenManager.java @@ -0,0 +1,70 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import java.util.Iterator; +import java.util.LinkedList; + +import com.newisys.parser.util.Token; + +/** + * Linked list implementation of VeraParserTokenManager that can be reset to + * the beginning and reread. + * + * @author Trevor Robinson + */ +public class VeraParserReusableTokenManager + implements VeraParserTokenManager +{ + private final LinkedList tokens = new LinkedList(); + private Iterator tokenIter; + + public void pushToken(VeraToken t) + { + tokens.addLast(t); + } + + public Token getNextToken() + { + if (tokenIter == null) tokenIter = tokens.iterator(); + VeraToken t = tokenIter.next(); + // break token chain from previous parse so parser is not confused + t.next = null; + return t; + } + + public void reset() + { + tokenIter = null; + } + + public String getContents() + { + int len = 0; + for (VeraToken t : tokens) + { + len += t.image.length(); + } + StringBuffer buf = new StringBuffer(len); + for (VeraToken t : tokens) + { + buf.append(t.image); + } + return buf.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraParserTokenManager.java b/java/vera-parser/src/com/newisys/parser/vera/VeraParserTokenManager.java new file mode 100644 index 0000000..5cd0a7b --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraParserTokenManager.java @@ -0,0 +1,32 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import com.newisys.parser.util.TokenManager; + +/** + * Extends the JavaCC TokenManager interface with the ability to push tokens + * into the token stream. + * + * @author Trevor Robinson + */ +public interface VeraParserTokenManager + extends TokenManager +{ + void pushToken(VeraToken t); +} diff --git a/java/vera-parser/src/com/newisys/parser/vera/VeraToken.java b/java/vera-parser/src/com/newisys/parser/vera/VeraToken.java new file mode 100644 index 0000000..96913a1 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/vera/VeraToken.java @@ -0,0 +1,54 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.vera; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.langsource.vera.CompilationUnitDeclMember; +import com.newisys.parser.util.PreprocessedToken; + +/** + * Extends PreprocessedToken to include leading and trailing comment tokens + * and adjacent preprocessor directives. + * + * @author Trevor Robinson + */ +public class VeraToken + extends PreprocessedToken +{ + public PreprocessedToken leadingComments; + public PreprocessedToken trailingComments; + + public List preprocDecls; + + public void addPreprocDecl(CompilationUnitDeclMember decl) + { + if (preprocDecls == null) + preprocDecls = new LinkedList(); + preprocDecls.add(decl); + } + + public void addPreprocDecls(Collection decls) + { + if (preprocDecls == null) + preprocDecls = new LinkedList(); + preprocDecls.addAll(decls); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/PathResolver.java b/java/vera-parser/src/com/newisys/parser/verapp/PathResolver.java new file mode 100644 index 0000000..511b9ce --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/PathResolver.java @@ -0,0 +1,106 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * Resolves filenames against a set of search paths, and caches the result to + * speed up future lookups of the same filename. + * + * @author Trevor Robinson + */ +public final class PathResolver +{ + private final Set searchPaths = new LinkedHashSet(); + + public void addSearchPath(String path) + { + searchPaths.add(path); + invalidateResolutions(); + } + + public Set getSearchPaths() + { + return Collections.unmodifiableSet(searchPaths); + } + + private final Map resolvedFileMap = new HashMap(); + + private void addResolution(String filename, String path) + { + resolvedFileMap.put(filename, path); + } + + private String getResolution(String filename) + { + return resolvedFileMap.get(filename); + } + + private void invalidateResolutions() + { + resolvedFileMap.clear(); + } + + public String resolve(String filename) + throws IOException + { + String result = getResolution(filename); + if (result == null) + { + final File f = new File(filename); + if (f.exists()) + { + result = f.getCanonicalPath(); + } + else if (!f.isAbsolute()) + { + final Iterator i = searchPaths.iterator(); + while (i.hasNext()) + { + final String path = i.next(); + File searchFile = new File(path); + if (f.getName().equals(searchFile.getName())) + { + searchFile = new File(searchFile.getParent(), filename); + if (searchFile.exists()) + { + result = searchFile.getCanonicalPath(); + break; + } + } + searchFile = new File(searchFile, filename); + if (searchFile.exists()) + { + result = searchFile.getCanonicalPath(); + break; + } + } + } + addResolution(filename, result); + } + return result; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPBaseHandler.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPBaseHandler.java new file mode 100644 index 0000000..91fc329 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPBaseHandler.java @@ -0,0 +1,489 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +import com.newisys.parser.util.IncludeLocation; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.util.PreprocessedToken; +import com.newisys.parser.util.Token; + +/** + * Base handler for Vera preprocessor callbacks. Performs basic functions like + * maintaining the #define table, resolving #include directives, and #if/#ifdef + * handling. + * + * @author Trevor Robinson + */ +public class VeraPPBaseHandler + implements VeraPPCallbacks +{ + private static final Logger logger = Logger.getLogger("VeraPPBaseHandler"); + + private static class CondInfo + { + boolean matched = false; + boolean gotElse = false; + } + + protected final PathResolver sysPathResolver; + protected final PathResolver userPathResolver; + private final Map defines; + private final LinkedList condStack; + private int skipDepth; + private int includeDepth; + private IncludeLocation includeLocation; + + public VeraPPBaseHandler() + { + this(new LinkedHashMap()); + } + + protected VeraPPBaseHandler(Map defines) + { + sysPathResolver = new PathResolver(); + userPathResolver = new PathResolver(); + this.defines = defines; + condStack = new LinkedList(); + skipDepth = 0; + includeDepth = 0; + } + + public void addSysPath(String path) + { + sysPathResolver.addSearchPath(path); + } + + public Set getSysPaths() + { + return sysPathResolver.getSearchPaths(); + } + + public void addUserPath(String path) + { + userPathResolver.addSearchPath(path); + } + + public Set getUserPaths() + { + return userPathResolver.getSearchPaths(); + } + + public String resolvePath(String path, boolean sysPath) + throws IOException + { + String foundPath = null; + if (!sysPath) + { + foundPath = userPathResolver.resolve(path); + } + if (foundPath == null) + { + foundPath = sysPathResolver.resolve(path); + } + return foundPath; + } + + public void addDefine(VeraPPMacro macro) + { + defines.put(macro.getName(), macro); + } + + public void removeDefine(String name) + { + defines.remove(name); + } + + public VeraPPMacro getDefine(String name) + { + return defines.get(name); + } + + public Map getDefines() + { + return defines; + } + + protected Map copyDefines() + { + return new LinkedHashMap(defines); + } + + public void processToken(VeraPPParser parser, PreprocessedToken t) + { + // do nothing + } + + public void processComment(VeraPPParser parser, PreprocessedToken t) + { + // do nothing + } + + public void processEndOfLine(VeraPPParser parser, PreprocessedToken t) + { + // do nothing + } + + public void processEndOfFile(VeraPPParser parser, PreprocessedToken t) + { + // do nothing + } + + protected void fillInPreprocessedToken(VeraPPParser parser, Token t) + { + PreprocessedToken ft = (PreprocessedToken) t; + ft.filename = parser.getFilename(); + ft.includedFrom = includeLocation; + } + + public IncludeLocation getIncludedFrom() + { + return includeLocation; + } + + public void processInclude( + VeraPPParser parser, + String path, + boolean sysPath, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + logDirective(parser, "#include " + path); + if (skipDepth == 0) + { + String foundPath; + try + { + foundPath = resolvePath(path, sysPath); + if (foundPath == null) foundPath = path; + } + catch (IOException e) + { + throw new ParseException("Error resolving include path: " + + e.getMessage()); + } + doInclude(parser, foundPath); + } + } + + protected void doInclude(VeraPPParser parser, String path) + throws ParseException + { + ++includeDepth; + + IncludeLocation saveLocation = includeLocation; + includeLocation = new IncludeLocation(parser.getFilename(), parser + .getCurrentLine(), saveLocation); + + try + { + VeraPPParser includeParser = new VeraPPParser(path, this); + includeParser.file(); + } + catch (FileNotFoundException e) + { + throw new ParseException("Include file not found: " + path); + } + finally + { + --includeDepth; + + includeLocation = saveLocation; + } + } + + public void processDefine( + VeraPPParser parser, + VeraPPMacro macro, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#define " + macro); + if (skipDepth == 0) + { + String name = macro.getName(); + VeraPPMacro existingMacro = lookupMacro(parser, name); + if (existingMacro != null && !macro.equals(existingMacro)) + { + StringBuffer buf = new StringBuffer(); + buf.append("Macro '"); + buf.append(name); + buf.append("' redefined as '"); + buf.append(macro.expand()); + buf.append('\''); + if (macro instanceof VeraPPUserMacro) + { + buf.append(" at "); + buf.append(((VeraPPUserMacro) macro).getLocation()); + } + buf.append("; was defined as '"); + buf.append(existingMacro.expand()); + buf.append('\''); + if (existingMacro instanceof VeraPPUserMacro) + { + buf.append(" at "); + buf.append(((VeraPPUserMacro) existingMacro).getLocation()); + } + doWarning(buf.toString()); + } + addDefine(macro); + } + } + + public void processUndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#undef " + name); + if (skipDepth == 0) + { + removeDefine(name); + } + } + + public void processIfdef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#ifdef " + name); + CondInfo condInfo = new CondInfo(); + condStack.addLast(condInfo); + if (skipDepth == 0 && lookupMacro(parser, name) != null) + { + condInfo.matched = true; + } + else + { + ++skipDepth; + } + } + + public void processIfndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#ifndef " + name); + CondInfo condInfo = new CondInfo(); + condStack.addLast(condInfo); + if (skipDepth == 0 && lookupMacro(parser, name) == null) + { + condInfo.matched = true; + } + else + { + ++skipDepth; + } + } + + public void processIf( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#if " + condition); + CondInfo condInfo = new CondInfo(); + condStack.addLast(condInfo); + if (skipDepth == 0 && condition) + { + condInfo.matched = true; + } + else + { + ++skipDepth; + } + } + + public void processElif( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + logDirective(parser, "#elif " + condition); + if (condStack.isEmpty()) + { + throw new ParseException("#elif without #if"); + } + CondInfo condInfo = condStack.getLast(); + if (condInfo.gotElse) + { + throw new ParseException("#elif after #else"); + } + if (skipDepth == 1 && condition && !condInfo.matched) + { + condInfo.matched = true; + skipDepth = 0; + } + else if (skipDepth == 0) + { + skipDepth = 1; + } + } + + public void processElse(VeraPPParser parser, PreprocessedToken t) + throws ParseException + { + logDirective(parser, "#else"); + if (condStack.isEmpty()) + { + throw new ParseException("#else without #if"); + } + CondInfo condInfo = condStack.getLast(); + if (condInfo.gotElse) + { + throw new ParseException("#else after #else"); + } + condInfo.gotElse = true; + if (skipDepth == 1 && !condInfo.matched) + { + condInfo.matched = true; + skipDepth = 0; + } + else if (skipDepth == 0) + { + skipDepth = 1; + } + } + + public void processEndif(VeraPPParser parser, PreprocessedToken t) + throws ParseException + { + logDirective(parser, "#endif"); + if (condStack.isEmpty()) + { + throw new ParseException("#endif without #if"); + } + condStack.removeLast(); + if (skipDepth > 0) + { + --skipDepth; + } + } + + public void processPragma( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#pragma " + text); + // do nothing + } + + public void processLine( + VeraPPParser parser, + int lineNo, + String path, + PreprocessedToken t1, + PreprocessedToken t2) + { + logDirective(parser, "#line " + lineNo + " " + path); + // do nothing + } + + public void processError( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException + { + throw new ParseException(text); + } + + public void processWarning( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + { + doWarning(text); + } + + protected void doWarning(String text) + { + System.err.println("Warning: " + text); + } + + public VeraPPMacro lookupMacro(VeraPPParser parser, String name) + { + return getDefine(name); + } + + public void processMacroReference( + VeraPPParser parser, + VeraPPMacro macro, + PreprocessedToken t) + { + if (skipDepth == 0) + { + parser.doExpansion(macro, t); + } + } + + public void processMacroReference( + VeraPPParser parser, + VeraPPFunctionMacro macro, + List argList, + PreprocessedToken t1, + PreprocessedToken t2) + { + if (skipDepth == 0) + { + parser.doExpansion(macro, argList, t1, t2); + } + } + + protected final boolean isSkipped() + { + return skipDepth != 0; + } + + protected final int getIncludeDepth() + { + return includeDepth; + } + + private static void logDirective(VeraPPParser parser, String msg) + { + logger.fine(msg + getLocationMsg(parser)); + } + + private static String getLocationMsg(VeraPPParser parser) + { + return " at " + parser.getFilename() + ", line " + + parser.getCurrentLine(); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCallbacks.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCallbacks.java new file mode 100644 index 0000000..6890a8e --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCallbacks.java @@ -0,0 +1,133 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.util.List; + +import com.newisys.parser.util.IncludeLocation; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.util.PreprocessedToken; + +/** + * Vera preprocessor callbacks. + * + * @author Trevor Robinson + */ +public interface VeraPPCallbacks +{ + void processToken(VeraPPParser parser, PreprocessedToken t); + + void processComment(VeraPPParser parser, PreprocessedToken t); + + void processEndOfLine(VeraPPParser parser, PreprocessedToken t); + + void processEndOfFile(VeraPPParser parser, PreprocessedToken t); + + IncludeLocation getIncludedFrom(); + + void processInclude( + VeraPPParser parser, + String path, + boolean sysPath, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException; + + void processDefine( + VeraPPParser parser, + VeraPPMacro macro, + PreprocessedToken t1, + PreprocessedToken t2); + + void processUndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2); + + void processIfdef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2); + + void processIfndef( + VeraPPParser parser, + String name, + PreprocessedToken t1, + PreprocessedToken t2); + + void processIf( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2); + + void processElif( + VeraPPParser parser, + boolean condition, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException; + + void processElse(VeraPPParser parser, PreprocessedToken t) + throws ParseException; + + void processEndif(VeraPPParser parser, PreprocessedToken t) + throws ParseException; + + void processPragma( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2); + + void processLine( + VeraPPParser parser, + int lineNo, + String path, + PreprocessedToken t1, + PreprocessedToken t2); + + void processError( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2) + throws ParseException; + + void processWarning( + VeraPPParser parser, + String text, + PreprocessedToken t1, + PreprocessedToken t2); + + VeraPPMacro lookupMacro(VeraPPParser parser, String name); + + void processMacroReference( + VeraPPParser parser, + VeraPPMacro macro, + PreprocessedToken t); + + void processMacroReference( + VeraPPParser parser, + VeraPPFunctionMacro macro, + List argList, + PreprocessedToken t1, + PreprocessedToken t2); +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCharStream.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCharStream.java new file mode 100644 index 0000000..1a8e4b4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPCharStream.java @@ -0,0 +1,610 @@ +/* + * JavaCC (TM) parser definition for the OpenVera (TM) language + * Copyright (C) 2003 Trevor A. Robinson + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; + +/** + * CharStream implementation that can have arbitrary data pushed into it. + * Used by VeraPPParserTokenManager to handle macro expansions. + * + * @author Trevor Robinson + */ +public final class VeraPPCharStream + implements CharStream +{ + public abstract class Chunk + implements Cloneable + { + Chunk prev; + Chunk next; + protected char[] buf; + protected int first; + protected int last; + protected int pos; + protected Object marker; + + public Chunk() + { + first = 0; + last = pos = -1; + } + + public int available() + throws IOException + { + return last - pos; + } + + public char read() + throws IOException + { + assert (pos < last); + ++pos; + assert (pos >= first); + ++currentPos; + return buf[pos]; + } + + public int getImageLength() + { + return pos - first + 1; + } + + public void backup(int count) + { + assert (count <= getImageLength()); + pos -= count; + currentPos -= count; + } + + public void appendImage(StringBuffer buf, int count) + { + assert (count <= getImageLength()); + buf.append(this.buf, pos - count + 1, count); + } + + public void copyImage(char[] buf, int offset, int count) + { + assert (count <= getImageLength()); + System.arraycopy(this.buf, pos - count + 1, buf, offset, count); + } + + public void split() + { + // do nothing if before first or at last character + if (pos >= first && pos < last) + { + try + { + Chunk newChunk = (Chunk) clone(); + + // insert new chunk after this chunk + if (next != null) + { + next.prev = newChunk; + newChunk.next = next; + } + newChunk.prev = this; + next = newChunk; + + // set buffer ranges + last = pos; + newChunk.first = pos + 1; + } + catch (CloneNotSupportedException e) + { + } + } + } + + public abstract int getLine(); + + public abstract int getColumn(); + + public Object getMarker() + { + return marker; + } + } + + private final class ReaderChunk + extends Chunk + { + private final int[] lines; + private final int[] columns; + private int lcPos; + + public ReaderChunk() + { + buf = new char[bufferSize]; + lines = new int[bufferSize]; + columns = new int[bufferSize]; + lcPos = -1; + } + + private void checkFill() + throws IOException + { + if (last < 0 && !eof) + { + int count = reader.read(buf); + if (count > 0) + { + last = count - 1; + } + else + { + eof = true; + } + } + } + + public int available() + throws IOException + { + // fill on first call + checkFill(); + + return super.available(); + } + + public char read() + throws IOException + { + // fill on first call + checkFill(); + + if (eof) + { + throw new IOException("End of file"); + } + + char c = super.read(); + + // set line/column if not already set + if (lcPos < pos) + { + lines[pos] = currentLine; + columns[pos] = currentColumn; + lcPos = pos; + + boolean newLine = false; + switch (c) + { + case '\r': + newLine = true; + break; + case '\n': + if (prevChar != '\r') + { + newLine = true; + } + break; + } + if (newLine) + { + ++currentLine; + currentColumn = 1; + } + else + { + ++currentColumn; + } + prevChar = c; + } + + return c; + } + + public int getLine() + { + return pos >= 0 ? lines[pos] : currentLine; + } + + public int getColumn() + { + return pos >= 0 ? columns[pos] : currentColumn; + } + } + + private final class InsertChunk + extends Chunk + { + private final int line; + private final int column; + + public InsertChunk( + char[] buf, + int offset, + int length, + int line, + int column, + Object marker) + { + this.buf = buf; + this.first = offset; + this.last = offset + length - 1; + this.line = line; + this.column = column; + this.marker = marker; + } + + public int getLine() + { + return line; + } + + public int getColumn() + { + return column; + } + } + + private static final int DEF_BUF_SIZE = 4096; + + // default access for efficient access by inner class + Reader reader; + int bufferSize; + + int currentPos; + int currentColumn; + int currentLine; + + private Chunk startChunk; + private int startChunkSkip; + private int startPos; + private int startColumn; + private int startLine; + + private Chunk curChunk; + char prevChar; + boolean eof; + + public VeraPPCharStream( + Reader dstream, + int startline, + int startcolumn, + int buffersize) + { + this.reader = dstream; + this.bufferSize = buffersize; + + this.currentPos = -1; + this.currentColumn = startcolumn; + this.currentLine = startline; + + this.startChunkSkip = -1; + this.startPos = -1; + this.startColumn = -1; + this.startLine = -1; + + this.curChunk = new ReaderChunk(); + } + + public VeraPPCharStream(Reader dstream, int startline, int startcolumn) + { + this(dstream, startline, startcolumn, DEF_BUF_SIZE); + } + + public VeraPPCharStream(Reader dstream) + { + this(dstream, 1, 1, DEF_BUF_SIZE); + } + + public VeraPPCharStream( + InputStream dstream, + int startline, + int startcolumn, + int buffersize) + { + this(new InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + public VeraPPCharStream(InputStream dstream, int startline, int startcolumn) + { + this(dstream, startline, startcolumn, DEF_BUF_SIZE); + } + + public VeraPPCharStream(InputStream dstream) + { + this(dstream, 1, 1, DEF_BUF_SIZE); + } + + public char readChar() + throws IOException + { + while (true) + { + // try to read from current chunk + if (curChunk.available() > 0) + { + return curChunk.read(); + } + + // move to next chunk if present + if (curChunk.next != null) + { + curChunk = curChunk.next; + continue; + } + + // check for EOF + if (eof) + { + throw new IOException("End of file"); + } + + // create new chunk from reader + Chunk newChunk = new ReaderChunk(); + + // add chunk to doubly-linked chain + curChunk.next = newChunk; + newChunk.prev = curChunk; + + // move to new chunk + curChunk = newChunk; + } + } + + public int getColumn() + { + return curChunk.getColumn(); + } + + public int getLine() + { + return curChunk.getLine(); + } + + public int getEndColumn() + { + return curChunk.getColumn(); + } + + public int getEndLine() + { + return curChunk.getLine(); + } + + public int getBeginColumn() + { + return startColumn >= 0 ? startColumn : currentColumn; + } + + public int getBeginLine() + { + return startLine >= 0 ? startLine : currentLine; + } + + public void backup(int amount) + { + while (amount > 0) + { + int imageLength = curChunk.getImageLength(); + int delta; + boolean goToPrev; + if (imageLength <= amount) + { + delta = imageLength; + goToPrev = true; + } + else + { + delta = amount; + goToPrev = false; + } + curChunk.backup(delta); + amount -= delta; + if (goToPrev) + { + if (curChunk.prev == null) + { + throw new IllegalArgumentException( + "Cannot backup past first chunk"); + } + curChunk = curChunk.prev; + } + } + } + + public char BeginToken() + throws IOException + { + // clear token start information + startChunk = null; + startChunkSkip = -1; + startPos = -1; + startLine = -1; + startColumn = -1; + + // drop any previous chunks + curChunk.prev = null; + + // read the first character + char c = readChar(); + + // set token start information + startChunk = curChunk; + startChunkSkip = curChunk.getImageLength() - 1; + startPos = currentPos; + startLine = curChunk.getLine(); + startColumn = curChunk.getColumn(); + + return c; + } + + public String GetImage() + { + // check that a token has been started + if (startPos >= 0) + { + // create string buffer of proper length + int length = currentPos - startPos + 1; + StringBuffer buf = new StringBuffer(length); + + // copy chunks into image buffer + Chunk imageChunk = startChunk; + int appendCount = startChunk.getImageLength() - startChunkSkip; + while (length > 0) + { + imageChunk.appendImage(buf, appendCount); + + length -= appendCount; + if (length == 0) + { + break; + } + + imageChunk = imageChunk.next; + assert (imageChunk != null); + + appendCount = imageChunk.getImageLength(); + } + + return buf.toString(); + } + else + { + // return empty string if token has not been started + return ""; + } + } + + public char[] GetSuffix(int len) + { + // create char buffer of requested length + char[] buf = new char[len]; + + // check that a token has been started + if (startPos >= 0) + { + // check that len <= image length + int imageLength = currentPos - startPos + 1; + assert (len <= imageLength); + + // copy chunks into image buffer + Chunk imageChunk = startChunk; + int appendCount = startChunk.getImageLength() - startChunkSkip; + int imageSkip = imageLength - len; + int offset = 0; + while (len > 0) + { + if (imageSkip > 0) + { + int skip = Math.min(imageSkip, appendCount); + imageSkip -= skip; + appendCount -= skip; + } + if (appendCount > 0) + { + imageChunk.copyImage(buf, offset, appendCount); + offset += appendCount; + } + + len -= appendCount; + if (len == 0) + { + break; + } + + imageChunk = imageChunk.next; + assert (imageChunk != null); + + appendCount = imageChunk.getImageLength(); + } + } + + return buf; + } + + public void Done() + { + try + { + reader.close(); + } + catch (IOException ignored) + { + } + + curChunk = null; + } + + public Chunk insert(char[] chars, int offset, int length, Object marker) + { + return insertAfter(null, chars, offset, length, marker); + } + + public Chunk insert(String s, Object marker) + { + return insert(s.toCharArray(), 0, s.length(), marker); + } + + public Chunk insertAfter( + Chunk chunk, + char[] chars, + int offset, + int length, + Object marker) + { + if (chunk == null) + { + // split current chunk at current position (if necessary) + curChunk.split(); + chunk = curChunk; + } + + // create chunk for inserted characters + InsertChunk newChunk = new InsertChunk(chars, offset, length, chunk + .getLine(), chunk.getColumn(), marker); + + // insert new chunk after current chunk + if (chunk.next != null) + { + chunk.next.prev = newChunk; + newChunk.next = chunk.next; + } + newChunk.prev = chunk; + chunk.next = newChunk; + + return newChunk; + } + + public Chunk insertAfter(Chunk chunk, String s, Object marker) + { + return insertAfter(chunk, s.toCharArray(), 0, s.length(), marker); + } + + public Object getBeginMarker() + { + // return null if token has not been started + return startPos >= 0 ? startChunk.getMarker() : null; + } + + public Object getEndMarker() + { + // return null if token has not been started + return startPos >= 0 ? curChunk.getMarker() : null; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacro.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacro.java new file mode 100644 index 0000000..dbd57b6 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacro.java @@ -0,0 +1,265 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.newisys.parser.util.FunctionMacro; +import com.newisys.parser.util.IncludeLocation; +import com.newisys.parser.util.MacroRef; +import com.newisys.parser.util.Token; + +/** + * VeraPPParser implementation of user function macros. + * + * @author Trevor Robinson + */ +public final class VeraPPFunctionMacro + extends VeraPPUserMacro + implements FunctionMacro +{ + private final List argumentNames = new LinkedList(); + + public VeraPPFunctionMacro(String name, IncludeLocation location) + { + super(name, location); + } + + public void addArgumentName(String name) + { + if (argumentNames.contains(name)) + { + throw new IllegalArgumentException("Duplicate argument name '" + + name + "' for macro " + getName()); + } + + argumentNames.add(name); + } + + public List getArgumentNames() + { + return argumentNames; + } + + public String expand(List argValueList) + { + return expand(getArgumentValueMap(argValueList)); + } + + public String expand(Map argValueMap) + { + StringBuffer buf = new StringBuffer(); + for (Token t : tokens) + { + String expansion = t.image; + if (t.kind == VeraPPParserConstants.MACRO_IDENT) + { + String value = argValueMap.get(expansion); + if (value != null) expansion = value; + } + else if (t.kind == VeraPPParserConstants.DEFINE_STRING) + { + expansion = stringify(expansion, argValueMap); + } + buf.append(expansion); + } + return buf.toString(); + } + + public void expand( + List argValueList, + VeraPPCharStream stream, + VeraPPFunctionMacroRef thisRef) + { + Map argValueMap = getArgumentValueMap(argValueList); + StringBuffer buf = null; + VeraPPCharStream.Chunk chunk = null; + for (Token t : tokens) + { + String expansion = t.image; + MacroRef macroArgRef = null; + if (t.kind == VeraPPParserConstants.MACRO_IDENT) + { + String value = argValueMap.get(expansion); + if (value != null) + { + if (thisRef != null) + { + macroArgRef = new VeraPPMacroArgRef(this, expansion, + thisRef); + } + expansion = value; + } + } + else if (t.kind == VeraPPParserConstants.DEFINE_STRING) + { + expansion = stringify(expansion, argValueMap); + } + + if (macroArgRef != null) + { + if (buf != null) + { + chunk = stream.insertAfter(chunk, buf.toString(), thisRef); + buf = null; + } + chunk = stream.insertAfter(chunk, expansion, macroArgRef); + } + else + { + if (buf == null) buf = new StringBuffer(); + buf.append(expansion); + } + } + if (buf != null) + { + chunk = stream.insertAfter(chunk, buf.toString(), thisRef); + } + } + + private Map getArgumentValueMap(List valueList) + { + Map result = new LinkedHashMap(); + + Iterator argIter = argumentNames.iterator(); + Iterator valueIter = valueList.iterator(); + while (argIter.hasNext()) + { + + if (!valueIter.hasNext()) + { + throw new IllegalArgumentException( + "Not enough actual arguments for macro " + getName()); + } + + String name = argIter.next(); + String value = valueIter.next(); + result.put(name, value); + } + + if (valueIter.hasNext()) + { + throw new IllegalArgumentException( + "Too many actual arguments for macro " + getName()); + } + + return result; + } + + private static final Pattern idPattern = Pattern.compile("\\b\\w+"); + private static final Pattern newlinePattern = Pattern + .compile("[ \t\013\f\r]*\n\\s*"); + + private static String stringify(String s, Map argValueMap) + { + StringBuffer result = new StringBuffer(); + + Matcher m = idPattern.matcher(s); + int prevEnd = 0; + while (m.find()) + { + int start = m.start(); + int end = m.end(); + + if (prevEnd < start) + { + result.append(s.substring(prevEnd, start)); + } + + // extract identifier and look up matching argument + String id = s.substring(start, end); + String value = argValueMap.get(id); + if (value != null) + { + // replace newlines (and adjacent spaces) with a single space + value = newlinePattern.matcher(value).replaceAll(" "); + + // escape double quotes + value = value.replaceAll("\"", "\\\\\""); + } + else + { + // argument not found + value = id; + } + result.append(value); + + prevEnd = end; + } + if (prevEnd < s.length()) + { + // optimization + if (prevEnd == 0) return s; + + result.append(s.substring(prevEnd)); + } + + return result.toString(); + } + + public boolean containsArgumentPasting() + { + int prevKind = 0; + boolean prevArg = false; + for (Token cur : tokens) + { + int curKind = cur.kind; + boolean curArg = (curKind == VeraPPParserConstants.MACRO_IDENT) + && argumentNames.contains(cur.image); + if ((curArg && isPasteable(prevKind)) + || (prevArg && isPasteable(curKind))) return true; + prevKind = curKind; + prevArg = curArg; + } + return false; + } + + public boolean containsStringification() + { + for (Token t : tokens) + { + if (t.kind == VeraPPParserConstants.DEFINE_STRING) + { + if (containsStringification(t.image)) return true; + } + } + return false; + } + + private boolean containsStringification(String s) + { + Matcher m = idPattern.matcher(s); + while (m.find()) + { + String id = m.group(); + if (argumentNames.contains(id)) return true; + } + return false; + } + + public String toString() + { + return getName() + "()"; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacroRef.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacroRef.java new file mode 100644 index 0000000..d5b98df --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPFunctionMacroRef.java @@ -0,0 +1,77 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.util.Iterator; +import java.util.List; + +import com.newisys.parser.util.Macro; +import com.newisys.parser.util.MacroRef; + +/** + * VeraPPParser implementation of function macros references. + * + * @author Trevor Robinson + */ +public class VeraPPFunctionMacroRef + implements MacroRef +{ + private final VeraPPFunctionMacro macro; + private final List argList; + private final MacroRef expandedFrom; + + public VeraPPFunctionMacroRef( + VeraPPFunctionMacro macro, + List argList, + MacroRef expandedFrom) + { + this.macro = macro; + this.argList = argList; + this.expandedFrom = expandedFrom; + } + + public Macro getMacro() + { + return macro; + } + + public List getArgList() + { + return argList; + } + + public MacroRef getExpandedFrom() + { + return expandedFrom; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + buf.append(macro.getName()); + buf.append("("); + Iterator iter = argList.iterator(); + while (iter.hasNext()) + { + buf.append(iter.next()); + if (iter.hasNext()) buf.append(','); + } + buf.append(")"); + return buf.toString(); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPHandler.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPHandler.java new file mode 100644 index 0000000..1421526 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPHandler.java @@ -0,0 +1,131 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.Writer; + +import com.newisys.parser.util.PreprocessedToken; + +/** + * Simple handler for Vera preprocessor callbacks. Writes preprocessed output + * to the given output stream with options to control passthrough of comments + * and pragmas. + * + * @author Trevor Robinson + */ +public class VeraPPHandler + extends VeraPPBaseHandler +{ + private PrintWriter out; + private boolean passPragmas = false; + private boolean passLineComments = true; + private boolean passBlockComments = false; + + public VeraPPHandler(OutputStream _out) + { + this(new PrintWriter(_out, true)); + } + + public VeraPPHandler(Writer _out) + { + this(new PrintWriter(_out, true)); + } + + private VeraPPHandler(PrintWriter _out) + { + this.out = _out; + } + + public void flushOutput() + { + out.flush(); + } + + public boolean isPassPragmas() + { + return passPragmas; + } + + public void setPassPragmas(boolean passPragmas) + { + this.passPragmas = passPragmas; + } + + public boolean isPassLineComments() + { + return passLineComments; + } + + public void setPassLineComments(boolean passLineComments) + { + this.passLineComments = passLineComments; + } + + public boolean isPassBlockComments() + { + return passBlockComments; + } + + public void setPassBlockComments(boolean passBlockComments) + { + this.passBlockComments = passBlockComments; + } + + public void processToken(VeraPPParser parser, PreprocessedToken t) + { + if (!isSkipped()) + { + out.print(t.image); + } + } + + public void processComment(VeraPPParser parser, PreprocessedToken t) + { + boolean lineComment = t.kind == VeraPPParserConstants.SINGLE_LINE_COMMENT; + boolean blockComment = t.kind == VeraPPParserConstants.MULTI_LINE_COMMENT; + if (!isSkipped() + && ((lineComment && passLineComments) || (blockComment && passBlockComments))) + { + out.print(t.image); + } + } + + public void processEndOfLine(VeraPPParser parser, PreprocessedToken t) + { + if (!isSkipped()) + { + out.println(); + } + } + + public void processEndOfFile(VeraPPParser parser, PreprocessedToken t) + { + out.flush(); + } + + public void processPragma(VeraPPParser parser, String text) + { + if (!isSkipped() && passPragmas) + { + out.print("#pragma"); + out.println(text); + } + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacro.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacro.java new file mode 100644 index 0000000..ba49e04 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacro.java @@ -0,0 +1,46 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import com.newisys.parser.util.Macro; + +/** + * Base VeraPPParser implementation of macros. + * + * @author Trevor Robinson + */ +public abstract class VeraPPMacro + implements Macro +{ + private final String name; + + public VeraPPMacro(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public String toString() + { + return name; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacroArgRef.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacroArgRef.java new file mode 100644 index 0000000..b1e3594 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPMacroArgRef.java @@ -0,0 +1,64 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import com.newisys.parser.util.Macro; +import com.newisys.parser.util.MacroRef; + +/** + * VeraPPParser implementation of function macro argument references. + * + * @author Trevor Robinson + */ +public class VeraPPMacroArgRef + implements MacroRef +{ + private final VeraPPFunctionMacro macro; + private final String arg; + private final MacroRef expandedFrom; + + public VeraPPMacroArgRef( + VeraPPFunctionMacro macro, + String arg, + MacroRef expandedFrom) + { + this.macro = macro; + this.arg = arg; + this.expandedFrom = expandedFrom; + } + + public Macro getMacro() + { + return macro; + } + + public String getArg() + { + return arg; + } + + public MacroRef getExpandedFrom() + { + return expandedFrom; + } + + public String toString() + { + return "<" + arg + ">"; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPObjectMacro.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPObjectMacro.java new file mode 100644 index 0000000..b5228e6 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPObjectMacro.java @@ -0,0 +1,34 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import com.newisys.parser.util.IncludeLocation; + +/** + * VeraPPParser implementation of user object macros. + * + * @author Trevor Robinson + */ +public final class VeraPPObjectMacro + extends VeraPPUserMacro +{ + public VeraPPObjectMacro(String name, IncludeLocation location) + { + super(name, location); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParser.jj b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParser.jj new file mode 100644 index 0000000..e52ab7e --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParser.jj @@ -0,0 +1,1067 @@ +/* + * JavaCC (TM) parser definition for the OpenVera (TM) language + * Copyright (C) 2003 Trevor A. Robinson + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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. + */ + +options { + STATIC = false; + USER_CHAR_STREAM = true; + COMMON_TOKEN_ACTION = true; +} + +PARSER_BEGIN(VeraPPParser) + +package com.newisys.parser.verapp; + +import java.io.*; +import java.util.*; + +import com.newisys.parser.util.*; + +/** + * JavaCC parser for the OpenVera (TM) preprocessor. + * + * Unimplemented features: + * #if and #elif with non-integer expressions, + * checking for infinite recursion in macro expansion + * + * @author Trevor Robinson + */ +public class VeraPPParser +{ + private String filename; + private VeraPPCallbacks handler; + private boolean trackMacroRefs = true; + + public VeraPPParser(InputStream stream, VeraPPCallbacks handler) + { + this(new VeraPPCharStream(stream, 1, 1)); + this.handler = handler; + } + + public VeraPPParser(Reader stream, VeraPPCallbacks handler) + { + this(new VeraPPCharStream(stream, 1, 1)); + this.handler = handler; + } + + public VeraPPParser(File file, VeraPPCallbacks handler) + throws FileNotFoundException + { + this(new FileReader(file), handler); + this.filename = file.getPath(); + } + + public VeraPPParser(String filename, VeraPPCallbacks handler) + throws FileNotFoundException + { + this(new File(filename), handler); + } + + public String getFilename() + { + return filename; + } + + public void setFilename(String _filename) + { + filename = _filename; + } + + public int getCurrentLine() + { + Token t = getToken(0); + return t != null ? t.beginLine : 0; + } + + public boolean isTrackMacroRefs() + { + return trackMacroRefs; + } + + public void setTrackMacroRefs(boolean trackMacroRefs) + { + this.trackMacroRefs = trackMacroRefs; + } + + public void pushInput(String s, MacroRef macroRef) + { + ((VeraPPCharStream) token_source.input_stream).insert(s, macroRef); + } + + public void doExpansion( + VeraPPMacro macro, + PreprocessedToken t) + { + String expansion = macro.expand(); + VeraPPSimpleMacroRef macroRef = null; + if (trackMacroRefs) { + macroRef = new VeraPPSimpleMacroRef(macro, t.expandedFrom); + } + pushInput(expansion, macroRef); + } + + public void doExpansion( + VeraPPFunctionMacro macro, + List argList, + PreprocessedToken t1, + PreprocessedToken t2) + { + VeraPPFunctionMacroRef macroRef = null; + if (trackMacroRefs) { + macroRef = new VeraPPFunctionMacroRef(macro, argList, t1.expandedFrom); + } + macro.expand(argList, (VeraPPCharStream) token_source.input_stream, macroRef); + } + + public static String escape(String str) + { + int len = str.length(); + StringBuffer buf = new StringBuffer(len); + for (int i = 0; i < len; ++i) + { + char c = str.charAt(i); + switch (c) + { + case '"': + buf.append("\\\""); + break; + case '\\': + buf.append("\\\\"); + break; + default: + buf.append(c); + } + } + return buf.toString(); + } + + public static String toStringLiteral(String str) + { + return '"' + escape(str) + '"'; + } + + private void checkComments(Token realToken) + { + if (realToken.specialToken != null) { + Token t = realToken.specialToken; + while (t.specialToken != null) t = t.specialToken; + while (t != null) { + handler.processComment(this, (PreprocessedToken) t); + t = t.next; + } + } + } + + private void expandSourceMacro(Token t, boolean mustExist) + throws ParseException + { + if (!expandMacro(t, true)) { + if (!mustExist) { + handler.processToken(this, (PreprocessedToken) t); + } else { + handler.processError(this, "Undefined macro: " + getMacroName(t), + (PreprocessedToken) t, (PreprocessedToken) t); + } + } + } + + private void expandDirectiveMacro(Token t, Token prevToken, int[][] expectedTokens) + throws ParseException + { + if (!expandMacro(t, false)) { + throw new ParseException(prevToken, expectedTokens, tokenImage); + } + } + + // built-in macros have their own (private) interface, since they rely on + // arbitrary parser state, and therefore do not have their references + // tracked + private interface BuiltinMacro + { + String expand(VeraPPParser parser, Token t); + } + + private static final HashMap builtinMacros; + + static + { + builtinMacros = new HashMap(); + builtinMacros.put("__FILE__", new BuiltinMacro() + { + public String expand(VeraPPParser parser, Token t) + { + return toStringLiteral(parser.getFilename()); + } + }); + builtinMacros.put("__LINE__", new BuiltinMacro() + { + public String expand(VeraPPParser parser, Token t) + { + return String.valueOf(t.beginLine); + } + }); + } + + private boolean expandMacro(Token t, boolean useHandler) + throws ParseException + { + String macroName = getMacroName(t); + + VeraPPMacro macro = handler.lookupMacro(this, macroName); + if (macro != null) { + PreprocessedToken pt = (PreprocessedToken) t; + if (macro instanceof VeraPPFunctionMacro) { + VeraPPFunctionMacro funcMacro = (VeraPPFunctionMacro) macro; + // semantic lookahead + int la = 1; + Token t1 = getToken(la); + // ignore intervening whitespace, including EOL + while (t1.kind == WS || t1.kind == EOL) { + t1 = getToken(++la); + } + if (t1.kind == LPAREN) { + // function macro with arguments + List argValueList = macro_args(funcMacro); + if (useHandler) { + handler.processMacroReference(this, funcMacro, argValueList, + pt, (PreprocessedToken) getToken(0)); + } else { + doExpansion(funcMacro, argValueList, + pt, (PreprocessedToken) getToken(0)); + } + } else { + // function macro without arguments; treat as non-macro + return false; + } + } else { + // object macro + if (useHandler) { + handler.processMacroReference(this, macro, pt); + } else { + doExpansion(macro, pt); + } + } + return true; + } + + BuiltinMacro builtinMacro = (BuiltinMacro) builtinMacros.get(macroName); + if (builtinMacro != null) { + pushInput(builtinMacro.expand(this, t), null); + return true; + } + + return false; + } + + private String getMacroName(Token t) + { + if (t.kind == MACRO_REF) { + int len = t.image.length(); + int pos = 1; + while (pos < len && Character.isWhitespace(t.image.charAt(pos))) ++pos; + return t.image.substring(pos); + } else { + return t.image; + } + } + + private IncludeLocation getLocation(Token t) + { + return new IncludeLocation(filename, t.beginLine, handler.getIncludedFrom()); + } +} + +PARSER_END(VeraPPParser) + +TOKEN_MGR_DECLS : +{ + private Stack stateStack = new Stack(); + + private void pushState(int newState) + { + stateStack.push(new Integer(curLexState)); + SwitchTo(newState); + } + + private void popState() + { + int newState = ((Integer)stateStack.pop()).intValue(); + SwitchTo(newState); + } + + private void notFirstChar() + { + if (curLexState == DEFAULT) { + SwitchTo(NOT_FIRST_CHAR); + } + } + + private void CommonTokenAction(Token t) + { + VeraPPCharStream stream = (VeraPPCharStream) input_stream; + MacroRef beginMacroRef = (MacroRef) stream.getBeginMarker(); + MacroRef endMacroRef = (MacroRef) stream.getEndMarker(); + MacroRef macroRef = MacroRefUtil.getCommonMacroRef(beginMacroRef, endMacroRef); + if (macroRef != null) { + PreprocessedToken pt = (PreprocessedToken) t; + pt.expandedFrom = macroRef; + } + } +} + +/* + Lexical states: + + DEFAULT nothing but whitespace since start of line + NOT_FIRST_CHAR token other than whitespace or '#' since start of line + INCLUDE_STATE tokens for #include + DEFINE_STATE tokens for #define + IFDEF_STATE tokens for #ifdef, #ifndef, #undef + IF_STATE tokens for #if, #elif + PRAGMA_STATE tokens for #pragma + LINE_STATE tokens for #line + OTHER_STATE ignore trailing characters after #else and #endif +*/ + +/* WHITE SPACE */ + + +TOKEN : +{ + < #_WS: " " | "\t" | "\f" > +| + < WS: (<_WS>)+ > +} + + +SKIP : +{ + < SKIPPED_WS: (<_WS>)+ > +} + + +SKIP : +{ + < #_EOL: "\n" | "\r" | "\r\n" > +| + < CONT: "\\" (<_WS>)* <_EOL> > +} + + +TOKEN: +{ + < EOL: <_EOL> > : DEFAULT +} + +/* COMMENTS */ + + +MORE : +{ + "//" { pushState(IN_SINGLE_LINE_COMMENT); } +| + "/*" { pushState(IN_MULTI_LINE_COMMENT); } +} + + +SPECIAL_TOKEN : +{ + < SINGLE_LINE_COMMENT: <_EOL> > { input_stream.backup(1); popState(); } +} + + +SPECIAL_TOKEN : +{ + < MULTI_LINE_COMMENT: "*/" > { popState(); } +} + + +MORE : +{ + < ~[] > +} + +/* RESERVED WORDS */ + + +TOKEN : +{ + < ALL: "all" > : NOT_FIRST_CHAR +| < ANY: "any" > : NOT_FIRST_CHAR +| < ASSOC_SIZE: "assoc_size" > : NOT_FIRST_CHAR +| < ASYNC: "async" > : NOT_FIRST_CHAR +| < BAD_STATE: "bad_state" > : NOT_FIRST_CHAR +| < BAD_TRANS: "bad_trans" > : NOT_FIRST_CHAR +| < BEGIN: "begin" > : NOT_FIRST_CHAR +| < BIG_ENDIAN: "big_endian" > : NOT_FIRST_CHAR +| < BIND: "bind" > : NOT_FIRST_CHAR +| < BIND_VAR: "bind_var" > : NOT_FIRST_CHAR +| < BIT: "bit" > : NOT_FIRST_CHAR +| < BIT_NORMAL: "bit_normal" > : NOT_FIRST_CHAR +| < BIT_REVERSE: "bit_reverse" > : NOT_FIRST_CHAR +| < BREAK: "break" > : NOT_FIRST_CHAR +| < BREAKPOINT: "breakpoint" > : NOT_FIRST_CHAR +| < CASE: "case" > : NOT_FIRST_CHAR +| < CASEX: "casex" > : NOT_FIRST_CHAR +| < CASEZ: "casez" > : NOT_FIRST_CHAR +| < CLASS: "class" > : NOT_FIRST_CHAR +| < CLOCK: "CLOCK" > : NOT_FIRST_CHAR +| < CONSTRAINT: "constraint" > : NOT_FIRST_CHAR +| < CONTINUE: "continue" > : NOT_FIRST_CHAR +| < COVERAGE: "coverage" > : NOT_FIRST_CHAR +| < COVERAGE_BLOCK: "coverage_block" > : NOT_FIRST_CHAR +| < COVERAGE_DEF: "coverage_def" > : NOT_FIRST_CHAR +| < COVERAGE_DEPTH: "coverage_depth" > : NOT_FIRST_CHAR +| < COVERAGE_GOAL: "coverage_goal" > : NOT_FIRST_CHAR +| < COVERAGE_OPTION: "coverage_option" > : NOT_FIRST_CHAR +| < COVERAGE_VAL: "coverage_val" > : NOT_FIRST_CHAR +| < _DEFAULT: "default" > : NOT_FIRST_CHAR +| < DEPTH: "depth" > : NOT_FIRST_CHAR +| < DIST: "dist" > : NOT_FIRST_CHAR +| < DYNAMIC_SIZE: "dynamic_size" > : NOT_FIRST_CHAR +| < ELSE: "else" > : NOT_FIRST_CHAR +| < END: "end" > : NOT_FIRST_CHAR +| < ENUM: "enum" > : NOT_FIRST_CHAR +| < EVENT: "event" > : NOT_FIRST_CHAR +| < EXHAUSTIVE: "exhaustive" > : NOT_FIRST_CHAR +| < EXPORT: "export" > : NOT_FIRST_CHAR +| < EXTENDS: "extends" > : NOT_FIRST_CHAR +| < EXTERN: "extern" > : NOT_FIRST_CHAR +| < FOR: "for" > : NOT_FIRST_CHAR +| < FORK: "fork" > : NOT_FIRST_CHAR +| < FUNCTION: "function" > : NOT_FIRST_CHAR +| < HDL_NODE: "hdl_node" > : NOT_FIRST_CHAR +| < HDL_TASK: "hdl_task" > : NOT_FIRST_CHAR +| < IF: "if" > : NOT_FIRST_CHAR +| < ILLEGAL_SELF_TRANSITION: "illegal_self_transition" > : NOT_FIRST_CHAR +| < ILLEGAL_STATE: "illegal_state" > : NOT_FIRST_CHAR +| < ILLEGAL_TRANSITION: "illegal_transition" > : NOT_FIRST_CHAR +| < IN: "in" > : NOT_FIRST_CHAR +| < INOUT: "inout" > : NOT_FIRST_CHAR +| < INPUT: "input" > : NOT_FIRST_CHAR +| < INTEGER: "integer" > : NOT_FIRST_CHAR +| < INTERFACE: "interface" > : NOT_FIRST_CHAR +| < JOIN: "join" > : NOT_FIRST_CHAR +| < LITTLE_ENDIAN: "little_endian" > : NOT_FIRST_CHAR +| < LOCAL: "local" > : NOT_FIRST_CHAR +| < M_BAD_STATE: "m_bad_state" > : NOT_FIRST_CHAR +| < M_BAD_TRANS: "m_bad_trans" > : NOT_FIRST_CHAR +| < M_STATE: "m_state" > : NOT_FIRST_CHAR +| < M_TRANS: "m_trans" > : NOT_FIRST_CHAR +| < NEGEDGE: "negedge" > : NOT_FIRST_CHAR +| < NEW: "new" > : NOT_FIRST_CHAR +| < NEWCOV: "newcov" > : NOT_FIRST_CHAR +| < NONE: "none" > : NOT_FIRST_CHAR +| < NON_RAND: "non_rand" > : NOT_FIRST_CHAR +| < NOT: "not" > : NOT_FIRST_CHAR +| < NULL: "null" > : NOT_FIRST_CHAR +| < OR: "or" > : NOT_FIRST_CHAR +| < ORDERED: "ordered" > : NOT_FIRST_CHAR +| < OUTPUT: "output" > : NOT_FIRST_CHAR +| < PACKED: "packed" > : NOT_FIRST_CHAR +| < PORT: "port" > : NOT_FIRST_CHAR +| < POSEDGE: "posedge" > : NOT_FIRST_CHAR +| < PROD: "prod" > : NOT_FIRST_CHAR +| < PRODGET: "prodget" > : NOT_FIRST_CHAR +| < PRODSET: "prodset" > : NOT_FIRST_CHAR +| < PROGRAM: "program" > : NOT_FIRST_CHAR +| < PROTECTED: "protected" > : NOT_FIRST_CHAR +| < PUBLIC: "public" > : NOT_FIRST_CHAR +| < RAND: "rand" > : NOT_FIRST_CHAR +| < RANDC: "randc" > : NOT_FIRST_CHAR +| < RANDCASE: "randcase" > : NOT_FIRST_CHAR +| < RANDSEQ: "randseq" > : NOT_FIRST_CHAR +| < REG: "reg" > : NOT_FIRST_CHAR +| < REPEAT: "repeat" > : NOT_FIRST_CHAR +| < RETURN: "return" > : NOT_FIRST_CHAR +| < SHADOW: "shadow" > : NOT_FIRST_CHAR +| < SOFT: "soft" > : NOT_FIRST_CHAR +| < STATE: "state" > : NOT_FIRST_CHAR +| < STATIC: "static" > : NOT_FIRST_CHAR +| < STRING: "string" > : NOT_FIRST_CHAR +| < SUPER: "super" > : NOT_FIRST_CHAR +| < TASK: "task" > : NOT_FIRST_CHAR +| < TERMINATE: "terminate" > : NOT_FIRST_CHAR +| < THIS: "this" > : NOT_FIRST_CHAR +| < TRANS: "trans" > : NOT_FIRST_CHAR +| < TYPEDEF: "typedef" > : NOT_FIRST_CHAR +| < UNPACKED: "unpacked" > : NOT_FIRST_CHAR +| < VAR: "var" > : NOT_FIRST_CHAR +| < VCA: "vca" > : NOT_FIRST_CHAR +| < VECTOR: "vector" > : NOT_FIRST_CHAR +| < VERILOG_NODE: "verilog_node" > : NOT_FIRST_CHAR +| < VERILOG_TASK: "verilog_task" > : NOT_FIRST_CHAR +| < VHDL_NODE: "vhdl_node" > : NOT_FIRST_CHAR +| < VHDL_TASK: "vhdl_task" > : NOT_FIRST_CHAR +| < VIRTUAL: "virtual" > : NOT_FIRST_CHAR +| < VOID: "void" > : NOT_FIRST_CHAR +| < WHILE: "while" > : NOT_FIRST_CHAR +| < WILDCARD: "wildcard" > : NOT_FIRST_CHAR +| < WITH: "with" > : NOT_FIRST_CHAR +} + + +TOKEN : +{ + < DEFINED: "defined" > +} + +/* OPERATORS */ + +// operators used in macro references + +TOKEN : +{ + < LPAREN: "(" > { notFirstChar(); } +| < RPAREN: ")" > { notFirstChar(); } +| < COMMA: "," > { notFirstChar(); } +} + +// operators used in #if and #elif directives + +TOKEN : +{ + < PLUS: "+" > { notFirstChar(); } +| < MINUS: "-" > { notFirstChar(); } +| < STAR: "*" > { notFirstChar(); } +| < SLASH: "/" > { notFirstChar(); } +| < MOD: "%" > { notFirstChar(); } +| < TILDE: "~" > { notFirstChar(); } +| < BIT_AND: "&" > { notFirstChar(); } +| < BIT_XOR: "^" > { notFirstChar(); } +| < BIT_OR: "|" > { notFirstChar(); } +| < LSHIFT: "<<" > { notFirstChar(); } +| < RSHIFT: ">>" > { notFirstChar(); } +| < LT: "<" > { notFirstChar(); } +| < LE: "<=" > { notFirstChar(); } +| < GT: ">" > { notFirstChar(); } +| < GE: ">=" > { notFirstChar(); } +| < EQ: "==" > { notFirstChar(); } +| < NE: "!=" > { notFirstChar(); } +| < BANG: "!" > { notFirstChar(); } +| < LOG_AND: "&&" > { notFirstChar(); } +| < LOG_OR: "||" > { notFirstChar(); } +} + +// operators used outside of directives + +TOKEN : +{ + < POUND: "#" > : NOT_FIRST_CHAR +| < SCOPE: "::" > : NOT_FIRST_CHAR +| < LBRACE: "{" > : NOT_FIRST_CHAR +| < RBRACE: "}" > : NOT_FIRST_CHAR +| < LBRACKET: "[" > : NOT_FIRST_CHAR +| < RBRACKET: "]" > : NOT_FIRST_CHAR +| < DOT: "." > : NOT_FIRST_CHAR +| < APOS: "'" > : NOT_FIRST_CHAR +| < INCR: "++" > : NOT_FIRST_CHAR +| < DECR: "--" > : NOT_FIRST_CHAR +| < UNARY_NAND: "~&" > : NOT_FIRST_CHAR +| < UNARY_NOR: "~|" > : NOT_FIRST_CHAR +| < UNARY_XNOR: "~^" > : NOT_FIRST_CHAR +| < GT_LT: "><" > : NOT_FIRST_CHAR +| < CASE_EQ: "===" > : NOT_FIRST_CHAR +| < CASE_NE: "!==" > : NOT_FIRST_CHAR +| < WILD_EQ: "=?=" > : NOT_FIRST_CHAR +| < WILD_NE: "!?=" > : NOT_FIRST_CHAR +| < BIT_NAND: "&~" > : NOT_FIRST_CHAR +| < BIT_XNOR: "^~" > : NOT_FIRST_CHAR +| < BIT_NOR: "|~" > : NOT_FIRST_CHAR +| < HOOK: "?" > : NOT_FIRST_CHAR +| < COLON: ":" > : NOT_FIRST_CHAR +| < ASSIGN: "=" > : NOT_FIRST_CHAR +| < PLUS_ASSIGN: "+=" > : NOT_FIRST_CHAR +| < MINUS_ASSIGN: "-=" > : NOT_FIRST_CHAR +| < STAR_ASSIGN: "*=" > : NOT_FIRST_CHAR +| < SLASH_ASSIGN: "/=" > : NOT_FIRST_CHAR +| < MOD_ASSIGN: "%=" > : NOT_FIRST_CHAR +| < LSHIFT_ASSIGN: "<<=" > : NOT_FIRST_CHAR +| < RSHIFT_ASSIGN: ">>=" > : NOT_FIRST_CHAR +| < AND_ASSIGN: "&=" > : NOT_FIRST_CHAR +| < OR_ASSIGN: "|=" > : NOT_FIRST_CHAR +| < XOR_ASSIGN: "^=" > : NOT_FIRST_CHAR +| < NAND_ASSIGN: "~&=" > : NOT_FIRST_CHAR +| < NOR_ASSIGN: "~|=" > : NOT_FIRST_CHAR +| < XNOR_ASSIGN: "~^=" > : NOT_FIRST_CHAR +| < SEMICOLON: ";" > : NOT_FIRST_CHAR +| < DIST_EACH: ":=" > : NOT_FIRST_CHAR +| < DIST_ACROSS: ":/" > : NOT_FIRST_CHAR +| < IMPLICATION: "=>" > : NOT_FIRST_CHAR +| < AT: "@" > : NOT_FIRST_CHAR +| < ATAT: "@@" > : NOT_FIRST_CHAR +| < ATATAT: "@@@" > : NOT_FIRST_CHAR +} + +/* IDENTIFIERS AND LITERALS */ + +// NOTE: identifiers must be defined after reserved words, +// since reserved words match the pattern for identifiers + + +TOKEN : +{ + < #BIN: ["0"-"1","x","X","z","Z","_"] > +| + < #OCT: ["0"-"7","x","X","z","Z","_"] > +| + < #DEC: ["0"-"9","_"] > +| + < #HEX: ["0"-"9","a"-"f","A"-"F","x","X","z","Z","_"] > +| + < #LETTER: ["a"-"z","A"-"Z","_"] > +| + < #_IDENT: (|)* > +| + < #_STRING_LITERAL: + "\"" + ( + ( ~["\"","\\","\n","\r"] ) + | + ( "\\" (~[] | "\r\n") ) + )* + "\"" + > +| + < #_INTEGER_LITERAL: ()+ > +| + < #_NUMBER_LITERAL: ()? "'" + ( + ["b","B"] ()+ + | ["o","O"] ()+ + | ["d","D"] ()+ + | ["h","H"] ()+ + ) + > +| + < IDENT: <_IDENT> > : NOT_FIRST_CHAR +| + < EXT_IDENT: "$" <_IDENT> > : NOT_FIRST_CHAR +| + < STRING_LITERAL: <_STRING_LITERAL> > : NOT_FIRST_CHAR +| + < INTEGER_LITERAL: <_INTEGER_LITERAL> > : NOT_FIRST_CHAR +| + < NUMBER_LITERAL: <_NUMBER_LITERAL> > : NOT_FIRST_CHAR +} + +/* SOURCE PRAGMAS */ + +// based on undocumented pragma syntax that appears in ListMacros.vrh + +SPECIAL_TOKEN : +{ + < SOURCE_PRAGMA: "%pragma" (~[";"])* ";" > +} + +/* DIRECTIVES */ + + +TOKEN : +{ + < #_DS: ( "#" | "`" ) ( <_WS> | )* > +| + < INCLUDE_DIRECTIVE: <_DS> "include" > : INCLUDE_STATE +| + < DEFINE_DIRECTIVE: <_DS> "define" > : DEFINE_STATE +| + < UNDEF_DIRECTIVE: <_DS> "undef" > : IFDEF_STATE +| + < IF_DIRECTIVE: <_DS> "if" > : IF_STATE +| + < IFDEF_DIRECTIVE: <_DS> "ifdef" > : IFDEF_STATE +| + < IFNDEF_DIRECTIVE: <_DS> "ifndef" > : IFDEF_STATE +| + < ELSE_DIRECTIVE: <_DS> "else" > : OTHER_STATE +| + < ELIF_DIRECTIVE: <_DS> "elif" > : IF_STATE +| + < ENDIF_DIRECTIVE: <_DS> "endif" > : OTHER_STATE +| + < PRAGMA_DIRECTIVE: <_DS> "pragma" > : PRAGMA_STATE +| + < LINE_DIRECTIVE: <_DS> "line" > : LINE_STATE +} + + +TOKEN : +{ + < #_MACRO_LETTER: ["a"-"z","A"-"Z","_","$"] > +| + < MACRO_IDENT: <_MACRO_LETTER> (<_MACRO_LETTER>|)* > +} + + +TOKEN : +{ + < MACRO_REF: "`" (<_WS>)* > +} + + +TOKEN : +{ + < INCLUDE_SYSPATH: "<" (~[">","\n","\r"])* ">" > +| + < INCLUDE_USERPATH: <_STRING_LITERAL> > +} + + +TOKEN : +{ + < DEFINE_NUMBER: (<_INTEGER_LITERAL> | <_NUMBER_LITERAL>) > +| + < DEFINE_STRING: <_STRING_LITERAL> > +| + < DEFINE_OTHER: ~[] > +} + + +TOKEN : +{ + < LINE_PATH: <_STRING_LITERAL> > +| + < LINE_NUMBER: (["0"-"9"])+ > +} + + +TOKEN : +{ + < PRAGMA_TEXT: <_EOL> > { input_stream.backup(1); SwitchTo(DEFAULT); } +} + + +MORE : +{ + < ~[] > +} + + +SKIP : +{ + < ~[] > +} + +/* GRAMMAR */ + +void file() : +{ + Token t; +} +{ + ( + LOOKAHEAD( { any_lookahead() } ) + ( + directive() + | + ( t= | t= ) + { + checkComments(t); + expandSourceMacro(t, false); + } + | + t= + { + checkComments(t); + expandSourceMacro(t, true); + } + | + t= + { + checkComments(t); + handler.processEndOfLine(this, (PreprocessedToken) t); + } + | + t=any() + { + checkComments(t); + handler.processToken(this, (PreprocessedToken) t); + } + ) + )* + t= + { + checkComments(t); + handler.processEndOfFile(this, (PreprocessedToken) t); + } +} + +JAVACODE +boolean any_lookahead() +{ + Token t = getToken(1); + return t.kind != EOF; +} + +JAVACODE +Token any() +{ + return getNextToken(); +} + +List macro_args(VeraPPFunctionMacro macro) : +{ + List argList = new LinkedList(); + StringBuffer buf; +} +{ + ( | )* + + [ + LOOKAHEAD( { macro_arg_lookahead() } ) + { buf = new StringBuffer(); } + macro_arg(buf) + { argList.add(buf.toString()); } + ( + + { buf = new StringBuffer(); } + macro_arg(buf) + { argList.add(buf.toString()); } + )* + ] + + { return argList; } +} + +JAVACODE +boolean macro_arg_lookahead() +{ + Token t = getToken(1); + return t.kind != EOF && t.kind != RPAREN; +} + +JAVACODE +void macro_arg(StringBuffer buf) +{ + top: while (true) { + Token t = getToken(1); + switch (t.kind) { + case EOF: + case RPAREN: + case COMMA: + break top; + case LPAREN: + paren_macro_arg(buf); + break; + default: + buf.append(t.image); + getNextToken(); + } + } +} + +void paren_macro_arg(StringBuffer buf) : +{ + Token t; +} +{ + t= { buf.append(t.image); } + ( + LOOKAHEAD( { macro_arg_lookahead() } ) + ( + t= { buf.append(t.image); } + | + macro_arg(buf) + ) + )* + t= { buf.append(t.image); } +} + +void directive() : +{ + Token t, pt, t1; + String path = null; +} +{ + ( + { boolean sysPath; } + t= { t1 = t; } + ( + { pt = t; } + ( t= | t= ) + { + int[][] expectedTokens = { { INCLUDE_SYSPATH }, { INCLUDE_USERPATH } }; + expandDirectiveMacro(t, pt, expectedTokens); + } + )* + ( + t= + { sysPath = true; } + | + t= + { sysPath = false; } + ) + + { + path = t.image.substring(1, t.image.length() - 1); + + //System.err.println("*Include: " + path); + + handler.processInclude(this, path, sysPath, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + { + String macroName; + VeraPPUserMacro macro; + } + t1= t= + { macroName = t.image; } + ( + LOOKAHEAD(1) // tell JavaCC to ignore ambiguity caused by '(' in macro body + + { + VeraPPFunctionMacro funcMacro = new VeraPPFunctionMacro( + macroName, getLocation(t)); + macro = funcMacro; + } + [ + [ ] t= [ ] + { funcMacro.addArgumentName(t.image); } + ( + [ ] t= [ ] + { funcMacro.addArgumentName(t.image); } + )* + ] + t= + | + { macro = new VeraPPObjectMacro(macroName, getLocation(t)); } + ) + [ + // ignore leading whitespace + LOOKAHEAD(1) + ] + ( + ( t= | t= | + t= | t= | + t= | t= | t= | + t= | t= ) + { macro.appendToken(t); } + )* + + { + //System.err.println("*Define: " + macro); + + handler.processDefine(this, macro, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t1= t= + + { + macroName = t.image; + + //System.err.println("*Undef: " + macroName); + + handler.processUndef(this, macroName, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t1= t= + + { + macroName = t.image; + + //System.err.println("*Ifdef: " + macroName); + + handler.processIfdef(this, macroName, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t1= t= + + { + macroName = t.image; + + //System.err.println("*Ifndef: " + macroName); + + handler.processIfndef(this, macroName, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t1= t= + + { + int value = Integer.parseInt(t.image); + + //System.err.println("*If: " + value); + + handler.processIf(this, value != 0, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t1= t= + + { + value = Integer.parseInt(t.image); + + //System.err.println("*Elif: " + value); + + handler.processElif(this, value != 0, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t= + + { + //System.err.println("*Else"); + + handler.processElse(this, (PreprocessedToken) t); + } + | + t= + + { + //System.err.println("*Endif"); + + handler.processEndif(this, (PreprocessedToken) t); + } + | + t1= t= + + { + //System.err.println("*Pragma: " + t.image); + + handler.processPragma(this, t.image, (PreprocessedToken) t1, (PreprocessedToken) t); + } + | + t= { t1 = t; } + ( + { pt = t; } + ( t= | t= ) + { + int[][] expectedTokens = { { LINE_NUMBER } }; + expandDirectiveMacro(t, pt, expectedTokens); + } + )* + t= { int lineNo = Integer.parseInt(t.image); } + ( + { pt = t; } + ( t= | t= ) + { + int[][] expectedTokens = { { LINE_PATH } }; + expandDirectiveMacro(t, pt, expectedTokens); + } + )* + [ t= { path = t.image; } ] + + { + //System.err.println("*Line: " + lineNo); + + handler.processLine(this, lineNo, path, (PreprocessedToken) t1, (PreprocessedToken) t); + } + ) + t= + { + checkComments(t); + handler.processEndOfLine(this, (PreprocessedToken) t); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParserTest.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParserTest.java new file mode 100644 index 0000000..913942b --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPParserTest.java @@ -0,0 +1,62 @@ +/* + * JavaCC (TM) parser definition for the OpenVera (TM) language + * Copyright (C) 2003 Trevor A. Robinson + * JavaCC is a trademark or registered trademark of Sun Microsystems, Inc. in + * the U.S. or other countries. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.io.File; + +/** + * Simple test program for VeraPPParser. + * + * @author Trevor Robinson + */ +public class VeraPPParserTest +{ + public static void main(String[] args) + { + try + { + VeraPPParser parser; + VeraPPHandler handler = new VeraPPHandler(System.out); + if (args.length > 0) + { + File inFile = new File(args[0]); + System.err.println("Input file: " + inFile); + parser = new VeraPPParser(inFile.getPath(), handler); + + File inFileDir = inFile.getCanonicalFile().getParentFile(); + System.err.println("Adding search path: " + inFileDir); + handler.addUserPath(inFileDir.getPath()); + } + else + { + System.err.println("Reading from stdin"); + parser = new VeraPPParser(System.in, handler); + parser.setFilename(""); + } + parser.file(); + handler.flushOutput(); + System.err.println("Preprocessing successful"); + } + catch (Throwable t) + { + t.printStackTrace(); + } + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPSimpleMacroRef.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPSimpleMacroRef.java new file mode 100644 index 0000000..61ed307 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPSimpleMacroRef.java @@ -0,0 +1,54 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import com.newisys.parser.util.Macro; +import com.newisys.parser.util.MacroRef; + +/** + * VeraPPParser implementation of non-function macro references. + * + * @author Trevor Robinson + */ +public class VeraPPSimpleMacroRef + implements MacroRef +{ + private final VeraPPMacro macro; + private final MacroRef expandedFrom; + + public VeraPPSimpleMacroRef(VeraPPMacro macro, MacroRef expandedFrom) + { + this.macro = macro; + this.expandedFrom = expandedFrom; + } + + public Macro getMacro() + { + return macro; + } + + public MacroRef getExpandedFrom() + { + return expandedFrom; + } + + public String toString() + { + return macro.getName(); + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPStaticMacro.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPStaticMacro.java new file mode 100644 index 0000000..780538c --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPStaticMacro.java @@ -0,0 +1,40 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +/** + * VeraPPParser implementation of static, predefined macros. + * + * @author Trevor Robinson + */ +public final class VeraPPStaticMacro + extends VeraPPMacro +{ + private final String value; + + public VeraPPStaticMacro(String name, String value) + { + super(name); + this.value = value; + } + + public String expand() + { + return value; + } +} diff --git a/java/vera-parser/src/com/newisys/parser/verapp/VeraPPUserMacro.java b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPUserMacro.java new file mode 100644 index 0000000..10b1ef5 --- /dev/null +++ b/java/vera-parser/src/com/newisys/parser/verapp/VeraPPUserMacro.java @@ -0,0 +1,114 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.parser.verapp; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.newisys.parser.util.IncludeLocation; +import com.newisys.parser.util.Token; + +/** + * Base VeraPPParser implementation for user macros. + * + * @author Trevor Robinson + */ +public abstract class VeraPPUserMacro + extends VeraPPMacro +{ + private final IncludeLocation location; + protected final List tokens = new LinkedList(); + + public VeraPPUserMacro(String name, IncludeLocation location) + { + super(name); + this.location = location; + } + + public IncludeLocation getLocation() + { + return location; + } + + public void appendToken(Token t) + { + tokens.add(t); + } + + public List getTokens() + { + return tokens; + } + + public String expand() + { + StringBuffer buf = new StringBuffer(); + for (Token cur : tokens) + { + buf.append(cur.image); + } + return buf.toString(); + } + + public boolean containsTokenPasting() + { + int prevKind = 0; + for (Token cur : tokens) + { + int curKind = cur.kind; + if (isPasteable(curKind) && isPasteable(prevKind)) return true; + prevKind = curKind; + } + return false; + } + + protected static boolean isPasteable(int kind) + { + return kind == VeraPPParserConstants.MACRO_IDENT + || kind == VeraPPParserConstants.DEFINE_NUMBER; + } + + public boolean equals(Object obj) + { + if (getClass().equals(obj.getClass())) + { + VeraPPUserMacro other = (VeraPPUserMacro) obj; + if (getName().equals(other.getName())) + { + List otherTokens = other.tokens; + if (tokens.size() == otherTokens.size()) + { + Iterator thisIter = tokens.iterator(); + Iterator otherIter = otherTokens.iterator(); + while (thisIter.hasNext()) + { + Token thisToken = thisIter.next(); + Token otherToken = otherIter.next(); + if (!thisToken.image.equals(otherToken.image)) + { + return false; + } + } + return true; + } + } + } + return false; + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/SourceSemanticException.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/SourceSemanticException.java new file mode 100644 index 0000000..ffc5356 --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/SourceSemanticException.java @@ -0,0 +1,91 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import com.newisys.langschema.util.SemanticException; +import com.newisys.langsource.SourceObject; + +/** + * Exception thrown for semantic errors with an associated source object. + * + * @author Trevor Robinson + */ +public class SourceSemanticException + extends SemanticException +{ + private static final long serialVersionUID = 3257291335462827573L; + + private SourceObject sourceObject; + + public SourceSemanticException() + { + super(); + } + + public SourceSemanticException(String message) + { + super(message); + } + + public SourceSemanticException(Throwable cause) + { + super(cause); + } + + public SourceSemanticException(String message, Throwable cause) + { + super(message, cause); + } + + public SourceSemanticException(String message, SourceObject sourceObject) + { + super(message); + this.sourceObject = sourceObject; + } + + protected static final String EOL = System.getProperty("line.separator", + "\n"); + + public String getMessage() + { + String msg = super.getMessage(); + if (sourceObject != null) + { + StringBuffer buf = new StringBuffer(msg); + buf.append(EOL); + buf.append("\tat "); + buf.append(sourceObject.getBeginFilename()); + buf.append(", line "); + buf.append(sourceObject.getBeginLine()); + buf.append(", column "); + buf.append(sourceObject.getBeginColumn()); + msg = buf.toString(); + } + return msg; + } + + public SourceObject getSourceObject() + { + return sourceObject; + } + + public void setSourceObject(SourceObject sourceObject) + { + this.sourceObject = sourceObject; + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraAnonymousScope.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraAnonymousScope.java new file mode 100644 index 0000000..b5c158a --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraAnonymousScope.java @@ -0,0 +1,64 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import java.util.Iterator; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.util.NameTable; + +/** + * Scope delegate that delegates to a) its own name table, and then b) the + * enclosing scope (if any). + * + * @author Trevor Robinson + */ +public final class VeraAnonymousScope + extends VeraScopeDelegate +{ + private final NameTable nameTable = new NameTable(); + + public VeraAnonymousScope() + { + super(null); + } + + public VeraAnonymousScope(VeraScopeDelegate enclosingScope) + { + super(enclosingScope); + } + + public void addObject(NamedObject obj) + { + nameTable.addObject(obj); + } + + public Iterator< ? extends NamedObject> lookupObjects( + String identifier, + NameKind kind) + { + Iterator< ? extends NamedObject> iter = nameTable.lookupObjects( + identifier, kind); + if (!iter.hasNext() && enclosingScope != null) + { + iter = enclosingScope.lookupObjects(identifier, kind); + } + return iter; + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraClassScope.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraClassScope.java new file mode 100644 index 0000000..44631f4 --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraClassScope.java @@ -0,0 +1,114 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import java.util.Iterator; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.vera.VeraClass; +import com.newisys.langschema.vera.VeraClassMember; +import com.newisys.langschema.vera.VeraVisibility; + +/** + * Scope delegate that delegates to a) the given class, then b) its successive + * base classes, and finally c) the enclosing scope (if any). When delegating + * to base classes, only members with non-local visibility are considered. + * + * @author Trevor Robinson + */ +public final class VeraClassScope + extends VeraScopeDelegate +{ + private final VeraClass cls; + + public VeraClassScope(VeraClass cls, VeraScopeDelegate enclosingScope) + { + super(enclosingScope); + this.cls = cls; + } + + public Iterator< ? extends NamedObject> lookupObjects( + String identifier, + NameKind kind) + { + Iterator< ? extends NamedObject> iter = cls.lookupObjects(identifier, + kind); + VeraClass currentClass = cls; + while (!iter.hasNext()) + { + currentClass = currentClass.getBaseClass(); + if (currentClass == null) + { + if (enclosingScope != null) + { + iter = enclosingScope.lookupObjects(identifier, kind); + } + break; + } + iter = new NonLocalIterator(currentClass.lookupObjects(identifier, + kind)); + } + return iter; + } + + private static class NonLocalIterator + implements Iterator + { + private final Iterator iter; + private NamedObject next; + + public NonLocalIterator(Iterator iter) + { + this.iter = iter; + findNext(); + } + + public void remove() + { + throw new UnsupportedOperationException("Iterator.remove()"); + } + + public boolean hasNext() + { + return next != null; + } + + public NamedObject next() + { + NamedObject result = next; + findNext(); + return result; + } + + private void findNext() + { + next = null; + while (iter.hasNext()) + { + NamedObject obj = iter.next(); + VeraClassMember member = (VeraClassMember) obj; + if (member.getVisibility() != VeraVisibility.LOCAL) + { + next = obj; + break; + } + } + } + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraCompilationUnitScope.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraCompilationUnitScope.java new file mode 100644 index 0000000..63c17c1 --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraCompilationUnitScope.java @@ -0,0 +1,145 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.vera.VeraCompilationUnit; +import com.newisys.langschema.vera.VeraCompilationUnitMember; +import com.newisys.langschema.vera.VeraVisibility; + +/** + * Scope delegate that delegates to a) a given set of non-header compilation + * units, then b) a given set of header compilation units, and finally c) the + * enclosing scope (if any). When delegating to header compilation units (i.e. + * those included by a #include of a .vrh file), only members with non-local + * visibility are considered. + * + * @author Trevor Robinson + */ +public final class VeraCompilationUnitScope + extends VeraScopeDelegate +{ + private final Set compUnits = new LinkedHashSet(); + private final Set headerCompUnits = new LinkedHashSet(); + private VeraCompilationUnit currentCompUnit; + + public VeraCompilationUnitScope(VeraScopeDelegate enclosingScope) + { + super(enclosingScope); + assert (enclosingScope != null); + } + + public void addCompilationUnit(VeraCompilationUnit compUnit, boolean header) + { + if (header) + { + headerCompUnits.add(compUnit); + } + else + { + compUnits.add(compUnit); + } + } + + public void setCurrentUnit(VeraCompilationUnit compUnit) + { + currentCompUnit = compUnit; + } + + public Iterator< ? extends NamedObject> lookupObjects( + String identifier, + NameKind kind) + { + // search in non-header compilation units + Iterator compUnitIter = compUnits.iterator(); + while (compUnitIter.hasNext()) + { + VeraCompilationUnit compUnit = compUnitIter.next(); + Iterator iter = compUnit.lookupObjects(identifier, + kind); + if (iter.hasNext()) return iter; + } + + // search in header compilation units + compUnitIter = headerCompUnits.iterator(); + while (compUnitIter.hasNext()) + { + VeraCompilationUnit compUnit = compUnitIter.next(); + Iterator iter = compUnit.lookupObjects(identifier, + kind); + if (compUnit != currentCompUnit) + { + iter = new NonLocalIterator(iter); + } + if (iter.hasNext()) return iter; + } + + // search in enclosing scope + return enclosingScope.lookupObjects(identifier, kind); + } + + private static class NonLocalIterator + implements Iterator + { + private final Iterator iter; + private NamedObject next; + + public NonLocalIterator(Iterator iter) + { + this.iter = iter; + findNext(); + } + + public void remove() + { + throw new UnsupportedOperationException("Iterator.remove()"); + } + + public boolean hasNext() + { + return next != null; + } + + public NamedObject next() + { + NamedObject result = next; + findNext(); + return result; + } + + private void findNext() + { + next = null; + while (iter.hasNext()) + { + NamedObject obj = iter.next(); + VeraCompilationUnitMember member = (VeraCompilationUnitMember) obj; + if (member.getVisibility() != VeraVisibility.LOCAL) + { + next = obj; + break; + } + } + } + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraPreprocessorInfo.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraPreprocessorInfo.java new file mode 100644 index 0000000..ccd41cc --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraPreprocessorInfo.java @@ -0,0 +1,61 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import com.newisys.langsource.SourceObject; +import com.newisys.langsource.vera.MacroDecl; +import com.newisys.parser.util.Macro; + +/** + * Provides information from the preprocessor to the schema builder. + * + * @author Trevor Robinson + */ +public interface VeraPreprocessorInfo +{ + /** + * Returns whether the given source object is from a source file (.vr) that + * was included in place of a header file (.vrh), or from a file included + * from such a file. + * + * @param obj SourceObject + * @return boolean + */ + boolean isFromHeader(SourceObject obj); + + /** + * Returns the compilation unit that the given source object should be + * associated with. This will normally be the file itself, except in the + * case of included .vr files, whose compilation unit will be the including + * non-.vr file. + * + * @param obj SourceObject + * @return String + */ + String getCompilationUnit(SourceObject obj); + + /** + * Attempts to parse the given macro into a source object. If the macro + * expansion does not correspond to a supported source object, this method + * returns null. + * + * @param macro the macro to parse + * @return a corresponding source object, or null + */ + MacroDecl parseMacro(Macro macro); +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSchemaBuilder.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSchemaBuilder.java new file mode 100644 index 0000000..b02ff3f --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSchemaBuilder.java @@ -0,0 +1,4688 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import java.util.*; + +import com.newisys.langschema.Expression; +import com.newisys.langschema.FunctionType; +import com.newisys.langschema.Name; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Scope; +import com.newisys.langschema.Type; +import com.newisys.langschema.util.SemanticException; +import com.newisys.langschema.vera.*; +import com.newisys.langsource.SourceObject; +import com.newisys.langsource.vera.*; +import com.newisys.parser.util.FunctionMacro; +import com.newisys.parser.util.Macro; +import com.newisys.parser.util.MacroRef; +import com.newisys.parser.verapp.VeraPPFunctionMacro; +import com.newisys.parser.verapp.VeraPPFunctionMacroRef; +import com.newisys.parser.verapp.VeraPPMacroArgRef; +import com.newisys.parser.verapp.VeraPPUserMacro; +import com.newisys.verilog.EdgeSet; + +/** + * VeraSourceVisitor implementation that builds a VeraSchema from the given + * source objects. + * + * @author Trevor Robinson + */ +public final class VeraSchemaBuilder + implements VeraSourceVisitor +{ + private final VeraSchema schema; + private final VeraAnonymousScope globalScope; + private final List deferredProcesses; + private final Map> macroArgMap; + + private VeraPreprocessorInfo preprocInfo; + private boolean wantShell; + + private VeraCompilationUnitScope compUnitScope; + VeraScopeDelegate currentScope; + private VeraCompilationUnit primaryCompUnit; + private Set shellMembers; + + private VeraUserClass currentClass; + private boolean externClass; + + private VeraType currentType; + private Type lhsType; + + private VeraEnumeration currentEnum; + private boolean newEnum; + private int nextEnumValue; + + private VeraFunction currentFunc; + private boolean newFunc; + private int currentArgPos; + + private VeraVariable currentVar; + + private VeraStatement currentStmt; + private VeraRandCase currentRandCase; + + private VeraExpression currentExpr; + + private VeraInterfaceType currentIntf; + private VeraInterfaceSignal currentIntfSignal; + + private VeraBindVariable currentBind; + private VeraBindMember currentBindMember; + + private VeraProgram currentProgram; + + public VeraSchemaBuilder() + { + schema = new VeraSchema(); + globalScope = new VeraAnonymousScope(); + deferredProcesses = new LinkedList(); + macroArgMap = new HashMap>(); + currentScope = globalScope; + + defineBuiltinFunctions(); + } + + private void defineBuiltinFunctions() + { + VeraFunction f; + VeraFunctionArgument a; + + f = defineBuiltinFunction("alloc", schema.integerType); + addArgument(f, "type", schema.integerType); + addArgument(f, "id", schema.integerType); + addArgument(f, "count", schema.integerType); + addOptArgument(f, "key_count", schema.integerType); + + // Vera extension: treat assert as a built-in function + f = defineBuiltinFunction("assert", schema.voidType); + addArgument(f, "expr", schema.integerType); + + f = defineBuiltinFunction("assoc_index", schema.integerType); + addArgument(f, "op", schema.integerType); + a = addArgument(f, "array", schema.magicType); + a.setByRef(true); + a = addOptArgument(f, "index", schema.magicType); + a.setByRef(true); + + f = defineBuiltinFunction("cast_assign", schema.integerType); + a = addArgument(f, "dst", schema.magicType); + a.setByRef(true); + a.setReturnsXZ(true); + addArgument(f, "src", schema.magicType); + addOptArgument(f, "fatal", 1); // CHECK = 0 + + f = defineBuiltinFunction("delay", schema.voidType); + addArgument(f, "time", schema.integerType); + + f = defineBuiltinFunction("error", schema.voidType); + addArgument(f, "format", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("error_mode", schema.voidType); + addArgument(f, "op", schema.integerType); + addArgument(f, "cls", schema.integerType); + + f = defineBuiltinFunction("exit", schema.voidType); + addArgument(f, "status", schema.integerType); + + f = defineBuiltinFunction("fclose", schema.voidType); + addArgument(f, "fd", schema.integerType); + + f = defineBuiltinFunction("feof", schema.integerType); + addArgument(f, "fd", schema.integerType); + + f = defineBuiltinFunction("ferror", schema.integerType); + addArgument(f, "fd", schema.integerType); + + f = defineBuiltinFunction("fflush", schema.voidType); + addArgument(f, "fd", schema.integerType); + + f = defineBuiltinFunction("flag", schema.integerType); + addOptArgument(f, "op", -1); // OFF = 0, ON = 1 + + f = defineBuiltinFunction("fopen", schema.integerType); + addArgument(f, "filename", schema.stringType); + addArgument(f, "mode", schema.stringType); + addOptArgument(f, "verbose", 4); // VERBOSE = 4, SILENT = 0 + + f = defineBuiltinFunction("fprintf", schema.voidType); + addArgument(f, "fd", schema.integerType); + addArgument(f, "format", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("freadb", schema.bitVectorType, true); + addArgument(f, "fd", schema.integerType); + addOptArgument(f, "verbose", 4); // VERBOSE = 4, SILENT = 0 + + f = defineBuiltinFunction("freadh", schema.bitVectorType, true); + addArgument(f, "fd", schema.integerType); + addOptArgument(f, "verbose", 4); // VERBOSE = 4, SILENT = 0 + + f = defineBuiltinFunction("freadstr", schema.stringType); + addArgument(f, "fd", schema.integerType); + addOptArgument(f, "verbose", 4); // VERBOSE = 4, SILENT = 0, RAWIN = 1 + + f = defineBuiltinFunction("getstate", schema.voidType); + a = addArgument(f, "state", schema.bitVector64Type); + a.setByRef(true); + addOptArgument(f, "obj", schema.magicType); + + f = defineBuiltinFunction("get_coverage", schema.integerType); + // no arguments + + f = defineBuiltinFunction("get_cycle", schema.bitVector32Type); + addOptArgument(f, "signal", schema.magicType); + + f = defineBuiltinFunction("get_inst_coverage", schema.integerType); + // no arguments + + f = defineBuiltinFunction("get_plus_arg", schema.bitVectorType, true); + addArgument(f, "op", schema.integerType); + addArgument(f, "name", schema.stringType); + + f = defineBuiltinFunction("get_systime", schema.bitVector32Type); + // no arguments + + f = defineBuiltinFunction("get_time", schema.bitVector32Type); + addArgument(f, "part", schema.integerType); + + f = defineBuiltinFunction("get_time_unit", schema.integerType); + // no arguments + + f = defineBuiltinFunction("initstate", schema.voidType); + addArgument(f, "seed", schema.integerType); + a = addArgument(f, "state", schema.bitVector64Type); + a.setByRef(true); + addOptArgument(f, "obj", schema.magicType); + + f = defineBuiltinFunction("lock_file", schema.integerType); + addArgument(f, "filename", schema.stringType); + addArgument(f, "timeout", schema.integerType); + + f = defineBuiltinFunction("mailbox_get", schema.integerType); + addArgument(f, "op", schema.integerType); + addArgument(f, "id", schema.integerType); + a = addOptArgument(f, "data", schema.magicType); + a.setByRef(true); + a.setReturnsXZ(true); + addOptArgument(f, "fatal", 1); // CHECK = 0 + + f = defineBuiltinFunction("mailbox_put", schema.voidType); + addArgument(f, "id", schema.integerType); + addArgument(f, "data", schema.magicType); + + f = defineBuiltinFunction("os_command", schema.integerType); + addArgument(f, "command", schema.stringType); + + f = defineBuiltinFunction("printf", schema.voidType); + addArgument(f, "format", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("prodget", schema.magicType, true); + addOptArgument(f, "name", schema.stringType); + addOptArgument(f, "occurrence", 1); + + f = defineBuiltinFunction("prodset", schema.voidType); + addArgument(f, "value", schema.magicType); + addOptArgument(f, "name", schema.stringType); + addOptArgument(f, "occurrence", 1); + + f = defineBuiltinFunction("psprintf", schema.stringType); + addArgument(f, "format", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("rand48", schema.integerType); + addOptArgument(f, "seed", schema.integerType); + + f = defineBuiltinFunction("random", schema.integerType); + addOptArgument(f, "seed", schema.integerType); + + f = defineBuiltinFunction("region_enter", schema.integerType); + addArgument(f, "op", schema.integerType); + addArgument(f, "id", schema.integerType); + setVarArgs(f, false); + + f = defineBuiltinFunction("region_exit", schema.voidType); + addArgument(f, "id", schema.integerType); + setVarArgs(f, false); + + f = defineBuiltinFunction("rewind", schema.voidType); + addArgument(f, "fd", schema.integerType); + + f = defineBuiltinFunction("semaphore_get", schema.integerType); + addArgument(f, "op", schema.integerType); + addArgument(f, "id", schema.integerType); + addArgument(f, "key_count", schema.integerType); + + f = defineBuiltinFunction("semaphore_put", schema.voidType); + addArgument(f, "id", schema.integerType); + addArgument(f, "key_count", schema.integerType); + + f = defineBuiltinFunction("setstate", schema.voidType); + a = addArgument(f, "state", schema.bitVector64Type); + a.setByRef(true); + addOptArgument(f, "obj", schema.magicType); + + f = defineBuiltinFunction("signal_connect", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + addArgument(f, "target_signal", schema.magicType); + addOptArgument(f, "attributes", schema.stringType); + addOptArgument(f, "clock", schema.magicType); + + f = defineBuiltinFunction("sprintf", schema.voidType); + a = addArgument(f, "str", schema.stringType); + a.setByRef(true); + addArgument(f, "format", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("srandom", schema.voidType); + addArgument(f, "seed", schema.integerType); + addOptArgument(f, "obj", schema.magicType); + + f = defineBuiltinFunction("sscanf", schema.voidType); + addArgument(f, "str", schema.stringType); + addArgument(f, "format", schema.stringType); + setVarArgs(f, true); + + f = defineBuiltinFunction("stop", schema.voidType); + // no arguments + + f = defineBuiltinFunction("suspend_thread", schema.voidType); + // no arguments + + f = defineBuiltinFunction("sync", schema.integerType); + addArgument(f, "op", schema.integerType); + setVarArgs(f, false); + + f = defineBuiltinFunction("timeout", schema.voidType); + setVarArgs(f, false); + + f = defineBuiltinFunction("trace", schema.voidType); + addArgument(f, "op", schema.integerType); + setVarArgs(f, false); + + f = defineBuiltinFunction("trigger", schema.voidType); + setVarArgs(f, false); + + f = defineBuiltinFunction("unlock_file", schema.voidType); + addArgument(f, "filename", schema.stringType); + + f = defineBuiltinFunction("urand48", schema.bitVector32Type); + addOptArgument(f, "seed", schema.integerType); + + f = defineBuiltinFunction("urandom", schema.bitVector32Type); + addOptArgument(f, "seed", schema.integerType); + + f = defineBuiltinFunction("urandom_range", schema.bitVector32Type); + addArgument(f, "maxval", schema.bitVector32Type); + addOptArgument(f, "minval", schema.bitVector32Type, + new VeraIntegerLiteral(schema, 0)); + + f = defineBuiltinFunction("vca", schema.voidType); + addArgument(f, "op", schema.integerType); + addArgument(f, "intf_signal", schema.magicType); + + f = defineBuiltinFunction("vera_bit_reverse", schema.voidType); + a = addArgument(f, "dst", schema.bitVectorType); + a.setByRef(true); + addArgument(f, "src", schema.bitVectorType); + + // X/Z inputs are documented to cause a fatal error, + // so we assume vera_crc does not return X/Z + f = defineBuiltinFunction("vera_crc", schema.bitVector64Type); + addArgument(f, "order", schema.integerType); + addArgument(f, "stream", schema.magicType); + addArgument(f, "index1", schema.bitVector64Type); + addArgument(f, "index2", schema.bitVector64Type); + addOptArgument(f, "init_crc", schema.bitVectorType); + + f = defineBuiltinFunction("vera_get_clk_name", schema.stringType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_dir", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_ifc_name", schema.stringType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_in_depth", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_in_skew", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_in_type", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_name", schema.stringType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_out_skew", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_out_type", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_get_surrx_D", schema.voidType); + addArgument(f, "port_signal", schema.magicType); + a = addArgument(f, "time_to_x", schema.integerType); + a.setByRef(true); + a = addArgument(f, "time_to_value", schema.integerType); + a.setByRef(true); + + f = defineBuiltinFunction("vera_get_surrx_F", schema.voidType); + addArgument(f, "port_signal", schema.magicType); + a = addArgument(f, "time_to_x", schema.integerType); + a.setByRef(true); + a = addArgument(f, "time_to_value", schema.integerType); + a.setByRef(true); + + f = defineBuiltinFunction("vera_get_surrx_R", schema.voidType); + addArgument(f, "port_signal", schema.magicType); + a = addArgument(f, "time_to_x", schema.integerType); + a.setByRef(true); + a = addArgument(f, "time_to_value", schema.integerType); + a.setByRef(true); + + f = defineBuiltinFunction("vera_get_surrx_Z", schema.voidType); + addArgument(f, "port_signal", schema.magicType); + a = addArgument(f, "time_to_x", schema.integerType); + a.setByRef(true); + a = addArgument(f, "time_to_value", schema.integerType); + a.setByRef(true); + + f = defineBuiltinFunction("vera_get_width", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_has_surrx", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_is_bound", schema.integerType); + addArgument(f, "port_signal", schema.magicType); + + f = defineBuiltinFunction("vera_pack", schema.integerType); + addArgument(f, "storage", schema.magicType); + a = addArgument(f, "bit_offset", schema.integerType); + a.setByRef(true); + setVarArgs(f, false); + + f = defineBuiltinFunction("vera_pack_big_endian", schema.integerType); + addArgument(f, "storage", schema.magicType); + a = addArgument(f, "bit_offset", schema.integerType); + a.setByRef(true); + setVarArgs(f, false); + + f = defineBuiltinFunction("vera_plot", schema.voidType); + addArgument(f, "filename", schema.stringType); + addArgument(f, "format", schema.integerType); + addArgument(f, "variable", schema.stringType); + addArgument(f, "mode", schema.integerType); + addOptArgument(f, "dump", schema.stringType); + + f = defineBuiltinFunction("vera_report_profile", schema.voidType); + addArgument(f, "type", schema.integerType); + addArgument(f, "filename", schema.stringType); + + f = defineBuiltinFunction("vera_unpack", schema.integerType); + addArgument(f, "storage", schema.magicType); + a = addArgument(f, "bit_offset", schema.integerType); + a.setByRef(true); + setVarArgs(f, false); + + f = defineBuiltinFunction("vera_unpack_big_endian", schema.integerType); + addArgument(f, "storage", schema.magicType); + a = addArgument(f, "bit_offset", schema.integerType); + a.setByRef(true); + setVarArgs(f, false); + + f = defineBuiltinFunction("vsv_call_func", schema.integerType); + addArgument(f, "connection", schema.integerType); + addArgument(f, "time_mode", schema.integerType); + addArgument(f, "func_name", schema.stringType); + addArgument(f, "return_value", schema.magicType); + setVarArgs(f, false); + + f = defineBuiltinFunction("vsv_call_task", schema.integerType); + addArgument(f, "connection", schema.integerType); + addArgument(f, "time_mode", schema.integerType); + addArgument(f, "task_name", schema.stringType); + setVarArgs(f, false); + + f = defineBuiltinFunction("vsv_close_conn", schema.integerType); + addArgument(f, "connection", schema.integerType); + + f = defineBuiltinFunction("vsv_get_conn_err", schema.stringType); + // no arguments + + f = defineBuiltinFunction("vsv_make_client", schema.integerType); + addArgument(f, "host", schema.stringType); + addArgument(f, "port", schema.integerType); + addArgument(f, "authentication", schema.integerType); + + f = defineBuiltinFunction("vsv_make_server", schema.integerType); + addArgument(f, "port", schema.integerType); + addArgument(f, "authentication", schema.integerType); + addOptArgument(f, "verbose", 0); // VERBOSE = 4 + + f = defineBuiltinFunction("vsv_up_connections", schema.integerType); + addArgument(f, "timeout", schema.integerType); + + f = defineBuiltinFunction("vsv_wait_for_done", schema.voidType); + // no arguments + + f = defineBuiltinFunction("vsv_wait_for_input", schema.voidType); + addArgument(f, "time_mode", schema.integerType); + + f = defineBuiltinFunction("wait_child", schema.voidType); + // no arguments + + f = defineBuiltinFunction("wait_var", schema.voidType); + setVarArgs(f, false); + } + + private VeraFunction defineBuiltinFunction(String id, VeraType returnType) + { + return defineBuiltinFunction(id, returnType, false); + } + + private VeraFunction defineBuiltinFunction( + String id, + VeraType returnType, + boolean returnsXZ) + { + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraFunctionType funcType = new VeraFunctionType(returnType, + returnsXZ); + final VeraGlobalFunction func = new VeraGlobalFunction(name, funcType); + schema.addMember(func); + globalScope.addObject(func); + return func; + } + + private VeraFunctionArgument addArgument( + VeraFunction func, + String id, + VeraType type) + { + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraFunctionArgument arg = new VeraFunctionArgument(name, type, + func); + VeraFunctionType funcType = func.getType(); + funcType.addArgument(arg); + return arg; + } + + private VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + int defValue) + { + return addOptArgument(func, id, schema.integerType, + new VeraIntegerLiteral(schema, defValue)); + } + + private VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + VeraType type) + { + return addOptArgument(func, id, type, null); + } + + private VeraFunctionArgument addOptArgument( + VeraFunction func, + String id, + VeraType type, + VeraExpression defValue) + { + final VeraFunctionArgument arg = addArgument(func, id, type); + arg.setInitializer(defValue); + arg.setOptional(true); + arg.setOptionalLevel(1); + return arg; + } + + private void setVarArgs(VeraFunction func, boolean byRef) + { + VeraFunctionType funcType = func.getType(); + funcType.setVarArgs(true); + funcType.setVarArgsByRef(byRef); + } + + public VeraSchema getSchema() + { + return schema; + } + + public VeraPreprocessorInfo getPreprocInfo() + { + return preprocInfo; + } + + public void setPreprocInfo(VeraPreprocessorInfo preprocInfo) + { + this.preprocInfo = preprocInfo; + } + + public boolean isWantShell() + { + return wantShell; + } + + public void setWantShell(boolean wantShell) + { + this.wantShell = wantShell; + } + + public VeraProgram getProgram() + { + return currentProgram; + } + + private void copyAnnotations(SourceObject from, VeraSchemaObject to) + { + if (from.hasAnnotations()) + { + to.addAnnotations(from.getAnnotations()); + } + } + + private void addDeferredProcess(Runnable process) + { + deferredProcesses.add(process); + } + + private void runDeferredProcesses() + { + final Iterator iter = deferredProcesses.iterator(); + while (iter.hasNext()) + { + Runnable process = (Runnable) iter.next(); + process.run(); + iter.remove(); + } + } + + private void checkDefineRef(MacroDecl srcObj, VeraDefineReferrer schemaObj) + { + MacroRef macroRef = null; + final MacroRef firstRef = srcObj.getFirstExpandedFrom(); + if (firstRef instanceof VeraPPMacroArgRef) + { + if (schemaObj instanceof VeraExpression) + { + // first expansion is function macro argument + addMacroArg((VeraPPMacroArgRef) firstRef, + (VeraExpression) schemaObj); + } + + // use next lower expansion, if any + MacroRef nextRef = srcObj.getLastExpandedFrom(); + while (nextRef != null && nextRef != firstRef) + { + macroRef = nextRef; + nextRef = nextRef.getExpandedFrom(); + } + } + else + { + // use first expansion + macroRef = firstRef; + } + + if (macroRef != null) + { + Map argRefMap = null; + if (macroRef instanceof VeraPPFunctionMacroRef) + { + argRefMap = getMacroArgs(macroRef); + } + + final Macro macro = macroRef.getMacro(); + final String id = macro.getName(); + final Iterator iter = currentScope.lookupObjects(id, + VeraNameKind.PREPROC); + badRef: if (iter.hasNext()) + { + VeraDefine define = (VeraDefine) iter.next(); + checkMultipleDefinition(iter); + + VeraDefineReference defineRef = new VeraDefineReference(define); + List defineArgs = define.getArguments(); + if (!defineArgs.isEmpty()) + { + if (argRefMap == null) break badRef; + + for (VeraDefineArgument defineArg : defineArgs) + { + String argID = defineArg.getName().getIdentifier(); + VeraExpression argExpr = argRefMap.get(argID); + if (argExpr == null) break badRef; + defineRef.addArgument(argExpr); + } + } + schemaObj.setDefineRef(defineRef); + } + + if (argRefMap != null) + { + clearMacroArgs(macroRef); + } + } + } + + private void addMacroArg(VeraPPMacroArgRef argRef, VeraExpression expr) + { + MacroRef funcRef = argRef.getExpandedFrom(); + assert (funcRef instanceof VeraPPFunctionMacroRef); + Map argRefMap = macroArgMap.get(funcRef); + if (argRefMap == null) + { + argRefMap = new HashMap(); + macroArgMap.put(funcRef, argRefMap); + } + argRefMap.put(argRef.getArg(), expr); + } + + private Map getMacroArgs(MacroRef funcRef) + { + return macroArgMap.get(funcRef); + } + + private void clearMacroArgs(MacroRef funcRef) + { + macroArgMap.remove(funcRef); + } + + public void visit(ArrayAccessDecl obj) + { + // process array expression + final ExpressionDecl arrayExprDecl = obj.getArrayExpr(); + final VeraExpression arrayExpr = processExpression(arrayExprDecl); + + // check array expression type + final Type arrayExprType = arrayExpr.getResultType(); + final Type[] indexTypes; + if (arrayExprType instanceof VeraArrayType) + { + final VeraArrayType arrayType = (VeraArrayType) arrayExprType; + indexTypes = arrayType.getIndexTypes(); + } + else if (arrayExprType instanceof VeraBitVectorType) + { + indexTypes = new Type[] { schema.integerType }; + } + else + { + throw new SourceSemanticException( + "Array or bit vector reference expected", arrayExprDecl); + } + + // check array dimensions + final List indexExprDecls = obj.getIndexExprs(); + if (indexExprDecls.size() != indexTypes.length) + { + throw new SourceSemanticException( + "Incorrect number of array indices; " + indexTypes.length + + " expected", obj); + } + + // create schema object + final VeraArrayAccess arrayAccess = new VeraArrayAccess(arrayExpr); + copyAnnotations(obj, arrayAccess); + + // process indices + final Iterator iter = indexExprDecls.iterator(); + int dimension = 0; + while (iter.hasNext()) + { + final ExpressionDecl indexExprDecl = (ExpressionDecl) iter.next(); + final VeraExpression indexExpr = processExpression(indexExprDecl); + final Type indexType = indexTypes[dimension]; + if (!indexType.isAssignableFrom(indexExpr.getResultType())) + { + throw new SourceSemanticException( + "Array index expression must be assignable to " + indexType, + indexExprDecl); + } + arrayAccess.addIndex(indexExpr); + ++dimension; + } + + checkDefineRef(obj, arrayAccess); + currentExpr = arrayAccess; + } + + public void visit(ArrayInitDecl obj) + { + // get array type + assert (lhsType != null); + if (!(lhsType instanceof VeraFixedArrayType)) + { + throw new SourceSemanticException( + "Fixed array type expected for left-hand expression", obj); + } + final VeraFixedArrayType type = (VeraFixedArrayType) lhsType; + + // create initializer expression + final VeraArrayInitializer initExpr = new VeraArrayInitializer(type); + copyAnnotations(obj, initExpr); + + // save LHS type + final Type prevLHSType = lhsType; + + // update LHS type for nested initializers + final Type[] indexTypes = type.getIndexTypes(); + final int[] highBounds = type.getHighBounds(); + final Type elementType = type.getElementType(); + int dimCount = indexTypes.length; + if (dimCount > 1) + { + // multi-dimensional array: drop the first dimension + --dimCount; + final int[] nestedDimensions = new int[dimCount]; + for (int i = 0; i < dimCount; ++i) + { + nestedDimensions[i] = highBounds[i + 1] + 1; + } + lhsType = new VeraFixedArrayType((VeraType) elementType, + nestedDimensions); + } + else + { + // no more array dimensions: use element type + lhsType = elementType; + } + + // process elements + final List elements = obj.getElements(); + if (elements.size() > highBounds[0] + 1) + { + throw new SourceSemanticException( + "Too many elements in array initializer", obj); + } + final Iterator elemIter = elements.iterator(); + while (elemIter.hasNext()) + { + final ExpressionDecl argExprDecl = (ExpressionDecl) elemIter.next(); + final VeraExpression argExpr = processExpression(argExprDecl); + if (!lhsType.isAssignableFrom(argExpr.getResultType())) + { + throw new SourceSemanticException( + "Type mismatch for array initializer element", argExprDecl); + } + initExpr.addElement(argExpr); + } + + // restore LHS type + lhsType = prevLHSType; + + checkDefineRef(obj, initExpr); + currentExpr = initExpr; + } + + public void visit(ArrayTypeRef obj) + { + // process the element type + final VeraType elementType = processType(obj.getElementTypeRef()); + + // return the array type in currentType + final ArrayKind arrayKind = obj.getArrayKind(); + final VeraArrayType arrayType; + if (arrayKind == ArrayKind.BIT_ASSOCIATIVE) + { + arrayType = new VeraAssocArrayType(elementType, + schema.bitVector64Type); + } + else if (arrayKind == ArrayKind.STRING_ASSOCIATIVE) + { + arrayType = new VeraAssocArrayType(elementType, schema.stringType); + } + else + { + assert (arrayKind == ArrayKind.DYNAMIC); + arrayType = new VeraDynamicArrayType(elementType); + } + checkDefineRef(obj, arrayType); + currentType = arrayType; + } + + public void visit(BindDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // look up bind by identifier in current scope + final String id = obj.getIdentifier(); + VeraBindVariable bind = lookupBind(id, false); + if (bind == null) + { + // create new bind type + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraPortType port; + try + { + port = lookupPort(obj.getPortIdentifier(), true); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + bind = new VeraBindVariable(name, port); + copyAnnotations(obj, bind); + + // add bind signals + HashSet portMembers = new HashSet( + port.getMembers()); + currentBind = bind; + final Iterator iter = obj.getSignals().iterator(); + while (iter.hasNext()) + { + final BindSignalDecl signalDecl = (BindSignalDecl) iter.next(); + signalDecl.accept(this); + assert (currentBindMember != null); + final VeraBindMember member = currentBindMember; + currentBindMember = null; + bind.addMember(member); + portMembers.remove(member.getPortSignal()); + } + currentBind = null; + if (!portMembers.isEmpty()) + { + final VeraPortSignal firstSignal = portMembers.iterator() + .next(); + throw new SourceSemanticException( + "Missing bind definition for port signal '" + + firstSignal.getName() + "'", obj); + } + + // add bind to compilation unit + compUnit.addMember(bind); + } + } + + public void visit(BindSignalDecl obj) + { + // get port signal + final VeraPortType port = currentBind.getPort(); + final VeraPortSignal portSignal; + { + final String portSignalID = obj.getPortMember(); + final Iterator nameIter = port.lookupObjects(portSignalID, + VeraNameKind.NON_TYPE); + if (!nameIter.hasNext()) + { + throw new SourceSemanticException("Unknown port signal '" + + portSignalID + "'", obj); + } + portSignal = (VeraPortSignal) nameIter.next(); + } + + // process signal ranges + VeraExpression firstRange = null; + VeraConcatenation concat = null; + Iterator iter = obj.getSignalRanges().iterator(); + while (iter.hasNext()) + { + final SignalRangeDecl rangeDecl = (SignalRangeDecl) iter.next(); + + // get interface + final VeraInterfaceType intf; + try + { + String intfID = rangeDecl.getInterfaceIdentifier(); + intf = lookupInterface(intfID, true); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + + // get signal + final String intfSignalID = rangeDecl.getSignalIdentifier(); + final VeraInterfaceSignal intfSignal; + { + final Iterator nameIter = intf.lookupObjects(intfSignalID, + VeraNameKind.NON_TYPE); + if (!nameIter.hasNext()) + { + throw new SourceSemanticException( + "Unknown interface signal '" + intfSignalID + "'", obj); + } + intfSignal = (VeraInterfaceSignal) nameIter.next(); + } + VeraExpression signalRef = new VeraSignalReference(intfSignal); + + // get bitfield (if any) + RangeDecl bitfield = rangeDecl.getBitfield(); + if (bitfield != null) + { + final int width = intfSignal.getWidth(); + final ExpressionDecl highExprDecl = bitfield.getTo(); + final ExpressionDecl lowExprDecl = bitfield.getFrom(); + + // check whether field is slice or single bit + if (lowExprDecl != highExprDecl) + { + VeraRange range = processRange(bitfield); + + // evaluate index expressions + int high = evalIntExpr(range.getFrom(), highExprDecl); + int low = evalIntExpr(range.getTo(), lowExprDecl); + + // check slice indices + if (low > high || low < 0 || high >= width) + { + throw new SourceSemanticException("Invalid bit slice", + bitfield); + } + + // create new range containing integer literals + VeraExpression highExpr = new VeraIntegerLiteral(schema, + high); + VeraExpression lowExpr = new VeraIntegerLiteral(schema, low); + VeraRange constRange = new VeraRange(schema, highExpr, + lowExpr); + constRange.setDefineRef(range.getDefineRef()); + + // change result expression to bit slice + signalRef = new VeraBitSliceAccess(signalRef, constRange); + } + else + { + // evaluate high index and create expression for it + int high = evalIntExpr(highExprDecl); + VeraExpression highExpr = new VeraIntegerLiteral(schema, + high); + + // check bit index + if (high < 0 || high >= width) + { + throw new SourceSemanticException("Invalid bit access", + bitfield); + } + + // change result expression to bit access + VeraArrayAccess arrayAccess = new VeraArrayAccess(signalRef); + arrayAccess.addIndex(highExpr); + signalRef = arrayAccess; + } + } + + // add expression to concatenation if necessary + if (firstRange != null) + { + if (concat == null) + { + concat = new VeraConcatenation(schema); + concat.addOperand(firstRange); + } + concat.addOperand(signalRef); + } + else + { + firstRange = signalRef; + } + } + + // determine final signal expression + final VeraExpression intfExpr; + if (concat != null) + { + // concatenation bind + intfExpr = concat; + } + else if (firstRange != null) + { + // simple bind + intfExpr = firstRange; + } + else + { + // void bind + intfExpr = new VeraVoidLiteral(schema); + } + + currentBindMember = new VeraBindMember(portSignal, intfExpr); + copyAnnotations(obj, currentBindMember); + } + + public void visit(BitSliceAccessDecl obj) + { + // process bit vector expression + final ExpressionDecl bitExprDecl = obj.getBitExpr(); + final VeraExpression bitExpr = processExpression(bitExprDecl); + final Type bitExprType = bitExpr.getResultType(); + if (!(bitExprType instanceof VeraBitVectorType)) + { + throw new SourceSemanticException("Bit vector reference expected", + bitExprDecl); + } + + // process range + final RangeDecl rangeDecl = obj.getRange(); + final VeraRange range = processRange(rangeDecl); + if (!range.getFrom().getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Bit slice index expression must be integral", rangeDecl + .getFrom()); + } + if (!range.getTo().getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Bit slice index expression must be integral", rangeDecl + .getTo()); + } + + currentExpr = new VeraBitSliceAccess(bitExpr, range); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(BitVectorLiteralDecl obj) + { + VeraBitVectorLiteral bvLiteral = new VeraBitVectorLiteral(schema, obj + .getValue()); + bvLiteral.setRadix(obj.getRadix()); + copyAnnotations(obj, bvLiteral); + checkDefineRef(obj, bvLiteral); + currentExpr = bvLiteral; + } + + public void visit(BitVectorTypeRef obj) + { + // determine size by evaluating high bit expression + final ExpressionDecl highExprDecl = obj.getHighBitExpr(); + final int size = evalIntExpr(highExprDecl) + 1; + if (size <= 0) + { + throw new SourceSemanticException( + "Invalid size for bit vector type", highExprDecl); + } + + final VeraFixedBitVectorType bvType = new VeraFixedBitVectorType( + schema, size); + checkDefineRef(obj, bvType); + currentType = bvType; + } + + public void visit(BlockDecl obj) + { + final VeraBlock block = new VeraBlock(schema); + copyAnnotations(obj, block); + + // block scope becomes current scope + final VeraScopeDelegate prevScope = currentScope; + currentScope = new VeraSimpleScope(block, prevScope); + + // process local variable declarations + Iterator iter = obj.getLocalVars().iterator(); + while (iter.hasNext()) + { + final LocalVarDecl varDecl = (LocalVarDecl) iter.next(); + varDecl.accept(this); + assert (currentVar != null); + final VeraLocalVariable var = (VeraLocalVariable) currentVar; + currentVar = null; + + checkDuplicateName(block, var, obj); + block.addMember(var); + } + + // process statements + iter = obj.getStatements().iterator(); + while (iter.hasNext()) + { + final StatementDecl stmt = (StatementDecl) iter.next(); + stmt.accept(this); + assert (currentStmt != null); + block.addMember(currentStmt); + currentStmt = null; + } + + // restore previous scope + currentScope = prevScope; + + checkDefineRef(obj, block); + currentStmt = block; + } + + public void visit(BreakDecl obj) + { + currentStmt = new VeraBreakStatement(schema); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(BreakpointDecl obj) + { + currentStmt = new VeraBreakpointStatement(schema); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(CaseDecl obj) + { + // process selector expression + final VeraExpression selectorExpr = processExpression(obj.getCaseExpr()); + + // create switch schema object + final VeraSwitchStatement switchStmt = new VeraSwitchStatement(obj + .getCaseKind(), selectorExpr); + copyAnnotations(obj, switchStmt); + + // process case members + final Iterator iter = obj.getCaseMembers().iterator(); + while (iter.hasNext()) + { + final CaseMemberDecl memberDecl = (CaseMemberDecl) iter.next(); + final VeraSwitchValueCase valueCase = switchStmt.newValueCase(); + + // process case value expressions + final Iterator valueIter = memberDecl.getExprs().iterator(); + while (valueIter.hasNext()) + { + ExpressionDecl valueExprDecl = (ExpressionDecl) valueIter + .next(); + VeraExpression valueExpr = processExpression(valueExprDecl); + if (!selectorExpr.getResultType().isAssignableFrom( + valueExpr.getResultType())) + { + throw new SourceSemanticException( + "Case expression must be assignable to type of selector", + memberDecl); + } + valueCase.addValue(valueExpr); + } + + // process case statement + final StatementDecl stmtDecl = memberDecl.getStatement(); + stmtDecl.accept(this); + assert (currentStmt != null); + final VeraStatement stmt = currentStmt; + currentStmt = null; + valueCase.setStatement(stmt); + } + + // process default statement + final StatementDecl defStmtDecl = obj.getDefaultStatement(); + if (defStmtDecl != null) + { + defStmtDecl.accept(this); + assert (currentStmt != null); + final VeraStatement defStmt = currentStmt; + currentStmt = null; + + // create default switch case for default statement + final VeraSwitchDefaultCase defCase = switchStmt.newDefaultCase(); + defCase.setStatement(defStmt); + } + + checkDefineRef(obj, switchStmt); + currentStmt = switchStmt; + } + + public void visit(CaseMemberDecl obj) + { + // handled in visit(CaseDecl) + assert false; + } + + public void visit(ClassConstraintDecl obj) + { + // must be within the context of a class + assert (currentClass != null); + + // look up constraint in class + final VeraClassConstraint cons; + final String id = obj.getIdentifier(); + final Iterator iter = currentClass.lookupObjects(id, + VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + final NamedObject foundObj = (NamedObject) iter.next(); + checkMultipleDefinition(iter); + if (!(foundObj instanceof VeraClassConstraint)) + { + throw new SourceSemanticException("Identifier '" + id + + "' already used for non-constraint", obj); + } + cons = (VeraClassConstraint) foundObj; + } + else + { + // create new class constraint + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, + currentClass); + cons = new VeraClassConstraint(schema, name); + copyAnnotations(obj, cons); + currentClass.addMember(cons); + } + + // process expressions in constraint body (if present) + if (!obj.isExtern() && !externClass) + { + if (cons.isDefined()) + { + throw new SourceSemanticException("Class constraint '" + id + + "' is already defined", obj); + } + + processConstraints(obj, cons); + + cons.setDefined(true); + } + } + + public void visit(ClassDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // determine base class + final VeraClass baseClass; + final String baseID = obj.getBaseClassIdentifer(); + if (baseID != null) + { + try + { + // look up base class by identifier + baseClass = lookupClass(baseID, true); + + if (((VeraUserClass) baseClass).isTypedefOnly()) + { + throw new SourceSemanticException( + "Cannot derived from typedef-only class '" + baseID + + "'", obj); + } + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + } + else + { + // use the implicit root class as the base class + baseClass = schema.rootClass; + } + + // look up class by identifier in current scope + final String id = obj.getIdentifier(); + final VeraClass cls = lookupClass(id, false); + final boolean local = obj.isLocal(); + final boolean newClass, likeNewClass; + if (cls != null) + { + currentClass = (VeraUserClass) cls; + newClass = false; + likeNewClass = currentClass.isTypedefOnly(); + + // skip consistency checks if we've only seen a typedef + if (!likeNewClass) + { + // check for consistent base class with previous declaration + if (baseClass != currentClass.getBaseClass()) + { + throw new SourceSemanticException( + "Base class type mismatch", obj); + } + + // check for consistent modifiers with previous declaration + if (currentClass.getVisibility() != localToVisibility(local)) + { + throw new SourceSemanticException( + "Class visibility mismatch", obj); + } + if (currentClass.isVirtual() != obj.isVirtual()) + { + throw new SourceSemanticException( + "Virtual class type mismatch", obj); + } + } + } + else + { + // create new class object + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + currentClass = new VeraUserClass(schema, name, baseClass); + copyAnnotations(obj, currentClass); + newClass = true; + likeNewClass = true; + } + + // put class in appropriate compilation unit + trackExternObject(currentClass, compUnit, newClass, local, obj + .isExtern()); + + if (likeNewClass) + { + // we have now seen a declaration for this class + currentClass.setTypedefOnly(false); + + // set base class + currentClass.setBaseClass(baseClass); + + // set class modifiers + currentClass.setVisibility(localToVisibility(local)); + currentClass.setVirtual(obj.isVirtual()); + } + + // member declarations need to know whether this is an extern definition + externClass = obj.isExtern() || isFromHeader(obj); + + // class may not be redeclared after its definition + if (!externClass && currentClass.isDefined()) + { + throw new SourceSemanticException("Class '" + id + + "' is already defined", obj); + } + + // process base ctor arguments (ignored for extern classes) + if (baseID != null && !externClass) + { + final Iterator argIter = obj.getBaseCtorArgs().iterator(); + while (argIter.hasNext()) + { + final ExpressionDecl argExprDecl = (ExpressionDecl) argIter + .next(); + final VeraExpression argExpr = processExpression(argExprDecl); + currentClass.addBaseCtorArg(argExpr); + } + } + + // class scope becomes current scope + final VeraScopeDelegate prevScope = currentScope; + currentScope = new VeraClassScope(currentClass, prevScope); + + // process class members + visitList(obj.getClassEnums()); + visitList(obj.getClassVars()); + visitList(obj.getClassConstraints()); + visitList(obj.getClassFuncs()); + + // generate a constructor if none present + final Iterator iter = currentClass.lookupObjects("new", + VeraNameKind.NON_TYPE); + if (!iter.hasNext()) + { + // create implicit no-argument constructor + final VeraName name = new VeraName("new", VeraNameKind.NON_TYPE, + currentClass); + final VeraFunctionType funcType = new VeraFunctionType(schema); + final VeraMemberFunction func = new VeraMemberFunction(name, + funcType); + func.setVisibility(VeraVisibility.PUBLIC); + func.setImplicit(true); + currentClass.addMember(func); + } + else + { + assert (iter.next() instanceof VeraMemberFunction); + } + + // restore previous scope + currentScope = prevScope; + + if (!externClass) + { + currentClass.setDefined(true); + } + + currentClass = null; + } + + private static VeraVisibility localToVisibility(boolean local) + { + return local ? VeraVisibility.LOCAL : VeraVisibility.PUBLIC; + } + + public void visit(ClassFuncDecl obj) + { + // must be within the context of a class + assert (currentClass != null); + + // look up method by identifier in current class + final String id = obj.getIdentifier(); + final Iterator iter = currentClass.lookupObjects(id, + VeraNameKind.NON_TYPE); + final VeraMemberFunction func; + final VeraFunctionType funcType; + if (iter.hasNext()) + { + // check that found object is a method + final NamedObject foundObj = (NamedObject) iter.next(); + if (!(foundObj instanceof VeraMemberFunction)) + { + throw new SourceSemanticException("Identifier '" + id + + "' already used for non-method", obj); + } + func = (VeraMemberFunction) foundObj; + funcType = func.getType(); + newFunc = false; + + // identifier should be unique + checkMultipleDefinition(iter); + + // check for consistent modifiers with previous declaration + if (func.getVisibility() != obj.getVisibility()) + { + throw new SourceSemanticException("Method visibility mismatch", + obj); + } + } + else + { + // create new method object + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, + currentClass); + funcType = new VeraFunctionType(schema); + func = new VeraMemberFunction(name, funcType); + copyAnnotations(obj, func); + func.setVisibility(obj.getVisibility()); + newFunc = true; + + // add method to class + currentClass.addMember(func); + } + currentFunc = func; + + // process method prototype + processFuncProto(obj); + + // set method modifiers + if (newFunc) + { + VeraMemberFunction baseFunc = findOverriddenVirtual(func); + if (baseFunc != null && !baseFunc.getType().equals(func.getType())) + { + throw new SourceSemanticException("Virtual method '" + id + + "' does not match super class definition", obj); + } + if (baseFunc != null || obj.isVirtual()) + { + func.setVirtual(true); + func.setPureVirtual(true); + } + } + else if (obj.isVirtual() && !func.isVirtual()) + { + // NOTE: Vera does not consider it an error to have a virtual + // mismatch between the extern definition and the body, but + // silently uses only the virtual-ness of the extern definition. + throw new SourceSemanticException("Virtual method type mismatch", + obj); + } + + // queue method body for second pass processing (if present) + if (obj.getBlock() != null) + { + // remember that method has a body, even if we don't process it + func.setPureVirtual(false); + + if (!externClass) + { + // method may not be redeclared after its definition + if (func.isDefined()) + { + throw new SourceSemanticException("Method '" + id + + "' is already defined", obj); + } + + queueFuncBody(currentFunc, obj, currentScope); + + func.setDefined(true); + } + } + + currentFunc = null; + } + + private void processFuncProto(AbsFuncDecl obj) + { + assert (currentFunc != null); + final VeraFunctionType funcType = currentFunc.getType(); + + // process return type + final VeraType returnType; + final TypeRef returnTypeRef = obj.getReturnType(); + if (returnTypeRef != null) + { + returnType = processType(returnTypeRef); + } + else + { + returnType = schema.voidType; + } + if (newFunc) + { + funcType.setReturnType(returnType); + } + else if (!returnType.equals(funcType.getReturnType())) + { + throw new SourceSemanticException("Return type '" + returnType + + "' does not match previous definition '" + + funcType.getReturnType() + "'", obj); + } + + // process arguments + final Iterator paramDeclIter = obj.getParams().iterator(); + currentArgPos = 0; + while (paramDeclIter.hasNext()) + { + ParamDecl paramDecl = (ParamDecl) paramDeclIter.next(); + paramDecl.accept(this); + } + + // check argument count + final List argList = funcType.getArguments(); + final int argCount = argList.size(); + if (!newFunc && currentArgPos != argCount) + { + throw new SourceSemanticException("Argument count mismatch; " + + argCount + " expected", obj); + } + } + + private VeraMemberFunction findOverriddenVirtual(VeraMemberFunction func) + { + String id = func.getName().getIdentifier(); + VeraClass cls = func.getStructuredType(); + while (true) + { + cls = cls.getBaseClass(); + if (cls == null) break; + + Iterator iter = cls.lookupObjects(id, VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + Object obj = iter.next(); + if (obj instanceof VeraMemberFunction) + { + VeraMemberFunction baseFunc = (VeraMemberFunction) obj; + if (baseFunc.isVirtual()) + { + return baseFunc; + } + } + assert (!iter.hasNext()); + // we can have two situations here: + // 1: an overridden function was found, but was not virtual; + // since this search was done for it, we can stop here + // 2: another type of object with the same identifier was found; + // in this case, Vera stops searching, so we stop too + return null; + } + } + return null; + } + + private void queueFuncBody( + final VeraFunction func, + final VeraFuncDecl funcDecl, + final VeraScopeDelegate scope) + { + addDeferredProcess(new Runnable() + { + public void run() + { + currentScope = scope; + processFuncBody(func, funcDecl); + currentScope = null; + } + }); + } + + void processFuncBody(VeraFunction func, VeraFuncDecl funcDecl) + { + final String funcID = func.getName().getIdentifier(); + final BlockDecl block = funcDecl.getBlock(); + + // non-local functions may not have multiple body definitions; + // + if (func.getBody() != null) + { + if (func.getVisibility() != VeraVisibility.LOCAL) + { + throw new SourceSemanticException("Non-local function '" + + funcID + "' has multiple body definitions", block); + } + else + { + System.err.println("Warning: Ignoring redefinition of local " + + "function '" + funcID + "'"); + return; + } + } + + // function argument scope becomes current scope + final FunctionType funcType = func.getType(); + final VeraScopeDelegate prevScope = currentScope; + currentScope = new VeraSimpleScope(funcType, prevScope); + + // create return variable for function + final VeraType returnType = (VeraType) funcType.getReturnType(); + if (!(returnType instanceof VeraVoidType)) + { + VeraName returnVarName = new VeraName(funcID, + VeraNameKind.NON_TYPE, null); + VeraLocalVariable returnVar = new VeraLocalVariable(returnVarName, + returnType); + func.setReturnVar(returnVar); + } + + // process the block statement + currentFunc = func; + if (func instanceof VeraMemberFunction) + { + currentClass = (VeraUserClass) ((VeraMemberFunction) func) + .getStructuredType(); + } + func.setBody((VeraBlock) processStatement(block)); + currentFunc = null; + currentClass = null; + + // restore previous scope + currentScope = prevScope; + } + + private void checkDuplicateName( + Scope scope, + NamedObject obj, + SourceObject srcObj) + { + final Name name = obj.getName(); + final String id = name.getIdentifier(); + final Iterator iter = scope.lookupObjects(id, VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + throw new SourceSemanticException("Duplicate identifier: " + id, + srcObj); + } + } + + public void visit(ClassVarDecl obj) + { + // must be within the context of a class + assert (currentClass != null); + + // process field type + final VeraType type = processType(obj.getTypeRef()); + + // look up field by identifier in current class + final String id = obj.getIdentifier(); + final Iterator iter = currentClass.lookupObjects(id, + VeraNameKind.NON_TYPE); + final VeraMemberVariable var; + if (iter.hasNext()) + { + // check that found object is a field + final NamedObject foundObj = (NamedObject) iter.next(); + if (!(foundObj instanceof VeraMemberVariable)) + { + throw new SourceSemanticException("Identifier '" + id + + "' already used for non-field", obj); + } + var = (VeraMemberVariable) foundObj; + + // identifier should be unique + checkMultipleDefinition(iter); + + // check for consistent modifiers with previous declaration + if (!var.getType().equals(type)) + { + throw new SourceSemanticException("Field type mismatch", obj); + } + if (var.getVisibility() != obj.getVisibility()) + { + throw new SourceSemanticException("Field visibility mismatch", + obj); + } + if (var.hasModifier(VeraVariableModifier.STATIC) != obj + .isStaticVar()) + { + throw new SourceSemanticException("Field static type mismatch", + obj); + } + if (var.hasModifier(VeraVariableModifier.RAND) != (obj + .getRandMode() == RandMode.RAND) + || var.hasModifier(VeraVariableModifier.RANDC) != (obj + .getRandMode() == RandMode.RANDC)) + { + throw new SourceSemanticException( + "Field randomization type mismatch", obj); + } + if (var.hasModifier(VeraVariableModifier.PACKED) != obj.isPacked()) + { + throw new SourceSemanticException( + "Field packing type mismatch", obj); + } + if (var.hasModifier(VeraVariableModifier.BIG_ENDIAN) != obj + .isBigEndian()) + { + throw new SourceSemanticException("Field endian type mismatch", + obj); + } + if (var.hasModifier(VeraVariableModifier.BIT_REVERSE) != obj + .isBitReverse()) + { + throw new SourceSemanticException("Field bit order mismatch", + obj); + } + } + else + { + // create new field object + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, + currentClass); + var = new VeraMemberVariable(name, type); + copyAnnotations(obj, var); + + // add field to class + currentClass.addMember(var); + + // set field modifiers + var.setVisibility(obj.getVisibility()); + if (obj.isStaticVar()) + { + var.addModifier(VeraVariableModifier.STATIC); + } + if (obj.getRandMode() == RandMode.RAND) + { + var.addModifier(VeraVariableModifier.RAND); + } + else if (obj.getRandMode() == RandMode.RANDC) + { + var.addModifier(VeraVariableModifier.RANDC); + } + if (obj.isPacked()) + { + var.addModifier(VeraVariableModifier.PACKED); + } + if (obj.isBigEndian()) + { + var.addModifier(VeraVariableModifier.BIG_ENDIAN); + } + if (obj.isBitReverse()) + { + var.addModifier(VeraVariableModifier.BIT_REVERSE); + } + } + + // random array size and initializer expression are ignored for extern + // classes + if (!externClass) + { + // field may not be redeclared after its definition + if (var.isDefined()) + { + throw new SourceSemanticException("Field '" + id + + "' is already defined", obj); + } + + // process random array size expression + final ExpressionDecl sizeExprDecl = obj.getRandomSizeExpr(); + if (sizeExprDecl != null) + { + final VeraExpression sizeExpr = processExpression(sizeExprDecl); + if (!sizeExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Random array size expression must be integral", + sizeExprDecl); + } + var.setRandomSize(sizeExpr); + } + + // process initializer expression + final ExpressionDecl initExprDecl = obj.getInitExpr(); + if (initExprDecl != null) + { + lhsType = var.getType(); + + final VeraExpression initExpr = processExpression(initExprDecl); + if (!var.getType().isAssignableFrom(initExpr.getResultType())) + { + throw new SourceSemanticException( + "Initializer type is not assignable to field type", + initExprDecl); + } + var.setInitializer(initExpr); + + lhsType = null; + } + + var.setDefined(true); + } + } + + public void visit(CompilationUnitDecl obj) + { + deferredProcesses.clear(); + macroArgMap.clear(); + + compUnitScope = new VeraCompilationUnitScope(globalScope); + currentScope = compUnitScope; + primaryCompUnit = getCompUnit(obj.getPath(), false); + if (wantShell) + { + shellMembers = new LinkedHashSet(); + } + + currentClass = null; + currentType = null; + lhsType = null; + currentEnum = null; + currentFunc = null; + currentVar = null; + currentStmt = null; + currentExpr = null; + currentIntf = null; + currentIntfSignal = null; + currentBind = null; + currentBindMember = null; + currentProgram = null; + + visitList(obj.getMembers()); + + // function/program bodies and defines must be processed last, since + // they may refer to variables and other functions declared later + runDeferredProcesses(); + + // if program block was found, associate Verilog shell members with it + if (wantShell && currentProgram != null) + { + currentProgram.getShellMembers().addAll(shellMembers); + } + shellMembers = null; + + primaryCompUnit.setComplete(true); + } + + public void visit(ConstraintDecl obj) + { + final VeraConstraintSet cons = new VeraConstraintSet(schema); + copyAnnotations(obj, cons); + processConstraints(obj, cons); + checkDefineRef(obj, cons); + currentExpr = cons; + } + + private void processConstraints(ConstraintDecl obj, VeraConstraintSet cons) + { + final Iterator exprIter = obj.getConstraintExprs().iterator(); + while (exprIter.hasNext()) + { + ExpressionDecl exprDecl = (ExpressionDecl) exprIter.next(); + VeraExpression expr = processExpression(exprDecl); + cons.addExpr(expr); + } + } + + public void visit(ContinueDecl obj) + { + currentStmt = new VeraContinueStatement(schema); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(DefaultValueDecl obj) + { + // visit(FuncCallDecl) handles DefaultValueDecl + assert false; + } + + public void visit(DefineDecl obj) + { + final Macro macro = obj.getMacro(); + + // compilation unit should not contain built-in macros + assert (macro instanceof VeraPPUserMacro); + + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // function macro argument pasting or stringification not supported + if (macro instanceof VeraPPFunctionMacro) + { + VeraPPFunctionMacro funcMacro = (VeraPPFunctionMacro) macro; + if (funcMacro.containsArgumentPasting() + || funcMacro.containsStringification()) return; + } + + // search for a macro with the given identifier + final String id = macro.getName(); + final Iterator iter = compUnitScope.lookupObjects(id, + VeraNameKind.PREPROC); + + // ignore redefinitions + if (iter.hasNext()) return; + + // attempt to parse macro + MacroDecl macroDecl = preprocInfo.parseMacro(macro); + if (macroDecl != null) + { + //System.out.println("Parsed " + id + ": " + macroDecl); + + VeraName name = new VeraName(id, VeraNameKind.PREPROC, null); + + final VeraScopeDelegate macroScope; + final List args; + if (macro instanceof FunctionMacro) + { + // begin new scope for define arguments + VeraAnonymousScope anonScope = new VeraAnonymousScope( + compUnitScope); + macroScope = anonScope; + + // create schema objects for define arguments + FunctionMacro funcMacro = (FunctionMacro) macro; + List argIDs = funcMacro.getArgumentNames(); + args = new LinkedList(); + Iterator argIter = argIDs.iterator(); + while (argIter.hasNext()) + { + String argID = (String) argIter.next(); + VeraName argName = new VeraName(argID, + VeraNameKind.NON_TYPE, null); + VeraDefineArgument var = new VeraDefineArgument(schema, + argName); + anonScope.addObject(var); + args.add(var); + } + } + else + { + macroScope = compUnitScope; + args = null; + } + + VeraDefine define = null; + if (macroDecl instanceof StatementDecl) + { + final StatementDecl stmtDecl = (StatementDecl) macroDecl; + final VeraStatementDefine stmtDefine = new VeraStatementDefine( + schema, name); + addDeferredProcess(new Runnable() + { + public void run() + { + currentScope = macroScope; + try + { + VeraStatement stmt = processStatement(stmtDecl); + stmtDefine.setStatement(stmt); + } + catch (RuntimeException e) + { + compUnit.removeMember(stmtDefine); + } + currentScope = null; + } + }); + define = stmtDefine; + } + else if (macroDecl instanceof ExpressionDecl) + { + final ExpressionDecl exprDecl = (ExpressionDecl) macroDecl; + final VeraExpressionDefine exprDefine = new VeraExpressionDefine( + schema, name); + addDeferredProcess(new Runnable() + { + public void run() + { + currentScope = macroScope; + try + { + VeraExpression expr = processExpression(exprDecl); + exprDefine.setExpression(expr); + } + catch (RuntimeException e) + { + compUnit.removeMember(exprDefine); + } + currentScope = null; + } + }); + define = exprDefine; + } + else if (macroDecl instanceof RangeDecl) + { + final RangeDecl r = (RangeDecl) macroDecl; + final VeraRangeDefine rangeDefine = new VeraRangeDefine(schema, + name); + addDeferredProcess(new Runnable() + { + public void run() + { + currentScope = macroScope; + try + { + VeraRange range = processRange(r); + rangeDefine.setRange(range); + } + catch (RuntimeException e) + { + compUnit.removeMember(rangeDefine); + } + currentScope = null; + } + }); + define = rangeDefine; + } + else if (macroDecl instanceof TypeRef) + { + final TypeRef typeRef = (TypeRef) macroDecl; + final VeraTypeDefine typeDefine = new VeraTypeDefine(schema, + name); + addDeferredProcess(new Runnable() + { + public void run() + { + currentScope = macroScope; + try + { + VeraType type = processType(typeRef); + typeDefine.setType(type); + } + catch (RuntimeException e) + { + compUnit.removeMember(typeDefine); + } + currentScope = null; + } + }); + define = typeDefine; + } + + if (define != null) + { + if (obj.isLocal()) + { + define.setVisibility(VeraVisibility.LOCAL); + } + if (obj.isVerilogImport()) + { + define.setVerilogImport(true); + } + if (args != null) + { + define.addArguments(args); + } + copyAnnotations(obj, define); + compUnit.addMember(define); + } + + // restore previous scope + currentScope = macroScope; + } + } + + public void visit(DepthAccessDecl obj) + { + final ExpressionDecl signalExprDecl = obj.getSignalExpr(); + final VeraExpression signalExpr = processExpression(signalExprDecl); + currentExpr = new VeraDepthAccess(signalExpr, obj.getDepth()); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(DriveSampleDecl obj) + { + // process assignment destination expression + final ExpressionDecl destExprDecl = obj.getDestExpr(); + final VeraExpression destExpr = processExpression(destExprDecl); + final Type destType = destExpr.getResultType(); + + // LHS for non-blocking drive must be port/interface member + final boolean nb = obj.getOperator() == Operator.NONBLOCKING_ASSIGN; + if (nb) + { + boolean valid = false; + if (destExpr instanceof VeraSignalReference) + { + valid = true; + } + else if (destExpr instanceof VeraMemberAccess) + { + VeraMemberAccess memberExpr = (VeraMemberAccess) destExpr; + Expression objectExpr = memberExpr.getObject(); + Type objectType = objectExpr.getResultType(); + if (objectType instanceof VeraPortType) + { + valid = true; + } + } + if (!valid) + { + throw new SourceSemanticException( + "Port/interface signal reference expected for drive", obj); + } + } + + final ExpressionDecl valueExprDecl = obj.getValueExpr(); + final VeraExpression valueExpr = processExpression(valueExprDecl); + final Type valueType = valueExpr.getResultType(); + if (!destType.isAssignableFrom(valueType) + && !(valueType instanceof VeraVoidType)) + { + throw new SourceSemanticException("Value [" + valueType + + "] is not assignable to signal [" + destType + "]", obj); + } + + final VeraDriveSampleStatement driveStmt = new VeraDriveSampleStatement( + destExpr, valueExpr); + copyAnnotations(obj, driveStmt); + + final ExpressionDecl delayExprDecl = obj.getDelayExpr(); + if (delayExprDecl != null) + { + final VeraExpression delayExpr = processExpression(delayExprDecl); + driveStmt.setDelay(delayExpr); + } + + driveStmt.setNonBlocking(nb); + driveStmt.setSoft(obj.isSoft()); + driveStmt.setAsync(obj.isAsync()); + + checkDefineRef(obj, driveStmt); + currentStmt = driveStmt; + } + + public void visit(EnumDecl obj) + { + final String id = obj.getIdentifier(); + if (currentClass == null) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // look up enumeration by identifier in current scope + currentEnum = lookupEnumeration(id, false); + if (currentEnum != null) + { + // found previously defined enumeration + newEnum = false; + } + else + { + // create new enumeration object + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + currentEnum = new VeraEnumeration(schema, name); + copyAnnotations(obj, currentEnum); + newEnum = true; + + // add enumeration to compilation unit + compUnit.addMember(currentEnum); + } + } + else + { + final Iterator iter = currentClass.lookupObjects(id, + VeraNameKind.TYPE); + if (iter.hasNext()) + { + // check that found object is an enumeration + final NamedObject foundObj = (NamedObject) iter.next(); + if (!(foundObj instanceof VeraEnumeration)) + { + throw new SourceSemanticException("Identifier '" + id + + "' already used for non-enumeration", obj); + } + currentEnum = (VeraEnumeration) foundObj; + newEnum = false; + + // identifier should be unique + checkMultipleDefinition(iter); + } + else + { + // create new enumeration object + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + currentEnum = new VeraEnumeration(schema, name); + copyAnnotations(obj, currentEnum); + newEnum = true; + + // add enumeration to class + currentClass.addMember(currentEnum); + } + } + + nextEnumValue = 0; + visitList(obj.getElements()); + + currentEnum = null; + } + + public void visit(EnumElementDecl obj) + { + // determine value of next element + int value; + final ExpressionDecl valueDecl = obj.getValue(); + if (valueDecl != null) + { + // use specified value + value = evalIntExpr(valueDecl); + } + else + { + // use default/consecutive value + value = nextEnumValue; + } + + final String id = obj.getIdentifier(); + final ExpressionDecl firstSuffixDecl = obj.getFirstSuffix(); + if (firstSuffixDecl != null) + { + // determine suffix range for range enumeration + final int firstSuffix, lastSuffix; + final int n = evalIntExpr(firstSuffixDecl); + final ExpressionDecl lastSuffixDecl = obj.getLastSuffix(); + if (lastSuffixDecl != null) + { + int m = evalIntExpr(lastSuffixDecl); + if (n <= m) + { + firstSuffix = n; + lastSuffix = m; + } + else + { + firstSuffix = m; + lastSuffix = n; + } + } + else + { + firstSuffix = 0; + lastSuffix = n - 1; + } + if (firstSuffix < 0 || lastSuffix < 0) + { + throw new SourceSemanticException( + "Invalid enumeration range value", obj); + } + + // define range enumeration + for (int i = firstSuffix; i <= lastSuffix; ++i) + { + addEnumElement(id + i, value++, obj); + } + } + else + { + // define single enumeration + addEnumElement(id, value++, obj); + } + + // store default value for next element + nextEnumValue = value; + } + + private void addEnumElement(String id, int value, EnumElementDecl obj) + { + if (newEnum) + { + // check that enumeration element values are unique + if (currentEnum.lookupValue(value) != null) + { + throw new SourceSemanticException( + "Duplicate enumeration element value: " + value, obj); + } + + // create new enumeration element object + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, + currentEnum); + final VeraEnumerationElement element = new VeraEnumerationElement( + currentEnum, name, value); + copyAnnotations(obj, element); + + // add element to enumeration and current scope + currentEnum.addMember(element); + final VeraCompilationUnit compUnit = currentEnum + .getCompilationUnit(); + if (compUnit != null) + { + compUnit.addMember(element); + } + else + { + final VeraUserClass cls = (VeraUserClass) currentEnum + .getStructuredType(); + assert (cls != null); + cls.addMember(element); + } + } + else + { + // look up element identifier in enumeration + final Iterator iter = currentEnum.lookupObjects(id, + VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + final VeraEnumerationElement element = (VeraEnumerationElement) iter + .next(); + + // check that element value is consistent + if (element.getValue() != value) + { + throw new SourceSemanticException( + "Enumeration element value (" + value + + ") does not match previous definition (" + + element.getValue() + ")", obj); + } + + // identifier should be unique + checkMultipleDefinition(iter); + } + else + { + throw new SourceSemanticException("Enumeration element '" + id + + "' not found in previous definition", obj); + } + } + } + + public void visit(ExpectDecl obj) + { + final VeraExpectStatement stmt = new VeraExpectStatement(schema, obj + .getExpectKind()); + copyAnnotations(obj, stmt); + + // process delay cycles, if present + final ExpressionDecl delayDecl = obj.getDelayExpr(); + if (delayDecl != null) + { + stmt.setDelay(processExpression(delayDecl)); + } + + // process window cycles, if present + final ExpressionDecl windowDecl = obj.getWindowExpr(); + if (windowDecl != null) + { + stmt.setWindow(processExpression(windowDecl)); + } + + // process terms + final Iterator iter = obj.getExpectExprs().iterator(); + while (iter.hasNext()) + { + final ExpectExprDecl exprDecl = (ExpectExprDecl) iter.next(); + final VeraExpression signalExpr = processExpression(exprDecl + .getSignalExpr()); + final VeraExpression valueExpr = processExpression(exprDecl + .getValueExpr()); + stmt.addExpectTerm(new VeraExpectTerm(signalExpr, valueExpr, + exprDecl.getOperator() == Operator.EQUAL)); + } + + // set options + stmt.setExpectAll(obj.isExpectAll()); + stmt.setSoft(obj.isSoft()); + stmt.setAsync(obj.isAsync()); + + checkDefineRef(obj, stmt); + currentStmt = stmt; + } + + public void visit(ExpectExprDecl obj) + { + // TODO: ExpectExprDecl + throw new UnsupportedOperationException(); + } + + public void visit(ExpressionStatementDecl obj) + { + final VeraExpression expr = processExpression(obj.getExpr()); + currentStmt = new VeraExpressionStatement(expr); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(ExtConstraintDecl obj) + { + // look up class by identifier + final VeraClass cls; + final String classID = obj.getClassIdentifier(); + try + { + cls = lookupClass(classID, true); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + + // look up constraint by identifier in class + final VeraClassConstraint cons; + final String id = obj.getIdentifier(); + final Iterator iter = cls.lookupObjects(id, VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + // check that found object is a method + final NamedObject foundObj = (NamedObject) iter.next(); + if (!(foundObj instanceof VeraClassConstraint)) + { + throw new SourceSemanticException("Identifier '" + id + + "' does not represent a constraint", obj); + } + cons = (VeraClassConstraint) foundObj; + + // identifier should be unique + checkMultipleDefinition(iter); + } + else + { + throw new SourceSemanticException("Unknown constraint: " + id, obj); + } + + // check that constraint body is not already defined + if (cons.isDefined()) + { + throw new SourceSemanticException("Constraint '" + id + + "' is already defined", obj); + } + + copyAnnotations(obj, cons); + + // class scope becomes current scope + final VeraScopeDelegate prevScope = currentScope; + currentScope = new VeraClassScope(cls, currentScope); + + // process expressions in constraint body + final Iterator exprIter = obj.getConstraintExprs().iterator(); + while (exprIter.hasNext()) + { + final ExpressionDecl exprDecl = (ExpressionDecl) exprIter.next(); + final VeraExpression expr = processExpression(exprDecl); + cons.addExpr(expr); + } + cons.setDefined(true); + + // restore previous scope + currentScope = prevScope; + } + + public void visit(ExternVarDecl obj) + { + // TODO: ExternVarDecl + throw new UnsupportedOperationException(); + } + + public void visit(FixedArrayTypeRef obj) + { + // process the element type + final VeraType elementType = processType(obj.getElementTypeRef()); + + // evaluate dimension expressions + final List dimExprDecls = obj.getDimensions(); + final int[] dimensions = new int[dimExprDecls.size()]; + final Iterator iter = dimExprDecls.iterator(); + int i = 0; + while (iter.hasNext()) + { + ExpressionDecl dimExprDecl = (ExpressionDecl) iter.next(); + int dim = evalIntExpr(dimExprDecl); + if (dim <= 0) + { + throw new SourceSemanticException("Invalid array dimension", + dimExprDecl); + } + dimensions[i++] = dim; + } + + final VeraFixedArrayType arrayType = new VeraFixedArrayType( + elementType, dimensions); + checkDefineRef(obj, arrayType); + currentType = arrayType; + } + + public void visit(ForDecl obj) + { + final VeraForStatement forStmt = new VeraForStatement(schema); + copyAnnotations(obj, forStmt); + + Iterator iter = obj.getInitExprs().iterator(); + while (iter.hasNext()) + { + final ExpressionDecl exprDecl = (ExpressionDecl) iter.next(); + final VeraExpression expr = processExpression(exprDecl); + final VeraExpressionStatement stmt = new VeraExpressionStatement( + expr); + forStmt.addInitStatement(stmt); + } + + final ExpressionDecl condExprDecl = obj.getCondition(); + if (condExprDecl != null) + { + final VeraExpression condExpr = processExpression(condExprDecl); + if (!condExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Integral expression expected in 'for' condition", + condExprDecl); + } + forStmt.setCondition(condExpr); + } + + iter = obj.getUpdateExprs().iterator(); + while (iter.hasNext()) + { + final ExpressionDecl exprDecl = (ExpressionDecl) iter.next(); + final VeraExpression expr = processExpression(exprDecl); + final VeraExpressionStatement stmt = new VeraExpressionStatement( + expr); + forStmt.addUpdateStatement(stmt); + } + + final VeraStatement stmt = processStatement(obj.getStatement()); + forStmt.setStatement(stmt); + + checkDefineRef(obj, forStmt); + currentStmt = forStmt; + } + + public void visit(ForkJoinDecl obj) + { + final VeraForkStatement forkStmt = new VeraForkStatement(schema, obj + .getJoinKind()); + copyAnnotations(obj, forkStmt); + + final Iterator iter = obj.getStatements().iterator(); + while (iter.hasNext()) + { + final StatementDecl stmtDecl = (StatementDecl) iter.next(); + forkStmt.addForkedStatements(processStatement(stmtDecl)); + } + + checkDefineRef(obj, forkStmt); + currentStmt = forkStmt; + } + + public void visit(FuncCallDecl obj) + { + // process function expression + final ExpressionDecl funcExprDecl = obj.getFunction(); + final VeraExpression funcExpr = processExpression(funcExprDecl); + final VeraFunction func; + if (funcExpr instanceof VeraFunctionReference) + { + VeraFunctionReference funcRef = (VeraFunctionReference) funcExpr; + func = funcRef.getFunction(); + } + else if (funcExpr instanceof VeraMemberAccess) + { + VeraMemberAccess memberRef = (VeraMemberAccess) funcExpr; + VeraStructuredTypeMember member = memberRef.getMember(); + if (!(member instanceof VeraMemberFunction)) + { + throw new SourceSemanticException( + "Function reference expected", funcExprDecl); + } + func = (VeraFunction) member; + } + else + { + throw new SourceSemanticException("Function reference expected", + funcExprDecl); + } + + // expand arguments and create function invocation expression + final VeraFunctionInvocation funcCall = new VeraFunctionInvocation( + funcExpr); + copyAnnotations(obj, funcCall); + final FunctionType funcType = func.getType(); + final List argExprs = expandArgs(funcType.getArguments(), funcType + .isVarArgs(), obj.getArguments(), obj); + final Iterator iter = argExprs.iterator(); + while (iter.hasNext()) + { + funcCall.addArgument((VeraExpression) iter.next()); + } + + // process randomize-with constraints + // FIXME: randomize-with constraints should be evaluated with the + // object's class brought into scope at the innermost nesting level + final ConstraintDecl cons = obj.getConstraints(); + if (cons != null) + { + if (!isRandomizeRef(func)) + { + throw new SourceSemanticException( + "'with' constraints only allowed for randomize() call", + cons); + } + + final Iterator exprIter = cons.getConstraintExprs().iterator(); + while (exprIter.hasNext()) + { + final ExpressionDecl exprDecl = (ExpressionDecl) exprIter + .next(); + final VeraExpression expr = processExpression(exprDecl); + funcCall.addConstraint(expr); + } + } + + checkDefineRef(obj, funcCall); + currentExpr = funcCall; + } + + private List expandArgs( + List formalArgs, + boolean isVarArgs, + List callArgs, + SourceObject obj) + { + // get default values for arguments and where to use them + final int formalArgCount = formalArgs.size(); + final boolean[] useDefault = new boolean[formalArgCount]; + final int callArgCount = callArgs.size(); + getDefaultArgs(formalArgs, isVarArgs, callArgCount, useDefault, obj); + + // process arguments + List result = new ArrayList(Math.max( + formalArgCount, callArgCount)); + int argIndex = 0; + final Iterator formalArgIter = formalArgs.iterator(); + final Iterator callArgIter = callArgs.iterator(); + while (formalArgIter.hasNext() || callArgIter.hasNext()) + { + VeraFunctionArgument formalArg = null; + VeraExpression defaultExpr = null; + if (formalArgIter.hasNext()) + { + formalArg = (VeraFunctionArgument) formalArgIter.next(); + defaultExpr = formalArg.getInitializer(); + } + + if (defaultExpr != null && useDefault[argIndex]) + { + // argument not specified; use default value + result.add(defaultExpr); + } + else if (callArgIter.hasNext()) + { + final ExpressionDecl argExprDecl = (ExpressionDecl) callArgIter + .next(); + final VeraExpression argExpr; + if (argExprDecl instanceof DefaultValueDecl) + { + // default value placeholder; use default value + if (defaultExpr == null) + { + throw new SourceSemanticException( + "Argument does not have a default value", + argExprDecl); + } + argExpr = defaultExpr; + } + else + { + // use given argument expression + argExpr = processExpression(argExprDecl); + + // check argument type + if (formalArg != null) + { + Type argType = formalArg.getType(); + Type exprType = argExpr.getResultType(); + if (argType != schema.magicType + && !argType.isAssignableFrom(exprType)) + { + throw new SourceSemanticException("'" + exprType + + "' expression is not assignable to '" + + argType + "' argument", argExprDecl); + } + } + } + result.add(argExpr); + } + else + { + // argument count should have been checked by getDefaultArgs() + assert (formalArg.isOptional()); + + // stop adding arguments at first optional, no-default argument + break; + } + ++argIndex; + } + return result; + } + + private void getDefaultArgs( + List formalArgs, + boolean isVarArgs, + int actualArgCount, + boolean[] useDefault, + SourceObject obj) + { + final int formalArgCount = formalArgs.size(); + + // determine last level to fill and how many arguments it gets + final int lastFillLevel; + int lastFillCount; + if (actualArgCount == 0) + { + // fill no arguments + lastFillLevel = Integer.MIN_VALUE; + lastFillCount = 0; + } + else if (actualArgCount < formalArgCount) + { + // build array of optional argument levels + final int[] argLevels = new int[formalArgCount]; + int argIndex = 0; + final Iterator iter = formalArgs.iterator(); + while (iter.hasNext()) + { + VeraFunctionArgument arg = (VeraFunctionArgument) iter.next(); + argLevels[argIndex++] = arg.getOptionalLevel(); + } + + // sort argument levels + Arrays.sort(argLevels); + + // last level to fill is level at last actual argument position + int searchPos = actualArgCount - 1; + lastFillLevel = argLevels[searchPos]; + + // get count of arguments to fill at last level + lastFillCount = 1; + while (searchPos > 0 && argLevels[searchPos - 1] == lastFillLevel) + { + ++lastFillCount; + --searchPos; + } + } + else + { + if (actualArgCount > formalArgCount && !isVarArgs) + { + throw new SourceSemanticException( + "Too many arguments for function", obj); + } + + // fill all arguments + lastFillLevel = Integer.MAX_VALUE; + lastFillCount = Integer.MAX_VALUE; + } + + // fill output arrays + int argIndex = 0; + final Iterator iter = formalArgs.iterator(); + while (iter.hasNext()) + { + final VeraFunctionArgument arg = (VeraFunctionArgument) iter.next(); + final int level = arg.getOptionalLevel(); + if (level < lastFillLevel) + { + // use actual argument + useDefault[argIndex] = false; + } + else if (level == lastFillLevel && lastFillCount > 0) + { + // use actual argument and decrement last fill count + useDefault[argIndex] = false; + --lastFillCount; + } + else + { + // use default argument + if (!arg.isOptional()) + { + throw new SourceSemanticException( + "Value not specified for required argument " + + arg.getName(), obj); + } + useDefault[argIndex] = true; + } + ++argIndex; + } + } + + private boolean isRandomizeRef(VeraFunction func) + { + String funcName = func.getName().getCanonicalName(); + return funcName.equals("::randomize"); + } + + private interface GlobalFuncFactory + { + VeraGlobalFunction create(VeraName name, VeraFunctionType funcType); + } + + private VeraFunction processGlobalFunc( + AbsFuncDecl obj, + GlobalFuncFactory factory) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // get class identifier and local modifier (if present) + final String classID; + final boolean local; + if (obj instanceof FuncDecl) + { + final FuncDecl funcObj = (FuncDecl) obj; + classID = funcObj.getClassIdentifier(); + local = funcObj.isLocal(); + } + else + { + classID = null; + local = false; + } + + // look up or create function + final String id = obj.getIdentifier(); + final VeraScopeDelegate funcScope; + if (classID != null) + { + if (local) + { + throw new SourceSemanticException( + "Class functions cannot be local", obj); + } + + // look up class by identifier + final VeraClass cls; + try + { + cls = lookupClass(classID, true); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + currentClass = (VeraUserClass) cls; + + // look up method by identifier in current class + final Iterator iter = cls.lookupObjects(id, VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + // check that found object is a method + final NamedObject foundObj = (NamedObject) iter.next(); + if (!(foundObj instanceof VeraMemberFunction)) + { + throw new SourceSemanticException("Identifier '" + id + + "' does not represent a method", obj); + } + final VeraMemberFunction func = (VeraMemberFunction) foundObj; + newFunc = false; + + // remember whether method has a body + if (((VeraFuncDecl) obj).getBlock() != null) + { + func.setPureVirtual(false); + } + + // identifier should be unique + checkMultipleDefinition(iter); + + currentFunc = func; + funcScope = new VeraClassScope(cls, currentScope); + } + else + { + throw new SourceSemanticException("Unknown method: " + id, obj); + } + } + else + { + VeraGlobalFunction func; + try + { + func = lookupFunction(id, false); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + if (func != null) + { + // found function with existing prototype + newFunc = false; + } + else + { + // create new function object + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, + null); + final VeraFunctionType funcType = new VeraFunctionType(schema); + func = factory.create(name, funcType); + copyAnnotations(obj, func); + newFunc = true; + + func.setVisibility(localToVisibility(local)); + func.setExport(obj.isExport()); + } + + // put function in appropriate compilation unit + trackExternObject(func, compUnit, newFunc, local, obj.isExtern()); + + currentFunc = func; + funcScope = currentScope; + } + VeraFunction resultFunc = currentFunc; + + // process function prototype + processFuncProto(obj); + + // queue function body for second pass processing (if present) + if (obj instanceof VeraFuncDecl && !isFromHeader(obj)) + { + final VeraFuncDecl veraObj = (VeraFuncDecl) obj; + final BlockDecl block = veraObj.getBlock(); + if (block != null) + { + queueFuncBody(currentFunc, veraObj, funcScope); + } + } + + currentFunc = null; + currentClass = null; + + return resultFunc; + } + + public void visit(final FuncDecl obj) + { + class FunctionFactory + implements GlobalFuncFactory + { + public VeraGlobalFunction create( + VeraName name, + VeraFunctionType funcType) + { + return new VeraGlobalFunction(name, funcType); + } + } + VeraFunction func = processGlobalFunc(obj, new FunctionFactory()); + + if (func instanceof VeraGlobalFunction) + { + VeraGlobalFunction globalFunc = (VeraGlobalFunction) func; + if (globalFunc.isExport()) + { + // add exported function to Verilog shell + if (shellMembers != null) shellMembers.add(globalFunc); + } + } + } + + public void visit(GlobalVarDecl obj) + { + // handled in visit(ProgramDecl) + assert false; + } + + private VeraExpression processInitExpr( + ExpressionDecl initExprDecl, + VeraType type) + { + lhsType = type; + + final VeraExpression initExpr = processExpression(initExprDecl); + if (!type.isAssignableFrom(initExpr.getResultType())) + { + throw new SourceSemanticException( + "Initializer type is not assignable to variable type", + initExprDecl); + } + + lhsType = null; + + return initExpr; + } + + public void visit(final HDLTaskDecl obj) + { + class FunctionFactory + implements GlobalFuncFactory + { + public VeraGlobalFunction create( + VeraName name, + VeraFunctionType funcType) + { + final VeraHDLFunction func = new VeraHDLFunction(name, funcType); + return func; + } + } + VeraHDLFunction func = (VeraHDLFunction) processGlobalFunc(obj, + new FunctionFactory()); + + // set instance path if present + if (!obj.isExtern()) + { + String objInstPath = obj.getInstPath(); + String curInstPath = func.getInstPath(); + if (curInstPath == null) + { + // got the instance path for the first time + func.setInstPath(objInstPath); + } + else + { + // if instance path appears in multiple declarations, + // at least make sure they are the same + assert (curInstPath.equals(objInstPath)); + } + + // add HDL function to Verilog shell + if (shellMembers != null) shellMembers.add(func); + } + } + + public void visit(IfElseConstraintDecl obj) + { + VeraExpression ifExpr = processExpression(obj.getIfExpr()); + VeraExpression thenExpr = processExpression(obj.getThenExpr()); + VeraExpression elseExpr = null; + ExpressionDecl elseExprDecl = obj.getElseExpr(); + if (elseExprDecl != null) + { + elseExpr = processExpression(elseExprDecl); + } + currentExpr = new VeraIfElseConstraint(ifExpr, thenExpr, elseExpr); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(IfElseDecl obj) + { + final ExpressionDecl ifExprDecl = obj.getIfExpr(); + final VeraExpression ifExpr = processExpression(ifExprDecl); + if (!ifExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Integral expression expected in 'if' condition", ifExprDecl); + } + final VeraStatement thenStmt = processStatement(obj.getThenStatement()); + final StatementDecl elseStmtDecl = obj.getElseStatement(); + final VeraStatement elseStmt = (elseStmtDecl != null) + ? processStatement(elseStmtDecl) : null; + currentStmt = new VeraIfStatement(ifExpr, thenStmt, elseStmt); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(ImplicationConstraintDecl obj) + { + VeraExpression predExpr = processExpression(obj.getPredicateExpr()); + VeraExpression consExpr = processExpression(obj.getConstraintExpr()); + currentExpr = new VeraImplicationConstraint(predExpr, consExpr); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(IntegerLiteralDecl obj) + { + currentExpr = new VeraIntegerLiteral(schema, obj.getValue()); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(InterfaceDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // look up interface by identifier in current scope + final String id = obj.getIdentifier(); + VeraInterfaceType intf = lookupInterface(id, false); + if (intf == null) + { + // create new interface type + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + intf = new VeraInterfaceType(schema, name); + copyAnnotations(obj, intf); + + // add interface signals + currentIntf = intf; + final Iterator iter = obj.getSignals().iterator(); + while (iter.hasNext()) + { + final SignalDecl signalDecl = (SignalDecl) iter.next(); + signalDecl.accept(this); + assert (currentIntfSignal != null); + final VeraInterfaceSignal signal = currentIntfSignal; + currentIntfSignal = null; + checkDuplicateName(intf, signal, obj); + intf.addMember(signal); + } + currentIntf = null; + + // add interface to compilation unit + compUnit.addMember(intf); + } + + // add interface to Verilog shell + if (shellMembers != null) shellMembers.add(intf); + } + + public void visit(LocalVarDecl obj) + { + // create new local variable + final String id = obj.getIdentifier(); + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraType type = processType(obj.getTypeRef()); + final VeraLocalVariable var = new VeraLocalVariable(name, type); + copyAnnotations(obj, var); + + // process modifiers + final Collection lvdModifiers = obj.getModifiers(); + if (lvdModifiers.contains(LocalVarModifier.STATIC)) + { + var.addModifier(VeraVariableModifier.STATIC); + } + if (lvdModifiers.contains(LocalVarModifier.SHADOW)) + { + var.addModifier(VeraVariableModifier.SHADOW); + } + + // process initializer expression + final ExpressionDecl initExprDecl = obj.getInitExpr(); + if (initExprDecl != null) + { + var.setInitializer(processInitExpr(initExprDecl, type)); + } + + currentVar = var; + } + + public void visit(MemberAccessDecl obj) + { + // evaluate object expression + final VeraExpression objExpr = processExpression(obj.getObjectExpr()); + final Type objType = objExpr.getResultType(); + + // look up member, depending on type of object + final VeraStructuredTypeMember member; + final String id = obj.getIdentifier(); + try + { + if (objType instanceof VeraClass) + { + final VeraClass cls = (VeraClass) objType; + member = lookupMember(cls, id, VeraNameKind.NON_TYPE, true); + currentExpr = new VeraMemberAccess(objExpr, member); + } + else if (objType instanceof VeraInterfaceType) + { + final VeraInterfaceType intf = (VeraInterfaceType) objType; + member = lookupMember(intf, id, VeraNameKind.NON_TYPE, true); + currentExpr = new VeraSignalReference( + (VeraInterfaceSignal) member); + } + else if (objType instanceof VeraPortType) + { + if (!id.startsWith("$")) + { + throw new SourceSemanticException( + "Port member name should start with '$'", obj); + } + final VeraPortType port = (VeraPortType) objType; + member = lookupMember(port, id.substring(1), + VeraNameKind.NON_TYPE, true); + currentExpr = new VeraMemberAccess(objExpr, member); + } + else + { + throw new SourceSemanticException( + "Class, interface, or port reference expected for member access", + obj); + } + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(NewArrayDecl obj) + { + assert (lhsType != null); + if (!(lhsType instanceof VeraDynamicArrayType)) + { + throw new SourceSemanticException("L-value must be dynamic array", + obj); + } + final VeraDynamicArrayType arrayType = (VeraDynamicArrayType) lhsType; + + final ExpressionDecl sizeExprDecl = obj.getSizeExpr(); + final VeraExpression sizeExpr = processExpression(sizeExprDecl); + if (!sizeExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Size expression must be integral", sizeExprDecl); + } + + final VeraArrayCreation createExpr = new VeraArrayCreation(arrayType, + sizeExpr); + copyAnnotations(obj, createExpr); + + final ExpressionDecl sourceExprDecl = obj.getSourceExpr(); + if (sourceExprDecl != null) + { + final VeraExpression sourceExpr = processExpression(sourceExprDecl); + if (!sourceExpr.getResultType().equals(arrayType)) + { + throw new SourceSemanticException( + "Source array must have same type as L-value", + sourceExprDecl); + } + } + + checkDefineRef(obj, createExpr); + currentExpr = createExpr; + } + + public void visit(NewCopyDecl obj) + { + // get class or port type + assert (lhsType != null); + if (!(lhsType instanceof VeraClass || lhsType instanceof VeraPortType)) + { + throw new SourceSemanticException( + "Class or port type expected for left-hand expression", obj); + } + final VeraComplexType type = (VeraComplexType) lhsType; + + // process source expression + final ExpressionDecl sourceExprDecl = obj.getSourceExpr(); + final VeraExpression sourceExpr = processExpression(sourceExprDecl); + if (!type.isAssignableFrom(sourceExpr.getResultType())) + { + throw new SourceSemanticException( + "Source object type not is not assignable to new object type", + sourceExprDecl); + } + + // create new expression + currentExpr = new VeraCopyCreation(type, sourceExpr); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(NewDecl obj) + { + assert (lhsType != null); + + final VeraInstanceCreation newExpr; + if (lhsType instanceof VeraClass) + { + // get class type + final VeraClass cls = (VeraClass) lhsType; + + // get formal args for constructor, if any + final List formalArgs; + Iterator iter = cls.lookupObjects("new", VeraNameKind.NON_TYPE); + if (iter.hasNext()) + { + final VeraMemberFunction newFunc = (VeraMemberFunction) iter + .next(); + final FunctionType funcType = newFunc.getType(); + formalArgs = funcType.getArguments(); + } + else + { + formalArgs = Collections.EMPTY_LIST; + } + + // expand arguments and create new expression + newExpr = new VeraInstanceCreation(cls); + final List argExprs = expandArgs(formalArgs, false, obj + .getArguments(), obj); + iter = argExprs.iterator(); + while (iter.hasNext()) + { + newExpr.addArgument((VeraExpression) iter.next()); + } + } + else if (lhsType instanceof VeraPortType) + { + if (obj.getArguments().size() > 0) + { + throw new SourceSemanticException( + "Arguments not allowed for port creation", obj); + } + + newExpr = new VeraInstanceCreation((VeraPortType) lhsType); + } + else + { + throw new SourceSemanticException( + "Class or port type expected for left-hand expression", obj); + } + copyAnnotations(obj, newExpr); + + checkDefineRef(obj, newExpr); + currentExpr = newExpr; + } + + public void visit(NullLiteralDecl obj) + { + currentExpr = new VeraNullLiteral(schema); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(OperationDecl obj) + { + // save LHS type (necessary for operations in array init elements) + final Type prevLHSType = lhsType; + + final Operator operator = obj.getOperator(); + + // process operands + final List operandDecls = obj.getOperands(); + final VeraExpression operands[] = new VeraExpression[operandDecls + .size()]; + int operandCount = 0; + final Iterator iter = operandDecls.iterator(); + while (iter.hasNext()) + { + ExpressionDecl operandDecl = (ExpressionDecl) iter.next(); + VeraExpression operand = processExpression(operandDecl); + operands[operandCount++] = operand; + + // 'new' expressions need to know type of variable on left-hand side + if (operandCount == 1 && operator == Operator.ASSIGN) + { + lhsType = operand.getResultType(); + } + } + + try + { + // process operator + if (operator == Operator.CONCATENATION) + { + final VeraConcatenation concat = new VeraConcatenation(schema); + for (int i = 0; i < operandCount; ++i) + { + concat.addOperand(operands[i]); + } + currentExpr = concat; + } + else if (operator == Operator.CONDITIONAL) + { + assert (operandCount == 3); + currentExpr = new VeraConditional(operands[0], operands[1], + operands[2]); + } + else if (operator == Operator.LOGICAL_OR) + { + assert (operandCount == 2); + currentExpr = new VeraLogicalOr(operands[0], operands[1]); + } + else if (operator == Operator.LOGICAL_AND) + { + assert (operandCount == 2); + currentExpr = new VeraLogicalAnd(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_OR) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseOr(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_NOR) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseOrNot(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_XOR) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseXor(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_XNOR) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseXorNot(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_AND) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseAnd(operands[0], operands[1]); + } + else if (operator == Operator.BITWISE_NAND) + { + assert (operandCount == 2); + currentExpr = new VeraBitwiseAndNot(operands[0], operands[1]); + } + else if (operator == Operator.EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraEqual(operands[0], operands[1]); + } + else if (operator == Operator.NOT_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraNotEqual(operands[0], operands[1]); + } + else if (operator == Operator.EXACT_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraExactEqual(operands[0], operands[1]); + } + else if (operator == Operator.EXACT_NOT_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraExactNotEqual(operands[0], operands[1]); + } + else if (operator == Operator.WILD_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraWildEqual(operands[0], operands[1]); + } + else if (operator == Operator.WILD_NOT_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraWildNotEqual(operands[0], operands[1]); + } + else if (operator == Operator.LESS) + { + assert (operandCount == 2); + currentExpr = new VeraLess(operands[0], operands[1]); + } + else if (operator == Operator.LESS_OR_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraLessOrEqual(operands[0], operands[1]); + } + else if (operator == Operator.GREATER) + { + assert (operandCount == 2); + currentExpr = new VeraGreater(operands[0], operands[1]); + } + else if (operator == Operator.GREATER_OR_EQUAL) + { + assert (operandCount == 2); + currentExpr = new VeraGreaterOrEqual(operands[0], operands[1]); + } + else if (operator == Operator.LEFT_SHIFT) + { + assert (operandCount == 2); + currentExpr = new VeraLeftShift(operands[0], operands[1]); + } + else if (operator == Operator.RIGHT_SHIFT) + { + assert (operandCount == 2); + currentExpr = new VeraRightShift(operands[0], operands[1]); + } + else if (operator == Operator.ADD) + { + assert (operandCount == 2); + currentExpr = new VeraAdd(operands[0], operands[1]); + } + else if (operator == Operator.SUBTRACT) + { + assert (operandCount == 2); + currentExpr = new VeraSubtract(operands[0], operands[1]); + } + else if (operator == Operator.MULTIPLY) + { + assert (operandCount == 2); + currentExpr = new VeraMultiply(operands[0], operands[1]); + } + else if (operator == Operator.DIVIDE) + { + assert (operandCount == 2); + currentExpr = new VeraDivide(operands[0], operands[1]); + } + else if (operator == Operator.MODULO) + { + assert (operandCount == 2); + currentExpr = new VeraModulo(operands[0], operands[1]); + } + else if (operator == Operator.REPLICATION) + { + assert (operandCount == 2); + currentExpr = new VeraReplication(operands[0], operands[1]); + } + else if (operator == Operator.ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssign(operands[0], operands[1]); + } + else if (operator == Operator.ADD_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignAdd(operands[0], operands[1]); + } + else if (operator == Operator.SUBTRACT_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignSubtract(operands[0], operands[1]); + } + else if (operator == Operator.MULTIPLY_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignMultiply(operands[0], operands[1]); + } + else if (operator == Operator.DIVIDE_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignDivide(operands[0], operands[1]); + } + else if (operator == Operator.MODULO_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignModulo(operands[0], operands[1]); + } + else if (operator == Operator.LEFT_SHIFT_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignLeftShift(operands[0], operands[1]); + } + else if (operator == Operator.RIGHT_SHIFT_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignRightShift(operands[0], operands[1]); + } + else if (operator == Operator.AND_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignAnd(operands[0], operands[1]); + } + else if (operator == Operator.OR_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignOr(operands[0], operands[1]); + } + else if (operator == Operator.XOR_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignXor(operands[0], operands[1]); + } + else if (operator == Operator.NAND_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignAndNot(operands[0], operands[1]); + } + else if (operator == Operator.NOR_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignOrNot(operands[0], operands[1]); + } + else if (operator == Operator.XNOR_ASSIGN) + { + assert (operandCount == 2); + currentExpr = new VeraAssignXorNot(operands[0], operands[1]); + } + else if (operator == Operator.NEGATIVE) + { + assert (operandCount == 1); + currentExpr = new VeraArithmeticNegative(operands[0]); + } + else if (operator == Operator.LOGICAL_NEGATIVE) + { + assert (operandCount == 1); + currentExpr = new VeraLogicalNegative(operands[0]); + } + else if (operator == Operator.BITWISE_NEGATIVE) + { + assert (operandCount == 1); + currentExpr = new VeraBitwiseNegative(operands[0]); + } + else if (operator == Operator.AND_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraAndReduction(operands[0]); + } + else if (operator == Operator.NAND_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraNotAndReduction(operands[0]); + } + else if (operator == Operator.OR_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraOrReduction(operands[0]); + } + else if (operator == Operator.NOR_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraNotOrReduction(operands[0]); + } + else if (operator == Operator.XOR_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraXorReduction(operands[0]); + } + else if (operator == Operator.XNOR_REDUCTION) + { + assert (operandCount == 1); + currentExpr = new VeraNotXorReduction(operands[0]); + } + else if (operator == Operator.BITWISE_REVERSE) + { + assert (operandCount == 1); + currentExpr = new VeraBitwiseReverse(operands[0]); + } + else if (operator == Operator.PRE_INCREMENT) + { + assert (operandCount == 1); + currentExpr = new VeraPreIncrement(operands[0]); + } + else if (operator == Operator.PRE_DECREMENT) + { + assert (operandCount == 1); + currentExpr = new VeraPreDecrement(operands[0]); + } + else if (operator == Operator.POST_INCREMENT) + { + assert (operandCount == 1); + currentExpr = new VeraPostIncrement(operands[0]); + } + else if (operator == Operator.POST_DECREMENT) + { + assert (operandCount == 1); + currentExpr = new VeraPostDecrement(operands[0]); + } + else + { + throw new RuntimeException("Unknown operator: " + operator); + } + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + + lhsType = prevLHSType; + } + + public void visit(ParamDecl obj) + { + assert (currentFunc != null); + final VeraFunctionType funcType = currentFunc.getType(); + + // get identifier + final String argID = obj.getIdentifier(); + final VeraName argName = new VeraName(argID, VeraNameKind.NON_TYPE, + null); + + // get type + final VeraType argType = processType(obj.getTypeRef()); + + // get by-reference flag + final boolean byRef = obj.isByRef(); + + // get optional argument information + final ExpressionDecl defExprDecl = obj.getDefaultExpr(); + final boolean optional = defExprDecl != null; + final int optLevel = obj.getOptLevel(); + if (optLevel > 0 && !optional) + { + throw new SourceSemanticException( + "Optional argument must have default value", obj); + } + + final VeraFunctionArgument arg; + if (newFunc) + { + // create argument object + arg = new VeraFunctionArgument(argName, argType, currentFunc); + copyAnnotations(obj, arg); + arg.setByRef(byRef); + arg.setOptional(optional); + arg.setOptionalLevel(optLevel); + funcType.addArgument(arg); + } + else + { + // get argument object from previous definition + final List argList = funcType.getArguments(); + if (currentArgPos >= argList.size()) + { + throw new SourceSemanticException("Argument count mismatch; " + + argList.size() + " expected", obj); + } + arg = (VeraFunctionArgument) argList.get(currentArgPos); + + // check that argument definition is consistent + if (!argType.equals(arg.getType()) || byRef != arg.isByRef()) + { + throw new SourceSemanticException( + "Argument definition mismatch at position " + currentArgPos, + obj); + } + + // update name + // NOTE: argument names are checked for uniqueness when the + // function body is processed + if (!argName.equals(arg.getName())) + { + funcType.renameArgument(arg, argName); + } + } + + // process default value expression + if (defExprDecl != null) + { + final VeraExpression defExpr = processExpression(defExprDecl); + arg.setInitializer(defExpr); + } + + ++currentArgPos; + } + + public void visit(PortDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // look up port by identifier in current scope + final String id = obj.getIdentifier(); + VeraPortType port = lookupPort(id, false); + if (port == null) + { + // create new port type + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + port = new VeraPortType(schema, name); + copyAnnotations(obj, port); + + // add port members + final Iterator iter = obj.getMembers().iterator(); + while (iter.hasNext()) + { + final String memberID = (String) iter.next(); + final VeraName memberName = new VeraName(memberID, + VeraNameKind.NON_TYPE, port); + final VeraPortSignal member = new VeraPortSignal(schema, + memberName); + checkDuplicateName(port, member, obj); + port.addMember(member); + } + + // add port to compilation unit + compUnit.addMember(port); + } + } + + public void visit(PragmaDecl obj) + { + // TODO: visit PragmaDecl + //System.out.println("#pragma " + obj.getText()); + } + + public void visit(PrimitiveTypeRef obj) + { + final VeraPrimitiveKind kind = obj.getPrimitiveKind(); + final VeraType type; + if (kind == VeraPrimitiveKind.INTEGER) + { + type = schema.integerType; + } + else if (kind == VeraPrimitiveKind.STRING) + { + type = schema.stringType; + } + else if (kind == VeraPrimitiveKind.BIT) + { + type = schema.bitType; + } + else if (kind == VeraPrimitiveKind.EVENT) + { + type = schema.eventType; + } + else + { + throw new AssertionError("Unexpected primitive kind: " + kind); + } + currentType = type; + } + + public void visit(final ProgramDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // program blocks do not appear in generated headers + if (isFromHeader(obj)) return; + + // at most one program block per compilation unit + assert (currentProgram == null); + + // process global variable declarations + Iterator iter = obj.getGlobalVars().iterator(); + while (iter.hasNext()) + { + final GlobalVarDecl varDecl = (GlobalVarDecl) iter.next(); + + // create new global variable + final String id = varDecl.getIdentifier(); + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraType type = processType(varDecl.getTypeRef()); + final VeraGlobalVariable var = new VeraGlobalVariable(name, type); + copyAnnotations(varDecl, var); + compUnit.addMember(var); + } + + // create new program block + final String id = obj.getIdentifier(); + final VeraName name = new VeraName(id, VeraNameKind.NON_TYPE, null); + final VeraBlock block = new VeraBlock(schema); + final VeraProgram program = new VeraProgram(name, block); + copyAnnotations(obj, program); + + // program blocks are not accessible by name, but we still check for + // uniqueness, since the Vera loader requires it + checkDuplicateName(compUnit, program, obj); + + // add program block to compilation unit + compUnit.addMember(program); + + // process program body later + addDeferredProcess(new Runnable() + { + public void run() + { + processProgramBody(program, obj); + } + }); + + currentProgram = program; + } + + void processProgramBody(VeraProgram program, ProgramDecl programDecl) + { + currentScope = compUnitScope; + + final VeraBlock block = program.getBlock(); + + // process global variable initializers + Iterator iter = programDecl.getGlobalVars().iterator(); + while (iter.hasNext()) + { + final GlobalVarDecl varDecl = (GlobalVarDecl) iter.next(); + final VeraGlobalVariable var = lookupGlobalVar(varDecl + .getIdentifier(), true); + + // if variable declaration has an initializer, translate it into an + // assignment at the beginning of the program block + // NOTE: for array initializers, this violates the syntactic rule + // that array initializers can only occur in variable declarations; + // still, we model global variables this way because it is the only + // way to allow separate programs to share global variables + final ExpressionDecl initExprDecl = varDecl.getInitExpr(); + if (initExprDecl != null) + { + VeraExpression initExpr = processInitExpr(initExprDecl, var + .getType()); + block.addMember(new VeraExpressionStatement(new VeraAssign( + new VeraVariableReference(var), initExpr))); + } + } + + // process statements + iter = programDecl.getStatements().iterator(); + while (iter.hasNext()) + { + final StatementDecl stmt = (StatementDecl) iter.next(); + stmt.accept(this); + assert (currentStmt != null); + block.addMember(currentStmt); + currentStmt = null; + } + + currentScope = null; + } + + public void visit(RandCaseDecl obj) + { + final VeraRandCaseStatement randCaseStmt = new VeraRandCaseStatement( + schema); + copyAnnotations(obj, randCaseStmt); + + final Iterator iter = obj.getCaseMembers().iterator(); + while (iter.hasNext()) + { + final RandCaseMemberDecl member = (RandCaseMemberDecl) iter.next(); + member.accept(this); + assert (currentRandCase != null); + randCaseStmt.addCase(currentRandCase); + currentRandCase = null; + } + + checkDefineRef(obj, randCaseStmt); + currentStmt = randCaseStmt; + } + + public void visit(RandCaseMemberDecl obj) + { + final ExpressionDecl weightExprDecl = obj.getWeightExpr(); + final VeraExpression weightExpr = processExpression(weightExprDecl); + if (!weightExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "'randcase' weight expression must be integral", weightExprDecl); + } + + final StatementDecl stmtDecl = obj.getStatementDecl(); + final VeraStatement stmt = processStatement(stmtDecl); + + currentRandCase = new VeraRandCase(weightExpr, stmt); + } + + public void visit(RepeatDecl obj) + { + final ExpressionDecl countExprDecl = obj.getCondition(); + final VeraExpression countExpr = processExpression(countExprDecl); + if (!countExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Integral expression expected in 'repeat' count", countExprDecl); + } + final VeraStatement stmt = processStatement(obj.getStatement()); + currentStmt = new VeraRepeatStatement(countExpr, stmt); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(ReturnDecl obj) + { + currentStmt = new VeraReturnStatement(schema); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(SetOperationDecl obj) + { + // process expression + final ExpressionDecl exprDecl = obj.getExpr(); + final VeraExpression expr = processExpression(exprDecl); + + // create expression object based on operator type + final VeraSetOperation setOp; + final Operator operator = obj.getOperator(); + if (operator == Operator.IN) + { + setOp = new VeraInSet(expr); + } + else if (operator == Operator.NOT_IN) + { + setOp = new VeraNotInSet(expr); + } + else + { + assert (operator == Operator.DIST); + setOp = new VeraDistSet(expr); + } + copyAnnotations(obj, setOp); + + // process set members + final List ranges = obj.getRanges().getRanges(); + final Iterator rangeIter = ranges.iterator(); + while (rangeIter.hasNext()) + { + final RangeDecl range = (RangeDecl) rangeIter.next(); + + final VeraSetMember setMember; + final ExpressionDecl lowDecl = range.getFrom(); + final VeraExpression low = processExpression(lowDecl); + final ExpressionDecl highDecl = range.getTo(); + if (lowDecl == highDecl) + { + // if low and high expressions reference same object, + // there is really only a single value + setMember = new VeraSetValue(low); + } + else + { + final VeraExpression high = processExpression(highDecl); + setMember = new VeraSetRange(low, high); + } + + // process weighting (if present) + if (range instanceof WeightedRangeDecl) + { + final WeightedRangeDecl weightedRange = (WeightedRangeDecl) range; + final ExpressionDecl weightDecl = weightedRange.getWeight(); + if (weightDecl != null) + { + final VeraExpression weight = processExpression(weightDecl); + setMember + .setWeight(weight, weightedRange.isWeightPerItem()); + } + } + + setOp.addMember(setMember); + } + + checkDefineRef(obj, setOp); + currentExpr = setOp; + } + + public void visit(SignalDecl obj) + { + // create interface signal + final VeraName name = new VeraName(obj.getIdentifier(), + VeraNameKind.NON_TYPE, currentIntf); + final ExpressionDecl highBitExpr = obj.getHighBitExpr(); + final int highBit = highBitExpr != null ? evalIntExpr(highBitExpr) : 0; + final VeraInterfaceSignal signal = new VeraInterfaceSignal(schema, + name, obj.getKind(), obj.getDirection(), highBit + 1); + copyAnnotations(obj, signal); + + // set sample/drive edges + final EdgeSet sampleEdges = obj.getSampleEdges(); + signal.setSampleEdges(sampleEdges); + signal.setDriveEdges(obj.getDriveEdges()); + + // process skews + final Iterator iter = obj.getSkews().iterator(); + while (iter.hasNext()) + { + final SignalSkewDecl skewDecl = (SignalSkewDecl) iter.next(); + final ExpressionDecl timeToXExpr = skewDecl.getTimeToXExpr(); + final int timeToValue = evalIntExpr(skewDecl.getTimeToValueExpr()); + if (timeToXExpr == null) + { + // simple skew + final int skew = timeToValue; + if (skew < 0) + { + // negative skew is sample skew + signal.setSampleSkew(skew); + } + else if (skew > 0) + { + // positive skew is drive skew + signal.setDriveSkew(skew); + } + else + { + // zero skew is ignored + } + } + else + { + // surround-by-X timing + final int timeToX = evalIntExpr(timeToXExpr); + signal.addSurrXParams(new VeraSurrXParams(skewDecl + .getTransitionKind(), timeToX, timeToValue)); + } + } + + // set sample depth + final ExpressionDecl depthExpr = obj.getDepthExpr(); + final int depth = depthExpr != null ? evalIntExpr(depthExpr) : 0; + signal.setSampleDepth(depth); + + // set VCA checking + signal.setVCAKind(obj.getVCAKind()); + signal.setVCAQValue(obj.getVCAQValue()); + + // set HDL node + signal.setHDLNode(obj.getHDLNode()); + + currentIntfSignal = signal; + } + + public void visit(SignalRangeDecl obj) + { + // handled in visit(BindSignalDecl) + assert false; + } + + public void visit(SignalSkewDecl obj) + { + // handled in visit(SignalDecl) + assert false; + } + + public void visit(StringLiteralDecl obj) + { + currentExpr = new VeraStringLiteral(schema, obj.getValue()); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(SuperRefDecl obj) + { + if (currentClass == null) + { + throw new SourceSemanticException( + "'super' outside of class context", obj); + } + final VeraClass baseClass = currentClass.getBaseClass(); + if (baseClass == null) + { + throw new SourceSemanticException("Class '" + + currentClass.getName() + "' has no superclass", obj); + } + currentExpr = new VeraSuperReference(currentClass); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(SyncDecl obj) + { + final VeraSyncStatement syncStmt = new VeraSyncStatement(schema); + copyAnnotations(obj, syncStmt); + + final Iterator iter = obj.getTerms().iterator(); + while (iter.hasNext()) + { + final SyncTerm term = (SyncTerm) iter.next(); + final ExpressionDecl signalDecl = term.getSignal(); + final VeraExpression signal = (signalDecl != null) + ? processExpression(signalDecl) : new VeraSystemClockReference( + schema); + + final SyncEdge edge = term.getEdge(); + final EdgeSet edgeSet; + if (edge == SyncEdge.POSEDGE) + { + edgeSet = EdgeSet.POSEDGE; + } + else if (edge == SyncEdge.NEGEDGE) + { + edgeSet = EdgeSet.NEGEDGE; + } + else + { + assert (edge == SyncEdge.ANYEDGE); + edgeSet = EdgeSet.ANYEDGE; + } + syncStmt.addTerm(new VeraSyncTerm(signal, edgeSet, term.isAsync())); + } + + checkDefineRef(obj, syncStmt); + currentStmt = syncStmt; + } + + public void visit(TerminateDecl obj) + { + currentStmt = new VeraTerminateStatement(schema); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + public void visit(ThisRefDecl obj) + { + if (currentClass == null) + { + throw new SourceSemanticException( + "'this' outside of class context", obj); + } + currentExpr = new VeraThisReference(currentClass); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(TypedefDecl obj) + { + // determine compilation unit + final VeraCompilationUnit compUnit = getCompUnit(obj); + + // search for a class with the given identifier + final String id = obj.getIdentifier(); + final VeraClass foundClass = lookupClass(id, false); + if (foundClass == null) + { + // create new typedef-only class + final VeraName name = new VeraName(id, VeraNameKind.TYPE, null); + final VeraUserClass cls = new VeraUserClass(schema, name); + copyAnnotations(obj, cls); + cls.setTypedefOnly(true); + + // put class in appropriate compilation unit + trackExternObject(cls, compUnit, true, true, true); + } + } + + public void visit(final UDFFuncDecl obj) + { + class FunctionFactory + implements GlobalFuncFactory + { + public VeraGlobalFunction create( + VeraName name, + VeraFunctionType funcType) + { + funcType.setVarArgs(obj.isVarArgs()); + final VeraUDFFunction func = new VeraUDFFunction(name, funcType); + func.setLanguage(obj.getLanguage()); + return func; + } + } + processGlobalFunc(obj, new FunctionFactory()); + } + + public void visit(UserTypeRef obj) + { + final VeraType type; + try + { + type = lookupType(obj.getIdentifier(), true); + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + currentType = type; + } + + public void visit(VarRefDecl obj) + { + final String id = obj.getIdentifier(); + final NamedObject foundObj; + try + { + final String classID = obj.getClassIdentifier(); + if (classID == null) + { + foundObj = lookupObject(id, VeraNameKind.ANY, true); + } + else + { + final VeraClass cls = lookupClass(classID, true); + foundObj = (NamedObject) lookupMember(cls, id, + VeraNameKind.ANY, true); + } + } + catch (SourceSemanticException e) + { + e.setSourceObject(obj); + throw e; + } + if (foundObj instanceof VeraVariable) + { + currentExpr = new VeraVariableReference((VeraVariable) foundObj); + } + else if (foundObj instanceof VeraFunction) + { + final VeraFunction func = (VeraFunction) foundObj; + if (obj.isFunctionCall()) + { + currentExpr = new VeraFunctionReference(func); + } + else + { + if (func != currentFunc) + { + throw new SourceSemanticException( + "Illegal function reference", obj); + } + VeraVariable returnVar = func.getReturnVar(); + if (returnVar == null) + { + throw new SourceSemanticException( + "Function has no return value", obj); + } + currentExpr = new VeraVariableReference(returnVar); + } + } + else if (foundObj instanceof VeraEnumerationElement) + { + final VeraEnumerationElement elem = (VeraEnumerationElement) foundObj; + currentExpr = new VeraEnumValueReference(elem); + } + else if (foundObj instanceof VeraInterfaceType) + { + final VeraInterfaceType intf = (VeraInterfaceType) foundObj; + currentExpr = new VeraInterfaceReference(intf); + } + else + { + throw new SourceSemanticException( + "Variable, function, enumeration element, or interface " + + "reference expected", obj); + } + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(VoidLiteralDecl obj) + { + currentExpr = new VeraVoidLiteral(schema); + copyAnnotations(obj, currentExpr); + checkDefineRef(obj, currentExpr); + } + + public void visit(WhileDecl obj) + { + final ExpressionDecl condExprDecl = obj.getCondition(); + final VeraExpression condExpr = processExpression(condExprDecl); + if (!condExpr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Integral expression expected in 'while' condition", + condExprDecl); + } + final VeraStatement stmt = processStatement(obj.getStatement()); + currentStmt = new VeraWhileStatement(condExpr, stmt); + copyAnnotations(obj, currentStmt); + checkDefineRef(obj, currentStmt); + } + + private void visitList(List l) + { + final Iterator iter = l.iterator(); + while (iter.hasNext()) + { + final VeraSourceObject obj = (VeraSourceObject) iter.next(); + obj.accept(this); + } + } + + private VeraCompilationUnit getCompUnit(VeraSourceObject obj) + { + final String path = preprocInfo.getCompilationUnit(obj); + final boolean fromHeader = preprocInfo.isFromHeader(obj); + return getCompUnit(path, fromHeader); + } + + private VeraCompilationUnit getCompUnit(String path, boolean fromHeader) + { + // look up or create compilation unit + final VeraCompilationUnit compUnit; + final Iterator iter = schema + .lookupObjects(path, VeraNameKind.COMP_UNIT); + if (iter.hasNext()) + { + compUnit = (VeraCompilationUnit) iter.next(); + checkMultipleDefinition(iter); + } + else + { + compUnit = new VeraCompilationUnit(schema, path); + schema.addMember(compUnit); + } + compUnitScope.addCompilationUnit(compUnit, fromHeader); + compUnitScope.setCurrentUnit(compUnit); + return compUnit; + } + + private boolean isFromHeader(SourceObject obj) + { + return preprocInfo.isFromHeader(obj); + } + + private void trackExternObject( + VeraCompilationUnitMember member, + VeraCompilationUnit compUnit, + boolean isNew, + boolean isLocal, + boolean isExtern) + { + boolean add = isNew; + + if (!isNew && !isLocal && !isExtern) + { + VeraCompilationUnit externCompUnit = member.getCompilationUnit(); + if (compUnit != externCompUnit) + { + externCompUnit.removeMember(member); + add = true; + } + } + + if (add) + { + compUnit.addMember(member); + } + } + + public VeraExpression processExpression(ExpressionDecl exprDecl) + { + exprDecl.accept(this); + assert (currentExpr != null); + final VeraExpression expr = currentExpr; + currentExpr = null; + return expr; + } + + public VeraRange processRange(RangeDecl rangeDecl) + { + VeraExpression from = processExpression(rangeDecl.getFrom()); + VeraExpression to = processExpression(rangeDecl.getTo()); + VeraRange range = new VeraRange(schema, from, to); + checkDefineRef(rangeDecl, range); + return range; + } + + public VeraStatement processStatement(StatementDecl stmtDecl) + { + stmtDecl.accept(this); + assert (currentStmt != null); + final VeraStatement stmt = currentStmt; + currentStmt = null; + return stmt; + } + + public VeraType processType(TypeRef typeRef) + { + typeRef.accept(this); + assert (currentType != null); + final VeraType type = currentType; + currentType = null; + return type; + } + + private int evalIntExpr(ExpressionDecl exprDecl) + { + final VeraExpression expr = processExpression(exprDecl); + return evalIntExpr(expr, exprDecl); + } + + private int evalIntExpr(VeraExpression expr, ExpressionDecl exprDecl) + { + if (!expr.getResultType().isIntegralConvertible()) + { + throw new SourceSemanticException( + "Integral constant expression expected", exprDecl); + } + final Integer result = VeraExpression + .toInteger(expr.evaluateConstant()); + if (result == null) + { + throw new SourceSemanticException("Expression may not contain X/Z", + exprDecl); + } + return result.intValue(); + } + + private VeraClass lookupClass(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.TYPE, mustExist); + if (obj != null && !(obj instanceof VeraClass)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a class"); + } + return (VeraClass) obj; + } + + private VeraPortType lookupPort(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.TYPE, mustExist); + if (obj != null && !(obj instanceof VeraPortType)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a port"); + } + return (VeraPortType) obj; + } + + private VeraInterfaceType lookupInterface(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.ANY, mustExist); + if (obj != null && !(obj instanceof VeraInterfaceType)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent an interface"); + } + return (VeraInterfaceType) obj; + } + + private VeraBindVariable lookupBind(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.NON_TYPE, + mustExist); + if (obj != null && !(obj instanceof VeraBindVariable)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a bind"); + } + return (VeraBindVariable) obj; + } + + private VeraEnumeration lookupEnumeration(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.TYPE, mustExist); + if (obj != null && !(obj instanceof VeraEnumeration)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent an enumeration"); + } + return (VeraEnumeration) obj; + } + + private VeraType lookupType(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.TYPE, mustExist); + if (obj != null && !(obj instanceof VeraType)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a type"); + } + return (VeraType) obj; + } + + private VeraGlobalFunction lookupFunction(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.NON_TYPE, + mustExist); + if (obj != null && !(obj instanceof VeraGlobalFunction)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a global function"); + } + return (VeraGlobalFunction) obj; + } + + private VeraGlobalVariable lookupGlobalVar(String id, boolean mustExist) + { + final NamedObject obj = lookupObject(id, VeraNameKind.NON_TYPE, + mustExist); + if (obj != null && !(obj instanceof VeraGlobalVariable)) + { + throw new SemanticException("Identifier '" + id + + "' does not represent a global variable"); + } + return (VeraGlobalVariable) obj; + } + + private NamedObject lookupObject( + String id, + VeraNameKind kind, + boolean mustExist) + { + NamedObject obj = null; + final Iterator iter = currentScope.lookupObjects(id, kind); + if (iter.hasNext()) + { + obj = (NamedObject) iter.next(); + checkMultipleDefinition(iter); + } + else if (mustExist) + { + throw new SemanticException("Unknown identifier: " + id); + } + return obj; + } + + private void checkMultipleDefinition(Iterator iter) + { + if (iter.hasNext()) + { + NamedObject obj = (NamedObject) iter.next(); + String id = obj.getName().getIdentifier(); + throw new SemanticException("Multiple occurrences of identifier: " + + id); + } + } + + private VeraStructuredTypeMember lookupMember( + VeraClass cls, + String id, + VeraNameKind kind, + boolean mustExist) + { + VeraStructuredTypeMember member = null; + while (cls != null) + { + Iterator iter = cls.lookupObjects(id, kind); + if (iter.hasNext()) + { + member = (VeraStructuredTypeMember) iter.next(); + checkMultipleDefinition(iter); + break; + } + cls = cls.getBaseClass(); + } + if (member == null && mustExist) + { + throw new SemanticException("Unknown member identifier: " + id); + } + return member; + } + + private VeraStructuredTypeMember lookupMember( + VeraStructuredType type, + String id, + VeraNameKind kind, + boolean mustExist) + { + VeraStructuredTypeMember member = null; + Iterator iter = type.lookupObjects(id, kind); + if (iter.hasNext()) + { + member = (VeraStructuredTypeMember) iter.next(); + checkMultipleDefinition(iter); + } + if (member == null && mustExist) + { + throw new SemanticException("Unknown member identifier: " + id); + } + return member; + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraScopeDelegate.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraScopeDelegate.java new file mode 100644 index 0000000..d06ef9c --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraScopeDelegate.java @@ -0,0 +1,37 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import com.newisys.langschema.Scope; + +/** + * Base class for scope implementations that delegate to other scopes, + * including an optional enclosing scope. + * + * @author Trevor Robinson + */ +public abstract class VeraScopeDelegate + implements Scope +{ + protected final VeraScopeDelegate enclosingScope; + + protected VeraScopeDelegate(VeraScopeDelegate enclosingScope) + { + this.enclosingScope = enclosingScope; + } +} diff --git a/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSimpleScope.java b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSimpleScope.java new file mode 100644 index 0000000..6decbce --- /dev/null +++ b/java/vera-parser/src/com/newisys/schemabuilder/vera/VeraSimpleScope.java @@ -0,0 +1,55 @@ +/* + * Parser and Source Model for the OpenVera (TM) language + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * VERA and OpenVera are trademarks or registered trademarks of Synopsys, Inc. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.schemabuilder.vera; + +import java.util.Iterator; + +import com.newisys.langschema.NameKind; +import com.newisys.langschema.NamedObject; +import com.newisys.langschema.Scope; + +/** + * Scope delegate that delegates to a) the given primary scope, and then b) + * the enclosing scope (if any). + * + * @author Trevor Robinson + */ +public final class VeraSimpleScope + extends VeraScopeDelegate +{ + private final Scope scope; + + public VeraSimpleScope(Scope scope, VeraScopeDelegate enclosingScope) + { + super(enclosingScope); + this.scope = scope; + } + + public Iterator< ? extends NamedObject> lookupObjects( + String identifier, + NameKind kind) + { + Iterator< ? extends NamedObject> iter = scope.lookupObjects(identifier, + kind); + if (!iter.hasNext() && enclosingScope != null) + { + iter = enclosingScope.lookupObjects(identifier, kind); + } + return iter; + } +} diff --git a/java/vlogdef/build.xml b/java/vlogdef/build.xml new file mode 100644 index 0000000..0479ce4 --- /dev/null +++ b/java/vlogdef/build.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/vlogdef/manifest.mf b/java/vlogdef/manifest.mf new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/java/vlogdef/manifest.mf @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/java/vlogdef/src/com/newisys/dv/vlogdef/Defines.java b/java/vlogdef/src/com/newisys/dv/vlogdef/Defines.java new file mode 100644 index 0000000..1865b69 --- /dev/null +++ b/java/vlogdef/src/com/newisys/dv/vlogdef/Defines.java @@ -0,0 +1,329 @@ +/* + * Jove Verilog Preprocessor Definition Importer + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * Java is a registered trademark of Sun Microsystems, Inc. in the U.S. or + * other countries. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.dv.vlogdef; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.StringReader; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +import com.newisys.langschema.vera.VeraExpression; +import com.newisys.langschema.vera.VeraRange; +import com.newisys.langsource.vera.ExpressionDecl; +import com.newisys.langsource.vera.RangeDecl; +import com.newisys.parser.util.FunctionMacro; +import com.newisys.parser.util.ParseException; +import com.newisys.parser.vera.VeraParser; +import com.newisys.parser.vera.VeraParserBasePPHandler; +import com.newisys.parser.vera.VeraParserReusableTokenManager; +import com.newisys.parser.verapp.VeraPPBaseHandler; +import com.newisys.parser.verapp.VeraPPMacro; +import com.newisys.parser.verapp.VeraPPParser; +import com.newisys.parser.verapp.VeraPPStaticMacro; +import com.newisys.schemabuilder.vera.VeraSchemaBuilder; +import com.newisys.verilog.util.BitRange; +import com.newisys.verilog.util.BitVector; +import com.newisys.verilog.util.ValueConverter; + +/** + * Provides dynamic access to #defines declared in Verilog and Vera source + * files. Uses facilities from Juno to perform evaluation of constant + * expressions. + * + * @author Trevor Robinson + */ +public class Defines +{ + final HashSet includedFiles = new HashSet(); + + private VeraPPBaseHandler ppHandler = new VeraPPBaseHandler() + { + @Override + protected void doInclude(VeraPPParser parser, String path) + throws ParseException + { + File f = new File(path); + if (!includedFiles.contains(f)) + { + includedFiles.add(f); + super.doInclude(parser, path); + } + } + }; + + public Defines() + { + String paths = System.getProperty("com.newisys.dv.vlogdef.paths"); + if (paths != null) + { + String[] pathArray = paths.split("\\" + File.pathSeparatorChar); + for (String path : pathArray) + { + addUserPath(path); + } + } + } + + public void addSysPath(String path) + { + ppHandler.addSysPath(path); + } + + public void addUserPath(String path) + { + ppHandler.addUserPath(path); + } + + public void addDefine(String name, String value) + { + ppHandler.addDefine(new VeraPPStaticMacro(name, value)); + } + + public void readFile(String filename) + { + String path; + try + { + path = ppHandler.resolvePath(filename, false); + if (path == null) path = filename; + } + catch (IOException e) + { + throw new VerilogDefineException("Error resolving path '" + + filename + "': " + e.getMessage(), e); + } + File f = new File(path); + if (!includedFiles.contains(f)) + { + includedFiles.add(f); + VeraPPParser ppParser; + try + { + ppParser = new VeraPPParser(f, ppHandler); + } + catch (FileNotFoundException e) + { + throw new VerilogDefineException("Error opening file '" + path + + "': " + e.getMessage(), e); + } + try + { + ppParser.file(); + } + catch (ParseException e) + { + throw new VerilogDefineException("Error parsing file '" + path + + "': " + e.getMessage(), e); + } + } + } + + private VeraPPMacro getDefine(String name) + { + VeraPPMacro macro = ppHandler.getDefine(name); + if (macro == null) + { + throw new VerilogDefineException("Unknown define: " + name); + } + return macro; + } + + private String expand(String name, String... args) + { + // look up macro + VeraPPMacro macro = getDefine(name); + String expansion; + if (args != null && args.length > 0) + { + // check for function macro + if (!(macro instanceof FunctionMacro)) + { + throw new VerilogDefineException("Macro '" + name + + "' does not accept arguments"); + } + FunctionMacro funcMacro = (FunctionMacro) macro; + + // check argument count + List argNames = funcMacro.getArgumentNames(); + int argCount = argNames.size(); + if (argCount != args.length) + { + throw new VerilogDefineException("Macro '" + name + + "' expects " + argCount + " arguments; " + args.length + + " were provided"); + } + + // build argument name->value map + int index = 0; + HashMap argValues = new HashMap(); + for (String argName : argNames) + { + argValues.put(argName, args[index++]); + } + + expansion = funcMacro.expand(argValues); + } + else + { + expansion = macro.expand(); + } + return expansion; + } + + private VeraParserReusableTokenManager preprocess( + String name, + String expansion) + { + VeraParserReusableTokenManager tm = new VeraParserReusableTokenManager(); + VeraParserBasePPHandler handler = new VeraParserBasePPHandler(tm, + ppHandler.getDefines()); + VeraPPParser macroPPParser = new VeraPPParser(new StringReader( + expansion), handler); + try + { + macroPPParser.file(); + } + catch (ParseException e) + { + throw new VerilogDefineException("Error preprocessing expansion '" + + expansion + "' of macro '" + name + "': " + e.getMessage(), e); + } + return tm; + } + + private Object evaluateExpression(String name, String expansion) + { + VeraParserReusableTokenManager tm = preprocess(name, expansion); + VeraParser macroParser = new VeraParser(tm); + ExpressionDecl exprDecl; + try + { + exprDecl = macroParser.cond_expr(); + } + catch (ParseException e) + { + throw new VerilogDefineException("Error parsing expression '" + + tm.getContents() + "' for macro '" + name + "': " + + e.getMessage(), e); + } + VeraSchemaBuilder builder = new VeraSchemaBuilder(); + VeraExpression expr; + try + { + expr = builder.processExpression(exprDecl); + } + catch (RuntimeException e) + { + throw new VerilogDefineException("Error resolving expression '" + + exprDecl + "' for macro '" + name + "': " + e.getMessage(), e); + } + if (!expr.isConstant()) + { + throw new VerilogDefineException( + "Unable to evaluate non-constant expression '" + + expr.toSourceString() + "' for macro '" + name + "'"); + } + return expr.evaluateConstant(); + } + + private BitRange evaluateRange(String name, String expansion) + { + VeraParserReusableTokenManager tm = preprocess(name, expansion); + VeraParser macroParser = new VeraParser(tm); + RangeDecl rangeDecl; + try + { + rangeDecl = macroParser.range(); + } + catch (ParseException e) + { + throw new VerilogDefineException("Error parsing range '" + + tm.getContents() + "' for macro '" + name + "': " + + e.getMessage(), e); + } + VeraSchemaBuilder builder = new VeraSchemaBuilder(); + VeraRange range; + try + { + range = builder.processRange(rangeDecl); + } + catch (RuntimeException e) + { + throw new VerilogDefineException("Error resolving range '" + + rangeDecl + "' for macro '" + name + "': " + e.getMessage(), + e); + } + if (!range.isConstant()) + { + throw new VerilogDefineException( + "Unable to evaluate non-constant range '" + + range.toSourceString() + "' for macro '" + name + "'"); + } + Object fromObj = range.getFrom().evaluateConstant(); + if (!(fromObj instanceof Number || fromObj instanceof BitVector)) + { + throw new VerilogDefineException("Unexpected from-index type '" + + fromObj.getClass().getName() + "' in range macro '" + name + + "'"); + } + Object toObj = range.getTo().evaluateConstant(); + if (!(toObj instanceof Number || toObj instanceof BitVector)) + { + throw new VerilogDefineException("Unexpected to-index type '" + + toObj.getClass().getName() + "' in range macro '" + name + + "'"); + } + int from = ValueConverter.toInt(fromObj); + int to = ValueConverter.toInt(toObj); + return new BitRange(from, to); + } + + public Object getObject(String name, String... args) + { + String expansion = expand(name, args); + return evaluateExpression(name, expansion); + } + + public int getInt(String name, String... args) + { + Object value = getObject(name, args); + return ValueConverter.toInt(value); + } + + public long getLong(String name, String... args) + { + Object value = getObject(name, args); + return ValueConverter.toLong(value); + } + + public BitVector getBitVector(String name, String... args) + { + Object value = getObject(name, args); + return ValueConverter.toBitVector(value); + } + + public BitRange getBitRange(String name, String... args) + { + String expansion = expand(name, args); + return evaluateRange(name, expansion); + } +} diff --git a/java/vlogdef/src/com/newisys/dv/vlogdef/VerilogDefineException.java b/java/vlogdef/src/com/newisys/dv/vlogdef/VerilogDefineException.java new file mode 100644 index 0000000..6ca3235 --- /dev/null +++ b/java/vlogdef/src/com/newisys/dv/vlogdef/VerilogDefineException.java @@ -0,0 +1,50 @@ +/* + * Jove Verilog Preprocessor Definition Importer + * Copyright (C) 2005 Newisys, Inc. or its licensors, as applicable. + * Java is a registered trademark of Sun Microsystems, Inc. in the U.S. or + * other countries. + * + * Licensed under the Open Software License version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You should + * have received a copy of the License along with this software; if not, you + * may obtain a copy of the License at + * + * http://opensource.org/licenses/osl-2.0.php + * + * This software 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 com.newisys.dv.vlogdef; + +/** + * Exception thrown when an error occurs importing a Verilog definition. + * + * @author Trevor Robinson + */ +public class VerilogDefineException + extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public VerilogDefineException() + { + super(); + } + + public VerilogDefineException(String message) + { + super(message); + } + + public VerilogDefineException(String message, Throwable cause) + { + super(message, cause); + } + + public VerilogDefineException(Throwable cause) + { + super(cause); + } +}